text
stringlengths 180
608k
|
---|
[Question]
[
Let's have a list of positive integers
```
[6,1,9,3,7,4,6,3,2,7,6,6]
```
this will represent a river. We would like to skip a stone across this river. We can throw the stone as far as we want and whatever number it lands on it will skip that many places. So if we start by throwing it 2 spaces, it will land on the `1` skip forward one place, land on the `9` skip forward 9 places, land on the final 6 and skip out of the river.
```
[6,1,9,3,7,4,6,3,2,7,6,6]
^
[6,1,9,3,7,4,6,3,2,7,6,6]
^
[6,1,9,3,7,4,6,3,2,7,6,6]
^
```
The question for us is: "How do we throw the stone so it skips the largest number of times?" In the above case `2` skips 3 times and indeed we can see that this is the optimum.
Here's all the ways to throw the stone with the number of skips labeled:
```
[6,1,9,3,7,4,6,3,2,7,6,6]
2 3 2 2 2 2 1 2 2 1 1 1
```
## Task
Given a list of positive integers as input output the maximum skips that can be achieved on that river.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to make your source code as small as possible as measured in bytes.
## Test cases
```
[1] -> 1
[1,1,1] -> 3
[9,1,1,1] -> 3
[9,3,1,2,2,9,1,1,1] -> 5
[6,6] -> 1
[6,1,9,3,7,4,6,3,2,7,6,6] -> 3
[1,1,9,1,1] -> 3
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
.sε.Γ¬.$]ζg
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fr/jcVr1zkw@t0VOJPbct/f//aEsdYx1DHSMgtATSQBgLAA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##yy9OTMpM/X9uq9J/veJzW/XOTT60Rk8l9ty29P9KemH/o6MNY3WiDXWAEEhb6iBYxkCWERAixMx0zMCkoQ5I1lzHRMcMSBsBWSCZWAA)
```
.sε # map over the suffixes of the list
.Γ # iterate until reaching a fixed point, collecting intermediate results:
¬.$ # get the first value, and drop that many values from the front
ζ # after the map: transpose, padding with spaces
g # get the length
```
[Answer]
# JavaScript (ES6), 49 bytes
```
a=>Math.max(...a.map(g=(v,i)=>v&&-~g(a[i+=v],i)))
```
[Try it online!](https://tio.run/##dY5BDoIwEEX3noIVaWMpKWiNi3IDT0BYTBBqDVIipHHl1etgXNUys5jJ5P0//w4O5vZppiUb7bXzvfKgqgssN/6AF@GcAy4T0Yo4ZqiqXJpmb02gNnvlGjxR6ls7znbo@GA16UktGkqTeOV5InYhzrDjEsTLED@zTUEcLxEvsP@EiB9DXDK5lT6WXaLj@uHEDkziLHD7WcTCiC8eTb/i/gM "JavaScript (Node.js) – Try It Online")
We turn the input array into a list of number of skips for each starting point, using the recursive callback function `g`:
```
g = ( // g is a recursive function taking:
v, // v = value at the current position
i // i = current position
) => //
v && // abort if v is undefined
-~g( // otherwise increment the result of a recursive call:
a[i += v], // add v to i and pass a[i] as the new value
i // pass the new position
) // end of recursive call
```
We then return the maximum of this list.
[Answer]
# [J](http://jsoftware.com/), 25 bytes
```
[:#[:+./ .*^:a:~#\=/~]+#\
```
[Try it online!](https://tio.run/##XU3BCoJAEL3vVwx6UHMdTctww1iKgiA6dF23EFGkhA52i/x1Gwsh4jHMvHkz7117A60KUgEWcAhAUHkIm9Nh1ythKuGiDzg5i1x0Zpb6nXbNrHfYcY1Q1GVxg7xp4FG2DyjytmxZWdR3sO1KGihfQr5QPrGDFNTAsYtc7VCUtwJrj3KL2lniJdQUHDA11YMwpYETPiRiKuF/NCIaEn6FOVMxj8f/mPbD3YLPeEw9pGmUo6998uPp9G8 "J – Try It Online")
We think of it as a graph problem.
Consider `1 1 9 1 1`
* `]+#\` Add `1 2 3 4 5` to the input:
```
2 3 12 5 6
```
* `#\=/` Create an equality table showing where that is equal to `1 2 3 4 5`:
```
1 2 3 4 5
+----------
2| 0 1 0 0 0
3| 0 0 1 0 0
12| 0 0 0 0 0
5| 0 0 0 0 1
6| 0 0 0 0 0
```
This is the adjacency of matrix of the directed graph showing connections between the indices.
* `[:+./ .*^:a:~` "OR" matrix multiply that graph with itself until we reach a fixed point, saving intermediate steps:
```
0 1 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
```
* `[:#` Return the length, which is also the length of the longest path:
```
3
```
## [J](http://jsoftware.com/), Bonus port of [ovs's answer](https://codegolf.stackexchange.com/a/241595/15469), 25 bytes
```
[:>./<:@#@(({.}.])^:a:)\.
```
[Try it online!](https://tio.run/##XU3BCoJAEL3vVwx20KV1UrcMt5SlKAiiQ9fNQsSICjrYTfTXbSwEiWGY9@bNvHdvLbSvECuwQYAHitpFWB/329aoBCdLpUfacSqsMeVnlSl@wpazwwohvxX5A7LnE95F@YY8K4uSsSK/vcBxrtpCXStdo66wgRhMx7GR45RTlpuAvUO9IdMFXoKUkj1m/LQTfAKC6kskM5H4o5JoQDUUZsyEIuz/Q9p3d3MxFSHNgFAvy599NPDk7Qc "J – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, ~~20~~ 16 bytes
```
żƛ{D?L<|?i+1$}!⇩
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwixbzGm3tEP0w8fD9pKzEkfSHih6kiLCIiLCJbNiwxLDksMyw3LDQsNiwzLDIsNyw2LDZdIl0=)
~~This feels too long~~ That's better.
## Explained
```
żƛ{D?L<|?i+1$}!⇩
ż # The range [1, len(input)] - this represents all possible starting throw lengths
∆õ # over each item N in that range:
{D?L<| # while the top of the stack (the position of the rock on the lake) (initially N) is less than the length of the input: - this keeps the top of the stack on the stack
?i+ # index into the input list at the current position of the rock and add the skip value to the position of the rock. This is what keeps track of how far the rock has travelled.
1$ # and push a 1 to the stack, placing it underneath the position of the rock - this keeps track of how many jumps have been made.
} # end loop
!‚á© # push the length of the stack minus 2 - this is the number of jumps made accounting for the remaining rock positions.
# the -G flag returns the maximum number of jumps from the resulting list.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 61 57 54 53 bytes
-4 bytes thanks to @ovs
Further -3 bytes thanks to @xnor
And an additional -1 byte thanks to @ovs
```
f=lambda l,b=1:l>[]and max(1+f(l[l[0]:],-1),f(l[b:]))
```
[Try it online!](https://tio.run/##XYzBasMwEETv@oolJ4muTRQnLjHYPyJ0kLFNF9aSsERpvt6VU0JLmcPu29mZ@MgfwTf7vvTs1nFywDj2uuPBWOcnWN2X1G@LZMPmbDuLlVZ44NhZpXZaY9gypEcSYgkbMJA/qE55Il9vs5uY/Jyk6gQQhn51Uc6fjpHrFJmyPFXDSSkBcSOfJZVuUhjUbrSFagAtjMaiJzTC3PEfNgUvRX@NmzAttq98W@7H3ztesS3zUraX3fzU3387vwE "Python 3 – Try It Online")
[Answer]
# x86-16 machine code, 24 bytes
```
00000000: 33c0 33db 5399 4202 183b d97e f93b d07c 3└3█SÖB☻↑;┘~∙;╨|
00000010: 028b c25b 43e2 edc3 ☻ï┬[CΓφ├
```
Listing:
```
33 C0 XOR AX, AX ; AX = max skip count
33 DB XOR BX, BX ; BX = starting point offset
THROW_LOOP:
53 PUSH BX ; save starting point
99 CWD ; clear skips counter for this throw (DX = 0)
SKIP_LOOP:
42 INC DX ; increment skip counter
02 18 ADD BL, BYTE PTR[BX+SI] ; add it's value to place offset
3B D9 CMP BX, CX ; did it skip out of the river?
7E F9 JLE SKIP_LOOP ; if not, let it keep skipping
END_SKIP:
3B D0 CMP DX, AX ; is skip counter higher than best?
7C 02 JL NOT_BEST ; if not, try next starting offset
8B C2 MOV AX, DX ; if so, save as current best score
NOT_BEST:
5B POP BX ; restore starting point
43 INC BX ; go to next starting point
E2 ED LOOP THROW_LOOP ; loop until end of array
C3 RET
```
Input array at `[SI]`, length in `CX`. Output most skips in `AX`.
Tests with DOS DEBUG (in Dark Mode):
[](https://i.stack.imgur.com/Hh3RX.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~71~~ ~~70~~ ~~68~~ ~~64~~ ~~62~~ ~~52~~ ~~50~~ 47 bytes
```
A|->Max[i=0;#0@@Check[!#+A[[#]],-1]+1&@++i&/@A]
```
–3 thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73/H9pIW@iRXRmbYG1soGDg7OGanJ2dGKytqO0dHKsbE6uoax2oZqDtramWr6Do6x/wOKMvNKopUVdO0U0kAK1BT0HRSqqw1rdRSqDXUUQAjEtIQwETxjMM8IjFAlzXQUzKC0IVgOqNRcR8EEKAxmG4G5MFWGMFVg7bX/AQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṫ‘ḢƊƬÐƤẈṀ_2
```
A monadic Link accepting a list of integers that yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8///hztWPGmY83LHoWNexNYcnHFvycFfHw50N8Ub///@PNtMx1LHUMdYx1zHRMQPSRkCWmY5ZLAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hztWPGmY83LHoWNexNYcnHFvycFfHw50N8Ub/D7c/alrz/390tGEsl060oQ4QghiWOkhMYyDTCAiRBM10zCCUoQ5I3lzHRMcMSBsBWVApQ7AUWHksAA "Jelly – Try It Online").
### How?
Unfortunately, while `Ḣ` pops off and yields the head of a list it affects the original list given to `ÐƤ` (for suffixes of the list) as well as the suffix being dealt with at the time and so affects the remaining suffixes. Without the popping we need to increment for `ṫ` (tail from) to do the correct thing so I've incremented all elements, tailed from each of those and then kept the head of those lists. Maybe there is a better way to do this challenge that will take less bytes...?
```
ṫ‘ḢƊƬÐƤẈṀ_2 - Link: list of integers, River
ÐƤ - for each suffix of River:
Ƭ - collect input values while distinct, applying:
Ɗ - last three links as a monad:
‘ - increment all values
·π´ - tail (vectorises, so tail at from incremented value)
·∏¢ - head (the list that used the first incremented value)
Ẉ - length of each
Ṁ - maximum
_2 - subtract two (the final [] and the 0 that heading [] (or 0) yields)
```
---
This one is 13 bytes, but maybe the idea can lead to a shorter solution?
```
J≈íP·ªã·πñ‚źI{ ã∆á‚Å∏·π™L
```
[Answer]
# [Nibbles](https://nibbles.golf), 10 bytes (19 nibbles)
```
`/.,,$-,`.$+=~$_$~]
```
## Explanation
```
`/.,,$-,`.$+=~$_$~]
`/ ] Maximum of list:
. Map over
,,$ each index i of the input:
`.$ Iterate starting at j = i, collecting all values:
+ Add
=~$_ the j-th element of the input or 0 if out of bounds
$ to j
, Get length
- ~ Subtract 1
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
eSmlP.u.x>NhN[)_d).__
```
[Test suite](http://pythtemp.herokuapp.com/?code=eSmlP.u.x%3ENhN%5B%29_d%29.__&test_suite=1&test_suite_input=%5B1%5D%0A%5B1%2C1%2C1%5D%0A%5B9%2C1%2C1%2C1%5D%0A%5B9%2C3%2C1%2C2%2C2%2C9%2C1%2C1%2C1%5D%0A%5B6%2C6%5D%0A%5B6%2C1%2C9%2C3%2C7%2C4%2C6%2C3%2C2%2C7%2C6%2C6%5D%0A%5B1%2C1%2C9%2C1%2C1%5D&debug=1)
##### Explanation:
```
eSmlP.u.x>NhN[)_d).__ | Full code
eSmlP.u.x>NhN[)_d).__Q | with implicit variables filled
-----------------------+----------------------------------------------------------------------------------------------------------------
m _ .__Q | Map over the list of suffixes `d` of the input:
.u d) | Repeat the following on `N`, starting with `d`, until a repeated value is given, collecting results in a list:
>NhN | `N` from index (the first value of `N`) on
.x [) | (or the empty list if an error is thrown)
lP | Length of the resulting list - 1
eS | Get the max value of the resulting list
```
The final 7 bytes can be omitted if input is taken as a list of suffixes (not allowed by challenge author).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
←▲mȯLU¡S↓←ṫ
```
[Try it online!](https://tio.run/##yygtzv7//1HbhEfTNuWeWO8Temhh8KO2yUCBhztX////P9pSx1jHUMcICC2BNBDGAgA "Husk – Try It Online")
## Explanation
```
←▲mȯLU¡S↓←ṫ
·π´ suffixes
m map each to
¬°S‚Üì‚Üê infinite list: drop first element no. of elements
LU length of unique prefix
‚Üê‚ñ≤ decrement maximum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
;0µ+J«LịƬ`L
```
[Try it online!](https://tio.run/##y0rNyan8/9/a4NBWba9Dq30e7u4@tibB5//hds3I//@jow1juXSiDXWAEMSw1EFiGgOZRkCIJGimYwahDHVA8uY6JjpmQNoIyIJKGYKloMpNgfIgWYQlIGYsAA "Jelly – Try It Online")
Feels like there ought to be one more byte to shave off, perhaps dealing with the final step with something shorter than `;0µ`, but it at least ties.
```
;0µ Append a 0 to the list.
+J Find the sum of each element and its 1-index
¬´L capped at the list's length.
ịƬ` Index this into itself (constant) until it doesn't change,
L and return the number of iterations that took.
```
`Ṗ’o¥\ċ1‘µÐƤṀ` and `’o¥\ÐƤI>-§Ṁ‘`, a byte longer and completely different, also work.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
F⌈θ⊞θ⁰F⮌…Lθ§≔θι∧§θι⊕§θ⁺ι§θιI⌈θ
```
[Try it online!](https://tio.run/##VY7NCoMwEITvPkWOG9hC/0gpnqQnoQXxKh6CbjWgKyZRfPtUPdm57DLzDUzValsNugvhO1gBH72YfuphlFJkk2thRHGWcbSHOc1kHUGuuSF4Eze@3ciVTZwzDSc@5ZqWrWRQJFzD0ZEoUq4s9cSe/qKsmxxsjSO9K44ya9jDSzt/HCfjEIpC4QWfeMMH3lGt97p@ClVZhtPc/QA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⌈θ⊞θ⁰
```
Append sufficient zeros so that we never jump off the end of the array.
```
F⮌…Lθ
```
Iterate over the array in reverse order.
```
§≔θι∧§θι⊕§θ⁺ι§θι
```
Update each non-zero element with `1` more than the number of skips of its next skip.
```
I⌈θ
```
Output the maximum number of skips.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes
```
.+
,$&;
\d+
$*
+`,1(1)*;((?<-1>1*,)*(1*))
;1$3,$2
O^`1+
\G;?1
```
[Try it online!](https://tio.run/##NYmxCgIxEET7/Y4om80oTE4iEvHKK/2BQyJoYWMh/n/cE45h5y1vPs/v633vG51a3ydB2FaZH0mCSWqgMlpVHc87XmiIprQYpTIMCFmut8Yk81RH9k4hPHLCysGZPaspKH7EshxxQHFm/xbPv/f@AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
,$&;
```
Wrap the input list with an extra prefix `,` and a trailing marker `;`.
```
\d+
$*
```
Convert to unary.
```
+`
```
Repeat until the marker has reached the beginning of the array.
```
,1(1)*;((?<-1>1*,)*(1*))
```
Try to skip ahead to find how many additional skips to take. (If there aren't enough values then this just runs off the end of the array and finds no skips.)
```
;1$3,$2
```
Replace the current value with `1` more than the number of additional skips.
```
O^`1+
```
Sort the numbers of skips in descending order.
```
\G;?1
```
Convert the maximum to decimal.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~78~~ ~~77~~ 75 bytes
```
i;c;m;f(a,n)int*a;{for(m=0;n--;++a)for(c=i=0;i<=n;m=++c>m?c:m)i+=a[i];i=m;}
```
[Try it online!](https://tio.run/##dZLbbsIwDEDf9xVRJaSGphr0KgiFh2lfAX2o0pRFWwMilYaG@PV1btNbQOvNsY/t2HGZe2SsrgVltKSFnRGJhazmGb0Vp4tdJgsqXZc6ToYbnSUCLGKTSFomjsO25Y6tSyycJNuLlIqkpPca4lGZCWljdHtBcDWGiqtquU9Rgm7LOx1MXmcicE/MvjavyCMIeuAD8OB@dgm1S0SiiTHqjUvSxMYkIBFID1amYzwWtNKJ@xbmLVeat@0Q3YIWvhaBFqEWkRbxmKXVpU6ixA8/FXabC7922lyrBE2oZ1LPpL5JfZMGJg1MGpo0NGlk0siksUljPOmSX8@cVTzvTxP57QPH0q07X3aSqkLsI7vM4cvZJ7/oEOtwffcO19UbvKFF0FT3rS4afklkN9sJmfMrhC1ot9z0hfaFjLUOFoocp/XGbTL9r47DhnR64K1PSqcYyY7KJ3q@AC9sa2/h0TgtdCgTipRdDXjwnKaYqVkOrQPfNSewtuBbNRum2KxGQU6YCUHyAXAAwyj@qzRF7hbNcjRTBwk7KDJMAvJCfL/b/eVe/7LiKzuq2v3@Aw "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 maximum number of skips.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) `-r`, 106 bytes
```
{({}(<()>)){({}<<>({}<>)>[(())])}{}<>(([(({})<><{{}({}<>)<>}{}>)]<>{}){(<{}>)[()]}{}<>({}()<>))<>}<>({}<>)
```
[Try it online!](https://tio.run/##NYwxCsNADAS/onK3cJE4XDAIfcRc4RSBkODCrbi3K1JMGmmHHelxbK99en62d4TDBxQ0sqKq1TTaCpCdowhI8kE19dR/glpWxq6WhUMLVrCfB2mlwbL@HyOaXGSRWe5yk5b7mqlJi@n4Ag "Brain-Flak – Try It Online")
Starting from the end (which is the top of the stack since I used the `-r` flag), computes the number of skips from each position as 1 more than the previously calculated number of skips from its destination. The implicit zeros on the right stack account for the initial running maximum and number of skips from positions beyond the river.
In each iteration, the left stack has the positions not handled yet, and the right stack has the running maximum on top, followed by the number of skips from already handled positions.
Full code breakdown later.
[Answer]
# T-SQL, 96 bytes
```
WITH c(a,b,x)as(SELECT*,1FROM t
UNION ALL
SELECT t.*,x+1FROM c,t
WHERE a+b=i)SELECT max(x)FROM c
```
**[Try it online](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=b4f04f50899874e476352c8b60c56295)**
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~41~~ 39 bytes
-1 (-2) thanks to [Roman](https://codegolf.stackexchange.com/questions/241591/how-many-times-can-i-skip-a-stone/241622?noredirect=1#comment544913_241622)
```
Depth[g=h@#;i=0;(g@i=g[++i+#]!)&/@#]-3&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yW1oCQjOt02w0HZOtPWwFoj3SHTNj1aWztTWzlWUVNN30E5VtdY7X9AUWZeSbSyrl0aUECtLjg5Ma@umqvasFYHSOgAIYhhqYPENAYyjYAQSdBMxwxCGeqA5M11THTMgLQRkAWVMgRLgZRz1f7/DwA "Wolfram Language (Mathematica) – Try It Online")
```
g=h@#; associate g with this input
i=0; ++i &/@# for indices i of input l:
(g@i=g[ i+#]!) g[i]->Factorial[g[i+l„Äöi„Äõ]]
Depth[ ] depth
-3 offset (-1 List, -2 g[_])
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 19 bytes
```
‚åଥ¬∑{‚ü®‚ü©:0;1+ùïä‚äë‚ä∏‚Üìùï©}¬®‚Üì
```
Anonymous function that takes a list of integers and returns an integer. [Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oyIwrTCt3vin6jin6k6MDsxK/CdlYriipHiirjihpPwnZWpfcKo4oaTCgpGwqgg4p+oCiDin6gx4p+pLAog4p+oOSwzLDEsMiwyLDksMSwxLDHin6ksCiDin6g2LDEsOSwzLDcsNCw2LDMsMiw3LDYsNuKfqSwKIOKfqDEsMSw5LDEsMeKfqQrin6k=)
### Explanation
```
‚åଥ¬∑{‚ü®‚ü©:0;1+ùïä‚äë‚ä∏‚Üìùï©}¬®‚Üì
‚Üì Get the suffixes of the input list
{ }¨ Apply this function to each of them:
⟨⟩:0 If the argument is an empty list, return 0
; Else:
ùï© Take the argument
⊸↓ Drop a number of elements from it
‚äë equal to its first element
(If there aren't that many elements, the result is empty)
ùïä Call this function recursively with that shorter list
1+ Add 1 to the result of the recursive call
⌈´· Get the maximum of the resulting list of integers
```
For example, with input `⟨1,1,9,1,1⟩`, the suffixes are `⟨⟨1,1,9,1,1⟩, ⟨1,9,1,1⟩, ⟨9,1,1⟩, ⟨1,1⟩, ⟨1⟩, ⟨⟩⟩`. When the inner function is called with the suffix `⟨1,9,1,1⟩`:
* `⟨1,9,1,1⟩` is not empty, so drop the first 1 element and recurse
+ `⟨9,1,1⟩` is not empty, so drop the first 9 elements and recurse
- `⟨⟩` is empty, so return 0
+ Add 1 to 0 and return 1
* Add 1 to 1 and return 2
This is the number of skips that are possible starting from the second 1 in the original list.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes
```
Max[l@Most@NestWhileList[#+w[[#]]&,#,#<=l@w&]&/@Range@(l=Length)[w=#]]&
```
[Try it online!](https://tio.run/##TYpBCsIwEEX3nkIIFMWB0CoVwcAcoBVx4yJ0ESQkgbSCGahQevaYqIvyYf5j3u8VWd0rcg8VjYitekuP7TMQXnSgu3VeNy6QZLtRStZ1BTBgZ@FxLLqC400NRuPGi0YPhuxWjiKP4vXlBlpzNByn1VTOkA6kZDjBAvcJq5TFs4b6VyVkf4QD1KmrRH9VflWezzF@AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~30~~ 24 bytes
```
FnRglAE:Uv<n|1+(lv-n)MXl
```
Takes the input numbers as separate command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhY73PKC0nMcXa1Cy2zyagy1NXLKdPM0fSNyINJQVZujLXWMdQx1jIDQEkgDYSxUCgA)
Implements the spec somewhat directly. Still searching for a golfier approach.
] |
[Question]
[
Write a program that takes in an odd length string containing only the characters `.` and `:`. With the aid of an initially empty [stack](http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29), generate a number from this string as follows:
For every character *c* in the string (going from left to right)...
* If *c* is `.` and the stack has less than 2 elements, push 1 on the stack.
* If *c* is `.` and the stack has 2 or more elements, pop the two top values off the stack and push their sum onto the stack.
* If *c* is `:` and the stack has less than 2 elements, push 2 on the stack.
* If *c* is `:` and the stack has 2 or more elements, pop the two top values off the stack and push their product onto the stack.
The resulting number is the value at the top of the stack. Your program should print this number to stdout (with an optional trailing newline).
(A little analysis shows that there is only ever one number left unless the string has even length, which is why we are ignoring those. In fact, the stack never has more than 2 elements.)
For example, the number for `::...:.:.` is 9:
```
2 1 2 2 /______ stack just after the character below is handled
2 2 4 4 5 5 7 7 9 \
: : . . . : . : . <-- string, one character at a time
```
As a sanity check, here are the numbers for all strings of length 1, 3, and 5:
```
. 1
: 2
... 2
..: 1
.:. 3
.:: 2
:.. 3
:.: 2
::. 4
::: 4
..... 3
....: 2
...:. 4
...:: 4
..:.. 2
..:.: 1
..::. 3
..::: 2
.:... 4
.:..: 3
.:.:. 5
.:.:: 6
.::.. 3
.::.: 2
.:::. 4
.:::: 4
:.... 4
:...: 3
:..:. 5
:..:: 6
:.:.. 3
:.:.: 2
:.::. 4
:.::: 4
::... 5
::..: 4
::.:. 6
::.:: 8
:::.. 5
:::.: 4
::::. 6
::::: 8
```
**The shortest program in bytes wins. Tiebreaker is earlier post.**
* You may assume the input is always valid, i.e. a string containing only `.` and `:` whose length is odd.
* Instead of writing a program, you may write a function that takes in a valid string and prints or returns the generated number.
[Answer]
# CJam, ~~27 24 23~~ 22 bytes
```
q{i]_,+~3<-"1+2* "=~}/
```
Pretty straight forward. I use CJam's stack as the stack mentioned in the question ;)
**Algorithm**
First lets look at the ASCII code for `.` and `:`.
```
'.i ':ied
```
>
> [46 58]
>
>
>
Since in CJam, index wraps around, lets see if we can use these values directly to get the desired operation ..
```
'.i4% ':i4%ed
```
>
> [2 2]
>
>
>
So I cannot simply use the ASCII codes in a 4 length operation string. Lets try some other values
```
'.i 10% ':i 10%ed
```
>
> [6 8]
>
>
>
which on a 4 length string boils down to
>
> [2 0]
>
>
>
I can use this mod 10 operation but that will cost be 2 bytes. Lets try something else
```
'.i5% ':i5%ed
```
>
> [1 3]
>
>
>
Nice!, now we just subtract 1 for the stack size condition to get the indexes `0, 1, 2 and 3` and use a `5` length array (`"1+2* "`) as a switch case. The last space is just a filler to make it of length 5. This is just 1 extra byte as compared to modding operation.
```
q{ }/ e# parse each input character in this loop
i] e# convert '. or ': into ASCII code and wrap everything
e# in stack in an array
_,+ e# Copy the stack array, take its length and add the length to
e# the stack array
~3< e# unwrap the stack array and check if stack size is less than 3
e# 3 because either . or : is also on stack
- e# subtract 0 or 1 based on above condition from ASCII code
"1+2* " e# string containing the operation to perform
=~ e# chose the correct operation and evaluate it
```
[Try it online here](http://cjam.aditsu.net/#code=q%7Bi%5D_%2C%2B%7E3%3C-%221%2B2*%20%22%3D%7E%7D%2F&input=%3A%3A...%3A.%3A.)
*1 byte saved thanks to [cosechy](https://sourceforge.net/p/cjam/tickets/53/#65b5)*
[Answer]
# [><> (Fish)](http://esolangs.org/wiki/Fish), 33 bytes
```
ib%1-i:1+?\~n;
5a*)?*+40.\b%1-0@i
```
Fairly straightforward with little tricks/optimizations.
Explanation:
* Info: `i` = codepoint of next input char, `-1` if end of input reached ; `a` = 10; `b` = 11; `)` = `>`
* `i`codepoint of first input char,
* `b%1-` `top_of_stack mod 11 - 1` masks `48 ('.') , 56 (':')` to `1 , 2`
* `i:1+?\~n;` if end of input reached print the last result and terminate
* otherwise:
* `b%1-` mask input to `1 , 2`
* `0@` push `0` under the two number
* `i5a*)` read next input and mask it to `0 , 1` comparing to `50`
* if `1` (`':'`) multiply top two elements creating stack [0 product]
* always add top two elements creating stack either `[0 sum]` or `[0+product=product]`
* `40.` jump (loop) back to position `(4,0)`, our point `4`, `i:1+?\~n;`
[Answer]
# Haskell, ~~73~~ 65 bytes
A straightforward solution, using the fact that the stack never has more than 2 elements.
```
[x,y]#'.'=[x+y]
[x,y]#_=[x*y]
s#'.'=1:s
s#_=2:s
f=head.foldl(#)[]
```
[Answer]
# JavaScript (ES6), 65
We only use 2 cells of our stack.
Start putting a value in s[0].
Then, at each odd position (counting from 0) in the input string, put a value in s[1].
At each even position, exec a calc (add or multiply) and store result in s[0].
So forget about the stack and use just 2 variables, a and b.
```
f=s=>[...s].map((c,i)=>(c=c>'.',i&1?b=1+c:i?c?a*=b:a+=b:a=1+c))|a
```
A quick test
```
for(i=0;i<128;i++)
{
b=i.toString(2).replace(/./g,v=>'.:'[v]).slice(1)
if(b.length&1) console.log(b,f(b))
}
```
*Output*
```
"." 1
":" 2
"..." 2
"..:" 1
".:." 3
".::" 2
":.." 3
":.:" 2
"::." 4
":::" 4
"....." 3
"....:" 2
"...:." 4
"...::" 4
"..:.." 2
"..:.:" 1
"..::." 3
"..:::" 2
".:..." 4
".:..:" 3
".:.:." 5
".:.::" 6
".::.." 3
".::.:" 2
".:::." 4
".::::" 4
":...." 4
":...:" 3
":..:." 5
":..::" 6
":.:.." 3
":.:.:" 2
":.::." 4
":.:::" 4
"::..." 5
"::..:" 4
"::.:." 6
"::.::" 8
":::.." 5
":::.:" 4
"::::." 6
":::::" 8
```
[Answer]
# C, 104 bytes
```
k[2],n;f(char*c){for(n=0;*c;)k[n]=*c++-58?n>1?n=0,*k+k[1]:1:n>1?n=0,*k*k[1]:2,k[1]=n++?k[1]:0;return*k;}
```
Well, this is too long.
[Answer]
# Pyth, ~~25~~ 24 bytes
```
eu?]?.xGHsGtG+GhHmqd\:zY
```
Got an idea by studying @isaacg's solution. But I'm using a stack.
[Online Demonstration](https://pyth.herokuapp.com/?code=eu%3F%5D%3F.xGHsGtG%2BGhHmqd%5C%3AzY&input=%3A%3A...%3A.%3A.&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=FN.zAzbcN)%2Ceu%3F%5D%3F.xGHsGtG%2BGhHmqd%5C%3AzYb&input=Test+cases%0A.+1%0A%3A+2%0A...+2%0A..%3A+1%0A.%3A.+3%0A.%3A%3A+2%0A%3A..+3%0A%3A.%3A+2%0A%3A%3A.+4%0A%3A%3A%3A+4%0A.....+3%0A....%3A+2%0A...%3A.+4%0A...%3A%3A+4%0A..%3A..+2%0A..%3A.%3A+1%0A..%3A%3A.+3%0A..%3A%3A%3A+2%0A.%3A...+4%0A.%3A..%3A+3%0A.%3A.%3A.+5%0A.%3A.%3A%3A+6%0A.%3A%3A..+3%0A.%3A%3A.%3A+2%0A.%3A%3A%3A.+4%0A.%3A%3A%3A%3A+4%0A%3A....+4%0A%3A...%3A+3%0A%3A..%3A.+5%0A%3A..%3A%3A+6%0A%3A.%3A..+3%0A%3A.%3A.%3A+2%0A%3A.%3A%3A.+4%0A%3A.%3A%3A%3A+4%0A%3A%3A...+5%0A%3A%3A..%3A+4%0A%3A%3A.%3A.+6%0A%3A%3A.%3A%3A+8&debug=0)
### Explanation
The first thing I do is to convert the input string into 0s and 1s. A `"."` gets converted into a `0`, a `":"` into a `1`.
```
mqd\:z map each char d of input to (d == ":")
```
Then I reduce this list of numbers:
```
eu?]?.xGHsGtG+GhHmqd\:zY
u Y start with the empty stack G = []
for each H in (list of 0s and 1s), update G:
G =
?.xGHsG product of G if H != 0 else sum of G
] wrapped in a list
? tG if G has more than 1 element else
+GhH G + (H + 1)
e take the top element of the stack
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~105~~ ~~75~~ 73 bytes
My first Retina program! *(Thanks to Martin Büttner for saving 2 bytes, not to mention inventing the language in the first place.)*
Each line should go in a separate file; or, you can put them all in one file and use the `-s` flag. The `<empty>` notation represents an empty file/line.
```
^(a+;)?\.
$1a;
^(a+;)?:
$1aa;
;(a+;)\.
$1
(a+);aa;:
$1$1;
)`;a;:
;
;
<empty>
a
1
```
Inspired by [mbomb007's answer](https://codegolf.stackexchange.com/a/57895/16766), but I take a somewhat different approach. One major difference is that I build the stack in front of the dotty string (with the top of the stack facing right). This makes it easy to convert symbols to the corresponding numbers in-place. I also use `a` instead of `1`, swapping it out only at the end, to avoid parsing ambiguity in sequences like `$1a`. If an answer like `aaaaaa` is acceptable as a unary number, the last two lines/files could be eliminated to save 4 bytes.
### Explanation:
```
^(a+;)?\.
$1a;
```
Matches if there are 0 or 1 items on the stack (`(a+;)?`) followed by a period (`\.`); if so, it replaces the period with `a;` (i.e. pushes a 1).
```
^(a+;)?:(.*)
$1aa;$2
```
Matches if there are 0 or 1 items on the stack followed by a colon. If so, it replaces the colon with `aa;` (i.e. pushes a 2).
```
;(a+;)\.
$1
```
Matches if there are two items on the stack followed by a period. Deletes the period and the semicolon between the items, thereby adding them.
```
(a+);aa;:
$1$1;
```
Matches if there are two items on the stack, the top of which is a 2, followed by a colon. Deletes the colon and the 2 and repeats the other number twice, thereby multiplying it by 2.
```
)`;a;:
;
```
The regex matches if there are two items on the stack, the top of which is a 1, followed by a colon. Deletes the colon and the 1, leaving the other number unchanged (i.e. multiplied by 1).
`)`` indicates the end of a loop. If any changes were made to the string, control returns to the top of the program and runs the substitutions again. If the string has stopped changing, we've replaced all the periods and colons, and all that's left is cleanup...
```
;
<empty>
```
Deletes the leftover semicolon.
```
a
1
```
Transforms all the a's into 1's. Again, if unary numbers are allowed to use any symbol, this step is unnecessary.
[Answer]
# Pyth, 27 bytes
```
Jmhqd\:zu?*GhHteH+GhHctJ2hJ
```
A stack? Who needs a stack.
```
Implicit: z is the input string.
Jmhqd\:z Transform the string into a list, 1 for . and 2 for :
Store it in J.
u ctJ2hJ Reduce over pairs of numbers in J, with the
first entry as initial value.
? teH Condition on whether the second number is 1 or 2.
*GhH If 1, update running total to prior total times 1st num.
+GhH If 2, update running total to prior total plus 1nd num.
```
[Demonstration.](https://pyth.herokuapp.com/?code=Jmhqd%5C%3Azu%3F*GhHteH%2BGhHctJ2hJ&input=.%3A.%3A%3A&debug=0)
[Answer]
# Python 3, 74
```
x,*s=[1+(c>'.')for c in input()]
while s:a,b,*s=s;x=[x*a,x+a][-b]
print(x)
```
First transforms the input list into a sequence of 1's and 2's, taking the first value as the initial value `x`. Then, takes off two elements at a time from the front of `s`, taking the first number and either adding or multiplying with the current number based on whether the second is 1 or 2.
[Answer]
# TI-BASIC, ~~78~~ ~~73~~ ~~70~~ ~~69~~ 66 bytes
```
Input Str1
int(e^(1=inString(Str1,":
For(A,2,length(Str1),2
Ans+sum({Ans-2,1,1,0},inString("::..:",sub(Str1,A,2
End
Ans
```
TI-BASIC is good at one-liners, because closing parentheses are optional; conversely, it is a poor language where storing multiple values is required because storing to a variable takes two to four bytes of space. Therefore, the goal is to write as much on each line as possible. TI-BASIC is also awful (for a tokenized language) at string manipulation of any kind; even reading a substring is lengthy.
Tricks include:
* `int(e^([boolean]` instead of `1+(boolean`; saves one byte
* Partial sum of a list instead of list slicing (which would require storing into a list): saves 3 bytes
[Answer]
# Rust, 170 characters
```
fn f(s:String)->i32{let(mut a,mut b)=(-1,-1);for c in s.chars(){if b!=-1{a=match c{'.'=>a+b,':'=>a*b,_=>0};b=-1}else{b=match c{'.'=>1,':'=>2,_=>0};if a==-1{a=b;b=-1}};}a}
```
More proof that Rust is absolutely terrible at golfing. Full ungolfed code:
```
#[test]
fn it_works() {
assert_eq!(dotty_ungolfed("::...:.:.".to_string()), 9);
assert_eq!(f("::...:.:.".to_string()), 9);
}
fn dotty_ungolfed(program: String) -> i32 {
let (mut a, mut b) = (-1, -1);
for ch in program.chars() {
if b != -1 {
a = match ch { '.' => a + b, ':' => a * b, _ => panic!() };
b = -1;
} else {
b = match ch { '.' => 1, ':' => 2, _ => panic!() };
if a == -1 { a = b; b = -1; }
}
}
a
}
fn f(s:String)->i32{let(mut a,mut b)=(-1,-1);for c in s.chars(){if b!=-1{a=match c{'.'=>a+b,':'=>a*b,_=>0};b=-1}else{b=match c{'.'=>1,':'=>2,_=>0};if a==-1{a=b;b=-1}};}a}
```
Here's an interesting trick I used in this one. You can shave off a character in an if/else statement by having them return a value that is immediately discarded, which means you only need one semicolon instead of two.
For example,
```
if foo {
a = 42;
} else {
doSomething(b);
}
```
can be changed into
```
if foo {
a = 42
} else {
doSomething(b)
};
```
which saves a character by shaving off a semicolon.
[Answer]
# Haskell, ~~88~~ ~~81~~ 79 Bytes
```
(h:t)![p,q]|h=='.'=t![p+q]|1<2=t![p*q]
(h:t)!s|h=='.'=t!(1:s)|1<2=t!(2:s)
_!s=s
```
It seems that someone beat me to the mark on a Haskell solution, not only that, their solution is shorter than mine. That's to bad but, I see no reason not to post what I came up with.
[Answer]
# APL (50)
I'm at a great disadvantage here, because APL is not a stack-based language. I finally got to abuse reduction to shorten the program, though.
```
{⊃{F←'.:'⍳⍺⋄2>⍴⍵:F,⍵⋄((⍎F⌷'+×')/2↑⍵),2↓⍵}/(⌽⍵),⊂⍬}
```
The inner function takes a 'command' on the left and a stack on the right, and applies it, returning the stack. The outer function reduces it over the string, starting with an empty stack.
Explanation:
* `(⌽⍵),⊂⍬`: the initial list to reduce over. `⊂⍬` is a boxed empty list, which represents the stack, `(⌽⍵)` is the reverse of the input. (Reduction is applied right-to-left over the list, so the string will be processed right-to-left. Reversing the input beforehand makes it apply the characters in the right order.)
* `{`...`}`: the inner function. It takes the stack on the right, a character on the left, and returns the modified stack.
+ `F←'.:'⍳⍺`: the index of the character in the string `.:`, this will be 1 or 2 depending on the value.
+ `2>⍴⍵:F,⍵`: If 2 is larger than the current stack size, just append the current value to the stack.
+ `⋄`: otherwise,
- `2↓⍵`: remove the top two items from the stack
- `(`...`)/2↑⍵`: reduce a given function over them, and add it to the stack.
- `⍎F⌷'+×'`: the function is either `+` (addition) or `×` (multiplication), selected by `F`.
* `⊃`: finally, return the topmost item on the stack
[Answer]
# Ruby - 96 chars
The sorta interesting piece here is `eval`.
Aside from that, I am making the assumption that after the first character, the stack will always go 2, math, 2, math, .... This lets me use less code by grabbing two chars at once - I never have to figure out whether a character is math or number. It's positional.
```
x,m=$<.getc>?.?2:1
(b,f=m.split //
b=b>?.?2:1
x=f ?eval("x#{f>?.??*:?+}b"):b)while m=gets(2)
p x
```
Ungolfed:
```
bottom_of_stack = $<.getc > '.' ? 2 : 1 # if the first char is ., 1, else 2
two_dots = nil
while two_dots = gets(2) do # get the next 2 chars
number_char, math_char = two_dots.split //
number = number_char > '.' ? 2 : 1
if math_char
math = math_char > '.' ? '*' : '+'
# so bottom_of_stack = bottom_of_stack + number ...
# or bottom_of_stack = bottom_of_stack * number
bottom_of_stack = eval("bottom_of_stack #{math} number")
else
# if there's no math_char, it means that we're done and
# number is the top of the stack
# we're going to print bottom_of_stack, so let's just assign it here
bottom_of_stack = number
end
end
p bottom_of_stack # always a number, so no need for `puts`
```
[Answer]
well this is so easy operation , sophisticated by the op (intentionally)
it is just ...
>
> parenthesed expression translated into postfixed \*/+ operation
>
>
>
## Code: C ( 80 bytes)
```
int f(char*V){return*(V-1)?f(V-2)*(*V==58?*(V-1)/29:1)+(*V&4)/4**(V-1)/29:*V/29;}
```
* this function should be called from the string tail like this : f(V+10) where V=".:..:.:..::"
## input
length=2n+1 vector V of type char '.' or ':'
## Output
an integer k
## Function
>
> * k = ( V[1] op(V[3]) V[2] ) op(V[5]) V[4] ....
> * op(x) : (x='.') -> + , (x=':') -> \*
>
>
>
---
## Simulation:
try it [here](http://rextester.com/TDB56869)
[Answer]
# Retina, ~~181~~ ~~135~~ 129 bytes
Each line should be in a separate file. `<empty>` represents an empty file. The output is in Unary.
```
^\..*
$&1;
^:.*
$&11;
^.
<empty>
(`^\..*
$&1
^:.*
$&11
^.(.*?1+;1+)
$1
^(\..*);(1+)
$1$2;
;1$
;
^(:.*?)(1+).*
$1$2$2;
)`^.(.*?1+;)
$1
;
<empty>
```
~~When `${0}1` is used, the braces separate `$0` from the `1`, otherwise it would be `$01`, the 1st matching group. I tried using `$001`, but this appears not to work in the .NET flavor of regex.~~
Edit: Found that `$&` is the same as `$0`.
In pseudo-code, this would essentially be a do-while loop, as seen below. I push the first number, then loop: push the second number, remove the operation (instruction), do math, remove the op. Continue looping. Note that when an operation is popped, this will also remove the space after all the instructions are done.
### Commented:
```
^\..* # Push if .
$&1;
^:.* # Push if :
$&11;
^. # Pop op
<empty>
(`^\..* # Loop, Push #
$&1
^:.*
$&11
^.(.*?1+;1+) # Pop op
$1
^(\..*);(1+) # Add if . (move ;)
$1$2;
;1$ # If mul by 1, remove
;
^(:.*?)(1+).* # Mul if : (double)
$1$2$2;
)`^.(.*?1+;) # Pop op, End Loop (clean up)
$1
; # Remove semicolon
<empty>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
v„.:yk>.gÍii+ë*
```
[Try it online](https://tio.run/##yy9OTMpM/f@/7FHDPD2rymw7vfTDvZmZ2odXa/3/b2Wlp6dnBYQA) or [verify all test cases](https://tio.run/##yy9OTMpM/f@oYZ6elenh1sOd57YcXnx6jpKVlZ6enhUQKh1aVVZpr6TwqG2SgpJ9pdL/MrDaymw7vfTDvZmZ2odXa/1X0gvT@Q8A).
**Explanation:**
```
v # Loop over the characters `y` of the (implicit) input-string:
„.: # Push string ".:"
yk # Get the 0-based index of character `y` in this string
> # Increase it by 1 to make it a 1-based index
.g # Get the amount of items currently on the stack
Í # Decrease it by 2
i # Pop, and if the amount of items on the stack - 2 equals 1:
i # Pop the 1-based index, and if it equals 1:
+ # Add the top two values on the stack together
ë # Else:
* # Multiply the top two values on the stack together
# (after the loop, the top of the stack is output implicitly)
```
Also works with even length inputs, after which it will just output the top `1` or `2`: [verify all even length test cases up to length 6](https://tio.run/##yy9OTMpM/f@oYZ6eldnh1sMd57YcXnx6TlmlvZLCo7ZJCkr2lUr/y8DSldl2eumHezMztQ@v1vqvpBemoxnzHwA).
[Answer]
# Go, ~~129~~ ~~115~~ 112 bytes
```
func m(s string){a,b:=0,0;for c,r:=range s{c=int(r/58);if b>0{a=a*b*c+(a+b)*(c^1);b=0}else{b,a=a,c+1}};print(a)}
```
## (somewhat) ungolfed:
```
func m(s string){
// Our "stack"
a, b := 0, 0
// abusing the index asignment for declaring c
for c, r := range s {
// Ascii : -> 58, we can now use bit fiddeling
c = int(r / 58)
if b > 0 {
// if r is :, c will be 1 allowing a*b to pass through, c xor 1 will be 0
// if r is ., c xor 1 will be 1 allowing a+b to pass through
a = a*b*c + (a+b)*(c^1)
b = 0
} else {
b, a = a, c+1 // Since we already know c is 0 or 1
}
}
print(a)
}
```
Try it online here: <http://play.golang.org/p/B3GZonaG-y>
[Answer]
# Perl, 77 bytes
```
@o=(0,'+','*');sub d{$_=shift;y/.:/12/;eval'('x s!\B(.)(.)!"$o[$2]$1)"!ge.$_}
```
expanded:
```
@o=(0, '+', '*');
sub d{
$_=shift;
y/.:/12/;
eval '(' x s!\B(.)(.)!"$o[$2]$1)"!ge.$_
}
```
The `@o` array maps digits to operators. Then we substitute pairs of digits with the appropriate operator, reordered to infix. The regexp begins with `\B` so we don't match the very first character. The result of `s///g` tells us how many open parens we need at the beginning. Then, when we've assembled the full infix expression, we can evaluate it. (Remove `eval` if you would like to see the expression instead).
Here's the test harness I used to verify the results:
```
while(<>) {
my ($a, $b) = m/(.*) (.*)/;
print d($a), " $b\n";
}
```
Input is the list of dotty expressions and their values (provided in the question) and output is pairs of {actual, expected}.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
```
(!ṅ‛+*‛12"inC∑iĖ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIoIeG5heKAmysq4oCbMTJcImluQ+KIkWnEliIsIiIsIjo6Li4uOi46LiJd)
Surely there's a byte save somewhere here
## Explained
```
(!ṅ‛+*‛12"inC∑iĖ
( # For each character n in the string:
!ṅ # is the length of the stack <= 1?
‛+*‛12"i # indexed into the list ["+*", "12"]
nC∑ # Digital sum of the character code of n
i # indexed into the result of the first index
Ė # execute that on the stack.
```
[Answer]
# [R](https://www.r-project.org), 83 bytes
```
\(s){v={};for(c in s){i=1+(c<".");v=`if`(sum(v|1)>1,c(sum,prod)[[i]](v),c(i,v))};v}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHKlPySksqyxBzbpaUlaboWN4NjNIo1q8tsq2ut0_KLNJIVMvMUgAKZtobaGsk2SnpKmtZltgmZaQkaxaW5GmU1hpp2hjrJII5OQVF-imZ0dGZsrEaZJlAsU6dMU7PWuqwWanQlzC6N1ByN4pKi4oKczBINJSsrPT09KyBU0lFS0tTUVFBWsOTCpdQKWZkZHmVWCGUWXBAHLFgAoQE)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~89~~ 71 bytes
Port of [xnor's Python answer](https://codegolf.stackexchange.com/a/49385/11261).
```
->s{x,*s=s.chars.map{_1>?.?2:1}
(a,b,*s=s;x=[x*a,x+a][-b])while s[0]
x}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY33XXtiqsrdLSKbYv1kjMSi4r1chMLquMN7ez17I2sDGu5NBJ1ksDS1hW20RVaiToV2omx0bpJsZrlGZk5qQrF0QaxXBW1EON2Fii4RSvpWelZWSnFcoE5VkCOnlIsRH7BAggNAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes
```
=”:‘+,×ɗị@ƭ/
```
[Try it online!](https://tio.run/##PY89CsJAEIX7nGJbMbzgT0J4INh7Ag9gI7mAXToLDxAbS0sbURDSJSB4jOQi687M6hbzdvft92Z2v6uqg/ersb5wrM/TtG8@zdCe1u9b5of20T2H170/pt0120y23sPNErp5AkArwxmEW4Qq94TsCd2H@2WoDBWy5BWAyKsraj5/iZYJWiqouWLrewov3YTPVekK6Y44heXTuotKPmE8YTxhPGE88Z/cZkecHpHX/rlqPAe/UKUr5ZfRZ/QZfeHLLw "Jelly – Try It Online")
Thought I could do something fun with matrix multiplication, but this seems to beat any possibilities in that direction.
```
=”: Is each character a colon?
‘ Increment to get the numeric values,
/ then reduce that by:
ƭ alternate between
+,×ɗ pair sum and product
ị@ and index element into accumulator.
```
[Answer]
# Python 3, 122 bytes
```
x=input()
l=[0,0]
for _ in x:
t=len(l)-2<2
l=[[[0,0,l[-2]*l[-1]],l+[2]][t],[[0,0,sum(l)],l+[1]][t]][_=='.']
print(l[-1])
```
Ungolfed:
```
x = input()
l = []
for i in x:
if i == '.':
if len(l) < 2:
l+=[1] #True, True = 1,1
else:
l=[sum(l)] #True, True = 1,0
else:
if len(l)<2:
l+=[2] #False, True = 0,1
else:
l=[l[0]*l[1]] #False, False = 0,0
print (l[0])
```
In python, you reference the index of a list like this:
```
list[index]
```
You can put a boolean value into that, `True` is `1` and `False` is `0`.
```
# t is True if the length is less than 2, else false.
l=[
# |------- Runs if char is : -------|
# |------- l<2 -------| |- l>=2 -|
[ [ 0,0, l[-2]*l[-1] ], l+[2] ] [t],
# |---- Runs if char is . ----|
# |--- l<2 ---| |- l>=2 -|
[ [0,0, sum(l)], l+[1] ] [t] ]
[_=='.']
```
Try it online [here](http://repl.it/lMu)
] |
[Question]
[
The Compiler Language With No Pronounceable Acronym, abbreviated [INTERCAL](https://en.wikipedia.org/wiki/INTERCAL), is a very unique programming language. Among its unreproducible qualities are its binary operators.
INTERCAL's two binary operators are **interleave** (also known as **mingle**), and **select**. Interleave is represented with a change (¢), and select is represented with a sqiggle (~).
Interleave works by taking two numbers in the range 0-65535 and alternating their bits. For instance:
```
234 ¢ 4321
234 = 0000011101010
4321 = 1000011100001
Result: 01000000001111110010001001
Output: 16841865
```
Select works by taking two numbers in the range 0-65535, taking the bits in the first operand which are in the same position as 1s in the second operand, and right packing those bits.
```
2345 ~ 7245
2345 = 0100100101001
7245 = 1110001001101
Taken : 010 0 10 1
Result: 0100101
Output: 37
```
In this challenge, you will be given a binary expression using either the interleave or select operation. You must calculate the result, using the fewest possible bytes.
The expression will be given as a space separated string, consisting of an integer in 0-65535, a space, either `¢` or `~`, a space, and an integer in 0-65535.
Input and output may be through any standard system (STDIN, function, command line, etc.). Standard loopholes banned.
Examples:
```
5 ¢ 6
54
5 ~ 6
2
51234 ¢ 60003
4106492941
51234 ~ 60003
422
```
This is code golf - fewest bytes wins. Good luck.
EDIT: Since some languages do not support INTERCAL's change (¢) symbol, you may use the big money ($) symbol instead, at a 5 byte penalty.
[Answer]
# Python 2, ~~115~~ 112 bytes
```
x,y,z=input().split()
d=y<""
f=lambda a,b:a+b and(b%2+5&4-d)*f(a/2,b/2)+(a%2*2+b%2)/3**d
print f(int(x),int(z))
```
The string on the second line contains a single unprintable character `\x7d`, the next char after `~`.
All hopes of a nice, single lambda get crushed by the input format. There's probably a better way to read in input. Input like `"51234 ¢ 60003"` via STDIN.
The function `f` combines the following two recursive functions:
```
g=lambda a,b:a+b and 4*g(a/2,b/2)+a%2*2+b%2 # ¢
h=lambda a,b:a+b and(b%2+1)*h(a/2,b/2)+a*b%2 # ~
```
*(-3 bytes with the help of @xnor)*
[Answer]
# CJam, 31 bytes
```
rrc\r]{i2bF0e[}%(7=\zf{_)*?~}2b
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=rrc%5Cr%5D%7Bi2bF0e%5B%7D%25(7%3D%5Czf%7B_)*%3F~%7D2b&input=51234%20%C2%A2%2060003).
### How it works
```
rr e# Read two tokens from STDIN.
c\ e# Cast the second to char and swap with the first.
r e# Read a third token from STDIN.
] e# Wrap everything in an array.
{ }% e# For all three elements:
i2b e# Cast to int and convert to base 2.
F0e[ e# Left-pad with zeroes to complete 15 digits.
( e# Shift out the first base 2 array.
7= e# Select its eighth MSB (1 for '¢', 0 for '~').
\ e# Swap with the array of base 2 arrays.
z e# Zip to transpose rows with columns.
f{ } e# For each pair of base 2 digits:
e# Push the bit, then the pair.
_ e# Copy the pair.
) e# Pop the second digit.
* e# Repeat the first digit that many times.
? e# Ternary if. Select the pair if the bit is
e# truthy, the repeated first bit if it's falsy.
~ e# Dump the selected array on the stack.
2b e# Convert from base 2 to integer.
```
[Answer]
# Pyth, ~~32~~ ~~31~~ 29 bytes
```
isummFdG}\~zCm.[Z16jvd2%2cz)2
```
Try it online: [Regular Input / Test Suite](http://pyth.herokuapp.com/?code=isummFdG%7D%5C~zCm.%5BZ16jvd2%252cz%292&input=234+%C2%A2+4321&test_suite_input=234+%C2%A2+4321%0A2345+~+7245%0A5+%C2%A2+6%0A5+~+6%0A51234+%C2%A2+60003%0A51234+~+60003&debug=0)
Thanks to @isaacg for golfing off one byte.
### Explanation:
```
cz) split input at spaces
%2 only take every second item (the numbers)
m map each number d to:
vd convert d to int
j 2 convert to base 2
.[Z16 pad zeros at the left
C zip
u }\~z apply the following function ("~" in input) times:
m G map each pair d to:
mFd convert [x,0] to [] and [x,1] to [x]
s take sum (unfold all lists)
i 2 convert back from base 2 and print
```
[Answer]
# JavaScript (ES6), 103 ~~117 119 124~~
**Edit** now working with numbers instead of strings
(not counting leading spaces, newlines and comments)
Test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go)
```
I=s=>
(i=>{
for(m=r=0,[a,o,b]=s.split` `;i>0;i<<=1) // loop until bit 31 of i is set
o>'~'?r+=(b&i)*i+(a&i)*2*i:b&i?r+=(a&i)>>m:++m
})(1)||r
// TEST
out=x=>O.innerHTML+=x+'\n\n';
[ ['234 ¢ 4321', 16841865], ['2345 ~ 7245', 37]
, ['5 ¢ 6', 54], ['5 ~ 6', 2]
, ['51234 ¢ 60003',4106492941], ['51234 ~ 60003', 422]]
.forEach(([i,o,r=I(i)])=>{
out('Test '+ (o==r?'OK':'Fail')+'\nInput: '+ i+'\nResult: '+r+'\nExpected: '+o)})
```
```
<pre id=O></pre>
```
[Answer]
## Matlab, ~~119~~ 113 bytes
```
function f(s)
t=dec2bin(str2double(strsplit(s,{'¢' '~'}))');u=any(s>'~');[~u u]*bin2dec({t(1,t(2,:)==49) t(:)'})
```
Ungolfed:
```
function f(s) % input s is a string
t = dec2bin(str2double(strsplit(s,{'¢' '~'}))'); % get the two numbers and convert to
% two-row char array of zeros of ones
u = any(s>'~'); % 1 indicates '¢'; 0 indicates '~'
[~u u]*bin2dec({t(1,t(2,:)==49) t(:)'}) % compute both results and display
% that indicated by u
```
Examples:
```
>> f('234 ¢ 4321')
ans =
16841865
>> f('2345 ~ 7245')
ans =
37
```
[Answer]
# R, 145 bytes
```
s=scan(,"");a=as.double(c(s[1],s[3]));i=intToBits;cat(packBits(if(s[2]=="~")c(i(a[1])[i(a[2])>0],i(0))[1:32] else c(rbind(i(a[2]),i(a[1]))),"i"))
```
Ungolfed + explanation:
```
# Read a string from STDIN and split it on spaces
s <- scan(, "")
# Convert the operands to numeric
a <- as.double(c(s[1], s[3]))
o <- if (s[2] == "~") {
# Get the bits of the first operand corresponding to ones in
# the second, right pad with zeros, and truncate to 32 bits
c(intToBits(a[1])[intToBits(a[2]) == 1], intToBits(0))[1:32]
} else {
# Interleave the arrays of bits of the operands
c(rbind(intToBits(a[2]), intToBits(a[1])))
}
# Make an integer from the raw bits and print it to STDOUT
cat(packBits(o, "integer"))
```
[Answer]
# Python 3, 174 166 148 126
Pretty straightforward, string operations, then conversion back to integer.
Limited to numbers which in binary have 99 digits (max 2^99-1 = 633825300114114700748351602687).
Thanks, Sp3000 and Vioz!
```
a,o,b=input().split()
print(int(''.join([(i+j,i[:j>'0'])[o>'~']for i,j in zip(*[bin(int(j))[2:].zfill(99)for j in(a,b)])]),2))
```
Or 165 chars, without limit:
```
a,o,b=input().split()
a,b=[bin(int(j))[2:]for j in(a,b)]
print(int(''.join([(i if j=='1'else'')if o=='~'else i+j for i,j in zip(a.zfill(len(b)),b.zfill(len(a)))]),2))
```
Ungolfed:
```
a, op, b = input().split()
a, b = [bin(int(j))[2:] for j in(a,b)] #convert to int (base 10), then to binary, remove leading '0b'
m = max(len(a), len(b))
a = a.zfill(m) #fill with leading zeroes
b = b.zfill(m)
if op == '~':
ret = [i if j=='1' else'' for i, j in zip(a, b)]
else:
ret = [i + j for i, j in zip(a, b)]
ret = ''.join(ret) #convert to string
ret = int(ret, 2) #convert to integer from base 2
print(ret)
```
[Answer]
## Pyth, 43 bytes
Part of me feels nervous posting such a long Pyth answer on isaacg's question... :oP
```
J.(Kczd1Am.BvdKiu?qJ\~u+G?qeH\1hHk+VGHk.iGH2
```
Explaination:
```
Implicit: z=input(), k='', d=' '
Kczd Split z on spaces, store in K
J.( 1 Remove centre element from K, store in J
m K For each d in K
.Bvd Evaluate as int, convert to binary string
A Store pair in G and H
~ processing:
+VGH Create vectorised pairs ([101, 110] -> [11, 01, 10])
u k Reduce this series, starting with empty string
?qeH\1 If 2nd digit == 1...
hHk ... take the 1st digit, otherwise take ''
+G Concatenate
.iGH ¢ processing: interleave G with H
?qJ\~ If J == ~, take ~ processing, otherwise take ¢
i 2 Convert from binary to decimal
```
[Answer]
# C, ~~127~~ 123 bytes + 5 penalty = 128
`scanf` counts the unicode symbol as more than one character which complicates things a lot, so I'm applying the 5-byte penalty for using `$`.
```
a,b,q,x,i;main(){scanf("%d %c %d",&a,&q,&b);for(i=65536;i/=2;)q%7?x=x*4|a/i*2&2|b/i&1:b/i&1&&(x=x*2|a/i&1);printf("%u",x);}
```
The changes from the original version are:
-The test for $ or ~ has been revised from `q&2` to `q%7`. This reverses the true/false values, allowing the code for $ operator to go before the `:` which means a set of parentheses can be eliminated.
-The `i` loop now counts down in powers of 2 which is longer, but permits `>>` to be substituted by `/` and saves some parentheses.
**Original version 127 bytes**
```
a,b,q,x,i;
main(){
scanf("%d %c %d",&a,&q,&b);
for(i=16;i--;)
q&2?
b>>i&1&&(x=x*2|a>>i&1): // ~ operator. && used as conditional: code after it is executed only if code before returns truthy.
(x=x*4|(a>>i&1)*2|b>>i&1); // $ operator
printf("%u",x);
}
```
I went with a single loop with the conditionals inside to avoid the overhead of two loops. In both cases I rightshift the bits of the operands down to the 1's bit, and build up the result from the most significant to least significant bit, leftshifting the result (multiplying by 2 or 4) as I go.
[Answer]
# K5, ~~53~~ 52 bytes
```
{b/({,/x,'y};{x@&y})[*"~"=y][b\.x;(b:20#2)\.z]}." "\
```
53-byte version:
```
{b/({,/x,'y};{x@&y})[*"¢~"?y][b\.x;(b:20#2)\.z]}." "\
```
Still needs a bit more golfing.
[Answer]
# CJam, ~~61~~ ~~50~~ ~~46~~ ~~41~~ 34 bytes
Thanks @Dennis for pointing out a 4 bytes golf.
```
rrc'~=:X;r]{i2bF0e[}/.{X{{;}|}&}2b
```
[Try it online](http://cjam.aditsu.net/#code=rrc%27%7E%3D%3AX%3Br%5D%7Bi2bF0e%5B%7D%2F.%7BX%7B%7B%3B%7D%7C%7D%26%7D2b&input=234%20%C2%A2%204321).
[Answer]
# Haskell, 77
```
g=(`mod`2)
h=(`div`2)
0¢0=0
a¢b=g a+2*b¢h a
a?0=0
a?b=g a*g b+(1+g b)*h a?h b
```
input is given by applying the input to the functions/operators `?` and `¢` defined in the code (Haskell can't define an operator `~` for technical reasons).
basically works the old recursive approach.
[Answer]
# J, 173
```
f=:|."1@(>@(|.&.>)@(#:@{:;#:@{.))
m=:2&#.@:,@:|:@:|.@:f
s=:2&#.@#/@:f
a=:{&a.@-.
(1!:2)&2(s@".@:a&126)^:(126 e.i)((m@".@:a&194 162)^:(1 e.194 162 E.i)i=._1}.(a.i.((1!:1)3)))
```
expects one line of input
input expected to terminate after new line with EOF
[Answer]
# Javascript ES6 (3 arguments) ~~141~~ ~~138~~ ~~136~~ ~~121~~ 119 bytes
```
b=x=>(65536|x).toString`2`
f=(x,o,y)=>+eval(`'0b'+(b(y)+b(x)).replace(/^1|${o=='~'?1:'(.)'}(?=.{16}(.)())|./g,'$2$1')`)
```
Test:
```
;[f(234,'¢',4321),f(2345,'~',7245)]=="16841865,37"
```
# Javascript ES6 (1 argument) ~~135~~ 133 bytes
```
b=x=>(65536|x).toString`2`
f=s=>([x,o,y]=s.split` `)|eval(`'0b'+(b(y)+b(x)).replace(/^1|${o=='~'?1:'(.)'}(?=.{16}(.)())|./g,'$2$1')`)
```
Test:
```
;[f('234 ¢ 4321'),f('2345 ~ 7245')]=="16841865,37"
```
PS: New line is counted as 1 byte as it can be replaced by `;`.
[Answer]
# Python 3, 157 bytes
```
a,x,y=input().split()
i=int
b=bin
print(i(''.join(([c for c,d in zip(b(i(a)),b(i(y)))if d=='1'],[c+d for c,d in zip(b(i(a))[2:],b(i(y))[2:])])['¢'==x]),2))
```
Full and explanatory version can be found on my [pastebin](http://pastebin.com/d9t8MTcE).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 201 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 25.125 bytes
```
⌈sṫ£⌊vΠ:ḣ∆Z$tJvf⌊÷¥\¢=[Y|Tİ]B
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwi4oyIc+G5q8Kj4oyKds6gOuG4o+KIhlokdEp2ZuKMisO3wqVcXMKiPVtZfFTEsF1CIiwiIiwiMjM0NSB+IDcyNDUiXQ==)
Bitstring:
```
110010100100100000011011100010011001001100101100100000110010011100111001000101011101011101101110001000110011011101000000100101011000110100110001000010010001101001011101001011100110111111100100110010111
```
Possibly golfable?
[Answer]
# Mathematica, 155 bytes
```
f=IntegerDigits[#,2,16]&;
g=#~FromDigits~2&;
¢=g[f@#~Riffle~f@#2]&;
s=g@Cases[Thread@{f@#,f@#2},{x_,1}->x]&;
ToExpression@StringReplace[#,{" "->"~","~"->"s"}]&
```
Evaluates to an anonymous function taking the string as input. Line breaks added for clarity.
`f` and `g` convert to/from base 2. `Riffle` does exactly what *interleave* is supposed to. I wanted to use `Select` for *select* but `Cases` is better unfortunately. The last line is a bit of trickery; spaces are changed to `~` which is Mathematica's infix operator, then the string is eval'd.
[Answer]
# [Go](https://go.dev), 186 bytes
```
func c(a,b uint)(o uint){for i:=0;i<16;i++{o|=(a&1<<(2*i+1))|(b&1<<(2*i))
a>>=1
b>>=1}
return}
func s(a,b uint)(o uint){for i,j:=0,0;i<16;i++{if b&1>0{o|=a&1<<j;j++}
a>>=1
b>>=1}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=3VPRbtMwFJV49FdcIhXZxFSxk2bdWldCYq8IQd_GhJzMmVLapEocBPLyJbxUSPuI8SfwK7zMTpqtsPHAK0p0r3Ou7zm-x8rXb5fl7mYr04_yUsFG5gXKN9uy0mMv22jvutHZi-mP71lTpJBiSRNo8kITXPbZZGUF-YkIZvmcxbPc9015JbB8xuZzzJ_nPiPkCifDJyFILhaCocTFFlVKN1XRoo6-_hs9XVkBeiCRZ2ApF4HT6qRWs5Xvt49y9xP8fPJLf9kqWEKtqybVYKwWVZ-3nU6L-hO48TEBg1Ktal3DiYCz86VBhocRjULOKIunEZvGk5YiM6ExnUTdirkNcRAEIY1YEEfH_DhitmKJ64dUE3rEbQiPBhb-gITzvhu9qez51gX2bFLVWslPyiP3qBAC3i1fvl2CXdmC8-sD1U6ukoW90f0kBsm0Q1Osx5LqcUKQddGBTwXosXPC9LQZ9kYXYF-xcBGPLsj7wqPg-mxIqOuifQ-5a4FRyJNh3-NwcggHFoeuYNnuC7grDIKdQmuf3-aF09evYD_vUDiwpFZrlep_Mqn-w6T6_zJp_w_sdn2-BQ)
`c` is `interleave`, and `s` is `select`.
## Explanations
### Interleave
```
func c(a,b uint)(o uint){ // init return value in `o` with zero value
for i:=0;i<16;i++{ // for each bit (in the uint16)...
o|= // OR to `o`...
(a&1 // the last bit of `a`
<< // shifted left by
(2*i+1)) // the current bit * 2 + 1
| // OR-ed with
(b&1 // the last bit of `b`
<< // shifted left by
(2*i)) // the current bit * 2
a>>=1;b>>=1} // discard the last bit of `a` and `b`
return}
```
### Select
```
func s(a,b uint)(o uint){ // init return value in `o` with zero value
for i,j:=0,0;i<16;i++{ // for each bit (in the uint16)...
if b&1==1{ // if the current bit in `b` is 1...
o|= // OR to `o`...
a&1 // the last bit of `a`
<<j // shifted over by the number of 1s so far
;j++} // increment the number of 1s
a>>=1;b>>=1} // discard last bit of `a` and `b`
return}
```
] |
[Question]
[
It's likely that anyone who used Twitter a couple of months ago would know about the 'Howdy! I'm the sheriff of X" meme. Where a simple image of a sheriff is drawn with emoji, and changes to fit a theme. So I thought it was time for the Sheriff of Code Golf. Here he is:
```
###
#####
###
###
###
#
#####
# # #
# # #
# # #
#
###
# #
# #
# #
# #
```
This one in particular has 'pixels' which are one character wide, and one character high. To generate him, the arguments will be 1 and 1.
What if he is to be wider than he is tall?
```
######
##########
######
######
######
##
##########
## ## ##
## ## ##
## ## ##
##
######
## ##
## ##
## ##
## ##
```
He's got a height of 1, but a width of 2.
---
# Rules:
* The challenge is to write code to draw your own Sheriff of Code Golf, in the fewest characters possible.
* Use any programming language your heart desires.
* Your code should take two arguments, both of which are integers, for the height and width of the Sheriff.
* The output should be composed of single white spaces for the background, and any other character(s) you choose for the Sheriff. (I've used hashes for the test cases, but it doesn't matter what you use).
* It should be possible for the height to be a negative integer, inverting the image.
* The width can be a negative integer, but because the image is symmetrical, it will be identical to it's positive value.
* Trailing white-spaces are irrelevant.
* If either argument is 0, that dimension is 'flattened' to a single row or column. The length of this line is the other argument multiplied by the height, or width of the Sheriff, respectively.
* If both arguments are 0, both lines are 'flattened', leaving a single positive character.
* Not essential, but please include a link to an online interpreter such as [tio.run](http://www.tio.run)
* The output should be a string, over multiple lines, or output to the console.
---
# Test Cases
1 high, 1 wide
```
###
#####
###
###
###
#
#####
# # #
# # #
# # #
#
###
# #
# #
# #
# #
```
2 high, 1 wide
```
###
###
#####
#####
###
###
###
###
###
###
#
#
#####
#####
# # #
# # #
# # #
# # #
# # #
# # #
#
#
###
###
# #
# #
# #
# #
# #
# #
# #
# #
```
1 high, 2 wide
```
######
##########
######
######
######
##
##########
## ## ##
## ## ##
## ## ##
##
######
## ##
## ##
## ##
## ##
```
2 high, 2 wide
```
######
######
##########
##########
######
######
######
######
######
######
##
##
##########
##########
## ## ##
## ## ##
## ## ##
## ## ##
## ## ##
## ## ##
##
##
######
######
## ##
## ##
## ##
## ##
## ##
## ##
## ##
## ##
```
-1 high, 1 wide
```
# #
# #
# #
# #
###
#
# # #
# # #
# # #
#####
#
###
###
###
#####
###
```
1 high, -1 wide
```
###
#####
###
###
###
#
#####
# # #
# # #
# # #
#
###
# #
# #
# #
# #
```
0 high, 0 wide
```
#
```
1 high, 0 wide
```
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
```
0 high, 2 wide
```
##################
```
---
Have fun, y'all!
[Answer]
# JavaScript (ES6), 171 bytes
Takes input in currying syntax `(width)(height)`. Returns an array of strings.
```
w=>h=>[...Array((h>0?h:-h)*16||1)].map((_,y)=>'012345678'.replace(/./g,x=>' #'[((c=+'3733317900134444'[(h<0?16-~y/h:y/h)|0]||17)>>4-x|c>>x-4)&1|!h].repeat(w>0?w:-w))||'#')
```
[Try it online!](https://tio.run/##VU7RTsMwDHznK4wmEZs1abKUFTYSxANfUSoUlW7ZNNqpm8gmAr9e2okXLJ3P9p1O3rpPd6i6zf7Im/a97lemD8Z6YwshxHPXuTOit/LJL7inWzWPUVEpPtwe8S05k7FMqpnO7ub5PRNdvd@5qsZUpOvkNGgwYQViZaZM51prlT9IqXQ21HD3j/JJzfnPOfWLARRlOaTnZG3GT7Gy9sQzulHx2pdjcu2OGIZPwoIHohjZhFG/LKCYJaDK5MJyZK4T4LNxkn@KHBUor8Sq7V5c5RGLkIAvCYyFL6ja5tDuarFr18iCYTCFMIBBCv6yeVr@M60wEHoS23bTIHttGE0vfQnf1P8C "JavaScript (Node.js) – Try It Online")
### How?
Only the left half of the sheriff is encoded as binary bitmasks, including the middle column:
```
##. 00011 3
###.. 00111 7
##. 00011 3
##. 00011 3
##. 00011 3
# 00001 1
###.. 00111 7
# # . 01001 9
# # . --> 10001 --> 17
# # . 10001 17
# 00001 1
##. 00011 3
# . 00100 4
# . 00100 4
# . 00100 4
# . 00100 4
```
Because there are only two values greater than \$9\$ and they're both equal to \$17\$, we can replace them with \$0\$ in order to have one character per row and still have a rather straightforward decoding process. Hence the packed string:
```
'3733317900134444'
```
For \$0 \le x \le 8\$ and \$0 \le y \le 15\$, the 'pixel' at \$(x,y)\$ is given by:
```
' #'[ // character lookup:
( // 0 = space
( // 1 = '#'
c = +'3733317900134444'[y] || 17 // extract the bitmask for this row; 0 -> 17
) >> 4 - x // test the left part, middle column included
| c >> x - 4 // test the right part, middle column also included
) & 1 // isolate the least significant bit
] // end of character lookup
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~228~~ ~~218~~ ~~202~~ ~~189~~ 173 bytes
```
lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin([62,120,224,238,438,750][int(l)])[2:])or'#']*abs(h)for l in'1211102455013333'),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']
```
[Try it online!](https://tio.run/##NY7basMwDIbv@xSCXtgKyrDUpAezPYnni4QRkpLYJW3p@vSZ43YCnfl@6fK89THI0n19L2MztT8N9PSw1/uktVPq4xyHoNUWlBvCTQf0RdNe9QO7OEOAIUCb9m4vxGJIpCLZHalKfqiNz8yIHp1Yj3FWW/Xi@8yPiVcszGykqmvDu2QKySXAWi51/2mwEB9nl8ji9D790llWhV96Jg2nmRhJS45Mkus1lvwelWsyZHJjci3o7QYu8/pj0sEN/P8EXR7YvINx@QM "Python 2 – Try It Online")
---
Alternatives:
# [Python 2](https://docs.python.org/2/), 173 bytes
```
lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin(ord(' >w(8\x96I'[l])*l)[2:])or'#']*abs(h)for l in map(int,'3433314655132222')),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']
```
```
lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin(ord(' >w(8\x96I'[int(l)])*int(l))[2:])or'#']*abs(h)for l in'3433314655132222'),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~169~~ ~~166~~ 157 bytes
```
@a=map"$_\n",(split 1,' #####1 ###1 #1 # # #1# # #1 # #')
[1011120344215555=~/./g];
print s/./$&x abs"@F"/ger x abs$F[1]for$F[1]<0?reverse@a:@a;
```
[Try it online!](https://tio.run/##JYjRCoIwGIVf5WeTLND0X/Mmk3blS5jEgikD07FJdNWjt@Y6HM53zjHKTpX3QjZPaUhyv80k2zsz6RUwSwHoJoRYNkBICtFIIZbt@jM9dFgiIitPnDOsgppPcSzGvjZWzyu4MJLdG@TDEdGSYlQW4kraDvthsZGX8mrVS1mnhDwLWXufc8jZdzGrXmbnc/kD "Perl 5 – Try It Online")
Maybe more could be gained by bit fiddling.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
NθNη¿θF⪪”{“↷C¿2t´⁴Q19·“*Ty”!E↔θ∨⭆ι×μ↔η#×#∨×⁵↔η¹‖OO←∨↔η¹¿‹θ⁰‖↓
```
[Try it online!](https://tio.run/##TY/PbsMgDMbveQqXXIxEpHbVLs1p0i6TumZa@wJJ5CxI5M8ITR@fmZB2lbDhM9/PmLotbT2UxvuPfry607WryOKvzJNn3bLWDXAdmsECnkejHYo03aRL3FeUAEv6z@EuHJ5CKBAbISV8Wd07/CxHfKsmfkBBYfHsuPoTilrBRXc0YacgGFop2SJSRvOEzERrg2gSoS/zUb0@EAU7GYBvagzVrpjJmnJcNzwcqXELF@2LO374SBMPpWDLk64wHt6HWy9z77MXyPY@m80f "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input the dimensions.
```
¿θF⪪”{“↷C¿2t´⁴Q19·“*Ty”!
```
If the height is nonzero, loop over the the right half of the sheriff...
```
E↔θ
```
... repeating the absolute height number of times...
```
∨⭆ι×μ↔η#
```
... if the width is nonzero then repeating each character the absolute number of times, otherwise a `#`.
```
×#∨×⁵↔η¹
```
But if the height is zero, then repeat `#` 5 times the absolute width, but at least 1 `#`.
```
‖OO←∨↔η¹
```
Reflect to produce the left half of the sheriff.
```
¿‹θ⁰‖↓
```
If the height is negative, flip the sheriff.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~217~~ 216 bytes
```
h,w=input();t=[];w=abs(w)
for i in range(16):c=bin(32+int('37333179HH134444'[i],26))[-5:];t+=[[''.join(abs(w)*' #'[d>'0']for d in c+c[3::-1]),'#'][w==0]]*abs(h)
print['\n'.join(t[::[1,-1][h<0]]),'#'*(w*16or 1)][h==0]
```
[Try it online!](https://tio.run/##LY8xT8MwEIXn@ldY6nBx4qI4hlQ4mK2oGwub6yFxDDEgJzKu0v764BROujvp9N53etM1DqOvFjP2VgYAWAY6S@enc8xIE6XSzSzb7iebCXofA3bYeRxa/2EzVhNhZOd8xqvC@ZgB33PO2f7xeGT8PhUop2lVE6J2D0I3sZBKAdx9jsnzx8wBb0H1z1CCXvH9ijeFUVyIHdOEwha0mqUstc5Xy0DQFNIzBSf/T4pKCMVokqvhKelupjybc1YnIiPpvPqXFA7Ng/u2@C2crUA4hqtAG3uxBq/x0eZGRthejJ0iPry@HEIYQ9J0wbZfS0lLVNIKsbQZZakrtFtHRdnyCw "Python 2 – Try It Online")
A Pythonic riff on [Arnauld's approach](https://codegolf.stackexchange.com/a/169293/69880).
Ugh! Now works for all edge conditions...
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~299~~ ~~275~~ 272 bytes
```
import StdEnv,Data.List
f=flatlines
r=repeatn
$0 0=['#']
$h w#w=abs w
|h==0=r(w*9)'#'
|w<1=f(r(abs h*16)['#'])
=f(if(h<0)reverse id[cjustify(w*9)(intercalate(spaces((0xde35945rem n)*10/n*w))(r((0xc8d88154f8fberem n)*10/n)(r w'#')))\\n<-map((^)10o~)[-16..0],_<-[1..abs h]])
```
[Try it online!](https://tio.run/##TZDBa8MgGMXv@SuEFqqhyZS1JYV46w6DHgY9ptmwRhdHNEFtXaHsT59z3WXH7/u9x3s8Pghmoh678yCAZspEpafRenDw3ZO5LHfMs3KvnM8klQPzgzLCZZZaMQnmTTbHANNmMVu02bwHYRYoOzkQsltPKaYWhnyLEs1uoSZUQgt/cZ@TDbqbUJaeSsK@xsiKi7BOANU1/OPsvJLXux0q44XlLKUL6CbGhYMQf3bicb1dra3QwKCc4AeTB4RSQmK86qqKrFeykifxT5EwCCkXIXQ8mrrQbILwFRE8fqGmIJuyxO3yrS4aUpb3om2L4sGztAcFc0AAid88zfDuYvG8j7urYVrxv@Ml9ZOj1bE4/QA "Clean – Try It Online")
[Answer]
# Powershell, ~~174~~ 170 bytes
Inspired by [Arnauld's](https://codegolf.stackexchange.com/users/58563/arnauld) [Javascript](https://codegolf.stackexchange.com/a/169293/80745)
```
param($w,$h)('CGCCCAGIQQACDDDD'[((0..15),(15..0))[$h-lt0]],31)[!$h]|%{$n=+$_
,(-join(4..0+1..4|%{,' #'[($n-shr$_)%2]*[Math]::Abs($w)}),'#')[!$w]*[Math]::Abs(($h,1)[!$h])}
```
Ungolfed, explained and test scripted:
```
<#
Script uses 5 bits of integer as 5 left chars of a line of a sheriff
Script ignores other bits in this integer, so we can use 6 bit to take a ASCII letter
##. 1 00011 C
###.. 1 00111 G
##. 1 00011 C
##. 1 00011 C
##. 1 00011 C
# 1 00001 A
###.. 1 00111 G
# # . 1 01001 I
# # . --> 1 10001 --> Q
# # . 1 10001 Q
# 1 00001 A
##. 1 00011 C
# . 1 00100 D
# . 1 00100 D
# . 1 00100 D
# . 1 00100 D
#>
$f = {
param($w,$h)
(
'CGCCCAGIQQACDDDD'[ # 5 bits of each char correspond to 5 left symbols of line of sheriff.
((0..15),(15..0))[$h-lt0]], # forward or reverse sequence of chars
31 # or sequence of one element = 11111
)[!$h]|%{ # choose a sequence and for each
$n=+$_ # integer or ASCII code
,( -join(
4..0+1..4|%{ # loop on bit range 4..0 and append fliped range 1..4
,' #'[($n-shr$_)%2]*[Math]::Abs($w)
} # returns space or # depend on bit, repeat $w times
),
'#' # returns # for $w equal 0
)[!$w]*[Math]::Abs(($h,1)[!$h]) # choose a sheriff line, repeat $h times
}
}
@(
,(1,0)
,(0,1)
,(1,-1)
,(0,0)
,(1,1)
,(0,0)
,(-2,-1)
,(0,0)
,(2,2)
) | % {
$w,$h = $_
$r = &$f $w $h
$r
}
```
] |
[Question]
[
You will be given two Arrays / Lists / Vectors of non-negative integers **A** and **B**. Your task is to output the highest integer **N** that appears in both **A** and **B**, and is also unique in both **A** and **B**.
* You may assume that there is at least one such number.
* Any [reasonable Input and Output method / format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) is allowed.
* [These Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in every programming language wins!
---
Test Cases:
```
A, B -> Output
[6], [1, 6] -> 6
[1, 2, 3, 4], [4, 5, 6, 7] -> 4
[0, 73, 38, 29], [38, 29, 73, 0] -> 73
[1, 3, 4, 6, 6, 9], [8, 7, 6, 3, 4, 3] -> 4
[2, 2, 2, 6, 3, 5, 8, 2], [8, 7, 5, 8] -> 5
[12, 19, 18, 289, 19, 17], [12, 19, 18, 17, 17, 289] -> 289
[17, 29, 39, 29, 29, 39, 18], [19, 19, 18, 20, 17, 18] -> 17
[17, 29, 39, 29, 29, 39, 18, 18], [19, 19, 18, 20, 17, 18] -> 17
```
[Answer]
# [Python 3](https://docs.python.org/3/), 61 56 54 bytes
Saved 7 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder), [@pizzapants184](https://codegolf.stackexchange.com/users/44694/pizzapants184) and [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)
```
lambda a,b:max(f*(a.count(f)==b.count(f)<2)for f in a)
```
[Try it online!](https://tio.run/##TVDbDoIwDH2Wr@gjM41hTB0Q@RIkZqiLJAoGMNGvx3YDMdmy051Lmz4/w61t1Gjz43g3j@piwGCVPcw7tOvQbM7tqxlCK/K8@uFDLGzbgYW6ASPG4doPp7Pprz3kUASrotiXCIVE2Jclck0wRlAIWya2CDviEPRERwSJVAnJUlZ45H@jJYMDnJGO05FMu8ozapLGrl08M9SM8xYDf8yppJLUSbIiSadCu/n/KKn9Jcls1H5Elfp3xjJx3vQvNpr8rmcZ8Ore@OHlLZvLgtWzq3m7IXFCjF8 "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
fċ@ÐṂ;Ṁ
```
[Try it online!](https://tio.run/##hU67DcIwEO09xQ1wEv4EbIuGNZCVEgqUBegQLQ1bMEPqsEgmMfeJRbpItu7d@9zd7TIM91qv39dpes/j8ziPjzp9/O5cazFQDj1CcQhUjQCPEBA6pjuEPSkIUURLgKSQyJRZV6SsbXkOS4ieuMgUpVMliNHLIt94WsOz/nYmdCJ5HO1wrKe8NFGuXkku6ieLxqKeFrLWhl2SZF4NtUs6bQQ3wqb/AQ "Jelly – Try It Online")
### How it works
```
fċ@ÐṂ;Ṁ Main link. Left argument: A. Right argument: B
f Filter; keep those elements of A that appear in B.
ÐṂ Yield all elements of the result for which the link to left yields a
minimal value (2).
ċ@ Count the occurrences of the element...
; in the concatenation of A and B.
Ṁ Take the maximum.
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 49 bytes
```
U()(sort -rn|uniq -u$1)
(U<<<$1;U<<<$2)|U D|sed q
```
*Thanks to @seshoumara for golfing off 1 byte!*
[Try it online!](https://tio.run/##S0oszvj/P1RDU6M4v6hEQbcor6Y0L7NQQbdUxVCTSyPUxsZGxdAaTBlp1oQquNQUp6YoFP7//9/QnMvIksvYEkRCGIYWQPTfEMgAs40MuIBqQAwA "Bash – Try It Online")
### How it works
*uniq* takes sorted input and performs one or several actions, depending on the command-line flags.
`U<<<$1` and `U<<<$2` call the function `U` with the first and second command-line argument as input. For each one, `sort -rn|uniq -u` is executed, sorting the input numerically (`-n`) and in descending order (`-r`) for *uniq*, which will print only unique lines (`-u`).
The output of both (unique elements of each array) is concatenated and piped to `U D`, i.e.,
`sort -rn|uniq -uD`. This time, *uniq* will only print duplicate lines (`-D`), and only the first repetition of each.
While the man page says it will print all repetitions, the added `-u` causes `-D` to print only the first occurrence of duplicated lines. This behavior is normally achieved with `uniq -d`.
Finally, `sed q` quits immediately, reducing its input (unique elements of both arrays) to its first line. Since the output was sorted in descending order, this is the maximum.
[Answer]
# Pyth, ~~12~~ 9 bytes
[Try it](https://pyth.herokuapp.com/?code=eS%40Fm.m%2Fd&input=[1%2C+3%2C+4%2C+6%2C+6%2C+9]%2C+[8%2C+7%2C+6%2C+3%2C+4%2C+3]&debug=0)
```
[[email protected]](/cdn-cgi/l/email-protection)/d
```
Saved 3 bytes thanks to Mr. Xcoder.
### Explanation
```
[[email protected]](/cdn-cgi/l/email-protection)/d
m /d Count the occurrences of each element.
.m Take only those that appear the minimum number of times.
@F Apply the above to A and B and take the intersection.
eS Take the largest.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
-1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)
```
εТÏ}`Ãà
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3NbDEw4tOtxfm3C4@fCC//@jDc11FIwsdRSMLSE0jG1oEcsVbQhigDlACQMgbQ6WAAA "05AB1E – Try It Online")
```
ε } # For each input
Ð¢Ï # Get the unique elements
`Ã # Keep only the elements that appear in both lists
à # Keep the greatest element
# Implicit print
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
→►≠OfEΠ
```
Takes input as a list of two lists, works for any number of lists as well (returning the highest number that occurs exactly once in each, if possible).
[Try it online!](https://tio.run/##dY49CgIxFIR7T7GlwhT52c3PAaw9QEgrgti4eAAtBFsL6z2FhaUH8BC5SHwviQiCJOQNM9/wsjmM29zt5mM6HfeL5z2n8zXdHukyrdbL15RzDsFEBAkT4yzQVNDoyekxwMAWV8BqaAflKSiTDdEaxBNpwKGDJcWOLqkCH3YGUK8RpGtXQXpICpwvyvJXPqa0fCmqrOW12vNbhXRM@0Z3SpSG@0v/FL78Gw "Husk – Try It Online")
## Explanation
This is the first Husk answer to (ab)use the new "maximum by" function `►`.
```
→►≠OfEΠ Implicit input, say [[3,2,1,3],[1,2,3,4]]
Π Cartesian product: [[3,1],[2,1],[3,2],[2,2],[1,1],[3,3],[1,2],[3,1],[3,4],[2,3],[1,3],[3,2],[2,4],[3,3],[1,4],[3,4]]
fE Keep those that have equal elements: [[2,2],[1,1],[3,3],[3,3]]
O Sort: [[1,1],[2,2],[3,3],[3,3]]
►≠ Find rightmost element that maximizes number of other elements that are not equal to it: [2,2]
→ Take last element: 2
```
[Answer]
# Bash + coreutils, 60 bytes
```
f()(sort -rn<<<"$1"|uniq -u);grep -m1 -wf<(f "$1") <(f "$2")
```
[Try It Online](https://tio.run/##S0oszvj/P01DU6M4v6hEQbcoz8bGRknFUKmmNC@zUEG3VNM6vSi1QEE311BBtzzNRiNNASSrqQBhGSlp/v//39Ccy4jLyJLL2BJEQhiGFkD03xDIALONDLiAqkAMAA)
# Bash, 89 bytes
```
c()(for e;{((e^$1||r++,2^r));});for x in $1 $2;{((x<r))||c $x $1||c $x $2||r=$x;};echo $r
```
[TIO](https://tio.run/##JYuxCsMwDER3f4UGDTbpUKlDG9T@SiAxLunSgLsY6ny7KjVwHA/u3TJ/VtUcU3xuFYp8YywTUu91GE481ZRkT@Jbg9cbkADZpXa3qfcM2MD1A9h@D2yyS8nrBlhVla6BA4/hMnofQDeLksGf@RzMcvgB)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ċ@Ị¥Ðf`€f/Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8//9It8PD3V2Hlh6ekJbwqGlNmv7DnQ3///@PjjbUUTDWUTDRUTADI8tYHYVoCx0FczAPImMcGwsA "Jelly – Try It Online")
[Answer]
# J, 23 bytes
```
>./@([-.-.)&(-.-.@~:#])
```
`(-.-.@~:#])` removes from a list any repeated elements
`&` do this to both args
`([-.-.)` We want A intersect B. This is the equivalent phrase: "A minus (A minus B)"
`>./` Take the max
[Try it online!](https://tio.run/##hUzLCsIwELz3KwYF24KNaWKbpFDpf4gnMYgXDz3rr9fZRMSDIJvNzs5jb0ucMQ7QYC8HtZuqY6MaVW8qGdNzWJ/qpS5WCmUchxJbPAbEuSgu5@sde4xoYWCJIrtDD5clZ6lpGdbDBMp5ktDfYYn2LHF4OCJhbLZ0tJhUQnc0mLeNOFuMD3LHoA1ofVoFOfo@JDc@SjlCPCYiwAb5M6AxpkA@pFPM/4v8Ti0v "J – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 94 bytes
```
param($a,$b)filter f($x){$x|group|?{$_.count-eq1}}
(f($a|sort|?{$_-in((f $b).Name)}))[-1].Name
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJMy0zpyS1SCFNQ6VCs1qloia9KL@0oMa@WiVeLzm/NK9EN7XQsLaWSwOoILGmOL@oBCynm5mnoZGmANSv55eYm6pZq6kZrWsYC@b8///fQcPQXEfByFJHwdgSQsPYhhaaIFkQC8wDyhgAaXOwDAA "PowerShell – Try It Online")
Takes input `$a` and `$b` as arrays. Constructs a `filter` that `group`s the input array elements together and pulls out only those with a `count` `-eq`ual to `1` (i.e., only those that are unique in the input array).
The next line then constructs the algorithm. First we `sort` `$a`, then pull out those that are `-in` the unique items of `$b`. Those are then themselves unique-ified, the largest `[-1]` is chosen, and we take the `.Name` thereof. That's left on the pipeline and output is implicit.
[Answer]
# Java 8, 133 bytes
```
a->b->{long r;for(java.util.Collections c=null;;a.remove(r))if(b.contains(r=c.max(a))&c.frequency(a,r)*c.frequency(b,r)==1)return r;}
```
**Explanation:**
[Try it here.](https://tio.run/##xZNBb8IgGIbv/gpOCyyVWHWzprbJsmSn7uRx2QERTR1CB9TNGH@7@6g1mmUna7OEBvpRHt73ha7YhnV1IdRq/nHgklmLXlmudh2ErGMu52gFX9DS5ZIuSsVdrhV9qQeT89yTMWyb5dZNMq2WaXDtsqpLEUcJOrBuOuumOwklZOKFNvi88FlLKSqaRTxRpZRxzKgRa70R2BCSL/CMcq0cmLHYJJyu2TdmhNxxujDisxSKbzELDLm/LMygkCQhMcKVRsGu@0MMUUArypmENOpQNjqfozWw8dSZXC3f3hEjPjSEplvrxJrq0tECppxUmFNWFHKLlfhCf3lP8a@qpcz6GfyYEUKuXh1mQQUg8e2VAbufBYMsGDaSOMyCB68yGLUltAdskDmIQPC4kdYaUeF6LeZaheozgdZMceRz9ZgjctCW6H51GfqnreBEfVQ3kF6R2koa9IZwnKHXGo3rl1GzP@6CCajq8ey2LIyON3IwPvancRg1czG@SKZXO4n@wUTLRvad/eEH)
```
a->b->{ // Method with two ArrayList<Long> parameters and long return-type
long r; // Result-long
for(java.util.Collections c=null;
// Create a java.util.Collections to save bytes
; // Loop indefinitely
a.remove(r)) // After every iteration, remove the current item
if(b.contains(r=c.max(a))
// If the maximum value in `a` is present in `b`,
&c.frequency(a,r)*c.frequency(b,r)==1)
// and this maximum value is unique in both Lists:
return r; // Return this value
// End of loop (implicit / single-line body)
} // End of method
```
[Answer]
# Javascript (ES6), 102 86 75 71 bytes
```
a=>b=>Math.max(...a.map(e=>(g=x=>x.map(y=>y-e||x--,x=1)|!x)(a)*g(b)*e))
```
Thanks @justinMariner for getting from 102 to 86
Thanks @tsh for getting from 86 to 75
Thanks @Arnauld for getting from 75 to 71
[Try it online!](https://tio.run/##nVDdboIwFL7fU3R3rSmEtrhCTHkDn8DsorrK3FSIGFMS3p2d02pmNnYxE@Cc0@/vlA97sd3mtGvPSdfu3tzp0Bw/XT9uzWhNtTbV0p7f04P1NE1TC01LnalobbypfBh7U/WJGwafJNwbwYZnz6hls5qu2cwxNm6aY9fsXbpvarqlq5dXRleCE6jwYYunHzhAkhPFSY7EnJM50DjRSM9/0zOAgKwKkJWoiF08zVCk1WQIJgRneIIQdDpMEVF/BMqwn7wxYTsM/DbAA5TOJ1JBJWA1gYqivA46/JA7SOj4AgWNoExY6XhLVcZ660UR3Mq7oOzqGLYS@j9eD/pxyRVXKJQ8D1dgi/EL "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~57~~ 53 bytes
```
x?y|let v!x=filter(==v)x==[v]=maximum[a|a<-x,a!x,a!y]
```
[Try it online!](https://tio.run/##fYrPCoJAGMTvPsXXTUEj62CKi4dOQT7B4uED11raP7JtsoLvvq1G1waGmeE3D3w9mRCey1EbCxetrNFi32qFvXfNvAhmYdo5MnBhmYkJmRJHCJ06ItFx@ZYUF6wzl@Ju9dx5iVwBgV5HEOSgzkDwwbZgGPZwZ/bGFdvY/IeNhisLsYMm3KoKrsomnuZFCscyhVP5zV/Pz11E87VsI4BDyGIDHw "Haskell – Try It Online")
**UPD:** Thanks @Laikoni
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
Max@Cases[Tally@#⋂Tally@#2,{x_,1}:>x]&
```
[Try it online!](https://tio.run/##hY@9CsIwFIX3PkVAcMrQtLVpBaVQcBMc3EqRIIqF/kB/oBLawdW39EXiTZNInQoJubnnO@cmBWsft4K12ZWJe1fuxJH1UcyaW5OcWZ4/o9Xn/dKVg3l/wWTY7vt0LU51VrZRXOVdUR6quki4hRD3hxFiRk4w8gcsO1A5GLkYeVryMNqAihFVgA0VyG4AYKgZdVGC/cuRIZMTliEBpFNDia6CnWmoYwSYJwP/LLKnk4EjMIxIJgj1hZqfzFRC1QZKW6l6pxuq09QkMO5wlm3rhGDJvBxgDan4Ag "Wolfram Language (Mathematica) – Try It Online")
# How it works
`Tally@#` gives a list of the unique elements of the first input, together with their counts: e.g., `Tally[{2,2,2,6,3,5,8,2}]` yields `{{2,4},{6,1},{3,1},{5,1},{8,1}}`.
`Tally@#2` does the same for the second list, and `⋂` finds pairs present in both. Then we pick out (with `Cases`) pairs ending in `1`, taking the first element of each result, which gives us a list of all the unique twins. Finally, `Max` returns the largest unique twin.
[Answer]
# [SQLite](https://www.sqlite.org/), 118 bytes
```
SELECT MAX(x)FROM(SELECT X FROM A GROUP BY X HAVING COUNT(X)=1
INTERSECT
SELECT X FROM B GROUP BY X HAVING COUNT(X)=1)
```
[Try it online!](https://tio.run/##rZGxbsMgFEVn8xV3BInFdRK3ijqAQ1JUDBHGkf0BGSJ1qZLBf@/gqqqUxgodOnLveYDOO39@nC7HsfJKBIUgpFEQlADQm0zbgL3XtfA93lWfWRdgW2P41A9Tnf1khK0J0bZRPiAWDgJUbzgGhoMwrWpAc448Uo@hJ44iCRUciyS04FgloeVfoBXHSxIqOcrJwY1K@S8q5ZzK518/knMqyyRU3AuQcyqLJLS8X4qcU5m@qfyCxkYZVQXUoqMD23pX0@@kw3SKO9h51@4h@5i8iYO2O1SutYF27DWPbwTlm8iT2zH5cIyN4xU "SQLite – Try It Online")
First time in SQL, any help is welcome!
[Answer]
# [Röda](https://github.com/fergusq/roda), 48 bytes
```
{m={|n|sort|count|[_]if[_=n]};[_()|m 1]|m 2|max}
```
[Try it online!](https://tio.run/##JcZBCsMgEADAc/KKPSrsJWnTQIsvsYtIi9SDGoyBgOvbbaGXYXJ62x6sj1DHwcFdwbPXoCpH3lMu/EpHLKwNeaeNitQe2gjJASb6MXOwZ@vDln0sYjv2j9ATznjBKy64EOr/brjiShIYnJBybP0L "Röda – Try It Online")
Inspired by [jq170727's jq answer](https://codegolf.stackexchange.com/a/147110/66323).
Explanation:
```
{ /* Anonymous function, takes input from the stream */
m={|n| /* Local function m with parameter n: */
sort|count| /* Count unique values in the stream */
[_]if[_=n] /* For each value, push it to the stream if its count is n */
};
[ /* For each list in the stream: */
_()| /* Flat it (push its values to the stream) */
m 1 /* Push values that appear only once to the stream */
]|
m 2| /* Push values that appear twice to the stream */
max /* Find the max value in the stream */
}
```
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~117~~ ~~115~~ ~~114~~ ~~111~~ 108 bytes
## ~~115~~ 114 bytes
Another solution with `countBy` this time:
```
let u x=x|>Seq.countBy id|>Seq.filter(fun a->snd a=1)|>Seq.map fst|>set
let f x y=Set.intersect(u x)(u y)|>Seq.max
```
[Try it online!](https://tio.run/##PY7NCoMwEITvfYqhUIgHBe3fIcRDX8Fj6UE0CwEbrVkhQt/drgqFZWHmY4ahkDb9aJfOMkIOg2euUWicNS4ad7nXYWPFysS6atxWd0tMiCZ@y8p@sqafPD9muHbX5Dq2o6LJo07L4FvUJk929q4HRYFFBctbPSFiNpXlzHmJBduwkvJE3vwPxWUYBZPH8eSOULQuDkWy/AA "F# (.NET Core) – Try It Online")
## ~~117~~ 111 bytes
```
let u x=x|>Seq.filter(fun a->x|>Seq.filter((=)a)|>Seq.length=1)|>set
let f x y=Set.intersect(u x)(u y)|>Seq.max
```
[Try it online!](https://tio.run/##ZY7LCoMwEEX3/YqLUDALBdPXIo0/4bJ0oTJpBU1bEyFC/91ObHeFYWDO4c6McVn7GGnpycMV0LgUClJhp7BXOHFdN6uT0TE6KBwjXRMTgg7vsqJXbrre05iayaLOyn/YZGWja/HlPdmbv58lj478esAgYNYV@byznHHU@pTXC27zLzXUYXmOrI1Fsu0SpCb@7KRYPg "F# (.NET Core) – Try It Online")
100% F#! Any help is welcome!
6 byte won thanks to prefix notation!
## 108 bytes
```
let f a b=Set.intersect(set a)(set b)|>Seq.filter(fun x->a@b|>Seq.filter(fun y->y=x)|>Seq.length<3)|>Seq.max
```
`@` is the concat function! Thank you @Ayb4btu for this algorithm.
[Try it online!](https://tio.run/##ZY7LCsIwEEX3fsWlIDSLFtr6WMQG/6FLcZGWiRZq1CZCCv57TEJ3wsAw58wwV5lieM7kJ7IwFVpcKo6ao@HYcRxDXTfJ1dEFtOc4RJouFCT6tiNbjtrSbGiwuQlcstR69hUdvUs1TsHm6qPhCiHP/R9eCrG0bl2fSN/s/dSs40M6/5rDA6WRbccMuYpRTc38Dw "F# (.NET Core) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~85~~ 84 bytes
```
x=>y=>x.Where(a=>x.Count(b=>b==a)<2).Intersect(y.Where(a=>y.Count(b=>b==a)<2)).Max()
```
[Try it online!](https://tio.run/##pZJRb4IwFIWf11/RR2oqCihIEF5MliyZyZI9@EB4QFY3ElcyWjeJ4be7tiiIUzFZAvS099yvl@QkrJ9kOdkPeqEdYRgaGNoR7AfQBlKbGFoYjmRlhOFYFDF0VH0EwqHQompNhM@VlkpVp0PlciyFkQzVKx7lFEZH7aqKdUSa6krzWBIXSmTTIQ@Udyy4wmaI2wxpmbiHjaP@4qRkONUrLKpTrKLXqSa13Go9amOi2t0T8vCAqO41nFvN9wF6A7BhKX2HrwXj5NNr7fTnlH55IFnHjMGXHWA85mkCv7P0Dc7jlGoI7MDjhibTlPIwwidSfIMArny4L/xgKx598UFyosVSzrIN5drSD5a@H6OpifQnyknOSMK1ojEWf41In8dbDe09AB5mGWXZmuiLPOVETEq0lUbJDwyjnV0iKaXCRomQd9PdZKtuawLW2d1KXg1oxe@eCVqxrDHn2ewkXQ7tGU@eds90OdI16kquu7lXE9ugL0b2H@R76SUo978 "C# (.NET Core) – Try It Online")
Naive solution with LINQ (`using System;using System.Linq;` +31chars so 116 bytes with header)
84! I forgot currying!
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~17~~ 16 bytes
```
MX{_Na=_Nb=1FIa}
```
This is a function that takes two lists as arguments. [Try it online!](https://tio.run/##K8gs@K/x3zeiOt4v0TbeL8nW0M0zsfZ/tKGCsYKJghkQWsYqRFsomANZIBHjWC7N/wA "Pip – Try It Online")
### Explanation
```
{ } Define function, args are a & b:
FIa Filter elements of a on this function:
_Na Count of element in a
=_Nb equals count of element in b
=1 equals 1
This gives a function that returns a list of unique twins
MX Modify it to take the max and return that instead
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 18 chars = 23 bytes\*
A full program body. Prompts for list of lists from STDIN. Works with any number of lists. Outputs to STDOUT.
```
⌈/∊∩/{⊂⍺⍴⍨1=≢⍵}⌸¨⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO9tOT/o54O/UcdXY86VupXP@pqetS761Hvlke9KwxtH3UuetS7tfZRz45DKx71TQWp/68ABqUlXEABr2B/P/XoaLNYHYVoQx0Fs9hYdS4s8kApIx0FYx0FE5BCEx0FU6BaHQVzHMoNgFJAxcYWQG2WIB0QFkTUALcdIAvABgMRWB9QmzmYB5ExxqHVCOw8I5hKoONA9iEMAAngshWoyxDoMkOQDgtLKMccHB5IUobmEAxUgssgc4gXjS0hNIxtaAE2yxLJGgOoeRYkG0XQOAA "APL (Dyalog Unicode) – Try It Online")
`⎕` prompt for evaluated input from STDIN
`{`…`}⌸¨` for each list, call the following function for each unique element in that list, using the unique element as left argument (`⍺`) and the list of indices of its occurrence as right argument (`⍵`):
`≢⍵` the tally of indices (i.e. the number of occurrences)
`1=` equal to 1
`⍺⍴⍨` use that to reshape the specific element (i.e. gives empty list if non-unique)
Now we have two lists of unique elements for each input list (although each element is a list, and there are empty lists as residue from the non-unique elements).
`∩/` intersection (reduction)
`∊` **ϵ**nlist (flatten)
`⌈/` max (reduction)
---
\* in Classic, counting `⌸` as `⎕U2338`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
,iSY'1=)]X&X>
```
[Try it online!](https://tio.run/##y00syfn/XyczOFLd0FYzNkItwu7//2hDcx0FI0sdBWNLCA1jG1rEckUbghhgDlDCAEibgyUA) Or [Verify all test cases](https://tio.run/##fU69CsIwEN59ikwW4YZcUr1k0Mk3qEOlFHQUdPP943e5VMShkHD3/XKv@/tZboUew7Xj424et@OpnC9lOsybicm1EchFcj1AT24PmpwAeAzwMcGRgW0x0ltSY9WPpxY4pAITIqhQ@8PCol5rvl7F2gUDo5tVTLkB@VNY7MOhitg9Mdtcdq6F@afQt2haTa0nPw).
### Explanation
```
, % Do twice
i % Take input: array
S % Sort array
Y' % Run-length encode: pushes array of values and array of run lengths
1= % Compare each run length with 1
) % Use as logical index. This keeps only values that have appeared once
] % End
X& % Intersection of the two arrays
X> % Maximum of array. Implicitly display
```
[Answer]
# PHP, 98 bytes
```
<?foreach(($c=array_count_values)($_GET[a])as$a=>$n)$n-1||$c($_GET[b])[$a]-1||$a<$r||$r=$a;echo$r;
```
Provide arrays as GET parameters `a` and `b`.
[Answer]
# [R](https://www.r-project.org/), 73 bytes
```
function(A,B)max(setdiff(intersect(A,B),c(A[(d=duplicated)(A)],B[d(B)])))
```
[Try it online!](https://tio.run/##NY3NCsIwEITvPkWOu7CCscGYoof0NUoPJT8Q0ChtCr59TFKFhZnZ@ZZdsme3Y/ZbNCm8Imga8Dl/YHXJBu8hxOSW1ZnUGjKgR7B3u70fwczJWQSNEw2jhQEnRMweDPBeVFT0EvHQFpLYWRHr1K5/z6@V49W1VJpTUdma32khiQlilzaqHhROtrQ3XXn7BQ "R – Try It Online")
Computes `A` intersect `B`, then the maximum of the difference between that and the duplicated elements of `A` and `B`.
[Answer]
# JavaScript ES5, ~~122~~ ~~121~~ 114 bytes
```
function f(a,b){for(i=a.sort().length;--i+1;)if(a[i]!=a[i+1]&&a[i]!=a[i-1]&&!(b.split(a[i]).length-2))return a[i]}
```
I'm new here, so I don't really know if I can remove the function definition and just put its contents (which would save me 17 bytes)
Here's the working example: ~~[122](https://tio.run/##lVDdaoMwFL7fU6Q3bYJRjNpGEZ9EvFBn2xRJiqbbxdizu3NMLWVzsIEm@fL9Hb3Ub/XYDupqfW1eu2k63nRrldHkSGvesI@m2O28JldFHYxmsJQFfadP9py/n1XfUd9XnmAKxKWqNgWsnqi22wfyEW1oE4zXXtlZtST4EWNDZ2@DJnj9ObVGj6bvgt6c6JGWh4qXgpNDxWBh@cs3GqiIk5iTBHQJJ3tQcSJRnfxUh0CBNk7BlYHBHdxliB4Zr1Zg/hwMD/rAJmfgiPiXumgeLlqUMBv2PfyI0blf6QSTgMEEGtLsDiT@iydGSPeCAnNgW0mS7hPjzO3LWaQYlj3VhPfAeSYh/xP1p7jpCw)~~ ~~[121](https://tio.run/##lVDdaoMwFL7fU6Q3bYJRjNpGEZ9EvFCnbYYkRdPdjD27O8fUUjYHG2iSL9/f0bf6vZ7aUV2tr81rN8/9TbdWGU16WvOGffRmpE1xOHgNV0UdTGa0lAVDp8/2kvu@8kTOFGhLVe0KWD1R7fcP5CPa0SaYroOyi2o1@xFjY2dvoyZ4/Tm3Rk9m6ILBnGlPy1PFS8HJqWKwsPzlGw1UxEnMSQK6hJMjqDiRqE5@qkOgQBun4MrA4A7uMkSPjDcrMH8Jhgd9YJMLcET8S120DBetSpgN@x5@xOg8bnSCScBgAg1pdgcS/8UTI6R7QYE5sG0kSfeJceb29SxSDMueasJ74DKTkP@J@lPc/AU)~~ [114](https://tio.run/##lZBBboMwEEX3PYWzSWzFIAwkBqGcBLEgFBJXyI7A6SbK2el4HNqopVIrge3xvP//wFv9Xo/NoC420Oa1nabuqhurjCYdrfmR3TozUHWow9EMlrKwb/XJnosgUFtRMAVQqarVAdatqNbrzypw1Yoew/HSK4vULA5ixobWXgdN3PV9aoweTd@GvTnRjpb7im9Kwcm@2jBYWfHyDYBezEnCSerIlJMdYJxI5NOffAQ9oJMMdLmT@JO/jVAlk8UYl4He8KAShBIr30l@i4xxxHhGYUAX@eXgLlC7W8gFmYDphJNk@aOQ@FeeWkL6FxB0gn3BS/ovTXK/z2eRoV3@lBQ9LP1cQv7H7I@G0wc)
122 to 121 bytes: Wrapping initialization in a for
121 to 114 bytes: `b` has to be a string
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), 76 bytes
```
def m(n):[.[indices(.[])|select(length==n)[]]]|unique[];[map(m(1))|m(2)]|max
```
Expanded
```
def m(n): # function to emit elements of multiplicity n
[
.[ # select elements with
indices(.[]) # number of indices in the array
| select(length==n)[] # equal to specified multiplicity
]
] | unique[] # emit deduped values
;
[
map(m(1)) # collect multiplicity 1 elements from each array
| m(2) # collect multiplicity 2 elements
] | max # choose largest of these elements
```
[Try it online!](https://tio.run/##hY/NboQgEIDvfQqSXiDBjYgr2mb7IoSD2aWtG0W3QtoDz147wOpuL22icX6@@WY8XxYpK0WRZBRVCoJHlL2g6kGGQkERp6gM7ZKiPRAUiQ0qAcqhAAivAW4Cl6JUzTdU8CQMtmiBJ@JAi5ilDv8lL@IFxdqH/UF@GwuFbWAfNgDLYDkLXN1cExF/767FRHoB2cYhDgKRrudN@q4xq6OjudPnV8/tAib@NPxnQX7VLCf9igZsyJPcyc6cuqOe8U4q4mfd66PFvTZv9v1wMEQqpbwz3cVpqZ7l0E54wIwQP@CCKD@0X8vyPU62G828ZJlxfZ91ZnIWko/2MxudheQH "jq – Try It Online")
Here is another solution which is the same length:
```
def u:[keys[]as$k|[.[$k]]-(.[:$k]+.[$k+1:])]|add;map(u)|.[0]-(.[0]-.[1])|max
```
Expanded
```
def u: # compute unique elements of input array
[
keys[] as $k # for each index k
| [.[$k]] - (.[:$k]+.[$k+1:]) # subtract other elements from [ .[k] ]
] # resulting in [] if .[k] is a duplicate
| add # collect remaining [ .[k] ] arrays
;
map(u) # discard duplicates from each input array
| .[0]-(.[0]-.[1]) # find common elements using set difference
| max # kepp largest element
```
[Try it online!](https://tio.run/##hY/daoMwFIDv9xSB9aLSRIyxRh3sRQ65CNhBZ6tuGtpBnn3ZSVJtd7OBmvPznS/H9w8HUCpKgFNSKgyeCXsl5RP4Qk6JoKTw7YKSPRKUyBUqEMqwgIioEK49F6NYzVZUiij0tmDBJ@BIy5DFjvglz8MG@dLH@738PuYL68De34Asx8u556r6lsjwew8tLuOLyDqOsRfIuL2o47nEvAqO@kGf3Tz3Dbj80/CfhdhF49rDGzENdIevCZSeNp2FFDadUmybQoPBzqc73qhEWd22L2c9bk1iU8gCgt8UuErsWV@d@x7G@Tj0k2OsN6cTO/ajmTH51Bc2mBmTHw "jq – Try It Online")
[Answer]
# APL, 47 bytes
```
{1↑R[⍒R←((1={+/⍵=A}¨A)/A←⍺)∩(1={+/⍵=B}¨B)/B←⍵]}
```
Declares an anonymous function that takes two vectors, eliminates duplicate elements, then finds the biggest element in the intersection of the results.
`A←⍺` and `B←⍵` store the arguments passed to the function in `A` and `B`.
`a=b` returns a vector with 1 in each index in which `a` is equal to `b`. If `a` is a scalar (i.e. single quantity and not a vector) this returns a vector with 1 wherever the element in `b` is `a` and 0 when it is not. For example:
```
Input: 1=1 2 3
Output: 1 0 0
```
`{+/⍵=A}`: nested anonymous function; find the occurrences of the argument in vector `A` and add them up i.e. find the number of occurrences of the argument in `A`
`1={+/⍵=A}¨A`: apply the nested anonymous function to each element in A and find the ones that equal 1 i.e. unique elements
`((1={+/⍵=A}¨A)/A←⍺)`: having found the *location* of the unique elements, select just these elements in the original vector (`/` selects from the right argument elements whose locations correspond to 1 in the left argument)
`R←((1={+/⍵=A}¨A)/A←⍺)∩(1={+/⍵=B}¨B)/B←⍵`: repeat the process for the second argument; now that we have just the unique elements, find the intersection i.e. common elements and store this in vector `R`
`R[⍒R]`: access the elements of `R` in decreasing order
`1↑R[⍒R]`: take the first element of `R` when it's sorted in decreasing order
Test case:
```
Input: 17 29 39 29 29 39 18 18 {1↑R[⍒R←((1={+/⍵=A}¨A)/A←⍺)∩(1={+/⍵=B}¨B)/B←⍵]} 19 19 18 20 17 18
Output: 17
```
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
[:>./@,[*([*+/"1(1=*/)+/)@(=/)
```
How it works:
I start with testing where the two list overlap by `=/` (inserts equality test between all the members of the lists:
```
a =. 1 3 4 6 6 9
b =. 8 7 6 3 4 3
]c=. a =/ b
0 0 0 0 0 0
0 0 0 1 0 1
0 0 0 0 1 0
0 0 1 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
```
More than one 1 in the same column means that the number is not unique for the left argument (6 in this case); in the row - for the right argument (3)
Then I sum up all rows and all columns to find where are the duplicates:
```
+/ c
0 0 2 1 1 1
+/"1 c
0 2 1 1 1 0
```
I find the cartesian product of the above lists and set the members greater than 1 to 0.
```
m =. (+/"1 c) (1=*/) +/c
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 1 1
0 0 0 1 1 1
0 0 0 1 1 1
0 0 0 0 0 0
```
I mask the equality matrix c with m to find the unique elements that are common to both lists and multiply the left argument by this.
```
]l =. a * m * c
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 4 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
```
Then I flatten the list and find the max element:
```
>./,l
4
```
[Try it online!](https://tio.run/##fU45DsMgEOz9ipEbnzKXbQ6JyP9wGQVFaVK4ztvJAnYXRQvL7BzAK4YD3oGDdtzdbWLbuPft3g@sFq3wPesG1m2tZ13sqnpCE7xrMOLjEI7qcX@@sSJAYC2DgITCTNSMhSRdaA6toAykJaWcRPArkxIrVVINNKHEqCLLXIlaSJSnhfCZlhAWghRjM9LpPxdJEy2STrNOTyubegHkCdlb7uA5Yf64fwfiFw "J – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 66+31=97 65+31=96 bytes
```
a=>b=>a.Intersect(b).Where(x=>a.Concat(b).Count(y=>y==x)<3).Max()
```
[Try it online!](https://tio.run/##pZBRa4MwFIWfl1@RxwTupGpbFasvhcFghcE2@lD6kGZhC3SRmrhair/dJQ5t@7SWYTD3nuR@5xCu73lRirbSUn3gl4M24itF5533JNUuRXzLtMbPR6QNM5Ljh0rxmVRmtYaL2m55jt@U3FXidS@VxhluWZZvspx5j8qIUgtuyIZ6y09RClI7fV4ozjpxXlTKkEOWH7KsprOQegtWE9qmqDf@LuQ7XjCpCEVHdGdHdbEV3rKURtiogpx5EyX2q/Vx2tC@Ar@hNL1uzIcAQhgPw2OYwBSi6wEjiEIIYwiSgdF1Th7dksOmsM5TOHFiiGzv9PB6UADuc2MTsDkuYFa5IVEAfgK@ZcRJV0UDazjyI7fshRuwkXucMHH/38KPT@Ck9xx17Ph/3L/RDWraHw "C# (.NET Core) – Try It Online")
+31 bytes for `using System;using System.Linq;`
I took inspiration from @aloisdg's answer. However, instead of searching for unique values in both arrays, I inverted the order of operations so that `intersect` is first, and then find the max value of the items that occur twice when the arrays are concatenated and are in their intersect. I can use `<3` as `Count` will be at least 2 for any value, as it will be in both arrays.
### Acknowledgements
-1 byte thanks to @aloisdg and his suggestion to use `Func` currying.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~57~~ 56 bytes
```
@(x)max(intersect(cellfun(@(x){x(sum(x'==x)==1)},x){:}))
```
Anonymous function that takes as input a cell array of two numerical arrays.
[**Try it online!**](https://tio.run/##hY5BCoMwEEX3PcXsmkAQY6yJhUDvIS5EFAraQtUSEM@eThK17oSEzMx//0/e9Vh9G9vqKIrsgxjaV4Y8X2PzGZp6JHXTde30Ik6ZDRmmnpir1oZqzenCcHhfKLUtmYushIJDVi704lrOIGEgGKQlgyJlcGOQMZCbHmONqlDI5Q4JVZjGhxQX4a14PIic9F1QxMYmfmOySbjPJf4dbrDnIsZxGXeIytdGOvgocRkuIrtThm@KPLxbzZU354fceA1Q595Tv/0B "Octave – Try It Online")
### Explanation
For each (`cellfun(@(x)...)`) of the two input arrays, this creates a matrix of pairwise equality comparisons between its entries (`x.'==x`); keeps (`x(...)`) only the entries for which the column sum is `1` (`sum(...)==1`); and packs the result in a cell (`{...}`). The intersection (`intersect`) of the two results (`{:}`) is computed, and the maximum (`max(...)`) is taken.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes
```
Last@Select[a=Join@##;Sort[#⋂#2],a~Count~#<3&]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d8nsbjEITg1JzW5JDrR1is/M89BWdk6OL@oJFr5UXeTslGsTmKdc35pXkmdso2xWqzaf01rroCizLwSh7ToakMjHQVDSyC20FEwsrCEcsxrdRRQpAzNIRiopDb2PwA "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
## Background
A **checkered tiling** of a rectangular grid is a tiling using some polyominoes, where each region can be colored either black or white so that no two polyominoes sharing an edge has the same color. In graph-theoretic terms, the [chromatic number](https://en.wikipedia.org/wiki/Graph_coloring#Chromatic_number) of the adjacency graph is 2.
Terminology adapted from [a Fillomino variant recently posted on GMPuzzles](https://www.gmpuzzles.com/blog/2021/05/fillomino-checkered-by-serkan-yurekli/).
The following is an example of a checkered tiling, with a possible black-and-white coloring on the right:
```
+-+-+-+-+-+ +-+-+-+-+-+
|A A A|B|C| |X X X| |X|
+ +-+-+-+ + + +-+-+-+ +
|A|D D|C C| |X| |X X|
+-+-+ + +-+ +-+-+ + +-+
|E|F|D|C|G| | |X| |X| |
+ +-+-+-+ + + +-+-+-+ +
|E E|H|G G| | |X| |
+ + + +-+-+ + + + +-+-+
|E E|H H H| | |X X X|
+-+-+-+-+-+ +-+-+-+-+-+
```
The following is not a checkered tiling, because it is not possible to color E, H, I with two colors.
```
+-+-+-+-+-+
|A A A|B|C|
+ +-+-+-+ +
|A|D D|C C|
+-+-+ + +-+
|E|F|D|C|G|
+ +-+-+-+ +
|E E|H|G G|
+ +-+ +-+-+
|E|I|H H H|
+-+-+-+-+-+
```
## Task
Given a tiling, test if it is a checkered tiling.
A tiling can be input as a 2D array or string where each region is represented by a unique single alphanumeric character or integer. For example, the top array can be represented as
```
AAABC
ADDCC
EFDCG
EEHGG
EEHHH
```
or
```
[[0, 0, 0, 1, 2],
[0, 3, 3, 2, 2],
[4, 5, 3, 2, 6],
[4, 4, 7, 6, 6],
[4, 4, 7, 7, 7]]
```
For output, you can choose to
1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
## Test cases
**Truthy**
```
0
00
00
012
0011
2013
2233
01234
56789
ABCDE
FGHIJ
000
010
002
```
**Falsy**
```
01
22
00
12
01
02
01234
05674
0011
0221
3244
3345
```
Brownie points to the first answer that beats or ties with 17 bytes in Dyalog APL (any version) or 96 bytes in JS (latest browser support, not very well golfed).
[Answer]
# JavaScript, ~~106~~ 101 bytes
```
s=>[...s,'!',s].reverse().join``.match(`(.)((?!\\1).)[^!]{${s.indexOf`
`-1}}((?!\\1|\\2).)(\\2|\\3)`)
```
[Try it online!](https://tio.run/##LZDZasMwEEXf5y8UCpEgGbSly0Naui8v/YAoRcaRW6WObCwTWtJ8uyslgYG5c7lnYGZdbItYdr7tp7H1K9dtmvDtfodqPsT59QIR42RMxpO4xM5tXRcdZbhufLAWN0VfflFLkVF6Q4wRDNnigyx3Z7uIPqzcz3tlwU7Ffn8K/BkjU4imlqRilg1lE2JTO6ybT2o5AOe5gAuZtRAguVAgpVIHU2mYnV9cXsHt3f3DIzw9v7y@5WCiRCYzlZgDDOI4Hc2M8sTq014upQAltQal9MxibGvf05EJJoxYuq2l6QGEVDQyxoZ/ "JavaScript (SpiderMonkey) – Try It Online")
(Returns inverted truthy/falsy.)
-5 by using spread syntax.
Focus on the boundaries of the tiling.
Suppose the tiling is not checkered. Then there is an odd cycle in the adjacency graph. Draw the odd cycle by connecting adjacent squares' centres, like this:
[](https://i.stack.imgur.com/Zu6oz.png)
Since the cycle is odd, the route crosses an odd number of boundaries.
Now divide the space enclosed by the route into small squares.
[](https://i.stack.imgur.com/2ejNN.png)
Notice that the route's boundary-crossing count has the same parity as the sum of the squares' boundary-crossing counts. Thus at least one of the squares has an odd boundary-crossing count. It cannot be 1, so it must be 3, giving a T shape.
A regular expression is used to look for a T shape oriented as ┤ or ┴, and applied to a combination of the given string and its reverse to cover all four orientations. This relies on `.` not matching `\n` by default, and `!` not being a character used in the input.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~100 99~~ 88 bytes
```
lambda a:2in[len({i,l}^{k,j})for x,y in zip(a,a[1:])for i,j,k,l in zip(x,x[1:],y,y[1:])]
```
[Try it online!](https://tio.run/##pY7LbsMgEEXXna9ArEBCEQykD0te9P34hTiViBqrJJRYMQu7Ub7dBdooH1BpFqM798493Rg/d0FPbd1M3n6tPiyxFbqw8OvADk744/thKzZH3u72ZBAjcYF8u45ZYReqWhbZiY3YCn86DWLIJzGKsViWU1z3sSc1oZRKACnzgFSYd6UApdKAqHURtYH55dX1Ddze3T88wtPzy@tbNqaUyklMX2Z9511ktAlNoBygUOT@0lTBRbd3IbKWubOTcs7hV0@JYqwzUOovIFB4FEg8YcjEYf4YJaICjcaA1mb@H4TpBw "Python 3 – Try It Online")
Return `True` if it isn't checkered tiling, `False` otherwise
-1 byte by inversing True/False for return value
-11 thanks to @xnor
## How it works:
The pattern is True if any of the following sub-pattern appears in the pattern :
```
AA Ax xy xA
xy Ay AA yA
```
We will then check each 2 by 2 sub-pattern.
* `for x,y in zip(a,a[1:])` allows me to iterate through 2 adjacent row at the same time
* `for i,j,k,l in zip(x,x[1:],y,y[1:])` define the 4 elements of our subpattern,
* `len({i,l}^{k,j})` do the mutual difference on the `2` diagonals (keeps only the elements which are not in both) and compute the length. This value is equal to 2 only for all the truthy sub-patterns (and for a case not possible geometricaly in this puzzle)
* `2in[ ... ]` verify that at least one of the subpatterns has his value equal to `2`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~167~~ ~~153~~ 143 bytes
```
def f(a):
m={a[0][0]:1}
for R in a+zip(*a)+a:
p=0
for c in R:
P=m.get(p);Q=m.get(c,0)
if(c==p)*2<Q==P:return 1
if(P>0)>Q:m[c]=3-P
p=c
```
[Try it online!](https://tio.run/##hZJdb4IwFIav7a848arVulBwH7LVy12j2R2SpWGgJBNIrVncst/OTgsONfsgDZxz@vTtW07rg9lUpd80L1kOOVUsJLCVHyr2Ehyh@CSQVxqWUJSgxu9FTUeKjRVSUEsP33Y2tbPLkAwiub1aZ4bW7H7RhSn3GBkUOU2lrNnIf1hIGYU6M3tdgnAz0dxj80W4jdNEBpOIDGqZNkbvzeYAEmLcBCBGNwk/hhy8hEP7Pa0KDv455mrCwv4xC7oMR2CzSwFXnlromsMNh1sOdxxmtiAsYgUREkgJhwnkBIICSYGomF16OLoVJ8Y7qwkhuXrdnZ20d@z/4Q4L3wanv53ac0v8LgtcOO0EglYLZToj9g6Y6nlndFGuqdLa3gboehXHWKcp6zuuq7fEZRi4@6E1itS42NDhqnxyHVyVE3yGjLhlapdZsm1u6By3fE77jS3FGOuVHu0P@lHI/bp/dJov "Python 2 – Try It Online")
*-10 or so bytes from @Bubbler*
*-1 byte independently from @Recursive Co.*
*-11 bytes from @ovs*
*+2 bytes from fixing a bug spotted by @tsh*
Returns `None` for truthy and `1` for falsey. Takes input as a list of lists of strings (it was numbers before, but strings saves a byte by making them distinct from `0` on line 4).
Using Python 2 to save indentation by mixing tabs and spaces.
## Ungolfed
```
def is_checkered(arr):
# mark the top-left column as color 0
m = {arr[0][0]: 0}
# zip(*arr) is the transpose of arr
# iterate over each row and column, then row again
# 1) loop over rows to guarantee computing colors for the top row
# 2) loop over columns to guarantee computing colors for the entire grid
# - at the same time, this checks that horizontally adjacent tiles have different colors
# 3) loop over rows again to check that vertically adjacent tiles have different colors
for transposal in [arr, zip(*arr), arr]:
for row in transposal:
prev = row[0]
for c in row:
if c != prev and c in m and prev in m and m[c] == m[prev]:
# this tile and the previous are the same color
return False
if c not in m and prev in m:
# this tile does not yet have a color,
# but the previous tile does, so assign the opposite color
m[c] = 1 - m[prev]
prev = c
return True
```
[Answer]
# JavaScript, 98 bytes
*-3 bytes by Arnauld*
```
a=>a.every(m=l=>a=!l.some((c,x)=>m[v=a[x],u=l[x-1]]==(M=m[c]??=-m[u??v]|1)&&c-u||m[v]==M&&c-v)&&l)
```
```
f=
a=>a.every(m=l=>a=!l.some((c,x)=>m[v=a[x],u=l[x-1]]==(M=m[c]??=-m[u??v]|1)&&c-u||m[v]==M&&c-v)&&l)
testcases = `
0
00
00
012
0011
2013
2233
01234
56789
ABCDE
FGHIJ
000
010
002
01
22
00
12
01
02
01234
05674
0011
0221
3244
3345
`.trim().split('\n\n').map(x => x.trim().split('\n').map(l => [...l].map(v => Number.parseInt(v, 36) + 1)));
testcases.forEach(t => {
console.log(f(t));
});
```
Input a 2-d array with positive numbers.
Output true / false.
```
a=>a.every( // For each row
m= // m is the mapping from regions to its color (-1 or 1)
l=>
a= // `a` is reused to storage last row
!l.some((c,x)=>
m[
v=a[x], // `v` is its upper neighbor
u=l[x-1] // `u` is its left neighbor
]==(
M=m[c]??= // If we haven't assign a color to current grid, assign color
-m[u??v]|1 // If this is first column, we use its upper neighbor
// Otherwise we use its left neighbor
// We use different color to its neighbor
// If this is the most top left one, we use 1
)&& // If this cell have same color with its left neighbor
c-u|| // But they are in different region
m[v]==M&&c-v // Check its upper neighbor this time
)&&l // Assign `l` to `a` for so you can access it when check next row
)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 108 bytes
```
->a{w,i,j,q=0;a.map{|x|w,i=(j=x.zip(j||x).map{|y,c|[y==i ?w:w^=1,i=y,q||=((c[0]==w)^(c[1]==i))&&j]})[0]};!q}
```
[Try it online!](https://tio.run/##fZDhaoMwFIX/@xR3f4qBu@JV164rt3uQkIIrFBQKOhjGNT67vYlautIOArnn5MvhJN8/X91w5OF1V5xbLLHChpNtsTwV9dlZJxbHFdvlb1nHlXNWjScdHpzumEv4bD/aPZNwHTbOcRwfdGKYW7WXiWQqlVosKtMr8fvtS9MPGgC0KIMRjCNCYhDG/dYlhPQvFjzycDqrbFKyMq/uA4Kde@gNYYWwRnhH2HiDPOIDBSKhKGAkHAlIQpKgtLnvMLelm@Khqpl/rgZt8aitMX0U6Wudueo/JcW49syfPT4JV9JJZWHMp4BszJKYx32GCw "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~36~~ ~~33~~ ~~27~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Prints 1 if the input is a checkered tiling and 0 if not.
```
˜Ù2.Œε€ã€`€ÙIDø«€ü2€`Ãg]0å
```
[Try it online!](https://tio.run/##yy9OTMpM/f//9JzDM430jk46t/VR05rDi4FEAogx09Pl8I5Dq0HMPUYgwcPN6bEGh5f@/x8dbaBjqGOkY6xjEqsDZJvqmOmYA9mxAA "05AB1E – Try It Online") or [Try more cases](https://tio.run/##XZDBboMwEETv/oo59OgSswYCFeqprdRTPyDiYC9WQKpClURq/p4uBlpSW7IH78xbG@8u3Xi7tXg84xk8tCEZLs73AXWN14@30SzjCewrBtuqgiUK4LwicPA5ApUEx2zhbCAgkUHJ31AzIRVGSY5RGHFFFWlZlWWifAkm52ca1uz7yx2DhBE7eba0Ni6MxEuLYp@3sGa6Rw5ExnKNY2OSZJTnKMXuun2mCtwNSn13/WfAObgW/Um1gwJ2w9d1N5uW7d/vqfEQvacwHg6maZSs2jQ6rvNXqmk9F51KjaKyUZG2otb6nExXwm9yTtGGn97VNs5IzOJZrgu9F33fXbwyJ2Vlz6LXThmdi/MH).
This tests if the graph of polyominoes is bipartite by trying all partitions into two subsets until it finds one where no polyominoes in the same subset are adjacent.
Technically `Ù` is not necessary, but this is already quite slow and would be unusable otherwise.
```
˜Ù # all unique integers from the input
2.Œ # all ways to partition those into two subsets
ε # for each partition:
€ã€` # generate pairs of two elements from the same subset
€Ù # deduplicate each pair, if both values were equal, this results into a singleton list
IDø« # input and input transpose concatenated (list of rows and columns)
۟2 # for each row or column: get all adjacent pairs
€` # and flatten into a single list of pairs
à # list intersection with the list from before
g # take the length
]0å # after the map: was the result 0 for any partition?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
FQŒPðfLḂɗþPẸµ;Z,Ɲ€ẎEÐḟ
```
[Try it online!](https://tio.run/##y0rNyan8/98t8OikgMMb0nwe7mg6Of3wvoCHu3Yc2modpXNs7qOmNQ939bkenvBwx/z/h9uB3P//o7m4oqMNdBQgyFBHwShWh0sBJGIMRkYwERMdBVOYiBlMBIjMgVwMERCKBQqBzIbRQAtgRiOJgW1EqAALGILVGcG4xjCuEcRRUOUgWZA0SBgkrmACVgdyJchFIDcoWACxJVjYEGQWyGygakOgakMTFFvhTjNEdiaK2@CuMkL3kSEWdWh6YY43gUmagoPNHCSC1fcGkKCHcSHhbgIzABI3oCiJjeXiigUA "Jelly – Try It Online") (comes with test cases)
Uses the same approach as [my Pyth answer](https://codegolf.stackexchange.com/a/230365/30164) and [ovs's 05AB1E solution](https://codegolf.stackexchange.com/a/230360/30164).
Turns out I just needed a love-hate relationship to Jelly for like 3 years to finally understand how the chains work.
### Explanation
```
FQŒPðfLḂɗþPẸµ;Z,Ɲ€ẎEÐḟ
F Flatten the input rows.
Q Find unique characters (polyominos).
ŒP Get all subsets of the characters.
Z Get the columns of the input.
; Append them to the input rows.
,Ɲ Get all overlapping pairs...
€ ...of each row/column. (Alternatively, ṡ€2.)
Ẏ Concatenate the lists of pairs.
Ðḟ Filter for pairs where...
E ...the elements are not equal.
þ For each subset/pair combination:
f Find items in the subset that are also in the pair.
L Take the length of the result.
Ḃ Take the length modulo 2.
This gives a 2D array where the outer index specifies
the pair and the inner index the subset.
P Take an elementwise product of the rows. This gives
1 for each subset that results in a product of 1.
Ẹ See if there are any subsets that produced a 1.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes
```
WS⊞υι≔⭆υ⭆ι⁺⎇κ⁺§§υ⊖κμλω⎇μ⁺§ι⊖μλωθ≔⁻⪪⁺θ⮌θ²Eθ⁺ιιη⊙η⊙θ⬤ι№η⁺λν
```
[Try it online!](https://tio.run/##XY/LjsIwDEX3@YosHSlIfc2KVcVsWCBVw/xAVSwSkYY2Dxi@PuMwHRBEunIc3@PYg@rdcO5NSlelDXLY2imGfXDaHkEI3kWvIEquxZq13uujhb/irp/y@zPRkncmevhGZ3t3g9OSt2FrD/jziAR94uBwRBvwACchJB9JhnQl/fPjG69fuVE8GJGv83PAnbbE7SejA9xbzJJ/4QWdR5iztyLlkeflC533ywVFTTpaKEBrb6Akz4FcrTHZtDlHKqmFMpJbcT/rlIqiLFlRVSWrq6Zhdd18sLS6mF8 "Charcoal – Try It Online") Link is to verbose version of code. Reverse output, i.e. `-` if not chequered. Explanation:
```
WS⊞υι
```
Input the tiling.
```
≔⭆υ⭆ι⁺⎇κ⁺§§υ⊖κμλω⎇μ⁺§ι⊖μλωθ
```
For each cell, concatenate it with the cell above and to the left (if any) and concatenate all of the results together.
```
≔⁻⪪⁺θ⮌θ²Eθ⁺ιιη
```
Concatenate that with its reverse, split it back into pairs, but remove all identical pairs.
```
⊙η⊙θ⬤ι№η⁺λν
```
Does there exist a pair in the adjacency list and a cell having the property that the cell is adjacent to both cells in the pair?
A port of @Jakque's answer is the same length but much faster:
```
WS⊞υι⊙υ∧κ⊙ι∧μ¬⁼⁼⁼λ§ι⊖μ⁼§§υ⊖κ짧υ⊖κ⊖μ⁼⁼맧υ⊖κμ⁼§ι⊖짧υ⊖κ⊖μ
```
[Try it online!](https://tio.run/##nY9NCoMwEIX3OUWWM2DBv65cCe3CTRF6gqChBmNsNWnr6VNDFamCi87mMcM3894UFeuKlklrX5WQnEKm7kZfdSfUDRBpbvoKjEcFJiQfhxpSNbhBqkqonQwgvl3j0Uur4fwwTPYrkSOiM1Xyt6NPvOh4w5Xm4xYienTCZmZW88vWDm1wubXHrU0Wl22mfb9tvu0Pf2aaKrHW94OA@GEYkCiMYxJF8ZHYw1N@AA "Charcoal – Try It Online") Link is to verbose version of code. Reverse output, i.e. `-` if not chequered.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 25 bytes
```
sm!-ml@dk{I#s.:R2+CQQ1y{s
```
[Try it online!](https://tio.run/##K6gsyfj/vzhXUTc3xyElu9pTuVjPKshI2zkw0LCyuvj//@hoAx0FIDIEolgdhWgjGM8YygMiYxAvFgA "Pyth – Try It Online")
Might time out on test cases with lots of unique characters (polyominos).
Turns out I came up with the exact same algorithm as [ovs's 27-byte 05AB1E answer](https://codegolf.stackexchange.com/a/230360/30164) ¯\\_(ツ)\_/¯
### Explanation
Essentially, the program tries all colorings of the tiling, and sees if there is a coloring for which all adjacent pairs have exactly one black tile.
`Q` is implicitly appended to the program and the input is read into `Q`.
```
sQ Concatenate the input rows.
{ Find unique characters in input.
y Take the powerset of these.
m For each subset d of the characters:
CQ Get the columns of the input.
+ Q Append the rows of the input.
.: 2 Get length-2 substrings...
R ...of each row/column.
s Concatenate the substring lists of rows/columns.
# Find substrings (pairs) that...
I ...stay the same when...
{ ...duplicates are removed.
m For each such pair k:
@dk Find the characters of k that are in d.
l Get the length of that.
- 1 Remove all ones from that array of lengths.
! True if the list is now empty.
s Sum the booleans in that list.
```
[Answer]
# Julia 1.5, ~~128~~ 99 bytes
```
M->(~M=diff(M,dims=1).!=0;!M=~x[M]!=~M;x=1:max(M...).>0;while(s=x[end])&&!M|!M' x.chunks.-=1end;s)
```
This basically tests each possible way of assigning each number either a 0 or 1 value, and determines whether the assignment keeps the number of boundaries constant (if two adjacent tiles are coloured the same, the boundary between them is removed).
M should take the form of an array of small positive integers (no zero or negatives).
This uses BitVectors - as it turns out, a bitvector is stored internally as an integer, so you can iterate through all combinations by incrementing the bitvector's internal representation (accessed as a "chunks" property of the variable).
**Ungolfed**:
```
function f(M)
# This is the function you use to determine whether the tiling is chequered.
x=trues(maximum(M)) #Initialise a bitarray, representing the assignment of tiles
while x[end] #Loop until the assignment of the last tile is changed
#from that point, all assignments are just bit-flips of the ones before!
if (diff(M,dims=1).!=0)==(diff(x[M],dims=1).!=0)
if (diff(M',dims=1).!=0)==(diff(x[M'],dims=1).!=0)
break #If both horizontal and vertical boundaries are retained...
#a successful tiling has been found!
end
end
x.chunks.+=1 #Move to the next tile assignment
end
return x[end] #x[end] is true if it finds a successful tiling
#but the loop ends if x[end] becomes false, indicating
#that no tiling is found.
end
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 109 bytes
```
1`(?<=(.)*)(.)(?(\2).+¶(?>(?<-1>.)*)(?!\2)(.)(?!\2|\3)|(.).*¶(?>(?<-1>.)*)(?(\2).(?!\2|\4)|(?!\4)(.)(\4|\5)))
```
[Try it online!](https://tio.run/##K0otycxL/P/fMEHD3sZWQ09TSxNIaNhrxBhp6mkf2qZhbweU0DW0A8vYKwKFwfJARk2MsWYNkKOnhaEMrBuqyASoCMgyAeuLMamJMdXU1Pz/38DA0JDLwMjIkMvYyMSEy9jYxBQA "Retina 0.8.2 – Try It Online") Reverse output, i.e. `1` if not chequered (-2 bytes if arbitrary non-zero output is allowed for not chequered). Explanation: Port of @Jakque's Python answer.
```
1`
```
Only look for 1 match.
```
(?<=(.)*)
```
Count the column of this cell.
```
(.)
```
Capture the top left cell of a 2×2 square.
```
(?(\2)...|...)
```
If the top right cell of the square has the same symbol, ...
```
.+¶(?>(?<-1>.)*)
```
Skip ahead to the bottom left cell of the square.
```
(?!\2)
```
This must not have the same symbol as the top left cell.
```
(.)(?!\2|\3)
```
The bottom right cell must not have the same symbol as either of the other cells.
```
(.)
```
Otherwise, capture the top right cell of the square.
```
.*¶(?>(?<-1>.)*)
```
Skip ahead to the bottom left cell of the square.
```
(?(\2).(?!\2|\4)|(?!\4)(.)(\4|\5))
```
If this has the same symbol as the top left cell, then check that the bottom right cell does not have the same symbol as the either of the other cells, otherwise check that the bottom left cell does not have the same symbol as the top right cell but the bottom right cell has the same symbol as either the top right or bottom left cell.
[Answer]
# [Haskell](https://www.haskell.org/), 111 bytes
```
w=zipWith
s=scanl
f(x,a)b=(x/=(a/=b),b)
u(a:b)=s f(1>0,a)b
z x@(a:b)=w(.tail)(s f<$>u(head<$>x))x==s(w f)(u a)b
```
[Try it online!](https://tio.run/##fYsxDoMwDEX3nCIDgy1FpaFbVaPeogNicAqIqCmgBkTE5dNA98rD@/r/uWf/ap2LcaXNTg8798KTf/LgRAdBMRqCkBNwTgaVQbEAXw2Slx3o8rwLYpPh/mtXOM1sHUKab1m5QN9yk0JADEQeVtkhLDI9xTfbgZpRSDl97DBnW1UVqlC6Von64EWlq2vxz9GHs1PvbvwC "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 116 bytes
```
f(x,a)b=(x/=(a/=b),b)
(i#j)(a:b)=scanl i(j a)b
k=w f#(f#(,)(1>0))
e=[]:e
t=foldr(w(:))e
w=zipWith
z=((==).t.k.t)<*>k
```
[Try it online!](https://tio.run/##fcpBCoMwEIXh/ZwiYBczJWhjd9LxGl2Ii1gVY1IVDShePlUPUN6Df/N1erGNcyG0uElNFeOWMOqEK5IVAZqoJ9RZRbx89OCEwV4cDCyvoo3wuCRU@YMIGi7KrAHP7ejqGVfMiBpYeTfT2/gOdkZkptjHNvb0uuc2fLUZuB5BiGk2g7/tRZHKVKpSHlVXn/JYWcI/oy5zVp02/AA "Haskell – Try It Online")
Probably not going to win any awards, but I had fun with both of these. They are a bit incomprehensible.
] |
[Question]
[
## The problem:
Given a non-empty set of points in the Cartesian plane, find the smallest circle that encloses them all ([Wikipedia link](https://en.wikipedia.org/wiki/Smallest-circle_problem)).
This problem is trivial if the number of points is three or less (if there's one point, the circle has a radius of zero; if there are two points, the line segment that joins the points is the diameter of the circle; if there are three (non-colinear) points, it's possible to get the equation of a circle that touches them all if they form a non-obtuse triangle, or a circle that touches only two points and encloses the third if the triangle is obtuse). So, for the sake of this challenge, the number of points should be greater than three.
## The challenge:
* **Input:** A list of 4 or more non-colinear points. The points should have X and Y coordinates; coordinates can be floats. To ease the challenge, no two points should share the same X coordinate.
For example: `[(0,0), (2,1), (5,3), (-1,-1)]`
* **Output:** A tuple of values, `(h,k,r)`, such that \$(x-h)^2 + (y-k)^2 = r^2\$ is the equation of the smallest circle that encloses all points.
## Rules:
* You can choose whatever input method suits your program.
* Output should be printed to `STDOUT` or returned by a function.
* "Normal", general-purpose, languages are preferred, but any esolang is acceptable.
* You can assume that the points are not colinear.
* This is code-golf, so the smallest program in bytes wins. The winner will be selected one week after the challenge is posted.
+ Please include the language you used and the length in bytes as header in the first line of your answer: `# Language: n bytes`
## Test cases:
* 1:
+ Input: `[(-8,0), (3,1), (-6.2,-8), (3,9.5)]`
+ Output: `[-1.6, 0.75, 9.89]`
* 2:
+ Input: `[(7.1,-6.9), (-7,-9), (5,10), (-9.5,-8)]`
+ Output: `[-1.73, 0.58, 11.58]`
* 3:
+ Input: `[(0,0), (1,2), (3,-4), (4,-5), (10,-10)]`
+ Output: `[5.5, -4, 7.5]`
* 4:
+ Input: `[(6,6), (-6,7), (-7,-6), (6,-8)]`
+ Output: `[0, -0.5, 9.60]`
Happy golfing!!!
---
## Related challenge:
* [Area of a 2D convex hull](https://codegolf.stackexchange.com/questions/183191/area-of-a-2d-convex-hull/)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~28~~ 27 bytes
```
#~BoundingRegion~"MinDisk"&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7nOKb80LyUzLz0oNT0zP69OyTczzyWzOFtJ7X9AUWZeSXRadHW1roWOQa2OQrWxjiGI0jXTM9LRtYCIWOqZ1tbGxnIhVJvrGeoAlViClZrr6IIZpjqGYCN0gepBelG1GEDMN9QxghiqawKiTXR0TcHCBjq6QN2oWsx0zCBu0TGHWQQWMIOa/h8A "Wolfram Language (Mathematica) – Try It Online")
Built-ins are handy here. Output is a disk object with the centre and radius. Like others, I’ve found the 2nd and 3rd test cases to be different to the question.
Thanks to @lirtosiast for saving a byte!
If a list is required as output, [this can be done in 35 bytes (at the cost of an additional 8 bytes)](https://tio.run/##VY7BCoJAEIbvPUUYdJoR19xVD4FF1yC6igfJ1ZZwlbLToq@@rbtFeJrh5/v@mbYc7rwtB3Erdb3Xh77nssqyzXTs3rISsrnyRnRy8s5CnsTr4W315SnkkNe5UphAMMJa7YDMA5kfAiYuSX06jkWx@tOxT8AgqUVjQLtQILYCDT@7SyVw/QRCV4rRPCNAauMA0NhLhQFzv0D8O2QD9m3XHw). Thanks to @Roman for pointing this out.
[Answer]
# JavaScript (ES6), ~~298 ... 243~~ 242 bytes
Returns an array `[x, y, r]`.
```
p=>p.map(m=([c,C])=>p.map(([b,B])=>p.map(([a,A])=>p.some(([x,y])=>H(x-X,y-Y)>r,F=s=>Y=(d?((a*a+A*A-q)*j+(b*b+B*B-q)*k)/d:s)/2,d=c*(A-B)+a*(j=B-C)+b*(k=C-A),r=H(a-F(a+b),A-F(A+B,X=Y,j=c-b,k=a-c)))|r>m?0:o=[X,Y,m=r]),q=c*c+C*C),H=Math.hypot)&&o
```
[Try it online!](https://tio.run/##TU/JbsJADL3zFTkhe2JPIS3QVnKqJBLi0jsoymGydIGmkyYRAqn/TrMI0ZP9nt8i783RNFn9WbX8bfPi8iaXSvxKl6aCUiDOKErwSkCcUvgfGgpG2Niy6PCJzj3ewIm3dOYd@jWtpRF/J5C/ABhl3EAF/INq70KqUjdUYY8OeJc/N3jnUS6ZgoBDdI2CvYQcoZsqOEjEAVItGzC8BuOmSEG3BG5IW9nRXjJO6SCGM0T8rf3yZfZsJd7SjkqpE6SfLjhzIxUhbeTVtB/641zZFqdTe2mLpnXEMY74Tma/G/tV6C/7DlrrNzA4fHvsj0fd2vXnqcjB62omk94IccyPNEvIie9p3g9eao/4cWSe9CJJ8Kpc6Tl156dBtiIelgXNBzt32t53k8/G3Dl5Yxg/9POBeDHQM@LOeZMvaTn20@paMBDLMfXyBw "JavaScript (Node.js) – Try It Online")
or [see a formatted version](https://tio.run/##bVLBbtpAEL37K94p2m1nt0ADJJWgAkuIS@9Blg@L7TQhIetgCxGp/05n1iG2055m9N68eW@83rmjq7LDY1mbF58X5/vZucRsHgGl3btS7TGDSjJCnOoGvzAq2RKWLdrijrDo4sJUfl8wdSK89SlgrU4wuGOGy0ZjjgN16BUnqPoKYCOxegiQ4@cnBFDK4QscvmLBdcEGr5qbHQNqy82WmyXX5YV50viG/NOeH//srXqIaEbdzDnHy3ibEselZhOJoXYMi1MsiNirJ0ZiRha6Kz8wuu6f53hopeSQbW8U4agVG/EhhDtWbgi74G/ALyQOIs50R9X2Gn/Ybo597@MNov@d7nlVwu/EBvJbHNJ37iPQ6/vZGYeJucZRh14z@cvVD/bhrfR1JNZXV/DnuqjqkHE2R@ZfKv9c2Gf/W1lr75XT4Z86Cnm0tV89nopcjbTWUSRClSTmhgYpIflOQylmYkdkbhrk1o7TVF8mp3ZITN@GsSmZ0IxpGOSGZ0XXjg@avUMaNcvMtdRrMuMAD8iwsh2f0KTxp@nFIACTZuv5Lw)
## How?
### Method
For each pair of points \$(A,B)\$, we generate the circle \$(X,Y,r)\$ whose diameter is \$AB\$.
$$X=\frac{A\_x+B\_x}{2},\;Y=\frac{A\_y+B\_y}{2},\;r=\sqrt{\left(\frac{A\_x-B\_x}{2}\right)^2+\left(\frac{A\_y-B\_y}{2}\right)^2}$$
For each triple of distinct points \$(A,B,C)\$, we generate the circle \$(X,Y,r)\$ which circumscribes the triangle \$ABC\$.
$$d=A\_x(B\_y-C\_y)+B\_x(C\_y-A\_y)+C\_x(A\_y-B\_y)$$
$$X=\frac{({A\_x}^2+{A\_y}^2)(B\_y-C\_y)+({B\_x}^2+{B\_y}^2)(C\_y-A\_y)+({C\_x}^2+{C\_y}^2)(A\_y-B\_y)}{2d}$$
$$Y=\frac{({A\_x}^2+{A\_y}^2)(C\_x-B\_x)+({B\_x}^2+{B\_y}^2)(A\_x-C\_x)+({C\_x}^2+{C\_y}^2)(B\_x-A\_x)}{2d}$$
$$r=\sqrt{(X-A\_x)^2+(Y-A\_y)^2}$$
For each generated circle, we test whether each point \$(x,y)\$ is enclosed within it:
$$\sqrt{(x-X)^2+(y-Y)^2}\le r$$
And we eventually return the smallest valid circle.
### Implementation
In the JS code, the formula to compute \$(X,Y)\$ for the triangle's circumscribed circle is slightly simplified. Assuming \$d\neq0\$, we define \$q={C\_x}^2+{C\_y}^2\$, leading to:
$$X=\frac{({A\_x}^2+{A\_y}^2-q)(B\_y-C\_y)+({B\_x}^2+{B\_y}^2-q)(C\_y-A\_y)}{2d}$$
$$Y=\frac{({A\_x}^2+{A\_y}^2-q)(C\_x-B\_x)+({B\_x}^2+{B\_y}^2-q)(A\_x-C\_x)}{2d}$$
This way, the helper function \$F\$ requires only two parameters \$(j,k)\$ to compute each coordinate:
* \$(B\_y-C\_y,\;C\_y-A\_y)\$ for \$X\$
* \$(C\_x-B\_x,\;A\_x-C\_x)\$ for \$Y\$
The third parameter used in \$F\$ (i.e. its actual argument \$s\$) is used to compute \$(X,Y)\$ when \$d=0\$, meaning that the triangle is degenerate and we have to try to use the diameter instead.
[Answer]
# [R](https://www.r-project.org/), 59 bytes
```
function(x)nlm(function(y)max(Mod(x-y%*%c(1,1i))),0:1)[1:2]
```
[Try it online!](https://tio.run/##dc5NCoMwEAXgfU@RjZA0GcmkGn@gR@gJSheiCIJGsRX09OnEQikFNy88yDczs2/Zlfl2cfWrGx1fhesH/q2bGKqV38aGr7BF56jmqLATQihdorhjaR7@WU1Tv/GW1xxyqTvFLhIpwcYG8r0WcUpIsXlcXKOYEacflMVIX4sgMghPKjFMAVLkD51WDKUJ8yGhTCClRA2ED42Vdr9MZp91odn/Jf4N "R – Try It Online")
Takes input as a vector of complex coordinates. `Mod` is the distance (modulus) in the complex plane and `nlm` is an optimization function: it finds the position of the center (output as `estimate`) which minimizes the maximum distance to the input points, and gives the corresponding distance (output as `minimum`), i.e. the radius. Accurate to 3-6 digits; the TIO footer rounds the output to 2 digits.
`nlm` takes a numeric vector as input: the `y%*%c(1,1i)` business converts it to a complex.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~100~~ 98 bytes
```
_²§½
1ịṭƊZIṚṙ€1N1¦,@ṭ@²§$µḢZḢ×Ø1œị$SḤ÷@P§
ZṀ+ṂHƲ€_@Ç+ḷʋ⁸,_²§½ʋḢ¥¥
œc3Ç€;ŒcZÆm,Hñ/$Ʋ€$ñ_ƭƒⱮṀ¥Ðḟ⁸ṚÞḢ
```
[Try it online!](https://tio.run/##y0rNyan8/z/@0KZDyw/t5TJ8uLv74c61x7qiPB/unPVw58xHTWsM/QwPLdNxAAo7gFSpHNr6cMeiKCA@PP3wDMOjk4FaVIIf7lhyeLtDwKHlXFEPdzZoP9zZ5HFsE1BzvMPhdu2HO7af6n7UuEMHas2pbqDuQ0sPLeU6OjnZ@HA7UJ310UnJUYfbcnU8Dm/UVwFrVTm8Mf7Y2mOTHm1cBzTy0NLDEx7umA80Beiww/OABvz//z9aw0DHQFNHQcNQxwhEGevomoBoEx1dU7CwgY6uoYFmLAA "Jelly – Try It Online")
In contrast to [my Wolfram language answer](https://codegolf.stackexchange.com/a/187318/42248), Jelly needs quite a lot of code to achieve this (unless I’m missing something!). This full program takes the list of points as its argument and returns the centre and radius of the smallest enclosing circle. It generates circumcircles for all sets of three points, and diameters for all sets of two points, checks which include all of the points and then picks the one with the smallest radius.
Code for the make\_circumcircle bit was inspired by code at [this site](https://www.nayuki.io/res/smallest-enclosing-circle/smallestenclosingcircle.py), in turn inspired by Wikipedia.
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), ~~244~~ 242 bytes
```
P={complex(*p)for p in input()}
Z=9e999,
for p in P:
for q in{p}^P:
for r in{p}^P:R,S=1j*(p-q),q-r;C=S.imag and S.real/S.imag-1jor 1;c=(p+q-(S and(C*(p-r)).real/(C*R).real*R))/2;Z=min(Z,(max(abs(c-t)for t in P),c.imag,c.real))
print Z[::-1]
```
[Try it online!](https://tio.run/##PY7RasMwDEWfl6/wo9RZ6VzoWif4qT9QmreUDrIs61IaR/E8aCj99sxJoCDQPdK9Qtz7n9auiHvuh2Fv7mXb8LW6wYLxu3WCRW1D8Z8HfES50ZXWWkbP1T6JxAhdgDs/PgK/jOyefJCZUZcFMHUoO3LpzmRx3RRnUdgvkcWuKq7LeULqEqIqLQ3wa0eQjRbYjVmHODsDHmYZOi5XaW6a2kIuoSluUHz@Qkl@et1P/6Esp9uhjSHEiF1tvciPSULqNAxH2MRK0nusUQqgjaRJrKV6mwY6Xkva4ukf "Python 2 (PyPy) – Try It Online")
This uses the brute-force O(n^4) algorithm, iterating through each pair and triangle of points, calculating the centre, and keeping the centre that needs the smallest radius to enclose all points. It calculates the circumcentre of 3 points via finding the intersection of two perpendicular bisectors (or, if two points are equal it uses the midpoint with the third).
[Answer]
# APL(NARS), 348 chars, 696 bytes
```
f←{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}
c←{⍵≡⍬:1⋄(x r)←⍵⋄(-r*2)++/2*⍨⍺-x}
p←{(b k)←⍺ ⍵⋄∧/¨1e¯13≥{{⍵{⍵c⍺}¨b}k[⍵]}¨⍳≢k}
s2←{(+/k),√+/↑2*⍨-/k←2÷⍨⍵}
s3←{0=d←2×-.×m←⊃{⍵,1}¨⍵:⍬⋄m[;1]←{+/2*⍨⍵}¨⍵⋄x←d÷⍨-.×m⋄m[;2]←{1⊃⍵}¨⍵⋄y←d÷⍨--.×m⋄(⊂x y),√+/2*⍨(x y)-1⊃⍵}
s←{v/⍨⍵p v←(s2¨2 f⍵)∪s3¨3 f⍵}
s1←{↑v/⍨sn=⌊/sn←{2⊃⍵}¨v←s⍵}
```
This is one 'implementation' of formulas in Arnauld solution...Results and comments:
```
s1 (¯8 0)(3 1)(¯6.2 ¯8)(3 9.5)
¯1.6 0.75 9.885469134
s1 (7.1 ¯6.9)(¯7 ¯9)(5 10)(¯9.5 ¯8)
¯1.732305109 0.5829680042 11.57602798
s1 (0 0)(1 2)(3 ¯4)(4 ¯5)(10 ¯10)
5.5 ¯4 7.5
s1 (6 6)(¯6 7)(¯7 ¯6)(6 ¯8)
0 ¯0.5 9.604686356
s1 (6 6)(¯6 7)(¯7 ¯6)(6 ¯8)(0 0)(1 2)(3 ¯4)(4 ¯5)(10 ¯10)
2 ¯1.5 11.67261753
s1 (6 6)(¯6 7)(¯7 ¯6)(6 ¯8)(1 2)(3 ¯4)(4 ¯5)(10 ¯10)(7.1 ¯6.9)(¯7 ¯9)(5 10)(¯9.5 ¯8)
1.006578947 ¯1.623355263 12.29023186
s1 (1 1)(2 2)(3 3)(4 4)
2.5 2.5 2.121320344
⎕fmt s3 (1 1)(2 2)(3 3)(4 4)
┌0─┐
│ 0│
└~─┘
```
f: finds the combination of alpha ojets in the omega set
```
f←{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}
```
((X,Y), r) from now represent one circonference of radius r and center in (X Y).
c: finds if the point in ⍺ is inside the circumference ((X Y) r) in ⍵ (result <=0) ot it is external (result >0)
In the case of circumference input in ⍵ it is ⍬ as input, it would return 1 (out of circumference)
each possible input in ⍺.
```
c←{⍵≡⍬:1⋄(x r)←⍵⋄(-r*2)++/2*⍨⍺-x}
```
p: if ⍵ is an array of ((X Y) r); for each of the ((X Y) r) in ⍵
writes 1 if all points in the array ⍺ are internal to ((X Y) r) otherwise writes 0
NB Here's something that do not goes because I had to round to epsilon= 1e¯13.
in other words in limit cases of points in the plane (and probably built on purpose)
it is not 100% solution insured
```
p←{(b k)←⍺ ⍵⋄∧/¨1e¯13≥{{⍵{⍵c⍺}¨b}k[⍵]}¨⍳≢k}
```
s2: from 2-point in ⍵, it returns the circumference in the format ((X Y) r)
that has diameter in those 2 points
```
s2←{(+/k),√+/↑2*⍨-/k←2÷⍨⍵}
```
s3: from 3 points it return the circumference in the format ((X Y) r) passing through those three points
If there are problems (for example points are aligned), it would fail and return ⍬.
```
s3←{0=d←2×-.×m←⊃{⍵,1}¨⍵:⍬⋄m[;1]←{+/2*⍨⍵}¨⍵⋄x←d÷⍨-.×m⋄m[;2]←{1⊃⍵}¨⍵⋄y←d÷⍨--.×m⋄(⊂x y),√+/2*⍨(x y)-1⊃⍵}
```
note that -.× find the determinant of a matrix nxn and
```
⎕fmt ⊃{⍵,1}¨(¯8 0)(3 1)(¯6.2 ¯8)
┌3─────────┐
3 ¯8 0 1│ |ax ay 1|
│ 3 1 1│ d=|bx by 1|=ax(by-cy)-bx(ay-cy)+cx(ay-by)=ax(by-cy)+bx(cy-ay)+cx(ay-by)
│ ¯6.2 ¯8 1│ |cx cy 1|
└~─────────┘
```
s: from n points in ⍵, it finds the type circumferences of those found by s2 or those of type s3
that contain all n points.
```
s←{v/⍨⍵p v←(s2¨2 f⍵)∪s3¨3 f⍵}
```
s1: from the set found from the s above calculates those that have minimum radius and returns
the first one that has minimal radius. The three numbers as arrays
(the first and second coordinates are the coordinates of the center, while the third is the
radius of the circumference found).
```
s1←{↑v/⍨sn=⌊/sn←{2⊃⍵}¨v←s⍵}
```
[Answer]
# [Python](https://www.python.org/) ~~212~~ 190 bytes
This solution is incorrect, and I have to work now so I do not have time to fix it.
```
a=eval(input())
b=lambda a,b: ((a[0]-b[0])**2+(a[1]-b[1])**2)**.5
c=0
d=1
for e in a:
for f in a:
g=b(e,f)
if g>c:
c=g
d=[e,f]
print(((d[0][0]+d[1][0])/2,(d[0][1]+d[1][1])/2,c/2))
```
[Try it online!](https://tio.run/##NY3LCoMwEEXX5iuynNj4SMRihfRHxEVijA1YFbGFfr2daAvzOmcWd/lsj3kq9l2r/q1H8NPy2oAxYtSon8ZqqrmpKYBu8jYxOFgcywuiCCgOxE5L0qmcWCWIm1faUz9RXZMogPtDNCgDPXcMT@/ocO@CjDo1hGVVg7@WLKufNgCwGIZ1sZgScjPJTyd@ThyuyyRj@95AUvGccQoFF2El11TypDrNLS1Z@wU)
I figured out which two points are furthest and then I generated an equation for a circle based off those points!
I know this isn't the shortest in python, but it's the best I could do! Also this is my first attempt at doing one of these, so please be understanding!
] |
[Question]
[
Can you recover a sequence of letters from a sequence of dots and dashes? In Morse code, `x` is represented by `-..-`, but without the help of spaces, `-..---.-...` could represent `xmas`, or `dole`, or `teettteteee`, etc.
I took the lyrics from "Rudolph, the Red-Nosed Reindeer" to make the following sequence of letters:
```
youknowdasheranddancerandprancerandvixencometandcupidanddonnerandblitzenbutdoyourecallthemostfamousreindeerofallrudolphtherednosedreindeerhadaveryshinynoseandifyoueversawityouwouldevensayitglowsalloftheotherreindeerusedtolaughandcallhimnamestheyneverletpoorrudolphjoininanyreindeergamesthenonefoggychristmasevesantacametosayrudolphwithyournosesobrightwontyouguidemysleightonightthenhowthereindeerlovedhimastheyshoutedoutwithgleerudolphtherednosedreindeeryoullgodowninhistory
```
and then I converted each letter to its Morse code representation to get
```
-.-----..--.--.---.---...-.........-..--.-..-...--.-.-...-..--.-...--..-..--.-.-...-..--.-.....-..-..-.-.-.-.-----.-.--.-..-.-...-.--...-...--.-..-..----.-...-..--.-..-....-....---...-.-.....---..----.-----..-.-..-.-..-.-...-..-.....-----...-..-..------..-....-....-.-.....-.---..-..-.-...-...-...--..---.-...--.....-......-..-..-.---....-...-....-.-.....-......--...-...-..-.-.--.........-.-.---.---.....--.-......-.-.-----..-....-..-.....-.--..--.-----..-.-----..-.-..-......-.-.....--.--..---..-..---.--....-.-...-..---..-.-.....----......-..-....-.-.....-...-....-..----.-...-..---......--.-..-.-..-.-...-........---..---....-.....-.---.....-..-..-...-.--.------.-..-...--..---.-...--......------..-...-..--.-.--.-....-.-.....-.--..---....-.....-.----....-.-----.--.-.---.-......-......---.-.......-.....--.-.--.-..---.----....--.--.-...--..---.-...--......--..-....-.-----..-.-.-.---.......----....-...--.....-.------.--.-----..---...-..-...---.--....-.....--.....-----...--.....--.....-.....---.---......-....-.-.....-..-..---...-.-........--.-...-.....-.--.......---..--.-..---..--.--..-....--..-.....-...--..---.-...--.....-......-..-..-.---....-...-....-.-.....-.-.-----..-.-...-..--.----..---.---...-..........----.-.-.--
```
For reference, here are a few Morse code libraries:
```
a .- b -... c -.-. d -.. e . f ..-. g --. h .... i .. j .--- k -.- l .-.. m -- n -. o --- p .--. q --.- r .-. s ... t - u ..- v ...- w .-- x -..- y -.-- z --..
```
```
.- a -... b -.-. c -.. d . e ..-. f --. g .... h .. i .--- j -.- k .-.. l -- m -. n --- o .--. p --.- q .-. r ... s - t ..- u ...- v .-- w -..- x -.-- y --.. z
```
```
.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..
```
Write the shortest code that takes as input the sequence of dots and dashes above and one of the Morse code libraries above, and then outputs the sequence of letters above.
**Edit 1:** Since we are ignoring [the letter spaces and word spaces that are typically used in Morse code](https://en.wikipedia.org/wiki/Morse_code#Timing), this challenge is nontrivial and significantly different from [previous challenges involving Morse code](https://codegolf.stackexchange.com/questions/tagged/morse). We are implicitly hunting for the *relative Kolmogorov complexity* of a fixed sequence of letters given the corresponding sequence of dots and dashes. This means your code only needs to run for the fixed inputs provided above, and produce the desired output provided above.
**Edit 2:** By popular request, I am relaxing the constraint on the Morse code library by providing two alternative libraries. If necessary, I am willing to add reasonable libraries in the future.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~356, 302,~~ 299 bytes
```
import sys
S,L,N="",input().split(),int("3EED3TD7OWRVC3DD9L9NKQY0NEADDU7704EYGXWLFF2PGCR6H6ET3DRODQ4O22XAAFV5KOSWET2D2CQZOMXRQWEO7I2US8FRU5Z2CU8D73B10GEG08YUJQPZND1978359JZOEUGKHT2HXO70Z6PK59T8RMY0BBRJ1D78AZEEYBWU4N7IW1TLUN57",36)
while N:S,N=S+chr(97+L.index(sys.stdin.read((N&3)+1))),N>>2
print(S)
```
[Try it online!](https://tio.run/##pVRbj6IwFH73VxAfNhA9DYIKbLKTqK066oByGZS3zWoiyaxj1Mnu/HqXIrSnOm8rUk97rt93Tj1@XvbvB/t6zX8f308X7fx5bkTtRdv/0Wy288Px46Ib5Hx8y4vfYn/RmzZj1I6pE6Th68im1Ft4/ny1MX02oDRxHLPLNpN1uhiPreVkFPanfRbbNAzoqhtY1nowGL/25kGUstii1miVBS/rcJWywHm2ksgdh0kvs0aJSx172DEnbGK6m2S2WmY@7XiOa/e8WRawZDKfxtZ0HThm1l/Oe17shi8bczgMZx3quIOMsc0wTbq@85x24kXi95xm2@4bjT/7/G2n@d@jAmHU@rU/6Z7TWpD8sN391Qvw5HzZ5gdy2v3c6rr/zTZaHcMw2v7Tk9U4njgBkXG9EtCAEFIswBeiFU8pAhf4vvgCcCsoBG7JZY0fEbgZlgqtjMKduVQqebzSEbgVaXAJuMR9yk358nz1p1LejkoJ8CkBkDtVQyovqJ8yFYhwN2uRTmSpzO5SV0tlXsUHYV7BIMoifGs9ygBqXFFxrRABJEqEWFIkrEFEu4tYFSCVUMOuI2DmEX2INVGqLLNqWo1bIYAoFYAon9QwUIlSJanC0FQoog6lSRLkA/9E6ZRkBOEVmUBAwhN3T7zSPjF68NjIrzKClKD2RHyLYoHgIzy3gOKAcgseypT8ye5I3ATVg6YKZG2AaBN8yO4R5FbPt3oq4QCGeHc/lTslBxATiZsoJwYQRjSb/3dd1Fkmcs7Jl/9P9SRyzT8 "Python 3 – Try It Online")
Takes the library followed by a newline followed by the morsecode from the standard input.
The library used is `.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..`
## Explanation:
The majority of the code is a precalculated number of morse widths.
A morse caracter in the library is between 1 and 4 dihs and dahs long. In the number i store this as two bits of information.
To recall this number i & it with 3 and shift the result over by two bits.
I then read the number of dihs and dahs from the standard input and lookup in the library what the offset of that caracter is from "a". Then repeat and print.
I think the best way to shave of bytes will be to store the number more compactly.
---
Edit: removed 54 bytes by changing the library format, and storing the number as base36 following the suggestions of A Rex and Chas Brown
---
Edit: -3 bytes for removing redundant parameter from str.split() - Chas Brown
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~189~~ 188 [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 the Morse code. Doesn't need the library. Requires `‚éïIO‚Üê0`
`⌊⌂morse⍞⊂⍨∊1↑⍨¨1+4⊤'⍳÷+≠í⍀÷<í∧○Ñ>å/∧∨êî∘ß∧äñ⍀○≠è[*⌷∨[î≠∇è⊂Øî⊃⍀[⌷Éäï\∘∧↑æ=íå⌿∧∨ëäÖ⌿ê/≤⌊∘[Å↓Öï○+Ü÷≥↓≤≥>⌷∘á⊃↑Ü⍳⊣[⌿-Ø↑ä/∧∧≠≠Ñíí+ßÜ+-○é↓↓≥≥×∧↑**⍨↑}∧⍨≥ç⍀∧}×⍀Àëç⍀Ø⍨∧∘[×/∘Å∧~≥○ëâ⊂å∨≥Àäè?'⍳⍨125↓⎕AV`
[Try it online!](https://tio.run/##pVSxbhNBEO3zFXRIPs0aI@ggiJKKjsY0kWzRBGIBBRRBVlCOu8OOsFBiFxYJ4OOORCZCFC4jMX8yP2JmfLe7s3Y6zvbd7s7sm/feznmntwudtzu7e8@g@@Z190Wn21nS0fGjxxR/urVFyYfekgYZDQ6e77181aXhF8oOaFhSkrUoHvHob9mK7lA2u0nDP7iIKD3DOQ37uLjHz6Sg8UccbWPelHFS4jn@omSCpzzFGf7mTM6QTWW7QYMFp7Q5Iz3jylhyLZzwNHvPeW0OY8qbLp8ygsDFI/xxH@eY0@Cqhr/g@AlP8bxJ6UyYJ5M2HlL8GU/wkktFOMUFpTmvSEKab6@qTvCrVGHEKeug7DtXuwKcyMqs4l4IKyY64orzCE9xGoGo@ylQgpbzF8cVsUZDTIpH@zLlEUcK0ZoU@5zC9vSZqqxwCXGzWPEcN4XJIU/fCRyDX@A3MSFnbYLRZ3nlA7Gad7Vu35W6R8cPnyzZruWN1dXbAgNyGX5U3@rHc2OvOlgtrUagVw2An4URU@8C@1mVAgdXZbtyrkqdtla6vtXpNT649FqGCW5ur42rChDiOsY24AC8SqXYW@SywaGtIdYEfBCsbIugnVf2KdccVU@zPjSrOzDABAzA0TdWhqLoQ94qLS2U4ngEh@RFbvhvgpPyjii9rhI4Sbrj1o0Pjs@1Hmwe5HUVwY/A7lR@O7Jg9JLuW1A4ELwFGzS9f/50vG6j@KiuAs8NlG3OD396Rm2z/R2uejmgJa69n8E75RtQG6kP0XcMKI2qN//vdQl72fg@N9f@P9lOlMg/ "APL (Dyalog Extended) – Try It Online")
`‚éïAV`‚ÄÉthe **A**tomic **V**ector (the character set)
`125‚Üì`‚ÄÉdrop the first 125
`'`…`'⍳⍨` the indices in that of these characters
`4⊤` To-base four
`1+`‚ÄÉincrement
This gives us the length of each Morse letter.
`¨` for each of those lengths:
‚ÄÉ`1‚Üë‚ç®`‚ÄÉtake that many elements from 1, padding with zeros when needed
`∊` **ϵ**nlist (flatten)
`⊂⍨` use that as a mask indicating partition-beginnings to **c**ut the following:
`‚çû`‚ÄÉprompt for Morse code
`⌂morse` convert from Morse code to uppercase text
`‚åä`‚ÄÉlowercase
[Answer]
# [APL (Dyalog) + dfns](https://www.dyalog.com/) + [Jelly's dictionary](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/dictionary.py), ~~181~~ 175 (172üêå) [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. Requires `‚éïIO‚Üê0` and `‚éïAV` redefinition. Doesn't use the challenge's Morse code library.
```
M←∊∘morse¨D⋄C←∊(7⍴51)⊤246⊥5 17⍴¯7+⎕AV⍳'k%aÏ⍵FþfÅ⍵ìÆ⌶á≥å3¶cÒ⍺\ujü─⍳%S⊣ì⍙ÒÛÙ3Ùp`Ø,hÇñ⊂┴Ö⍪l∪⍒i1⍵Í:-îà⌽ì≥3€ã(⍝S]ÁGXræ∇O7Uæî'
C↓⍨←≢i↓⍨←≢M⊃⍨w←(⊃C)⌷∊(⍸M⍷⍨⊂)¨⌽,\24↑i
⍞←819⌶w⊃D
‚Üí2
```
[Try it online!](https://tio.run/##pVRtbxtFEP4YyX8BCY0sqrNV79lnJ45NxIdiQ1XUEOSkCISL2JzX8SXXu9O91LIACUJJUzdXIBTUCIGAkiqqrCJEaSsEfMj@k/0jYe99LymfONt3uzOzz8w885yxpaPBBOvmxgm7882lFbbzZa3AVxfevvJesw7NBjRr0G6AokB7/ir3tmtKE9q1wFpbaEKr1WjxlRLcWjVg/vewNiKAVdfDOqy@2lmFMZFsAp6jGRsF6ZppO0TiCTrvSoOh4UiFLgdVSi2lzfaelKX3@@Pz8ApI0oeNjz8K733ZsXTN7Zf65ZeCgz1JYtPP@OLNi6@tSVXPsau6qWK9qmvrVWvijkyjIS9WHc0lyMLqFt4gTnWT6PqkOtBUVzMNbE9kayIpYbWXTTyANwK35EAWANgYgGoa14ntgmuCbo6JrWKHFNjuzS70QFvqLC0vjUMMqSeBQcjAgbASuI5tDa/rhAMSVcc2GVRCPM2wPBcs7DhkEIBqbiV4rBOe6Zql6dxq2aZFbH0CpRF2wDCBDIdEdcE0YOgZUXWcjUkFNj3HBcfiacsny5xDtjtlu/dCfo@Puuz2jU5kLC0y//GCUmbTX@rzTTY9XAAlMB3/ung@HDTzf5e2zmH6BfP/eH2O/jM3pJ/zJZ3N0R0@E/oTu3VIDxvHT1S6z/w/@94m/Yvd/YQfO7fKpvfpjPkHdJ9@Rw8a9MD6gN6rjOhN@hubbrO7j@m3zH@os92HLzB/X1MCXP9lRB/RH9ne33T2IsdusO0ZvV/iRK5epZ9efMemDzjHK4tX6AP6SCrwNr5m/lHQzK2fNXGzHOjAPxrzXYkvO2W29zRomPnPlpn/NIibbpePj3imSr8@z3a@0grM/4GHR2ob80PdAtvZr5/whIV6ab5WC0XIxxkLNRxvJxoOuDbmkoVirxhOc93TdFczILSF4UUOf0fi6giy3L7B/FkE0PMM8fBYc0dQ7Bb/QxNLPFZTt2Dt0gpceOsyOMT1LB7HnapOsMENFrZxIAUwhzFAJNcBOUEyCi6ZP6Jv9ON7ObliZ2QKV0i0yghlu7xHjk@h5BOmQilcFJ2mS7PEYadSx7c4PMZHaXjchpy7pWcTv5AB5XHTihNHCpB1KXScUZRGoxTtFGJcQOZESdsJgsi8QJ/AWlpqVmY8tKTvHAFyrgKUli8nbQglZq6MKrG1fCtpHbkhZU2e4V/OTSpjROg3zYTSlkTFnSY@N75UeujsIJ@XEWUrlJwU@E6LRbJoEnWLBByUewvOlJnxl00n61sW6hFUhbLakEBbykc2PVk4lug7b83aQWKLp97P3DuVCVAkUhxiphgk9Cho8/@9Lnkty5nO5ef@PyVKDDz/Ag "APL (Dyalog Unicode) – Try It Online") - 175 byte version, running at decent speed
```
M←∊∘morse¨D⋄C←∊(7⍴51)⊤246⊥5 17⍴¯7+⎕AV⍳'k%aÏ⍵FþfÅ⍵ìÆ⌶á≥å3¶cÒ⍺\ujü─⍳%S⊣ì⍙ÒÛ─3Ùp`Ø,hÇñ⊂┴Ö⍪l∪çi1⍵Û:-îà⌽ì≥3€ã(⍟S]ÁôXræ∇O7Uæî'
C↓⍨←≢i↓⍨←≢M⊃⍨w←(⊃C)⌷∊(⍸M⍷⍨⊂)¨⌽,\i
⍞←819⌶w⊃D
‚Üí2
```
[Try it online!](https://tio.run/##pVRtb9tUFP5YKX8BCR1FTE60XCdu2jSh4sNIAA2tFKUdApEhbp2b1q1nW35ZFAESlNF1WT1QGWjTxOvoqKZoCFE2hIAPvf/k/pFy7di@1@34hJPY955z7nPOec7jYMdE/RE27fUTdvuri8ts54taga8uvHX53cYsNOrQqEGrDpoGrbkr3NuqaQ1o1SJrbb4BzWa9yVdadGvWgIXfwOoGAaz7ATZh5eX2CgyJ4hIIPMNaLyhXbdcjCk/QfkfpDyxPKXQ4qFZqai2296SsvNcbnoeXQFE@qH/0YXzvqZ5jGn6v1Cu/EB3sKgobf8oXb7z2yqpSDTy3ato6NqumsVZ1Rv6GbdXVhapn@AQ5WN/C68SrbhLTHFX7hu4btoXdkeqMFC2u9pKN@/B65FY8EAGArT7otnWNuD74Npj2kLg69kiB7d7oQBeMxfbi0uIwxlC6CliE9D2IK4Fr2DXwmkk4INFN7JJ@JcYzLCfwwcGeR/oRqOFXosca4ZmuOobJrY5rO8Q1R1DawB5YNpDBgOg@2BYMAmtaHWdjVIHNwPPBc3ja8skS55Dtjtnu3Zjf48MOu3W9PTWWFlh4NK@V2fin2bkGGx/MgxaZjn9ZOB8PmoW/KVvnMP2chb@/OkP/mRnQz/iSTmboDp8J/YHdPKAH9eMnOt1n4Z@9YJP@xe58zI@dW2HjB3TCwnt0n97ntjq957xP71Y26A36KxtvsztH9GsWPjLZ7qPn6M@GFuHefxHRx/R7tvc3nTzPsetse0IflFj43coV@gk9etulDznJywuX6UP6WCnwPr5k4WHUzc0fDXmzFAkhPBzyXYkv22W29zTqmIV/LLHwaRQ33i4fH/JUlZ5RYOG3PHKqtCGP7xTYzv7sCc9VmC3N1WqxAPkoE5HGo21PBwO@i7lcodgtxpNcCwzTNyyIbXF4kcPfVrgyoiy3rrNwMgXoBpZ8eGj4G1DsFP9DD4s81tC3YPXiMlx48xJ4xA8cHsedukmwxQ0OdnEkA7AHCcBUqn1yglQUXSp/TL/TH9@r6ZU4p6Z4hWSripDY5T1qcgqlnzgVyuCm0Vm6LEsSdip1ckvCE3yUhSdtqLlbdjb1SxlQHjerOHVkAKJLqWNBURaNMrRTiEkBwonStlMEmXmJPom1rFRRZjK0tO8cAWquApSVr6ZtSCUKl6BKbi3fSlZHbkiiyTP8q7lJCUakfrNMKGtJVtxp4nPjy6SHzg7yWRmRWKH0pMR3VixSZZOsWyThoNxbcKZMwZ@YjuhbleqRVIVEbUiiLeNDTE@VjqX6zltFO0hu8dT7mXunhABlIuUhCsUgqUdJm//vdclrWRU6V5/5/5QqMfL8Cw "APL (Dyalog Unicode) ‚Äì Try It Online") - 172 byte üêå version, taking about 20 times as long to finish (especially slow at beginning)
*-3 bytes by packing base 51 into base 246 instead of base 64 into base 256 and losing the apostrophe*
*-3 bytes by ending with an error message instead of cleanly*
*-3 bytes by running about 20 times more slowly*
When I saw this question, I thought that the ultimate solution, the one the question was *made* for, would involve combining both the Morse code and a dictionary. I was surprised when the only submitted solutions turned out to use a table of letter boundaries. My interest was sparked; I'd take a crack at it myself.
The first step was to look for a suitable dictionary (I tried a few). Then I implemented the [first version of the algorithm](https://tinyurl.com/rudolph-C-v0-50) in C++. This enumerated all the possible words that could be at a given point, numbering them sequentially, until finding the one matching its corresponding value in an array made from running the same algorithm with the words of the song as a reference. This initial version enumerated the words in alphabetical order.
I was rather astonished to see just how ambiguous Morse code is without the inter-letter gaps. I expected it to be somewhat ambiguous, but not to the extent that it actually turns out to be! Some of the alternatives are pretty funny, too. Every time `reindeer` comes up, for example, it could also be `leech`. And the entire song can be mapped to completely different words, all the way from start to finish (gibberish, but present in the dictionary).
The dictionaries I tried turned out to be not so well-suited to the task. Either they were missing too many words, requiring them to be added to the dictionary for the algorithm to work, or they were *too* comprehensive, and the resulting array of "word choices" had elements exceeding 63, meaning it couldn't be packed into 6 bits per word.
Then it occurred to me to try [Jelly's dictionary](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/dictionary.py). It turned out to be *perfect* for this. Not every word is in the dictionary, including simple words like `a`, `names`, `games`, and `glows`, and the contractions `won't` (`wont` isn't in it either) and `you'll`, but I took advantage of the fact that there are no spaces in the output for this challenge, and cheated:
* `Blitzen` ‚Üí `blitz` `en`
* `had` `a` ‚Üí `Ha` `DA`
* `glows` `all` ‚Üí `glow` `sall`
* `names` `they` ‚Üí `Nam` `EST` `hey`
* `games` `then` ‚Üí `gamest` `hen`
* `won't` `you` ‚Üí `won` `Ty` `ou`
* `him` `as` `they` ‚Üí `Hima` `ST` `hey`
* `you'll` ‚Üí `you` `LL`
It was a spookily perfect fit for this challenge, even containing all of the proper nouns other than `Blitzen`. Another cheat was to use compound words to shrink the size of the array of word choices: `outwith` and `godown`. As result of all this, the word choice array had 116 elements in it, and with none exceeding 63, the whole thing could be packed into **87 bytes**. (This, despite the compromise of encoding `then` as `th` `en` so as not to exceed the value of 63.) Contrast this with the array of Morse codeword boundaries, which takes 119 bytes (118.5 rounded up).
But that leads to the next problem: Although the data size is considerably smaller, the code complexity is ballooned in comparison. I didn't know any golfing languages, and most of them have very limited documentation that's quite hard to use to learn from scratch.
So I worked on refining the algorithm. The next optimization was to iterate through letters [from longest Morse codeword length to shortest](https://tinyurl.com/rudolph-C-v0-61), still in C++. This actually decreased the maximum index value to 59, meaning that with arithmetic rather than bitwise packing it could use base 60 to fit in 86 bytes. (For illustrative purposes I also [ported this one to Java](https://tinyurl.com/rudolph-Java-v0-62), which was interesting... I learned a little more Java, and was surprised to see it run even faster than the C++ version, using >125% of a CPU core, even though the algorithm is inherently single-threaded. My best guess is that the hash function is multithreaded even for individual look-ups.) This data set would respond better to Huffman encoding than the previous one, though not enough to even break even.
I tried optimizing the C++ code for smaller compiled object code, evaluating if it was worthwhile to attempt hand-coding it in x86-32 assembly. It stubbornly remained way too large; the best I could do was to squeeze it in at just under 256 bytes, *not* including the data. So it wasn't worth hand-coding in asm (the letter-boundary version beats it by a huge margin).
So it seemed that the only way this algorithm would have justice done to it would be for me to learn a golfing language. Quite daunting, given that I've never used anything like these languages.
And then [Ad√°m](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) offered to teach me APL. I jumped at the chance; while APL doesn't usually win challenges where there's also a Jelly or 05AB1E contender, it tends to come pretty close, has a deep and rich past, and formed the basis of or influenced many newer languages. Heck, I knew of it as a child, and was a bit curious about it even then, but never took a crack at learning it until now.
Many thanks to Adám for extensive help in teaching me various aspects of Dyalog APL and golfing down this program – my first APL program.
I initially tried [porting the algorithm as it stood to Dyalog APL](https://tio.run/##pVTLbtNAFF3HXzELJKcqM36meamrqEKVoKCKDVJEFWKnNRg7SlyVCNhQVJrSVkCFxAqhigULJHbs2PAp/pFwr@15Jd2RNO7M3Nc5597xYBzTYDaI0/1Ffvl5@35@8sE2zOfpZBqacNB7ZAajZGoaQTTMwObUW047P/@9Zj7uH62TTWKaL73Xr4pnn03HcZT16/21Wxi7a5r52TEsdu5sPTStw@nEitPhILbi6Ik1nmUHaeKxpjWNspCOB8Nng/1waj0N43hmYbUoTQaTGRvPTMcIoHR@epaffkGLkZ@@qwdkd41E3V43SsaH2YN02h0epNEw3Iu6QTjODrpH6SToFkTuhkl3lB4mwT3cLXrIgzgucTaIu0Ech7ge8YlnE5c0iecQj7hNXLmkgSaPOPi1iddCZ/D1iA1218GV0yBt4kMmtLXx0SJugzhNiPF8cINAqIDZHI9sYDhEgwU8ffDzy5xeA84BTIt4HqRpOOWxi6GAE6LLWi3MgsAALmyhro1U0K/AYEMaOC/Q2eiN8GDdaCMpKNkkvg@OUKoNlhKPygTZ2qQg4BlcW1CMqwvLQt9iUFBjbM3FTyMJX2R7cZhl4aRj1LjuYPTl7m6ajsFY62yPSD6/lj0Bt8InP3sjIz/K6lcRRNWw2m1wlXF4iskCCEQr7osDjnYTJrBXnNbyi68QW46v8K0pDIo9DMdVfvEDR6Q8UHjbZfqtuCwsbevCvbOVBNsjQ18BnnY@/w6MRd2ybFXp7y/H0BJz4utcF9CjMOQnnxSdtTJ8wf13wA@15ntaYYQUajssgGDn82@yDDgEaRIWhk2BmUOiCiTUbX4NCle9O87P/5Teq/SUsojMwBKdBVxko@yLW/dtu3ix7Jqkev@A6dKEe44e799Ci8wFZRQ/DP6Vf@UP9ox/KmN5VKyoesoolTvdwqooyr9FKSrSld6inKhSuS2Vrh6Ve5WfCveKBtMeIpbblQpUzysQc4NIIFkqjKVEwpuKbEsZKwDSSDltnkFVXpFPUU1AlTCrpnHemgBMQ0AFfMZpKBClSUqlUtOpCBxakyTJFf2Z1impiMJXVKKCkjpxy8Jr7ROjR1cbeVNFKleURyp6C7CUqUfq3FIlD9VuwQpMqZ/sjuTNFDzKVFGJjSqyCT1k95gSxudbP5V0qEpx6X5qd0oOoCqk2kQ5MVThqMzm/10XfZaZnHN24/uJTyJa/gE). It worked, but was very slow, even when compiled; in 60 seconds it only gets up to `donner` or so. Ad√°m conferred with Marshall at Dyalog, and there wasn't really a way to speed it up any further. But it was suggested that encoding the entire dictionary in Morse code could result in a speedup. And I realized that this strategy could make for much better golf, too.
So the next stage in adapting the algorithm was to translate the entire dictionary to Morse code, and at each point in the encoded song, iterate through possible words in reverse order of their length in Morse dots+dashes (with the longest being 24). Not only is this approach far, far faster in APL (and probably many other languages), and far more concise, but even the data is more lightweight ‚Äì far more of the "word choice" array elements are `0` or `1`, the largest value is just `50`, and there are only 115 elements (the `then` no longer needed or benefited from breaking up), meaning that in languages with arbitrary-precision base conversion, it could be packed in base 51 and take up only **82 bytes**. In APL though, the overhead of implementing arbitrary-precision base conversion would override the benefit, and I stuck with packing groups of 7 elements, in base 51, into groups of 5 bytes in base 246 (as log246 517 ‚âà 4.999295), taking up **85 bytes**. This data set responds even better to Huffman encoding than the previous, but still wouldn't break even: `4 1 2 21 1 13 0 23 0 3 26 1 23 0 26 0 27 15 8 6 0 34 10 0 1 1 7 0 43 23 0 4 37 50 1 0 3 23(24üêå) 22 6 15 6 16 3 2 17 10 12 5 0 9 31 1 3 9 21 0 32 16 9 20 32 8 12 31 5 0 4 27 14 1 7 13 16 0 0(1üêå) 27 4 4 22 10 0 16 5 7 15 3 12 18 4 2 13 1 0 50 4 49 2 1 4 38 20 0 0 19 0 43 23 0 1 6 12 0 38 0`
So as it turns out, in APL it still doesn't golf well enough to beat the existing letter-boundary solutions, even if the overhead for unpacking the "word choice" array (24 bytes) and for using Dyalog Unicode instead of Extended (7 bytes) are subtracted (yielding **144 (141üêå) bytes** code+data). I still think that it might be possible to make it shorter than 129 bytes in one of the languages more specialized towards golfing, and will likely try that eventually.
Of course, with bigger source material than the song this challenge uses, this dictionary-based approach would win hands-down. Some interesting extensions to it would be: Look 2 or more words ahead, and perhaps use an [N-gram](https://en.wikipedia.org/wiki/N-gram) frequency table; Look all the way ahead, using a model of most-likely N-grams (probably would be incredibly slow).
---
## Explanation of the code
Dyalog Unicode is used, even though Dyalog Extended could save 7 bytes (4+3, as described below), because the former allows compiling for speed, whereas the latter is very slow, to the point that it would be impractical for demonstration.
On my system, this version takes about 45 (or 901üêå) seconds to finish (the first 7 seconds of this are taken converting the dictionary into Morse code). On TIO it doesn't quite finish within 60 seconds.
### Header
`‚éïIO‚Üê0` - set Index Origin to 0 (for 0-based array indexing)
`⎕AVU[62 63 60 93 11 94]←9016 9060 9056 8838 9018 9080` - modify the default Atomic Vector to match the actual Single-Byte Character Set we're using (`£¢¥ýɫ·` overwritten with `⌸⍤⍠⊆⌺⍸`, at each character's respective index within the Atomic Vector)
`'morse'⎕CY'dfns'` - import the Dyalog APL Morse code dfn – I decided to keep this in the header because Dyalog Extended has it by default
```
D←1(819⌶)'^\w+ = ''{3}|''{3}\.split\(\)$'⎕R''⊃⎕NGET'/usr/local/lib/python3.7/site-packages/jelly/dictionary.py'1
```
Load Jelly's dictionary, and convert it to lowercase:
`⊃⎕NGET'/usr/local/lib/python3.7/site-packages/jelly/dictionary.py'1` - read the file as a set of newline-delimited lines into an array (with empty lines dropped, of which there is one)
`'^\w+ = ''{3}|''{3}\.split\(\)$'‚éïR''` - using a regex (PCRE) Replace, remove the Python code that surrounds the dictionary's two word lists (`short` and `long`), resulting in a merged list that keeps everything from `short` before everything from `long` (but is otherwise in case-insensitive alphabetical order)
`1(819‚å∂)` - convert to uppercase, so that the `morse` dfn will work on it (since it only takes/gives uppercase input/output)
`D‚Üê` - assign to the variable `D`
```
‚àáD R i;C;M;w
```
Define the tradfn `R`, taking left argument `D` (dictionary word list) and right argument `i` (the input, i.e. the song in undelimited Morse code), and having local variables `C` (word choice array), `M` (dictionary translated to Morse code), and `w` (array listing the indices into the dictionary of what the current word could be). The arguments are passed and the local variables are declared to allow the `R` to be compiled properly (see footer).
### Code
```
M←∊∘morse¨D⋄C←∊(7⍴51)⊤246⊥5 17⍴¯7+⎕AV⍳'k%aÏ⍵FþfÅ⍵ìÆ⌶á≥å3¶cÒ⍺\ujü─⍳%S⊣ì⍙ÒÛÙ3Ùp`Ø,hÇñ⊂┴Ö⍪l∪⍒i1⍵Í:-îà⌽ì≥3€ã(⍝S]ÁGXræ∇O7Uæî'
```
`∊∘morse¨D` - compose the two functions `∊` (Enlist - flatten / join) and `morse`, and apply the composed function to the dictionary `D`. Without the `∊` composed in, `morse` returns an array of Morse codewords when given an alphabetical string as input, but we need the Morse-encoded dictionary to leave out inter-letter gaps, thus the `∊` flattening.
`M‚Üê` - assign the result to `M`, the Morse-encoded dictionary.
`⋄` - statement separator
`'k%aÏ⍵FþfÅ⍵ìÆ⌶á≥å3¶cÒ⍺\ujü─⍳%S⊣ì⍙ÒÛÙ3Ùp`Ø,hÇñ⊂┴Ö⍪l∪⍒i1⍵Í:-îà⌽ì≥3€ã(⍝S]ÁGXræ∇O7Uæî'` - word choice array, packed into a string using Dyalog APL's updated SBCS. For this to work, the encoding must not contain newlines, i.e. `⎕UCS` `10`, `12`, or `13` (`⎕AV[2 3 5]`), and any apostrophes must be doubled (but there are none).
`‚éïAV‚ç≥` - map characters to SBCS indices (in the range 0-255) using the modified Atomic Vector.
`¯7+` - add −7 to all SBCS indices. The corresponding addition of 7 was done during the encoding, to avoid occurrences of any of the three types of newlines. Due to use of base 246, this addend is quite flexible, and could range from 6 to 10 and be guaranteed to stay within range regardless of the data; thus it can be adjusted to minimize the number of apostrophes (which would each cost 1 byte, as they need to be doubled in a quoted string). As it happened, it was possible to have zero apostrophes.
`5 17⍴` - arrange into a matrix for base conversion; each of the 17 columns will be converted as a unit. (In Dyalog Extended, this could be done as `5 ¯1⍴`.)
`246‚ä•` - base-convert the 5 values in each column that range 0-245 (base 246) into a single number ranging 0-900897818975, the top row being most significant, yielding a flat array. (But due to the nature of the underlying data, it will actually range 0-897410677850.)
`(7⍴51)⊤` - base-convert each array element back into a column, with 7 rows, each number in the range 0-50 (base 51). (In Dyalog Extended, this could be done as `51⊤`. The number of rows would be autodetected, so if by a coincidence all values were less than 516, this shorthand syntax wouldn't work properly. In this case though, in would work, and would save **4 bytes**.)
`‚àä` - flatten the matrix into an array, row by row.
`C‚Üê` - assign to the variable `C`, the word choice array.
```
C↓⍨←≢i↓⍨←≢M⊃⍨w←(⊃C)⌷∊(⍸M⍷⍨⊂)¨⌽,\24↑i
```
This is Line 2 (as referred to by the `:GoTo` at the end of the loop):
`i` - take the current value of the input (with the parts of it that have already been processed deleted)
`\24‚Üë` - truncate to 24 characters (dots+dashes). That is the length of the longest Morse encodings (`rudolph` and `christmas`). This step is omitted in the üêå version, which results in almost identical operation, but far slower; the word choice array only needs to be modified in two places (increasing the choice value by 1 at the `and` in `andifyoueversawit` and at `christmas`), meaning that at all other words, no matches for >24 dots+dashes are found in the dictionary.
`,\` - make a list of Morse subsequences starting at the beginning of this, ranging from 1 dot/dash long to 24 dots/dashes long (or maximum length, in the üêå version), from shortest to longest (e.g., at the very beginning, would be `'-' '-.' '-.-' '-.--' '-.---' '-.----' '-.-----' '-.-----.'`...`'-.-----..--.--.---.---..'`)
`‚åΩ` - reverse that list, so that it goes from longest to shortest (this way of encoding results in smaller element values for the word choice array on average)
`(⍸M⍷⍨⊂)¨` - to each item in this list, apply the function `⍸M⍷⍨⊂`: `⊂`=enclose one level of nesting deeper, to match the nesting of the Morse-encoded dictionary; `M⍷⍨`=return an array the same size as the dictionary, where values of 0 mean "not found" and 1 means "found", `⍸`=convert the list of `0`s and `1`s into a list of the indices of the `1`s. The result is a matrix with 24 rows (ranging from longest to shortest Morse, top to bottom), each of which contains a variable number of columns (minimum zero), listing the indices of all the words in the dictionary that match the Morse sequence from the input of the corresponding length (in alphabetical order, but with Jelly's `short` dictionary entries preceding its `long` ones).
`‚àä` - flatten this. The end result is a list of the indices of all the words in the dictionary that match any item in the list of Morse sequences from the input that range from 24 to 1 dots+dashes long, retaining the sorting of longest to shortest (and within each length, entries from Jelly's `short` come before those from its `long`, and within that, they're alphabetically ordered).
`(⊃C)⌷` - from the resulting list, take the element at the index of the current word choice (`⊃`=first element of) from the word choice array `C`. Equivalent to wrapping everything to the right in `(` `)` and putting `[⊃C]` to the right of it, but saves 2 bytes.
`w‚Üê` - assign this (the index into the dictionary of the correct current word in the song) to the variable `w`, returning it as a result
`M⊃⍨` - return the `w`th element of `M` (the Morse code of the current word), unwrapped. Equivalent `⊃M` followed by wrapping everything to the right in `[` `]`, but saves 1 byte.
`≢` - return the length of the Morse code of this word (in characters, i.e. dots+dashes). If it had not been unwrapped by `⊃`, the result would always be `1`.
`i↓⍨←` - delete that many characters (the length of the word in Morse code) from the beginning of the input `i`, so that on the next iteration of the loop, the next word will be handled, and return the number of characters deleted as the result
`≢` - return the length of the number of characters; since that is a scalar, it will always be `1`
`C↓⍨←` - delete that many (1) characters from the beginning of `C`, the word choice array, so that on the next iteration of the loop, the next word choice will be ready. This saves 1 byte relative to what a separate statement (`C↓⍨←1`) would take.
```
⍞←819⌶w⊃D
```
`w⊃D` - Take the `w`th element of `D` (the current alphabetical word) and unwrap it, so that when printed, there are no spaces to its left or right. Equivalent to `⊃D[w]`.
`819‚å∂` - Convert to lowercase. Equivalent to `0(819‚å∂)`. (In Dyalog Extended, this could be done as `‚åä`, saving **3 bytes**.)
`‚çû‚Üê` - Print the result without a newline. In TIO, this prints to stderr.
```
‚Üí2
```
`:GoTo` Line `2` (the beginning of the loop), unconditionally. A line number is used to save the 2 bytes that defining a label (e.g. `L:`) would cost. The lack of a looping condition results in the program ending with `* Command Execution Failed: INDEX ERROR` when it tries to access the first element of an empty array (after it has successfully printed the entire song).
If running this program locally, note that the error prevents `]runtime` from working. To work around this, the program may be called with `:Trap 3`...`:Else ⋄ :EndTrap` wrapping it.
The clean version, avoiding this error, would be `→2⊣¨i`, meaning `:GoTo` Line 2 while `i` is not empty. This would work because `2⊣¨i` returns an array of `2`s matching the length of `i`, and the `:GoTo` goes to the line number of the first value in the array, if one exists.
### Footer
`‚àá` - end the tradfn `R`
`2(400‚å∂)'R' 'morse'` - compile the user tradfn `R` and the built-in dfn `morse`. Without this, the program would run far slower.
`⍎'D R⍞⋄⍬'` - Call tradfn `R` with dictionary `D` as its left argument and the input (`⍞`) as its right argument. This passing of arguments is done only for speed, so that the compile can work properly (it doesn't like global variables, or directly using input). The `⍎` and `⍬` constitute a workaround Adám wrote for me for the way the APLs work currently on TIO. They expect code in the input, but I wanted a clean separation between code and input.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~138~~ 135 bytes
```
·∏≤i‚±Æ‚ÄúQ¬Æ·∏É∆łź·πá√ë1¬ø·ªå…†\∆•»•‚ź·πô‚Å¥E≈Ä∆•≈íE√¶ ã√ò>√æ>‚Å¥√æ ã[‚Åæ∆ë]e√û·∏ç8√ü¬Æ‚±Æ»Æ√∏‚Åπ√ß√∑R?g¬Æ=,¬•ƒó¬µ@√òU~"/X√ßq¬Æ√Ü∆¨¬∞…†s·π≠·π≠?dC#ƒä?g√ë¬∂P√áH5p@ ÇE≈ì‚Åπ¬ΩG6·∏å∆ò·π™¬µ…¶8‚Ǩ(S¬¶·∏§‚Å∏·π´"·∏ü·∏¢l·π欶∆§·∏É∆≠·∫ä@‚Äô·∏É4$√Ñ·π¨k‚Å𬧷ªã√òa
```
[Try it online!](https://tio.run/##pVRPaxNBFP8qofbgwTdFUOnFJlCCHv2DIKgHwVLUHBRPXiRbxUJbD9GDKYgtkqSg6aJi66zVCDPN0uRbzH6RdWYyM@9N0pvZZHj7/v9@700erTQaz8tS8e8Pi29p0fxwXaSKv8yTIvmtsnXZOi/@qqOt0e7dvHvStcrtIvlRHzbz7vBtXfbGm7K9JAdLWikH4807RTLIW/dW5EfF3yzKHZHqtCep5EWSyT3580Z1VaSXz4nu8XtxUJPtWy/mFm7Lvacila/zvvg62n2msn39rT5YPnO8UV2VLXF4Ta5fvfikNl6rD9/pPOLPlUuKb@VtlX0WB6PeYrHWP3tT9BTvFAlX2Zc5xXcU/9RQ2UD08o7Bs69@bdSK5raWL8zLVyrrPzaZOupI93@/LEsGFWCM6QPMwSr6sSIYwbzrL4DxAi0YTyNXjIrBxNEaKjaLCTaSNZp8NhCMFyuNBEYyMfbF/kw9/3HGicpKQLUMAN9iC3NR4B9bCkK6iXcoF6o4t6nS7nDuLj8EdweDRUeI9XZSAeK8oWNvCAkQJUGMFAVvCNmmMroG0Agets9AmSf0EdZCq9imG5rHHRHAog4gtM88DNIimpAqCi2GEvqIhoQgZ/hn0aSQEYI3VIIAiW7cNPHR@MLqwewgT6sIKIGPJHyHZoFRFd1bIHkgugUzbSJ/OB3EzUg/ZKsAewNCW@ADp8dImN/vWItwgEKcup/RncIFpETSIeLGAMFIdvP/rku8ywz3nJ36/@Q30Vj@AQ "Jelly – Try It Online")
A dyadic link taking the library as the left argument and the Morse code input as the right argument. Returns a Jelly string of the lyrics. The long integer that takes the majority of the code has the lengths of each Morse code character encoded within it.
## Explanation
```
·∏≤ | Split at spaces
iⱮ ¤ | Find index of these in each of the following:
“Q...@’ | - Base-250-encoded integer 742925387377430937422864458121941352705403867269973650879937105837755604647313120541399315429452997316260711263757137193164236124383957174543961671910365268304120327243209050996915401898167278257845227193061059012165352924148307417330452740236835399667569278751322913192633409885614815
ḃ4$ | - Bijevtive base 4
Ä | - Cumulative sum
·π¨ | - Convert to logical list with 1s at the appropriate indices
k‚Åπ | - Split right argument at those positions
ịØa | Finally, index into lowercase letters
```
[Answer]
## Python, 487 bytes
`lambda a,b:'youknowdasheranddancerandprancerandvixencometandcupidanddonnerandblitzenbutdoyourecallthemostfamousreindeerofallrudolphtherednosedreindeerhadaveryshinynoseandifyoueversawityouwouldevensayitglowsalloftheotherreindeerusedtolaughandcallhimnamestheyneverletpoorrudolphjoininanyreindeergamesthenonefoggychristmasevesantacametosayrudolphwithyournosesobrightwontyouguidemysleightonightthenhowthereindeerlovedhimastheyshoutedoutwithgleerudolphtherednosedreindeeryoullgodowninhistory'`
Takes morse code and any of the three libraries as input, returns the text.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~149~~ ~~131~~ 129 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•Nα0Ω¤èGë™jƒć›
Ù¾₂¶É¨=Yàf§ì[ðEÎλ`÷¡2Ä|~āΔí¹–4₂≠āó3Tv₁‰[Öò‚S»‰CþEηFA‡γ÷¯¿Þ₃âÖ.³εûV^ÕÜ₄Ú¹þ‘ΘVÅÍÅΘΛ9m|\Ó8g8ì&ÓiUΩÎQ:ǺZÎgöæ•4в>£I#A‡
```
-18 bytes thanks to *@Deadcode*.
-2 bytes thanks to *@Grimmy*.
Uses the complete morse-string as first input, and the lookup format as second input.
[Try it online.](https://tio.run/##pVRLa1NBFN73V1wQ3J1BtItWUChSRReCVAtaKSpoaUFcCK6K3FxTShdmYbTEKtJG6QNb@gi2tIEIc4LLwd8wfyTOuZmZcybpzvvKmTnP7ztn8ur102fzz3s9mzfvmsNLZkf/wO1b@NNWmwt/PnSXbX42gp91xxaFPsYVvX3tIa6/0Fu4O4MHk1gz7Sd4ojcuY3XxbbdiPuKePrV5fdTZ25X1bgVbV@6/sUXF5gczuIpHNl@b0m23uoGdSXNyc8LmG6blQuzr3/jNFu@wiatKt8wvbE/P4if8aosqrulT7Ni8YRrTuITvcck0zJfxl4uPsT42N4a7F7E@/8DsYO3eVVzWZ4@wNofHuOlAjf49uq6/375AeXp3eqCALuV@@k//dWsVLq/sb5USyF0FwKtUo7wXhLtMBTFc3zqmi1m82UBq//HmPj5Ecw9DJZ/oG/QiA6RxY8VBEQMwSoGYKYrWEKMNRPQFsBIC7BBBMi/oE6zFUrlM37SAOyFAJRVALF8FGKJEVjFVEloKJdaRNIlBDvGvkk4xIwJvzAQRkpy4QeKT9sXRg@FGnpcRWILgKfiOxYKSW3JuQcSB5BQMlcn8cXcYtxL1iKkCrg0EbZEP7p4SbmG@012GAxLiwPlMzhQPoCRSNpEnBgRGMZv/d1zSWVY85@rc/6cwiaQZUZCRJqMlSZm7SxFIoLV7nD0ZZBQkK@WMtigNGZaKrIxCziSVSopXOgJZqX8) (Outputs as a list of characters, so the `J` in the footer is to join it together to a single string to pretty-print.)
**Explanation:**
```
•Nα0...göæ• # Push compressed integer 2178625864988239449532491166807818445418276694861550892023336765049187401437036816274840827319861935617150192366925629812414499033245212320687403711053517272798896860734190937884895522347710320033920004354990136205425279052925026955638024859428057287730519725429748232597858786841294379
4–≤ # Converted to base-4 as list: [3,2,2,2,1,2,2,2,1,2,3,0,2,1,1,2,2,1,1,3,0,2,1,1,2,3,2,1,1,3,0,2,1,1,2,3,1,3,0,1,3,2,1,0,0,1,1,2,3,2,3,1,2,1,1,2,2,2,1,1,0,2,1,1,2,3,3,1,0,3,0,1,3,2,0,2,2,3,2,2,2,0,3,1,3,3,0,3,0,1,2,2,0,3,1,1,2,2,2,2,0,1,1,2,0,0,2,2,3,1,3,3,2,2,2,2,3,3,3,0,3,0,2,0,2,1,2,2,0,2,2,0,1,1,2,0,0,2,3,1,2,1,3,0,2,3,2,3,1,1,3,1,2,2,0,1,1,2,1,3,3,2,2,0,3,0,2,2,1,2,1,0,3,2,2,2,2,2,3,2,0,3,0,1,2,1,3,1,0,2,3,2,2,2,1,3,3,2,3,0,3,0,2,0,3,0,2,2,0,1,1,2,0,0,2,2,2,0,2,0,2,3,1,2,2,3,1,1,2,3,1,3,3,3,1,1,1,1,1,0,2,0,3,0,3,1,0,3,0,2,3,0,0,3,2,2,2,2,2,2,2,3,3,3,3,2,1,1,1,1,1,1,3,2,0,1,1,2,0,0,2,2,1,1,0,2,0,3,0,1,2,1,0,3,2,2,2,3,3,3,2,1,2,0,1,1,2,0,3,0,2,1,1,0,1,3,1,1,0,0,2,2,1,3,2,2,2,2,3,3,3,2,1,0,3,3,2,2,2,1,2,2,0,2,2,3,2,1,2,3,0,2,2,1,0,3,2,2,2,2,1,2,0,1,3,2,3,0,1,2,3,0,2,1,1,2,3,0,0,3,0,1,3,2,2,0,3,0,2,0,1,1,2,0,0,2,3,2,3,0,2,3,1,1,1,2,0,3,0,3,2,3,2,2,0,0,2,2,2,0,2,1,0,3,2,3,0,0,2,2,2,2,3,3,3,0,3,0,2,0,2,1,2,2,0,2,2,0,1,1,2,0,0,2,3,2,2,3,3,2,2,2,2,2,1,1,1,3,1,2,0,2,2,3]
> # Increase each value by 1
£ # Split the first (implicit) input-string into parts of that size
I# # Push the second input-string spit by spaces
A # Push the lowercase alphabet: "abcdefghijklmnopqrstuvwxyz"
‡ # Transliterate all morse-strings in the list by the characters in the alphabet
# (after which the resulting character-list is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression works.
---
Also, since I was curious what the program length would be if we wouldn't take any input and just use [the 05AB1E dictionary](https://github.com/Adriandmen/05AB1E/blob/master/lib/reading/dictionary/words.ex) to output the string, I created a program for that as well, which is **266 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**:
```
’4ƒ€Þßer0–›r0prancer0vixen†„t0ï›id0¥Úner0bÙî؈€³€·4¾Î3‚¢£–2€‚€Ÿ13†¾5d2‚†a‚Òshiny5€ƒ€¬4ˆë–怕4€ÞƒÎ…耕é»s€Ÿ€‚3€¶2‚›€„ÇÇ0„Ò„šŒî€»†™†³—‹1…¯€†€Æ2ƒ‚‚½€µÚƒgyŒÎ»ˆš´‹é€„…è1€Ž€ž5€Ê®Á¢²t4„²€¯slŸ¯o†æ‚½€ß32®œ„š€œ€»sh€Äed€Ä€Žgï³13†¾5d24ll‚œ„‹€†„ª’5Ý’€ƒ rudolph reinÆÓ €€ €î ÄÃ’#:
```
[Try it online.](https://tio.run/##RVHLasJQEP2VQH8gxrjp32gTNBCiJLbU3W0rEbpwEbuoQjVaKrWVBLQPq9TFDHHjX9wfSWduhG5muDPnnDkztxlUa46d51IMzUMkb5c4xont61IMpNj6esuvehf0vnKubU@KWIpxW8eUeo6lwwuOPGrWcIgJPh5D4sOaw7cJe@yXpRjBDJ5JzKAqvShmmxLVY9hXLIMrIq5SwihoOF6nQgBlA5bmMcR3YuJcUWemMneIsC/FHF@LIi5gFyjRQr/M1K9Cd6tKY@xhT@ccUcimWYQJg3a8THfGTtZSPEjxUyJdSBUp5lmhQU5YaAS/zPjE0SGqd0igD7tjmE3hg1i4KMYoUyW2wuBsz5vgPSR4QxdYtU2CwIpl0sDNNpA2aQqtdhLHSdmAJBsoi8wfKI9Bg3td21JJidcxhfX/BU3XJQ1FJDMn8zTqjT60gk8U1UU1/9Jquq2G5tuOhyEONIbeLjlhomEX7wh6dp7nfw)
**Explanation:**
```
’4ƒ€Þßer0–›r0prancer0vixen†„t0ï›id0¥Úner0bÙî؈€³€·4¾Î3‚¢£–2€‚€Ÿ13†¾5d2‚†a‚Òshiny5€ƒ€¬4ˆë–怕4€ÞƒÎ…耕é»s€Ÿ€‚3€¶2‚›€„ÇÇ0„Ò„šŒî€»†™†³—‹1…¯€†€Æ2ƒ‚‚½€µÚƒgyŒÎ»ˆš´‹é€„…è1€Ž€ž5€Ê®Á¢²t4„²€¯slŸ¯o†æ‚½€ß32®œ„š€œ€»sh€Äed€Ä€Žgï³13†¾5d24ll‚œ„‹€†„ª’
# Push dictionary string "4knowdasher0dancer0prancer0vixencomet0cupid0donner0blitzenbutdo4recall3mostfamous2ofall13red5d2hadaveryshiny5andif4eversawit4wouldevensayitglowsallof3other2usedtolaugh0callhimnamestheyneverletpoor1joininany2gamesthenonefoggychristmasevesantacametosay1withyour5sobrightwont4guidemysleightonightthenhow32lovedhimastheyshoutedoutwithglee13red5d24llgodowninhistory"
5√ù # Push a list in the range [0,5]: [0,1,2,3,4,5]
’€ƒ rudolph reinÆÓ €€ €î ÄÃ’
# Push dictionary string "and rudolph reindeer the you nose"
# # Split it on spaces: ["and","rudolph","reindeer","the","you","nose"]
: # Replace all [0,1,2,3,4,5] with ["and","rudolph","reindeer","the","you","nose"] in the string
# (after which the result is output implicitly)
```
See the same 05AB1E tip as linked above (but section *How to use the dictionary?* this time), to understand how the dictionary strings work.
[Answer]
# [MATLAB R2016a](https://www.mathworks.com/help/matlab/release-notes-R2016a.html), ~~290~~ ~~285~~ ~~277~~ ~~266~~ ~~245~~ ~~223~~ 219 bytes (99+119+1)
```
function r(m,d);[a,b]=ismember(mat2cell(m,1,fread(fopen('j'),474,'bit2')+3),strsplit(d));char(b+96)
```
The inputs are the Morse code sequence `m` and the dictionary `d` in the third format. The function uses a 119-byte file `j` [available here](https://www.dropbox.com/s/88x42yob0q5of78/j.bin?dl=0) that contains the lengths of the 474 Morse codewords. According to [the rules of scoring multiple files](https://codegolf.meta.stackexchange.com/questions/4933/counting-bytes-for-multi-file-programs/4934#4934), this adds an additional byte to the score.
[Answer]
# [Perl 5](https://www.perl.org/), ~~283~~ 244 bytes
```
$s=<>;$s=~s/..{$_}//+print$s=~/(.) \Q$& / for map{vec unpack('u',q{MJZDYEM98;HWE31N4>Y9:6'Y,BZYRSZ1<JI2@]ZH_(Z8H)7@V[G5*V2NC&:NZM3':XVCLCHY2@(IY>WE\5,L<XK*K^6U5+"5K(9*S^)B5CT07:JK_Q:HINCL:J=23LYEL.T,E*".U[)[`HJQ@ZJ/R.F*"6XOJK5B0X`}),$_,2}0..473
```
[Try it online!](https://tio.run/##pVT7U9pAEP5XdhhGHrIbBAMSkWFA2hAeHXwgCVakFlurIoLYB0P/dZqT5G4P/K0Bktzt7rf7fbvHZDR9MFer6OyoWDr0739nBtEiOlgaxu5kejd@EXtGnBJw2YnugAG3T1N4HE4Wr6MbmI8nw5v7eGweSz0vWo537NZahYND@6KW3Wvvl9yClYu5qYrnnpx6e0Wnnil/9uxB3DuwE/lyt//RTHYz7eqO1fZa2ZjV61abVdvNlON1t3RRuzRTzWKvkWxc5c7N3YjZiBeSp1eJilk9S@ctpzHoWHa9XW1azlEm23RrTTpL1ZIROu8n@te20yl7jnFCH5KRXO@T0zAr6d71MpGKDlKZZZpoP59drZBQXOQ/1t/1z19TeAXG9dbbG/JdQlQr3UJBFIaft1Qo4dbeMp3MErhtpA5ugXuAj9I9oEHaTcaGdpYBdVxZcWiQAIolY6wkkt4o0TYQgwKUEUPaIQJXnsnHVJOlqjKDpoW8NQFIqwBl@RTSYCUqk5KKU9OpyDq0JimSW/qT1imlCOMrM6GkxCduU3itfXL0cLuR72VE9YZhJNNbFovEt/jcIsNB7RRslan0U91RvInVw6YKVW3IZJN6qO4RCwvnW99VdJBT3Dif2plSA8iF5E1UE4OMI5vN/zsu@iyTmnN69/8pnERhGQIhfAFhhBsQe/BVrGAEBLcgwuAb@O7wHUQo3PkP@AECA@5FADyAwIZH3wvG/g48gTBOhA/BswhGmAonmAkMeAGEuYCGV7FG@Clc4ZfIi/BbgCL8EXEE/wA "Perl 5 – Try It Online")
This corresponds to:
```
$L = <<''; # length bits in base64
MJZDYEM98;HWE31N4>Y9:6'Y,BZYRSZ1<JI2@]ZH_(Z8H)7@V[G5*V2NC&:NZM3':XVCLCHY2@(IY>WE\5,L<XK*K^6U5+"5K(9*S^)B5CT07:JK_Q:HINCL:J=23LYEL.T,E*".U[)[`HJQ@ZJ/R.F*"6XOJK5B0X`
$s = <>; # read inputs
$s =~ s/..{$_}// # take current length morse code from start
+ print $s=~/(.) \Q$& / # ...and print corresponding letter
for map vec(unpack('u',$L), $_, 2), # find morse code lengths of the letters
0..473 # 474 letters
```
This could perhaps be further shortened by encoding in base128 or directly in "base256". Huffman encoding the lengths could shorten the length data, but most probably enlarge the rest of the code by too much.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~145~~ 141 bytes
```
≔⪪⮌θ¹θF”)“1§μX↶)⟧¶»-↘3ω◧i⌊⊞⁸Q9m;T›|LDμ…›O⦄hTYIO5x÷↶׋,⟲"yMLUCgq.BNE2⁴⎇c⬤χN±⸿↙&7⟧χ⁰‹Ys´ΣC⁼{9ω�Pi&◧êKσPDfY9wi⟲f[Φτ³J‹‴V[^WREαF[-T^ς”§β⌕⪪η ⭆⊕ι⊟θ
```
[Try it online!](https://tio.run/##pVTBbtswDL33K4ScHCAULOvYUy8DehhQrF@QJV5rIHNSxyj29x4fLYlU0p3mxA4lPj6ST3QO7/vpcN6fluXpeh3exub1chrm5kf/2U/XvvnY7lzg@2P7@PDrPLlmE7uuC3LHtgtshbAaUS3@DbxsW9mOQXD8WL0xtOJvuw5kLcMjdsQEsENcCzd7sI4C4ABgihu8vIsEIYZ1WwKAZSin6SS6E3bGtJIQmJUvKhmIhRJskph/A0pmlFTMMYlQCkK7uGJhSOCcWCCrU2ThlvkBXO4JwCSnaCGS5rIRijqzzsiOHWHLCsCHOqVINJc6AUcU@1/awSGtBBEP@Tdb9zIN49w8zc/jsf/T/Ny5b8N4TCPxvnMbt@FZeJ0Z9fZ9f2mex8PU/@7HuT82A3tezheeGFyPy0KecHn@Wb/rzWufr@Rct8Qiu@uJdFV7fIqi/JFUVOhWdElXsiTYTer0SPDETwWe2vDVo8Rmv8lANW@pODsKgXZpOlaJCpoK2w1jKkCdlNvODFZ5I59RrZSqZaZDy31XAviqAirl@9yGKVFdKpVtrW6l1FEdkjZ5p7@vTkoVMf2WTFRashN3K3x1fGX06P4gv8pIalGONHqXYsnbLTu3ZHioegvuylT99HS0b2/qMVNFWhsZ2YoeenrehOX5rne1HbIt3ryf1TulA2iFtIeoE0OmRzOb//e61LPsdc79l/9PeRLhefDk4HFYwnL8EZNgYM1fxgPgQOLEdthCGgDF4YQFwbDECT4JJKD8Qp@nvw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved ~~3~~ 4 bytes by using a less inconvenient library format. (Thanks to @Deadcode for pointing out that I'd pasted in the wrong version.) Explanation:
```
≔⪪⮌θ¹θ
```
Reverse the sequence and split it into individual characters.
```
F...
```
Loop over the characters of a compressed string which are the digits `0..3` (which compress better than `1..4` for some reason).
```
§β⌕⪪η ⭆⊕ι⊟θ
```
For each digit, pop one more than that many characters from the sequence, concatenate them, look them up in the library split in spaces and output the desired character (using the predefined lowercase alphabet).
137 bytes with an even more convenient library format:
```
≔⪪⮌θ¹θF”)“1§μX↶)⟧¶»-↘3ω◧i⌊⊞⁸Q9m;T›|LDμ…›O⦄hTYIO5x÷↶׋,⟲"yMLUCgq.BNE2⁴⎇c⬤χN±⸿↙&7⟧χ⁰‹Ys´ΣC⁼{9ω�Pi&◧êKσPDfY9wi⟲f[Φτ³J‹‴V[^WREαF[-T^ς”§η⭆⊕ι⊟θ
```
[Try it online!](https://tio.run/##pVRNb9swDL3vVxg@OUAoWNZtPfXYw4BiPQ47ZImbZEudxPGybsN@e0ZSlEgl3WlubT@KT48forPcLMblfrG7XO5Pp@16aJ4Ou@3UfOzP/Xjqm@NsXnm8j7O7d8/7sWrq0HWd5zu0nUfkfQRBEb49mm3Ly8EzDx/RG3zL/rbrSKxFeqAVhkTsaF9LbvSQHZiAG4iT3aSLqxTABx@XeQNxkYphOt7dsTpyWg5InKgXVIyEWZLUODC@PaWMLM4Y94ggJ0Tl0hWygpBTYKZEJ7cFS8YH8VJNRJR2ci@4pSlt2kp5pj5TdFphtdQB8lGenCQVJ5WQRmD8r96Rg0vx3DyKX8@qx3E7TM399DCs@tdmM6@eJlxZf1gcmodhOfYv/TD1q2aLE/G4P@B04HV3uXyqwQFdDl/xP95ou3SJMy4xArvqANQqPU52QfrjUJDlIjuHy1GEdhVaHkIXfch0KcMVj7w3@U0EKHVzxsmRBbRKU7G2KLMhq10pSgLqhFR2UrCdN@0zXcupappyaKnuogGuyABy@i6VYVJUl7bKllaWkvMoDkmLvOm/K05KO2LqzZEgl2Qn7rrxxfHl0YPbg3wrIiiCtNP0OycLzi7ZuQWjA8VXcJOm9k9PR@t2Jh8zVaC5gWlb7oeenjPb0nyXq1oO2BKvvs/im9IBtI20h6gTA6ZGM5v/97mUs@x0zt2bv09pEslTz6vftYP6fVUvENfEIuNLNICNpXgIrwgz6hkJ5ZkpEa@jI/I30SC4ZYixyfgqAQh/i47I2kUlgi@RQ3CIq7y8Fx12HCQwe44iRHiULAifmERokqQJfxcGG2cRJfxD6mXjVRJl46dEY9Vf9Z/PFzjv/gI "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪⮌θ¹θ
```
Reverse the sequence and split it into individual characters.
```
F...
```
Loop over the characters of a compressed string which are the digits `0..3` (which compress better than `1..4` for some reason).
```
§η⭆⊕ι⊟θ
```
For each digit, pop one more than that many characters from the sequence, concatenate them, look them up in the library and output the desired character.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth) + [Jelly's dictionary](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/dictionary.py), ~~135~~ ~~134~~ ~~131~~ ~~130~~ 129 (126üêå) bytes[SBCS](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block))
The algorithm and data in this answer were originally implemented in [this APL answer](https://codegolf.stackexchange.com/a/197980/17216), and their explanation is there. But as implemented there, it failed in its entire purpose, which was to beat the previously lowest-scoring submission to this challenge, [Kevin Cruijssen's **129 byte** 05AB1E answer](https://codegolf.stackexchange.com/a/197652/17216). Here, it finally succeeds in its very purpose for existing, and just barely manages to beat that answer's length. I learned Pyth to do this; it was a promising choice with very good documentation. It's unclear if any of the other golfing languages would be able to implement an imperative algorithm like this in fewer bytes.
With a longer Morse code message this algorithm would win by a significantly larger margin.
```
Kcwd=bmsm@KxGkdTVjC"êêVÞøA?cUqg´§¼F¦e~zEºÊú[!Áw¶uQå´çý½Ê*¤jrkIæwÐó*S.(4áëÌöÅ×¹ñp.ÑQÐgBê "51=>zl@bJ@sxRb_._<z24Np@TJ
```
(contains C1 control characters, forbidden by HTML5, thus the above can't be copied to clipboard and is for illustration purposes only)
[Try it online!](https://tio.run/##pVTNaxNBFMeDIJ68KB7HEEhS@waVerFGo6JiK2I19tJKyMfmq5vddZOQj4Mg2kvxUA8qePADtIV4EkvRYi/z/i/jzmZ35k3Sm7ubzZt5n7/fe7PeoFMfs6TVt8rpVMWqsoee33A66WLmCoukeWY5lWwiMc@qdrddz@b9rpVZZL7V6foOK647hUbLK4TGLMuUvLjuyHhqHYas2W6paLfTmbWEUiSeBm5EUSAanSaVSQaZ71@ISq36bos1LdseyAyu32GVRrnTcJ2iP0hlmOuTNW/XpcF5umW7Ti05Xi73KtlSq93KLffvblTyq81biWPirXiHIxyt4kf8deN6@cmzmtgTu@LPHbFjPR/eFge4hQcn1s7hi57Y767gN7GHu3goDnFrTnxt@hv3zuBO7yxu48@5xzy9ID7gF/yOr4/jPm7ie/FS/MYfHsc3p8SrFdwWm7XTN3EkPotPicsXs9eGdq60lGv3H5UKvHB1eGnhgZfLL43HwEFePPibPJNfsObxFSknW6EEdJcD6JWp4ZEXxHeYClS4ibVKp7JEZlOpo1dkHsUHZR7B4MZL@cZ6kgHMuKriWKECaJQEsaZIWYOKNhUxKkArIYYdR6DME/oIa6pUXWbUtBi3QQA3KgBVPo9hkBK1SlNFoZlQVB1GkzTIGf650SnNCMGrMoGCRCdumnijfWr0YLaRR2UELUHsSfhWxQKnW3RugcQB4xTMlKn5093RuDmph0wV6NqA0Kb40N3jxC2eb3NXwwEKcep8GmdKDyAlkjZRTwwQjGQ2/@@4mLPM9ZzzI79P8SRKzUkOTGqYXEqJBXcoghTkOngCe2nAZBAWykxuyTTSMFSwMIp0llKolPFCR5BW/K/ryQ9/ewxQsUrd2j8 "Pyth – Try It Online") - 129 byte version, running at decent speed
```
Kcwd=bmsm@KxGkdTVjC"êêVÞøA?cUqg´§¼F¦e~zEºÊúvMÇìý÷¼]¾I/||ÊÁê,Ømø×i]Z8©b¤0åé'½bIý>ä
lG√πUK¬Ω"51=>zl@bJ@sxRb_._zNp@TJ
```
(contains C1 control characters, forbidden by HTML5, thus the above can't be copied to clipboard and is for illustration purposes only)
[Try it online!](https://tio.run/##pVTNaxNBFMeb9CIePDssgSTYN9aDIJbUiGhpoyKS9qANIZvdfNTNbtxNNAlF8KJg8djqyVNVGjwK1tJ4mPm/jDub2Zk3SW/ubjZv5n3@fu/Ndoe91pRk3IFbz2Udt0GedMO238vV8reJlJaJ6zsFy1omDa8ftQrlsO/mV0no9vqhT2o7frXd6VYTY1IgSl7d8UU8tU5CNr3ArnlRLv/cUgqrErshRRVpdJpsPhNnfrgiS22EQYfsup43FBmCsEecdr3XDvxaOMzmSRCiNY1awuAa3vICv5mZluqvnYLdiTrF0mD9hVPe3r1nXWAH7JCP@Xibf@End@/Ut1422U/2nZ09YN/cN6P77JR/4KcXX7H9R/w9/8En/Bc7q7A/7N3G9b29S7HyLR8v888dfsL2@ad25dktdmyzoxX@lR9nr7CJzT5u8Ak7WONHS1e9df5763KJHbKJdfNGYW3kFe3NYjR4aldpdfS4WyxvTqdAQVw0/ps9s1@8pukllbOtRAK8SwH0ytRQ6QXpnaQCFW5mrdKpLNJsLrV8SXMZH5S5hEGNl/JN9SgDmHFVxalCBdAoEWJNkbIGFW0uoixAKyGFnUbAzCP6EGuqVF2mbFqK2yCAGhWAKp@mMFCJWqWpwtBMKKoOo0ka5AL/1OiUZgThVZlAQcITN0@80T41erDYyPMygpYg9UR8q2KB4i08t4DigHEKFsrU/OnuaNwU1YOmCnRtgGhTfOjuUeSWzre5q@EAhjh3Po0zpQcQE4mbqCcGEEY0m/93XMxZpnrO6bnfp3QShWaJAhEaIpZCIvGdiCAEsY6f2F4YEBGEJDIRWyKNMEwUJIkinIWUKEW8xBGEFf0bdMU3P5oCOK7db/4D "Pyth ‚Äì Try It Online") - 126 byte üêå version, taking about 20 times as long to finish (especially slow at beginning)
## Explanation of the code
### Header
```
$exec('
```
Anything in `$`...`$` is `eval`ed as Python code. Open an `exec` block here (since statements can't be executed in `eval`). The leading space suppresses `imp_print`.
```
def Pprint(a): print(a, end="", flush=True); return a
```
On my system, this program takes 46.4 (or 921üêå) seconds to finish, but on TIO, it is on the very edge between not finishing in 60 seconds or just barely finishing. If it didn't manage to finish, no output would be shown. If it was manually interrupted before finishing, the incomplete output would be shown ‚Äì so it appears TIO sends a SIGINT (Ctrl+C) to the process for this, but something more powerful (perhaps even SIGKILL) when reaching the 60 second limit.
By default, Python only flushes its standard output on newlines. The `-u` command line argument forces stdout (and stderr) to be unbuffered, but TIO does not provide a way to send arguments to the host Python process that spawns Pyth.
This header line redefines Pyth's `Pprint()` macro to flush its output, so that if the program does not finish within 60 seconds, the incomplete output will still be shown. It's the next best thing to `-u`.
Funnily enough, forcing each individual print to flush seems to actually make it run faster on TIO; it was able to finish in under 58 seconds with this, whereas in my tests on TIO the 134 byte version never finished without this.
```
_imp_print = imp_print;
def imp_print(a): globals()["imp_print"] = globals()["_imp_print "]; return a
```
Work around the newline inserted by TIO between the Header and Code sections, which would trigger an `imp_print()` on the first expression otherwise. Suppress only the very first `imp_print` that happens next, and then allow all subsequent ones.
```
')$
```
End the `exec` block.
```
=TrL0$exec('from jelly import dictionary') or dictionary.short + dictionary.long$
```
Import Jelly's dictionary and assign the concatenation of its short and long dictionaries, changed to all-lowercase, to the Pyth variable `T`. Equivalent to:
`from jelly import dictionary`
`T = list(map(lambda arg:arg.lower(), dictionary.short + dictionary.long))`
### Code
```
Kcwd
```
The Morse code version of the song has already been read from input implicitly, as `z = input()`.
Read the Morse code look-up table from input. Equivalent to `K = input().split(' ')`.
```
=bmsm@KxGkdT
```
Translate Jelly's dictionary into Morse code, with the inter-letter gaps deleted. Equivalent to:
`b = list(map(lambda d:''.join(map(lambda k:K[string.ascii_lowercase.index(k)], d)), T))`
(The outer lambda uses `d` as its argument, whereas the inner lambda automatically advances to using `k` as its argument.)
`jC"êêVÞøA?cUqg´§¼F¦e~zEºÊú[!Áw¶uQå´çý½Ê*¤jrkIæwÐó*S.(4áëÌöÅ×¹ñp.ÑQÐgBê "51`
`jC"√™√™V√û√∏A?cUqg¬¥¬ß¬ºF¬¶e~zE¬∫√ä√∫vM√á√¨√Ω√∑¬º]¬æI/||√ä√Å√™,√òm√∏√ói]Z8¬©b¬§0√•√©'¬ΩbI√Ω>√§‚êälG√πUK¬Ω"51` üêå
(contains C1 control characters, forbidden by HTML5, thus the above can't be copied to clipboard and is for illustration purposes only)
Unpack the word choice array (115 elements), packed in base 51 in an **82 byte** base 256 encoded string. Luckily there happened to be no characters that needed escaping.
`C"`...`"` - convert the base 256 encoded string into an arbitrary-precision integer
`j`...`51` - convert the base 51 integer into a list of integers
---
`V`...`=>zl@bJ@sxRb_._<z24Np@TJ`
`V`...`=>zl@bJ@sxRb_._zNp@TJ` üêå
Main loop.
`V`... - `for N in` ...`:` - for each element `N` of the list decoded above, execute all of the following statements:
`_._<z24` - `reverse(list(map(lambda arg1:z[:arg1], range(1, 24+1))))` - make a list of Morse subsequences starting at the beginning of input (`z`), ranging from 24 to 0 dots/dashes long (from longest to shortest)
`_._z` üêå - `reverse(list(map(lambda arg1:z[:arg1], range(1, len(z)))))` - make a list of Morse subsequences starting at the beginning of input (`z`), ranging from maximum length to 0 dots/dashes long (from longest to shortest)
`J@sxRb`...`N` - `J = sum(map(lambda arg2:index(arg2,b),` ...`), [])[N]`, where `index(arg2,b)` finds all occurrences of `arg2` in `b` - enumerate all words that match the Morse code at the current position in the input, up to 24 dots+dashes, and store this list of dictionary indices (which apply to both `b` and `T`) in `J`
`=>zl@bJ` - `z = z[len(b[J]):]` - remove the processed Morse code from the beginning of the input
`p@TJ` - `print(T[J])` - look up this word in the dictionary and print it
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~ 270 ~~ 269 bytes
Takes input as `(string)(lookup)`, where *lookup* is in the 3rd format.
```
s=>t=>(B=Buffer)("SNB6>B5>V]@a5U)McAQ>@a/;3bRD7;2?R:1P_Sb7K@22MHO5V?O:AWZPATRV4A/VBW[0K:1PJ`Q?Fg=-ZD46TRRgC=]:1P-ZLYRgN<Z@9?H^RfCdRQPC6BTR1U;6>64UZ0MHc`=ZTSH2.cHRg4JQP<*VfRB]1b").map(n=>[0,2,4].map(i=>o+=B([97+t.split` `.indexOf(s.slice(p++,p+=n-40>>i&3))])),o=p='')&&o
```
[Try it online!](https://tio.run/##pVVtc5pAEP6eX8H4wUB1L2pQJzGHipmOk9So@JIpjq2K4pBaYYRk8u8th3C3p/lWQdy7fX2e3cO35ccydA5eEMHeX2@OLj2G1IiooZrUfHfdzUFTc6MXs2aYVWM6by2rE63ntIdGa3nTuF1Zj/VGpWndlwe/R6v6c6tS6XX71Wmzf99@tQftsTXV2zdT83VWeo5tnhbD5vctBftRr40ta9uh83gX7B8/re3Lg926a3Z/WW5nbQ0HnZo5tsqTRs2o6RO71Os6C2qPR90KcbrWVn8aDh6@TV3LnJdXOY38XQbqnhqzUrFS1OfJ0qOGX6CmOrurFyISBjsvWigL4u3Xm8@@q4Yk3HnORg0KhWJQoHvQS4bh5W81ba5pRZ8G9Ppay@f9YxgdFKrkgAD7kPjndJ@@8Zpkn1R52kokwLsEQKxkDUm9ILuSVMDDnax5Op4lNTtLnT5S8zQ@cPMUBpEe3DfTowwgx@UVZwoeQKBEiAVF3Bp4tLOIaQFCCRnsLAJmHtGHWOOlijLTpmW4JQKIVAHw8kkGA5UoVIIqDE2GwuuQmiRAXvBPpE4JRhBengk4JDxx58RL7eOjB5eN/CojCAkyT8Q3LxYI3sJzCygOSKfgokzBn@iOwE1QPWiqQNQGiDbOh@geQW7ZfMu7Ag5giGfnUzpTYgAxkbiJYmIAYUSz@X/HRZ5lIuacfPl@yiaRaXKNq6ud7/95D9jLjYDCzBSmY5ISX4kITGDr@I6dmYHCIiqJrLAtlpMZJgolicKcmZQoWbzEEZgVYYkdfx/6uw3Z@Vs1fhNH8V/MqRZNO/4D "JavaScript (Node.js) – Try It Online")
### How?
For each character in the data string, we take the ASCII code minus \$40\$ to get a 6-bit value holding the lengths of the next 3 morse codes.
*Example:*
```
"S" --> ASCII code 83 --> 43 --> 101011 --> 10 10 11
| | |
| | +--> 3+1 = 4 -> -.-- (y)
| +-----> 2+1 = 3 -> --- (o)
+--------> 2+1 = 3 -> ..- (u)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 452 bytes
```
lambda a,b:''.join([chr(96+int(''.join([f'{ord(c):07b}'for c in'''ezVswP,A8BpeH A82d
DY
po4ZqVH
Dw
,A8AMa+!ezd(a1J+/NCkuN"Rq'L
JR
dQd)>2I)8BK
3!2ssIY>Rl,StiKu]zX!6iCJ4
Go,1s(A/Qe)8BK3J
`5
\0\ a1DkA4YhA98[
R_Uv BO%d\
YHT\!%HpZ,t W
q&<sr&:
eXYBu
K#s*#lA
S">Y
|eMq$IhRw]&/TzR!-f6
IhQw:Q\CwQd*.RdcvDh3QsVBH}4];*H{"D
$9yJ$E%b
,Y>V;d>wr N'''])[i:i+5],2))for i in range(0,2346,5)])+'tory'
```
[Try it online!](https://tio.run/##PZHdb5oAAMRTVtdWzIoMP2cNWBVQVr/Qqd1IQJqhrm7QzpUK2VBwsDpQ0BLt@rc73cNe7uFyl1x@N18vTceubacflO1M@z3WNVSjxm0cv/jlWDYxmpgu0WoULXtJ/Pem@JPj6sSEbJffjZ/xqeOiE9SycRw3NkPPhxJfKLbJAXNDiJ0css2qDvJyKjh36Htg8WJ4KIB82E/tImz8OhnRitipsdEJrdKDiqVBB3hYDTLSIhDFP4GhnpTWj0VAJ18x1W6YbHJ9@AB6A0ZrWKzqeUjsuCsz0oy6ebm0@it1c4c1IlanR599dOJUxSPYkggY/2qRGtJL/6ifKWUF1So8/MDSssm2miPwdUA6@o58DT@i3OecroCycKtgOWF@Ty3Rb@lF/r3nJuF8Oxky7mRudRCK9s@9o0ThfMaCN5kEI6f@GNeLbNeUfDVfut1I2NtpI9g1RR9uIyKgdPzd/MIFJOmTR4SHzZoIeMnTISc802oSugxEC8ITlOHBcLa17mWvcuMgJTPD@KXO@LB7MtgxVcmR1baKdZWqkuSetbVjjbqa/dMgylS1RjeoOqmSRXzpuGt8O3f3X02JgWMb1F5IcvsX "Python 3 – Try It Online")
Same morse-ignoring, hardcoding approach as [ScoopGracie's answer](https://codegolf.stackexchange.com/a/197479/90219), but with each character's 5 LSB concatenated and re-encoded in printable ASCII (i.e. 7 free bits out of each byte).
This shortens the string from 474 to 339 bytes, not counting delimiters (which need to be multiline for the encoded string) and an escape sequence in place of a NUL byte. I also cut the string off at the last clean byte boundary (to not deal with partial bytes) so I had to hardcode the final four characters.
Then there's not-insignificant overhead for the decoding process, so it's not much shorter this way. Improvement suggestions welcome!
Using the standard library instead to compress the lyrics with `base64.b64encode(gzip.compress(...))` actually saves 2 bytes:
# [Python 3](https://docs.python.org/3/), 450 bytes
```
lambda a,b:decompress(b64decode('H4sIAAaPGF4C/3WQ0XbsIAhFv5UJRG2VkyU41n79xdzJY19cBE62WxbGt2IyWZZOykx63MXVn+pdfkQPNPH4OMZVeOegek9ftfiv6Gs4Y2F0OahWz9JgflLDsC5FWaTjjEkfjHrlCHRhhQk/40xMb+nLctG1JwEvZyAlukazeNQTo3I01GgVTxXTAoozeNjMBzYC7Kg0Ut7SkcmlKTWxSC3dyCp+Af0j9IWiRUnXQ0ifsELlRErryL2YN7L42Uidjkg4QuSDCMO8N7DdDa9eUvYJ3dppFJa2rMpuQve52Rnz3sT/KyvewuFJt6RlDBeOY4NT3a/6a3dxRa0JjBmPyKGJvv4BRj4fyNoBAAA=')).decode('ascii')
from gzip import*
from base64 import*
```
[Try it online!](https://tio.run/##NdDJjqJQAIXhfT@FO6WttAhXaDqpBbMigyCImN5c4F7mIYAU8PJ2VTq1Ocn/LU87D2lT0y/8/vdVwiqM4Qq@hX9iFDVV26G@34QM@KoYbdZH0J94Hl5UBYg72rfJe/gJqTIePM1RqVsxe2Bfs9wUL1qw5yJBZih/CtWBOs3@42HNxcTQxv1Wb9sYF/bFvByBZTxuyEIJKjg84Gxk1B4ElEJaMPUXTktwqUu9eFB86Oa5XOD82JXi0UlTu9gBcjLCba1Hg7rXPuTxMfPls4ALMm23oU/kXk1u7nR3@ab5tNwQlkBkzwnpDey1iKry7PrTVaTjWWy3PCZz7uRnjlffbTLDvayXjtx1s04FJqsDysvivEiA/bxKomH9NlkpliCHvDHQ6LhtFQ1SndE@7REdKKde6N7dnecRfTwVbWCcUhKQFQDTpeGOgXQ8OZDUcqG6zGdVG0cgODnAs9kIPM@/rwni1/fnsI@ybE38wF1TrZIla1dZ1Tbd8PO/hLBHDPi2V9tl9bDBG7Op0dvXEMTrHw "Python 3 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 142 bytes[SBCS](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block))
Like many of the other answers, and [my Python answer](https://codegolf.stackexchange.com/a/197732/17216), encodes the lengths of the 474 Morse codewords into **119 bytes** using base 4. Shares many similarities with [my Pyth + Jelly's dictionary answer](https://codegolf.stackexchange.com/a/198173/17216).
My primary reason for posting this answer is to show that in Pyth, apparently the 474-codeword-lengths method does *not* beat the 115-Jelly-dictionary-word-indices method!
Takes the Morse representation and library as two lines from stdin and outputs to stdout:
```
Kcwdsm@GxK<~>zddhMjC"¦¦Éir[%·AnÙjR[Ó+¨ß1£Z¡`­ú¯Ì¢Ù˵Ú~¦NªãÒê~Ì¡`¨k[UHÍ2ê«þU^
R1¬´√πu
z¯äú+):¦ÆÉl1èÈX.ËV3º
;
¯Ì¢ëê¥v+"4
```
(contains C1 control characters, forbidden by HTML5, thus the above can't be copied to clipboard and is for illustration purposes only)
[Try it online!](https://tio.run/##pVTPa1NBEL6/g8eCl/Ao9CBhFqI9qZSKB4Wih0KlNCBFI7ZV22Jbf/QQQVEaEi@2UFoPotUQUkpPIvbgYeb/8rnzsjszm/Rm3svL7M7sN/N9My/rrzeXimLm4cvGxrPpW69mrjenthuNpTsrN8cvYBe71Fp@Xsf9CfxVubFKByuzddqtVLFHX2p4tIBfF/GEzvCUOtjCb/ge39IBtfEnHY41sYPdu9ino4v0ifpNH9Lh@B62n9TfzN2mj5fpHfbxmP7M3R/LZmu46@3fHqODe1vZtgf97qEPq/j50lXsVugDtZ7WqEc7847a967gWYata1mS@5j6@ONFdXyyKMABf5z/GdyDr1@7@AnOwVZpgd11ALpKPS6cgniVqUDgBtGSTrKEsKHU4RHCAz5IeKDhkoecjX6TAVJcqTg6BEBZGsYqkUSDoA0hhgLUCZF2RLDKG/mMalKqlhmaFnknArikApDyXaRhSlSXSmWppVSkjqRJSnJEf5d0ShUxfCUTCCU7ccPCJ@2T0YPRRp6XEdSCeNLoLcWCs1t2bsHgQPIWjJSp@ml3lLcz9ZipAq0NjGyih3bPmWNxvtNdpQOW4tD7mbxTOoBWSNtEnRgwHM1s/t/rks6y0zl35/4/xUlkT@YgZ0/OS7Zyf5UmsMFrf/t4DsgZJC/tnLc4DQeWjrxE4cNslU7GKw8CR7m/a@uby2urGwVA49GDrcf/AA "Pyth – Try It Online")
## Explanation of the code
```
Kcwd
```
The Morse code version of the song has already been read from input implicitly, as `z = input()`.
Read the Morse code look-up table from input. Equivalent to `K = input().split(' ')`.
```
hMjC"¦¦Éir[%·AnÙjR[Ó+¨ß1£Z¡`­ú¯Ì¢Ù˵Ú~¦NªãÒê~Ì¡`¨k[UHÍ2ê«þU^
R1¬´√πu
z¯äú+):¦ÆÉl1èÈX.ËV3º
;
¯Ì¢ëê¥v+"4
```
Unpack the array that stores the Morse code width (in dots+dashes) of each letter of the song (474 elements), packed in base 4 (with 1 subtracted from each element) in an **119 byte** base 256 encoded string. Luckily there happened to be no characters that needed escaping.
`C"`...`"` - convert the base 256 encoded string into an arbitrary-precision integer
`j`...`4` - convert the base 4 integer into a list of integers
`hM` - add 1 to all elements
```
sm@GxK<~>zdd
```
`m` - map each element `d` of the list decoded above through the following lambda:
`~>zd` - `z = z[d:]` - remove the first `d` dots+dashes from the input (`z`), and return the previous value of `z` (let's call it `ê`)
`@GxK< êd` - `string.ascii_lowercase[K.index( ê[:d])]` - alphabetical letter decoded from the first `d` dots+dashes from the input
`s` - join the resulting list of characters into a string
[Answer]
# [Python 3](https://docs.python.org/3/), ~~265~~ ~~261~~ ~~259~~ 255 bytes
Uses the same base-256-in-a-string data-encoding method as [my other Python answer](https://codegolf.stackexchange.com/a/197731/17216), but actually uses the Morse code input. Like many of the other answers, encodes the lengths of the 474 Morse codewords into **119 bytes** using base 4. The Morse stage of the decoding is based on [steviestickman's answer](https://codegolf.stackexchange.com/a/197461/17216), with some further golfing.
Takes the Morse library and representation as two lines from stdin and outputs to stdout:
```
#coding=L1
i=int.from_bytes('Õª¾¸%(¦#?ªÆ*\nìÉ^;R2´Ã9;IªÆnjñ¿ªÚÑc%&þ¬dÈZ KU[þª¬8Ç2_Þ^" £#;Ú¸vLº«£+ÙJuî6x%(¦#?ª÷ ª\¤Ïr®L~XZ{MånXÖ9©«'.encode('L1'),'big')
*m,I=input().split()
while i:j=i%4+1;print(end=chr(97+m.index(I[:j])));I=I[j:];i//=4
```
(contains C1 control characters, forbidden by HTML5, thus the above can't be copied to clipboard and is for illustration purposes only)
[Try it online!](https://tio.run/##pVTNaxNBFD95MIfePIiXYIi72/RNaS3aZlk8r8aLUChNP6DJ2mxoNiFNtUXwoFCtoiLUgD0UoSqYhoIgWDxUePOHxZ3NzsybpDf3Y/J23ufv996ktdepNaPbg0Gu0qyG0aa3OJ8JvTDqsMftZmN9Y68TbNvWBB7wT9jDCzzP2/g9dw97E3x/ciXifX6w5uKLR7P4i7/E7oLrY4/v4/sI39T5T/wbfx1d4R8r@Vv8AvtV/nr56oPFciz3sD/PX81eW@fHa3h8E7/gIZ7kXH6E509K@AdPr@NJgX@@v8PP7uzKpPx3Ytdbwa/8QxvP8G3p@dIydp/h4Y2H/Bu@i5Z4N64Cf@CpxYIoxhTYVmnGcqasjXDTcjKTjSk/htfa6dgO225thfFv5mkt3AqyYbHuhfm5wozbascE2EFU9Sq1tr1wt9BgYVQNdm2/XKyvOo7j@p5frhdX3XB62psbDBhkgTEWLyAWlo3vRAQhiO/4ARBWEAvCUshZscVgaJgoskkU4SykRCniJY4grJIc4mLCL3mGr8gnr1Q53EokoLsMQH@ZGpZ6gbyTVKDCDa1VOpUlNRtJnS6peRoflHkKgxmL8pV6kgHMuKpiqVABNEqCWFOkrEFFG4mYFqCVIGHLCJR5Qh9hTZWqy0ybJnEbBDCjAlDlMwmDlKhVmioKzYSi6jCapEGO8c@MTmlGCF6VCRQkOnGjxBvtU6MH4428LCNoCaQn4VsVC4xu0bkFEgeMUzBWpuZPd0fjZqQeMlWgawNCm@JDd48RNznf5q6GAxTiyPk0zpQeQEokbaKeGCAYyWz@33ExZ5npOWeX/j/JSRSafw "Python 3 – Try It Online") (can't use the actual Latin-1 coding header, since TIO only accepts UTF-8)
[Try it on repl.it](https://repl.it/@Davidebyzero/Rudolph-PPCG-197455-Python-3-split-by-codeword-v1) (demonstrates the actual 255 byte source code file)
*-4 bytes by using the alias* `437` *for* `cp437`
*-2 bytes by using* `L1` *instead of* `437`
[Here's a Python program (TIO) to generate the full program with choice of string encoding.](https://tio.run/##dVTBjts2ED1XXzFxUEiKLSWb3XSxXuhSoAUWSHMq2sPCMGhxJHFDcQSSWq1y6j/0D/sjzozWNtpDYZsYcd68efNIeZhjR@76eDT9QD5CmMOmV7G7B3R1ld5c36bwFv5U3hnXbsE0QA6BGkg/X6VlmX6@S8EEGANqUAFih1JImtEb@NV4bOgFJmMtRK9csCoiuEMYIBKEQdUIU4cOahoMM/Bmbc1wIOU1ZD@PLVx/urv@cJ1DYqoP99BXrK9Uvn1@/Lgrw2BNzPKkIQ81GAcen9GzkuyCutrl2@QHAxWYdzewBosu6x/J66zOi7vbXV5cJUGyZaT9YY4YMpm@rNHY18hSm5nNx08/5fkmPZg2zUuNPCBmPGeesAL0yjLFKk3TFbcI/FviBL0n/1toOfmFXUuin0VMA/isbHaqzOFNBWEL/wKnvQncu@5kJuMYNniMbA@NcRhjmuBLjUOEP5Qd8RepE@sXgv/wLGHyVhqeNt9UImQrp1ziC5u3@r3j0zufGGjC4NIIE/mv8M9ff4MMlF0omckE40JUrsbL9gZC9DmgDXhpVO73tVUh7PccOdXjfi@2bBdChl@K8zxPBs9Dsp1aXDQVP5SNp/50HlJxdpkpykUsZulqzdF6leYCWK1Wp9NJ3vWbB@Zgo7L8ckWmzlgEs32qzI8366v7S8uq7nx2d7vuS@M0vmQPj9unHYu6f6geHp@2u3vz/n11w/T58XicafzqaNIqdCzHaS0@SDD4c/RsXkRgj@yRrsfBaMGRc0v2wGq@oTuMUROTeayVtfzO9BRio3oag0fRgZ4azvhRkx06BnjUjvhmn9Od0orv@hw642bJMLlpmHJ5A9RkIscTjVbzhgtqNrG1NAUmpYb5SDjPZPLyRrJqbDsRzZjO9HJogVGzE0qLcSDyJ0FPZPjvQLn5zNCewI5vV0NtO7OrJsReBS4OykVVMyISCzlRsMJOHBDtgQ7etF2cyInsdjQa@zlYlE1ysgp3R9PixGtLS8@oWadaRIaO3w3UvAhxa2Wq//OOW1jbkqaJh@DrH8nPx7KAoixLXgpZSuDPEhYSyDN/i0JQBQeClBhkqyxegUsCFhYplmhJCt9SWAiq/A4 "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 131 bytes
```
¬ª ÄAŒªT‚Äõ‚äç¬Ω‚áß·πó.‚Äπ·∫á·π°N‚Ü≥·∏¢Z¬µ·∫ä‚ÇÉr#‚â§*‚ÇÇ‚á©v«ê‚Ć‚Å∞‚Çà{‚⨂àö¬¨·πñ}‚Üë≈ºP«çƒä·πÅ‚üëZU≈º«ì‚àß‚àû:YŒ≤v‚Ç¥«í‚Ä∫∆àƒñŒ≤‚Ä¢‚Äû‚ĆG‚Ǩ
→C≬⁋İꜝ[≠₴m∑E¼ y±⋎\↲Ċ„ġQ Ṙ₍ṘQ∵«1}w⌊×+×⇩e⌊-¨T⁰ɽoṪḊ$⁰+‡∪»4τ›⟑;ẇ⁰⌈yĿ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiwrvKgEHOu1TigJviio3CveKHp+G5ly7igLnhuofhuaFO4oaz4biiWsK14bqK4oKDciPiiaQq4oKC4oepdseQ4oCg4oGw4oKIe+KJrOKImsKs4bmWfeKGkcW8UMeNxIrhuYHin5FaVcW8x5PiiKfiiJ46Wc6yduKCtMeS4oC6xojEls6y4oCi4oCe4oCgR+KCrFxu4oaSQ+KJrOKBi8Sw6pydW+KJoOKCtG3iiJFFwrwgecKx4ouOXFzihrLEiuKAnsShUSDhuZjigo3huZhR4oi1wqsxfXfijIrDlyvDl+KHqWXijIotwqhU4oGwyb1v4bmq4biKJOKBsCvigKHiiKrCuzTPhOKAuuKfkTvhuofigbDijIh5xL8iLCIiLCItLi0tLS0tLi4tLS4tLS4tLS0uLS0tLi4uLS4uLi4uLi4uLi0uLi0tLi0uLi0uLi4tLS4tLi0uLi4tLi4tLS4tLi4uLS0uLi0uLi0tLi0uLS4uLi0uLi0tLi0uLi4uLi0uLi0uLi0uLS4tLi0uLS0tLS0uLS4tLS4tLi4tLi0uLi4tLi0tLi4uLS4uLi0tLi0uLi0uLi0tLS0uLS4uLi0uLi0tLi0uLi0uLi4uLS4uLi4tLS0uLi4tLi0uLi4uLi0tLS4uLS0tLS4tLS0tLS4uLS4tLi4tLi0uLi0uLS4uLi0uLi0uLi4uLi0tLS0tLi4uLS4uLS4uLS0tLS0tLi4tLi4uLi0uLi4uLS4tLi4uLi4tLi0tLS4uLS4uLS4tLi4uLS4uLi0uLi4tLS4uLS0tLi0uLi4tLS4uLi4uLS4uLi4uLi0uLi0uLi0uLS0tLi4uLi0uLi4tLi4uLi0uLS4uLi4uLS4uLi4uLi0tLi4uLS4uLi0uLi0uLS4tLS4uLi4uLi4uLi0uLS4tLS0uLS0tLi4uLi4tLS4tLi4uLi4uLS4tLi0tLS0tLi4tLi4uLi0uLi0uLi4uLi0uLS0uLi0tLi0tLS0tLi4tLi0tLS0tLi4tLi0uLi0uLi4uLi4tLi0uLi4uLi0tLi0tLi4tLS0uLi0uLi0tLS4tLS4uLi4tLi0uLi4tLi4tLS0uLi0uLS4uLi4uLS0tLS4uLi4uLi0uLi0uLi4uLS4tLi4uLi4tLi4uLS4uLi4tLi4tLS0tLi0uLi4tLi4tLS0uLi4uLi4tLS4tLi4tLi0uLi0uLS4uLi0uLi4uLi4uLi0tLS4uLS0tLi4uLi0uLi4uLi0uLS0tLi4uLi4tLi4tLi4tLi4uLS4tLS4tLS0tLS0uLS4uLS4uLi0tLi4tLS0uLS4uLi0tLi4uLi4uLS0tLS0tLi4tLi4uLS4uLS0uLS4tLS4tLi4uLi0uLS4uLi4uLS4tLS4uLS0tLi4uLi0uLi4uLi0uLS0tLS4uLi4tLi0tLS0tLi0tLi0uLS0tLi0uLi4uLi4tLi4uLi4uLS0tLi0uLi4uLi4uLS4uLi4uLS0uLS4tLS4tLi4tLS0uLS0tLS4uLi4tLS4tLS4tLi4uLS0uLi0tLS4tLi4uLS0uLi4uLi4tLS4uLS4uLi4tLi0tLS0tLi4tLi0uLS4tLS0uLi4uLi4uLS0tLS4uLi4tLi4uLS0uLi4uLi0uLS0tLS0tLi0tLi0tLS0tLi4tLS0uLi4tLi4tLi4uLS0tLi0tLi4uLi0uLi4uLi0tLi4uLi4tLS0tLS4uLi0tLi4uLi4tLS4uLi4uLS4uLi4uLS0tLi0tLS4uLi4uLi0uLi4uLS4tLi4uLi4tLi4tLi4tLS0uLi4tLi0uLi4uLi4uLi0tLi0uLi4tLi4uLi4tLi0tLi4uLi4uLi0tLS4uLS0uLS4uLS0tLi4tLS4tLS4uLS4uLi4tLS4uLS4uLi4uLS4uLi0tLi4tLS0uLS4uLi0tLi4uLi4tLi4uLi4uLS4uLS4uLS4tLS0uLi4uLS4uLi0uLi4uLS4tLi4uLi4tLi0uLS0tLS0uLi0uLS4uLi0uLi0tLi0tLS0uLi0tLS4tLS0uLi4tLi4uLi4uLi4uLi0tLS0uLS4tLi0tXG4uLSBhIC0uLi4gYiAtLi0uIGMgLS4uIGQgLiBlIC4uLS4gZiAtLS4gZyAuLi4uIGggLi4gaSAuLS0tIGogLS4tIGsgLi0uLiBsIC0tIG0gLS4gbiAtLS0gbyAuLS0uIHAgLS0uLSBxIC4tLiByIC4uLiBzIC0gdCAuLi0gdSAuLi4tIHYgLi0tIHcgLS4uLSB4IC0uLS0geSAtLS4uIHoiXQ==)
Port of 05AB1E.
-1 byte thanks to Deadcode
[Answer]
# [Python 3](https://docs.python.org/3/), ~~381~~ ~~375~~ 372 bytes
Just like [Seb's answer](https://codegolf.stackexchange.com/a/197717/17216) and [ScoopGracie's answer](https://codegolf.stackexchange.com/a/197479/90219), gracefully takes the Morse code representation and any of the three libraries as input, blithely ignores them and gives you the output.
Takes Seb's strategy a step further, encoding the text in base 26 in an integer encoded in base 256 in a string (as opposed to Seb's which encodes in base 32 in base 128 in a string). Both of our solutions are confined by not being able to contain the bytes NUL (0x00) or CR (0x0D), which Python interprets as end-of-file and LF (0x0A), respectively, even when found in a triple-quoted raw string literal. CR+LF is also interpreted as LF. Backslash escape codes are interpreted (unless the raw prefix `r` is used). Backslash followed by any kind of newline is treated as nothing, stripping both the backslash and the newline. And the string can't end in a backslash. (So it's really sort of a slightly-less-than-base-254 masquerading with the help of luck as base 256.)
To work around this problem I had to complicate the encoding a bit. Neither ASCII-97 nor 122-ASCII, nor using base 27 instead of 26 (and optionally adding 1), avoided containing these bytes or sequences, so I settled upon adding 1 to the encoded integer before each multiplication by 26, which luckily costs only 3 bytes (compare `i//=26` to `i=i//26-1`). With significantly larger text, the luck would have to be incredible, or every NUL, CR, and `\` would have to be replaced with `\0`, `\r`, and `\\` respectively. On the other hand, with better luck, newlines might be absent altogether, meaning single-quoting could be used instead of double-quoting.
The `#coding=L1` costs 11 bytes (without this it'd be 361 bytes), but this beats the cost of using base 128 (which would take 319 bytes for the string, whereas base 256 takes **279 bytes**, and thus would cost 40 bytes instead of 11, not counting the different Python code that would be needed to decode it). An alternative coding is [`437`](https://en.wikipedia.org/wiki/Code_page_437), which would cost a further 2 bytes, since the [encoding name](https://docs.python.org/3.7/library/codecs.html#standard-encodings) is used twice. Note that the disadvantage of using `L1` instead of `437` is that ISO 8859-1 doesn't map as cleanly to UTF-8, and there may be difficulty faithfully copying and/or pasting it in some software.
This standalone program, written in the [ISO 8859-1 codepage](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)), ignores the Morse code representation and library taken as command-line parameters, and prints the output to stdout:
```
#coding=L1
i=int.from_bytes(' îã¸ÌÒ^ë9|iéëMþ³\H0Äï;ÿÒ¸FȪΩ«|°M®QcWtgUî[¡U*¤ßºN¨øA¡:¾ç¢Àãþú/æòêåá\IÕi#vv³Ü¡\'jîÐtÄí6.ñÎ餥Yî³d}fLLEXµ*îB§ ç^eleW?Ð|¶S¯±[Iûçä2ý¥ð°,üT÷0èÅEÛçå\LW&uMeÑ@ûÍÿ`Ñ3CÒæ%2¿¬ÌïÆçGÌîXë[MDØmI¥íâý9t±¤]#ÏYî8M·Ck­ò¡"J'.encode('L1'),'big')
while i:print(end=chr(i%26+97));i=i//26-1
```
(contains C1 control characters, forbidden by HTML5, thus the above can't be copied to clipboard and is for illustration purposes only)
[Try it online!](https://tio.run/##DZH7S5NxGMWhyELBclSsRTYa9m5mm04wL4wuZrXYAqmh4bLQvW5v6Sa2DMHQ0tTQdsvJaM2Ybk5dblMpxXKDc/6w9X1@OvBcOOf5jE74PT5vc7msG/S5FK/b4mitVCyK128cGvONvByY8Mtv9ZL2BHNcxyEWucRIP@LMtk0q57jF7JSdRew7EcDio0bOMt8xxRIjKjG8dOEBPnEB2zUMIIyVWkSxhSzmJ6tRsCPXjeXziA72qPxuB3N9SDrqETqFFH/i6Ak2eXgXMUwj2Y4iM9VX1UhgjdNcV7HII3w0IcGNi9w7y22mmcRqrdPKKMKK7sr4OPbxnT8wh2StU3ot3If8wtxOVYuRuwxwCymknzOHfdcHzA7ZbF29@I04gpqT9VjGAnP3kNEyg2C/Wh6We25XMDSJP0@Rr8Gups/Kv6L3hSkzj5FGjAUUqhpU@MZ/zziDg8YKbvJzF@YYZ4Zpp63n@jus2mWGEbkjdr@y9ErNcHMnI9zQ1JlROo1fZ8Rv85zDCjMPhcxhppfZPvt9xkYwf9mKNHe4dkmcP27zYxepFzoGRYRWJOw46HyDHe4hee2xZJS9gqWsl2xNkqFBGlDckqHyvUcZlrVK@@iYYKuXvS7LoGdMr9SZW2603TIYOgRzk8nccrOpLOo/ "Python 3 – Try It Online") (can't use the actual coding header, since TIO only accepts UTF-8)
[Try it on repl.it](https://repl.it/@Davidebyzero/Rudolph-PPCG-197455-Python-3-ignore-input-v1) (demonstrates the actual 372 byte source code file)
*-6 bytes by using* `L1` *instead of* `cp437`
*-3 bytes by using* `i=i//26-1` *instead of* `i=i//26^4`*, resulting in no newlines, allowing single-quoting*
[Here's a Python program (TIO) to generate the full program with choice of string encoding.](https://tio.run/##dVTNjts2ED7HTzGroqBUe5V43exivXAPBZpTmlPRHurCoMWRxIbiCCRlrXrqO/QN8yLujNd2s4cebAyH33zzzQ/VT6klvzoebddTSBCnuOh0ahdt6twToK826vvVg4Jv4DcdvPXNGmwN5BGoBvVxqcpSfXxUYCMMEQ3oCKlFCSTD6AV8sAFreobROgcpaB@dTgh@H3tIBLHXFcLYooeKessM7Kyc7fekg4H8x6GB1fvH1btVMbObd0@zmgJUYD0EPGDglDlrLnVoDr8v/yjWszcWNpDb@bL47u4e5kDB5FVx@/gwi3xhy0S7/ZQw5lJmWaF1L5ajJreLu/f3RbFQe9uoojTIRWDOtXDuGmJZW29ytfWquNncLpn6P1948XF@ZxMG7ThZppTKWELk38meoYsoEoWsosGnPFNZAT9cjypTUsNXJOwRijJg77hVglio7ZZx7ObD7M2Z9FXi7FUMnxfZdiupRAnrCIHCz7Fh7Cee5SyF6UUWHrTLz0QF3GwgruErsOps5G5VrQzAeob1ARMPjYbUD0nN8LnCPsGv2g34k8TJQpwIXvGcTOnpxXezER1r2b8Sny335ZeWV@qyRmAIo1cJRgqf4cvf/4AUmF8ZmclG62PSnsu9uBcQUyhA@nNNVO52ldMx7nZsed3hbic9WZ8IGX4NLopi1geukedvpKd2w4eyDtSdF0giLj1nivIkVgY0Z2vOAxJAlmXndZqNrXUIdn1l3VRtyO23d/fzx4eieOIEb9/e3d8uOaY4Ho8TDZ89jUbHlnN4Y6Q4MfpwsQ72WbJ2yIWbauitERx5f7rds7q/0O@HZIjJAlbaOX6dHcVU646GGJC3FzFQzTdhMOT6lgEBjSd@WpfrVhvNj22KrfWT3DC5rZny9AT1aBPbIw3OsMNHPdnUOBojk1LNfCScFzL5TCRyemhaEc2Y1nYyicioyQulw9QThbOgP8nyh0f76cLQnMGeV6amppm4jzamTkcOjtonXTEiEQs5U7DCVjog2iPtg23aNJIX2c1gDXZTdChO8vIv3C2Np068pHR0QMM69UlkbHnf0fCfEDdOqvq/3nEK5xoyNHIRvNOJwvQv)
---
If it absolutely has to be a function and not a program, then it's **382 bytes** (not counting the `#coding=L1`):
```
def R(a,b):
s='';i=int.from_bytes('…'.encode('L1'),'big')
while i:s+=chr(i%26+97);i=i//26-1
return s
```
[Try it online!](https://tio.run/##FVL9T1IBFN1qWepmyaqZLWM5e6CEihuljvVhVjZwy3LaICvlKa8UHDxtbjYtDW0aColjkjYURCQQZaWzlO2cP4yev9zd7Z5zdu65d3hMdricDfm8XexXd2je6nq1TUWFHpMgNEsmySnr@92uode9Y7Lo0QjqU0xzAweY4zwDPQgz2TguXWCCyQkLj5G1wYe5J3Wc5k7zBHMMqBTw/KVH@MxZbJfSBz@WKxBEAknMjJcgY0H6GZYuItjXpZIHOpm2ItJZjcUziPInDtuxxYP7CGESkSYcM15yvQyrWOckN1Q85iE@1WKVm5e5d57bjDGCtQpbG4PwS5XXRkeRxQp/wItIhU14p7hflBVzqWKjnrv0MYEoYi@ZRtb@EdP9ZnNrN34jjIXy09VYwizTDxBXM46FnjJxUOy6W8DFcfx5jp1S7JZb2/hXmX1l1MAjxBBiBplinQrf@e8Fp7BfV8AtfmmFl2HGGbOZu26OYM0i0o/APYX7jbk3ZfQ3tDDAzfIqA3Jn8eucku0OvVhm/LHSpjHVzaTV8pChIcxcbUOMKa5fUeSPGmXsIvqqkgvKCnewasF@y3ukuIfIjaeCXnT2ueyiRjDXC1qd0CsNCNqiwg8OaVBUS02eGlOfw62RqgzGmsbb2pNj19YajLfqiwrdojzidqo9@WG38gAa0Wk3dWjaXU5Rd1K02vx/ "Python 3 – Try It Online")
If it has to be a lambda, **391 bytes** (not counting the `#coding=L1`):
`lambda a,b,i=int.from_bytes('…'.encode('L1'),'big'):exec("global s;s=''\nwhile i:s+=chr(i%26+97);i=i//26-1")or s` - [Try it online!](https://tio.run/##FVL9T1IBFN1qWZubJatmtojh7IESKm6WMtaHWdnALctpgyw@nvoKwQFZbjQtDW2aCqlzGTYURCQQZaWzhO2cP4xev9zd7Z5zdu7ZGRkLDHk9zaVuk63ktg87XHaVXefQSSbJE9AP@LzDLxxjAdGvEVQnmOUmDjHLOUb6scZ0a1A6xxTT4xYWkLdhHrMPGznFXeM4i4woZPDchfv4yBnsVHIeYawosYwU0pgOViBnQfYxls5j2dmrCAz2MGtFrKcOi6cQ5w8cdWGbh3ewignE2lBgsuJqFaLY4AQ3FSzwCB8aEOXWRe6f5Q4TjGFdaevkMsJSzZXRUeTxjd8RQkxpE17J7hcDsrlMeYuee5xnCnEknjGLvOs9pgbM5o4@/MIaFqpP1mEJM8zeRVLFJBb6q0S32HurjItB/H6C3UrsVVs7@Ue@fWbcwGMksMoccuU6Bb7y71NO4qCxjNv81IEQ15hkwmbuvfYG6xaRYURuy9wvLL6sYri5nRFuVdcaUDyNn2fkbHcZwgqTD@Q1i8k@pq2We1wdxvTlTiSY4cYlWf64NYA9xJ/XcEF@4SaiFhy0v0aG@4ipHwl60eP0ukSNYG4StDrBIQ0K2jbxnejUqAfdXofdrfIb/SZBsHneDkluUSW1@etNziGfRqo1tNS33tAa5QI0NBharjeptV6fyl8a8cmF0Igel6lb0@X1iLr/Q6st/QM "Python 3 – Try It Online")
If it has to be a lambda that doesn't modify any globals, **395 bytes** (not counting the `#coding=L1`):
`lambda a,b,l={'i':int.from_bytes('…'.encode('L1'),'big')}:exec("s=''\nwhile i:s+=chr(i%26+97);i=i//26-1",l)or l['s']` - [Try it online!](https://tio.run/##FVL/S5NxGIQiCwTLUWFGayj22XRtOsFyMvpiVsYmZInGpuW2V31rbrItS1K0NDW06ZaKaBrTzanLuTlKsVS4@8PW2y/HA889x93D9Q0Ee3ze6lyzxZHzdPY63Z2aTr1T77F8ELIwy96gocvv633pHAhKAa3QnGKK6zjAFKcZ6cAyk7WD8gVuMTls4zGyDoQw9biSY9ytG@YJIyqFPH3pIT5xEtuFDCGMBTXmsYUkJgYLkLYh9RRzFzHvalUFu1uYsiPaUo7ZM4jxBw6bsMmDe1jECKJmHDNRcL0IK1jjCNdVPOYhPhqxwo3L3DvPbcYZxara0ch5hOXSa/39yGKJ3zGOqNohXivuZ4OKuZ38GgMzDHELMcRfMIWsewhjXVZrQxt@YRkzxafLMYdJpu4joWECMx1FkkdqvZPH2UH8fobdQmSK7Y38o@y@MGbiEeJYZBrpfL0K3/j3OUexX5nHTX5uwDiXmWDcYW298RarNolhRO4qt1958qqI4ep6RrhRXGbCyVn8PKf8dpfjWGDikTKmMNrGpN32gIu9mLjaiDh3uHZFkT@qDSKDWHspZ5QIt7Fiw379G@xwD9GSJ8IgeV0@t6QV1iqh0wun3C10Q2bpveTSlgQsQji873pkj6SRzYEKi6vHr5XLTDUVtbd0dbJFNhpNNTerSvQenc@v8dhFQLTn@vxKH7SS121p1jb5vJL@P@h0uX8 "Python 3 – Try It Online")
[Answer]
# Deadfish~, 2496 bytes
```
{{i}}{ii}ic{d}ciiiiiic{d}ciiicic{i}ddc{dd}icdddc{ii}ddc{d}dcdddc{i}iiic{dd}iiic{i}iiic{d}ccdddc{i}iiic{d}dciic{i}iiic{dd}iiic{i}iiic{d}c{i}iiciic{dd}iiic{i}iiic{d}dciic{i}iiic{dd}iiic{i}iiic{d}c{ii}ddc{d}dddc{i}iiiiic{dd}ic{i}dc{d}dc{i}iicddc{d}iic{i}iiiiic{dd}ic{i}iiic{d}cdc{ii}ddcdddddc{d}iiicdddddcdddc{i}iiic{d}cc{i}icdcc{d}ic{i}iiic{dd}iiic{i}iiic{d}cddc{i}cdddc{i}iciiiiiic{dd}dc{i}dc{d}ddc{ii}dcdc{d}ddddddc{i}ic{i}c{d}ciiiiiicdddc{d}dddcddcddc{i}icc{i}ddc{d}ddcdddc{i}ddciiciiiicic{d}ddddcdddddc{i}iiciiciiiiiicddcdc{d}dddciiiiciiiiic{d}cicc{i}iiicdddc{d}icdddddc{i}icciiiiiiciiic{dd}iiic{i}icdddciiiic{d}iic{i}iic{d}ddcdddc{i}iiic{d}dddcdc{i}ciciiiic{d}ddddcdc{i}iiiic{d}dddciiiiciiiiic{d}cicc{i}iiic{d}c{d}iiiciiicdddc{ii}ic{dd}iiic{i}iiic{i}dddcddddddc{d}dciciiiiic{i}ic{d}dciciiiic{d}ddddcddddc{i}iiic{d}ciiiiicdddc{ii}dc{d}ciiiiiic{d}ddddddc{ii}dddc{dd}iiic{i}iiicic{dd}iic{ii}iic{d}ddddc{i}iciiiiic{d}ciiiiiiciic{d}iiciiiiiic{d}ic{d}iicic{ii}dddc{dd}iiic{i}dciiiiic{dd}iic{ii}iiiic{d}ddddddc{i}ic{d}dddciiiiiciiic{i}ddcddddc{dd}iic{i}icciiic{d}ic{i}iiiic{d}ddcdddc{i}ciiiiic{d}ddcdddc{i}iiicc{d}dddciiiiciiiiic{d}cicc{i}iiiciiicddc{d}ddddcdc{i}iiiiiicdddddcdddc{d}dc{ii}c{d}ddddcic{d}iiic{i}iiic{d}cdcddc{i}iccddddciciiiicic{d}dddc{i}iic{d}iic{i}iiiicic{d}ddcdddc{ii}c{d}dc{d}ic{ii}dddc{dd}iiic{i}iiicddddddc{d}iiic{i}iiiiicddddcdcciiicciiic{dd}iiic{i}icdddciiiic{d}iiciiciiiiicddddddciiiiicdddddciiiiic{d}dddc{i}iiic{i}ic{d}iiic{d}dddciiiiciiiiic{d}cicc{i}iiic{d}dcddddddc{i}iic{d}iic{i}iiiicic{d}ddcdddc{i}dcicdc{d}icic{i}dc{d}iicc{ii}ddc{dd}ddciiiiic{i}c{d}ic{i}cic{d}iiic{d}ddc{ii}ddc{d}ddddc{ii}dddc{dd}iiic{i}iiiic{dd}iic{i}iiiciiiiiic{dd}iciicddc{i}iic{d}iic{i}iiiiicdddddciiiic{dd}iic{ii}iiiic{d}iiiciiic{dd}iiic{i}icdddciiiic{d}iic{i}iiiiic{d}ddddc{i}ic{d}ddc{ii}dddc{d}ciiiiiicdddcddddciciiiic{d}ddddc{i}iiiicddddc{d}dddc{i}iiiiiic{d}icddcic{i}iiciiic{d}iicdciiiiiiciiiiic{d}ciiiiiic{d}ddddc{i}iiiic{d}ddcdddddcic{i}ddc{i}iicddddddc{d}iiic{d}iiiciiiicddcic{i}iicdddddcdcdddddcddcic{i}iicc{d}ddcdddc{i}dcddddddc{i}dddc{i}ddcdddc{d}ddcdddc{i}iiic{d}dddciiiiciiiiic{d}cicc{i}iiicddddddciiic{i}dddc{dd}iiicdciiiiciciiiic{d}ddc{ii}ddcic{d}ddcdddc{ii}cddddddc{d}dc{i}dddciiiiiicdc{d}dddddcdc{i}iciiiiiicdciiic{d}ddddc{i}ic{d}ddcdciiiiic{d}iiicc{i}iiiciiic{dd}iiic{i}icdddciiiic{d}iic{i}iic{d}ddcdddc{i}iiic{d}dddcdc{i}ciciiiic{d}ddddcdc{i}iiiic{d}dddciiiiciiiiic{d}cicc{i}iiic{i}dddc{d}ciiiiiic{d}iccdddddc{i}ddc{d}dc{i}ic{i}ddc{d}icdddddciiiiicddddddcic{i}cicdddddciiic{i}dddc
```
Uses an alternative interpreter. [But in the ordinary one](https://tio.run/#deadfish-), you can give it input. It's not going to do anything though.
[Try it online!](https://tio.run/##xVdLb@M2EL7rV3BPkhonsFtsgQbrvTRbdIGiuRRogTQwFJKOBlFEQ5IfC0O/PeX7Jcl2Ll0hSCjOg9/MfDNUNt@6ktU/vb3B64Y1HWq/tUmCq6Jt0R0tyBra8kvTsCb7csB00wGr89sE8YfQNVqtoIZutcpaWq1n6JW2bfFMtYJ4Ng3UXWb27TY/5IYeoMsWeZJs0BL9yWqawBql15sUQS0ViuZ5pzwJDbPzYBY3UBN6yIRFfrV4TJLdinG934qqpXzd8fVfzVZ73Y14VfopC0RD9zvlXlkIr2l3mUWC5QESBF4dLDYJCI8AwpcBwg6QcpseLrNI9itqUey9bO1X9966CZHuR5AqRyk9c@7eId1fFltgIUCl9@@xENDT5jKLBL@SlusfU0hvUZrOUErMojULZhbYLEqz2JtFZha5WRzNopeLXiSSc0fljq95oV2LCBgPHMMjuuLgIY0ERAtILGi1oI0FTAtYLMBagGNBqQVlLNhrwT4WZFqQxYJcC/JYcNSCYyzotaBPXXoOU@k5vDs9L1Pp@fXd6bmbSs/LVHoOU@m5m0rPP1Pp4Ra0kjxi34dH/1theP4TcbnQA8XbjmYFxjN@kbDnGYLlfIYavt20/CJayimlb5unpsAvtBMdPVfToISKIkCfUEXrTNh79xIuuZ7YewA@CcyuCLEUw8PG5izEw5EIhAu7KSvim5Axk@uTJu2YyQ9L8WfaaB8bqYs2/Z1WFZuhv1lTkQ98AtGaLNM0n3aUxY64XABY8jSGAikMwzfPyVT7T5D2MYUIXR6j85@nhhYv417GYXLngD4vz4Ec@qWcZkNdy7jTlDjGMaxZg1ZC3hT1M804o38ZQSKLMNoD6AotZvKzIn@Yh2lsu6Kj582S4UHSMnYHVrB4DAN8YqzKTAJyVNTkdN1sroa9YNt54KWPvTS02zY1epBhweN0zsuJ9vi3/oPVz6iCHUVdSZH4uv2Qhvmw36bzqG3E54WGuJSfGbcjeZyHNjXrUOYjE0OO19/f4vdOPuhB/oU15ERTQEujz3Ie09d6V1QggBU8zR1t0LFHRYfkBw9fpzeccq9Fx4HwtOX5Bdy2@fJmiD8mMz0jrhciGv3y48efc/GaiU83kSmp9QnNjc5nrvIxHwuWXRzs/Y4264rtRYAiYBFr9lVHmotjtq/bquiY@BaMY58J@UUJMNWcuhvYOMMkM88OXTxujMtGOMiHHryBFvdAkhioUIv/k/jvbZflycj84CIxMd7ejkfo@yNAD/hIegzyMUvMV9ATwt8JVyBiBXqjJ/q9VwZE/TWvPQ7FXN0XD7TlEo/KzlpaRPZAoynhKx/qAKVoHfh6xp@NkRBi1EG/hCFhueYGUukERGVlrV2WNTCNXh2MTSxWXdh6xSEuWvUjlWyleoeTyNSBrqRyip1jMFKVGOtVGTgiYBOLyYfnAxsHcejYevISHsIz9VVngzgJ3J7e9HamgUkeqLMtTs3psBjQ2xRoXliHugXIAEVUdK8IoEvntY2tmzopOt8AUujcGY4VvjubO@fe7oydQLBHaXNGBKsPkqnLZunuTHVlfWZH1cMw3BMbZ4sFtg/DKoddplpDMV/ugqlw0KuWhlonILsjnet4HELWB5g4R6tGgklgJ4dGL@M5S3@bC@3Mj9cnj8dUF/B59jtOn41YMlwH7AakLBzYYe9QqQSB7k8fUTh5pzgPPqcgmH0yK@OY/dSM8fniiQNxl/nQSTxWfRL5Vrbc0S0DZhxisBPVHE@8yQgwMiaGbWX8EHddBcyzcQdH6qaxzWMFcdkdRdz9QOI74xLCOQ5bZ7oOxshLoaHJoO/8KazdmFLYkYXDG5PgiXp6TaRmEPTf/1IaUEySBXtVcJ8m7j2cCsSjBfZExvt/ "Python 3 – Try It Online")
] |
[Question]
[
The powers that be want to be able to quickly convert any number they have into their own number base using any format they would like.
**Input**
Your program must accept 3 parameters.
1. Number: The string number to be converted
2. InputFormat: the base string the number is currently in
3. OutputFormat: the base string that the number is to be converted to.
**Output**
Your program must convert the `Number` from the old number base `InputFormat` to the new number base `OutputFormat`
**Examples**
```
("1","0123456789","9876543210") = "8"
("985724","9876543210","0123456789ABCDEF") = "37C3"
("FF","0123456789ABCDEF","0123456789") = "255"
("FF","0123456789ABCDEF","01234567") = "377"
("18457184548971248772157", "0123456789","Aa0Bb1Cc2Dd3Ee4Ff5Gg6Hh7Ii8Jj9Kk,Ll.Mm[Nn]Oo@Pp#Qq}Rr{Ss-Tt+Uu=Vv_Ww!Xx%Yy*Zz") = ",sekYFg_fdXb"
```
***Additional***
The new base 77 test is not required props if it works though
1. if your in a language where you have to convert to a number first and are locked within 32Bit you can skip it.
2. as it's an additional test.
All examples were generated by PHP 7.2 with the bcmath extension using the following code (vars mins but code formatted). there will probably be a shorter way this is just the way I came up with for the system I needed to do this with would be nice to see if anyone could come up with a shorter version though.
PHP 7.2 (bcmath - extension) 614 bytes
```
<?php
function f($a, $b, $c)
{
$d= str_split($b,1);
$e= str_split($c,1);
$f= str_split($a,1);
$g=strlen($b);
$h=strlen($c);
$k=strlen($a);
$r='';
if ($c== '0123456789')
{
$r=0;
for ($i = 1;$i <= $k; $i++)
$retval = bcadd($retval, bcmul(array_search($f[$i-1], $d),bcpow($g,$k-$i)));
return $r;
}
if ($b!= '0123456789')
$l=f($a, $b, '0123456789');
else
$l= $a;
if ($l<strlen($c))
return $e[$l];
while($l!= '0')
{
$r= $e[bcmod($l,$h)].$r;
$l= bcdiv($l,$h,0);
}
return $r;
}
```
[Try it Online](https://tio.run/##lVLZkppAFH33K3pIp6QjWjSCYCGVzGb2fY9jWU3TCLEHCKBmMuW3mx4ZBCq8hCqWe865y7l0EiT7/eRxEiQdfx3RPIwj4MuQKAC64qaoc9sB4oKeA7I8XWQJD3NZcBjZBcEaBK0Iv0GQilg6AucsEmVKKDhCtIRWR4iUUOp0u8Vn6AMhdRzQVbE21I2RaY276EAV897rVfsY@XEqckLgAGyL18QRLWwAw14PHTVFFss3hAudS4nnyfexIsLrNZdJmpKbRcZISgMZ@jMY9vFcbMpDikuTeCvDpQJXfRgihKrmosY6jUTtAtpVJtyTNhOHQbhT/YmGpCjCeMbqYgBJbTl8Um0U/TMHm0E@L9TbIORM6A9ztO3wTi28x2IVXIEBmg9KG2Vjl3rhpmAVFdUt1nzv9owGsThcEpYUqbIjgrFljgx9qGFVQgPpKr2KJLtTqseWYWp6U1XPPz07v7ictiROp226Ruv/T2pJwZZumHcP3RqbWNMt09SwYUoKaLo8JeqZi8@pduENL5k@9Y2ny9GzwHweWi9@jl@ulFd88Pp69iaav42fvEsevP@1@5Defsz6n/Le57XzZbP4uj359vvh95tHP/5Uc@z/Ag)
**Scoring**
This is code golf; shortest code wins. Standard loopholes apply.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Za
```
[Try it online!](https://tio.run/##y00syfn/Pyrx/391Nzd1LnUDQyNjE1MzcwtLRydnF1dkIXUA "MATL – Try It Online")
[All test cases.](https://tio.run/##y00syfmf8D8q8b9LyH91Q3UudQNDI2MTUzNzC0sgx9LC3MzUxNjI0ADMMTU3MkEXRah3dHJ2cXUDCrm5YRdHMZqQInUA "MATL – Try It Online")
For the [Za lord](https://www.deviantart.com/mommyspike/art/Pizza-or-Death-113693905)!
[Answer]
# [R](https://www.r-project.org/), 124 bytes
```
function(n,s,t,T=L(t),N=(match(!n,!s)-1)%*%L(s)^(L(n):1-1))intToUtf8((!t)[N%/%T^rev(0:log(N,T))%%T+1])
"!"=utf8ToInt
L=nchar
```
[Try it online!](https://tio.run/##Vc7NCoJAFEDhvU@hAwP31kTaf5KLsoRgcDWtIsHESqg7oFdf31zW9uMsTt3f86aMLXVlze5u4vaPlgquLAGpRrEykQZGlUbwybl4gUfKa3ASoBxJDQ1moIEwDAbBitjYCz82AB7jNZVTabK67MAP3/YJqTKIUppxcENHeCJqh9TYM7GjIypeef07AyJJhBJ@MJsvlqv1Zrs/xMfTPwnsvw "R – Try It Online")
Ugh, this was a doozy. I use the typical base conversion tricks for R, but string manipulations in R are still messy!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 bytes
Anonymous infix lambda. Takes `InputFormat` as left argument and `OutputFormat` as right argument, and prompts for `Number` from stdin. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.
```
{⍵[(≢⍵)⊥⍣¯1⊢(≢⍺)⊥⍺⍳⎕]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9W6N1njUuQhIaz7qWvqod/Gh9YaPuhZBxHZBxHY96t0M1BNb@z8NqOtRbx/EgK7mQ@uNH7VNBPKCg5yBZIiHZ/B/dQNDI2MTUzNzC0v1NHVLC3MzUxNjI0MDdS51QyBGEkhDUuro5Ozi6gaWNzU3MgEyMOSQlQPl3dzwK4IoAQA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` "dfn"; `⍺` is left argument, `⍵` is right argument
(mnemonic: left and right ends of the Greek alphabet)
`⍵[`…`]` index the output format with the following:
`⎕` prompt for input
`⍺⍳` **ɩ**ndices of those characters in the input format
`(`…`)⊥` evaluate as being in the following base:
`≢⍺` the length of the input format
`⊢` yield that (separates `¯1` from `(≢⍺)`)
`(`…`)⊥⍣¯1` convert to the following base:
`≢⍺` the length of the output format
[Answer]
## C (gcc), 79 + 46 = 125 bytes
```
char*O;l,n;g(n){n/l&&g(n/l);write(1,O+n%l,1);}
```
This must be compiled with the
```
-Df(s,i,o)=for(n=l=0;n=n*strlen(i)+index(i,s[l])-i,s[++l];);l=strlen(O=o);g(n)
```
flag. (Yes, this is incredibly sketchy, which is why I'm keeping my old answer below.) This defines a macro `f` that outputs the answer to STDOUT.
[Try it online!](https://tio.run/##nZDBSsNAEIbvPkVYaNlpNjSbJk3Csge15poHkB7CmqQL40SyEYXSV3dNi4IFvTiXmR@@bxjGRL0x3ptDM65qhYJUzwmOtMblcp7WCOpttFPLpahDWqCQoE7e0hQ8N5Y4BMebYK6OM8kEi2WySbNtXpRzKIt8m6WbRMYM1IV6eZ0cZ99pdsoiy5P0mv255fbufvdQ/alX1W/01Rn/Vc/oyX@YDpve@WjXcSesGEB3w8hJo44VaVq5acSWuIXQ0lP7zq1wj7iH6NzDEPcKFOovqNYDXL77CQ)
## C (gcc), ~~133~~ 131 bytes
```
char*O;l;g(n){n/l&&g(n/l);write(1,O+n%l,1);}f(s,i,o,n)char*s,*i,*o;{for(n=0,l=strlen(O=o);n=n*strlen(i)+index(i,*s)-i,*++s;);g(n);}
```
[Try it online!](https://tio.run/##nY7BaoNAEIbvfQpZaJjRCXGNRmXx0KT16jMEq@nCZgyupQXx2c1GWmigvXQOw/zwfTNTr091Pc/127H3K2XUCRhH3pjVyk0bg@qj10MDkqqAHw1JVFMLljR1xLhYlnxNfqfGtuuBi5BMYYfeNAxV0aHigv2vrDHQ/Np8guMtrl0PAqtwuammWfPgnY@aAb3xwXPVgpCCRCijbZzs0ix3Ic/SXRJvIxkKVAt1eR8siO/knDxL0ii@Z39uedofnl/KP/Wy/I2@e@O/6g2d5is)
This defines a function `f` that outputs the answer to STDOUT.
```
char*O; // declare variable to store output charset
l; // will be set to length of O
g(n){ // helper function to print the result
n/l&&g(n/l); // recursively calls itself if there are more digits
write(1, // output to stdout...
O+n%l,1); // the byte at (n mod output base) in O
}
f(s,i,o,n) // main function
char*s,*i,*o;{ // declare string inputs
for(n=0, // initialize n to 0
l=strlen(O=o); // assign output charset so we don't have to pass it to g
n=n*strlen(i) // repeatedly multiply n by input base...
+index(i,*s)-i, // ... add the index of the digit in input charset...
*++s;); // and move to the next digit until there's none left
g(n); // call the helper function on the resulting integer
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~5~~ 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
nVW
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=blZX&input=IkZGIgoiMDEyMzQ1Njc4OUFCQ0RFRiIKIjAxMjM0NTY3Ig)
---
## Explanation
```
:Implicit input of U=Number, V=InputFormat & W=OutputFormat
nVW :Convert U from base V to base W
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
ÅβIÅв
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cOu5TZ6HWy9s@v/fzY3LwNDI2MTUzNzC0tHJ2cUVWQAA "05AB1E – Try It Online")
This does *not* work in the legacy version of 05AB1E. It only works on the new version, the Elixir rewrite.
### How it works
```
ÅβIÅв – Full program.
Åβ – Convert from custom base to decimal.
I – Push the third input.
Åв – Convert from decimal to custom base.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
⍘⍘SSS
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITEdmeuYVlJZA2Zo6CihcDL6m9f//0UqWFqbmRiZKOkCGuZmpibGRoQGQY2BoZGxiamZuYeno5Ozi6qYU@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input the "number"
S Input the input format
⍘ Convert to number using that format
S Input the output format
⍘ Convert to string using that format
Implicitly print
```
The `BaseString` function automatically converts between number and string depending on the type of the first parameter.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
[sundar found the real builtin to do this!](https://codegolf.stackexchange.com/a/170740/67312) Go upvote that answer instead of my dumb one :-(
```
ZAwYA
```
[Try it online!](https://tio.run/##y00syfn/P8qxPNLx/391Nzd1LnUDQyNjE1MzcwtLRydnF1dkIXUA "MATL – Try It Online")
```
% implicit input N, the number, and S, the digits of the Source base
ZA % base2dec, convert string N using S as digits into a base 10 integer
w % swap stack elements, with implicit input T, the digits of the Target base
YA % dec2base, reverse the ZA operation with digits coming from T instead.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~132~~ ~~129~~ ~~122~~ 121 bytes
```
lambda n,a,b:g(sum(len(a)**i*a.find(j)for i,j in enumerate(n[::-1])),b)
g=lambda n,c:c[n:n+1]or g(n/len(c),c)+c[n%len(c)]
```
[Try it online!](https://tio.run/##jZDPboMwDMbPzVNEkSolNN1KgAKROGzdeImOQ6CBUYFbQTjs6VnC/qiVdtjFlu3v91n29cO8X0DMdfY2d6ovTwoDV7yUDR2nnnYaqGKe13rqoW7hRM@svgy45WfcAtYw9XpQRlM4Srn1C8Z4yVCT/TpVsjqChI1fWKqh8OgMK8YrtrGD9VdVzEaPZsQZpmhFKfEJJztfBGG0j5PUFmkS76MwEP6OMI5JYuMiTJMoFuG94BZ9ej68vOYLE8SH4AfL879UdzsdIqLov8T3CpsRQ8h9yF3EBz1OnXGfWg6UaHUdWjC4pp5rsPkT "Python 2 – Try It Online")
An anonymous function (thanks, [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)!) which converts the original number to a base 10 integer, then passes the integer and the new base string to function g(), which recursively converts to the new base. Now passes length of the OutputFormat as a parameter to g().
Updated g() for a lower bytecount. (thanks, [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)!)
Replaced index() with find(). (thanks, [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)!)
## Ungolfed Explanation:
```
def f(n, a, b):
# reverse the string to that the least significant place is leftmost
# Ex: 985724 -> 427589
n = n[::-1]
# get the value of each place, which is its index in the InputFormat, times the base to the power of the place
# Ex: 427589, 9876543210 -> 5*10^0, 7*10^1, 2*10^2, 4*10^3, 1*10^4, 0*10^5 -> [5,70,200,4000,10000,0]
n = [a.find(j)*len(a)**i for i,j in enumerate(n)]
# add all of the values together to bet the value in base 10
# Ex: (5 + 70 + 200 + 4000 + 10000 + 0) = 14275
n = sum(n)
# call the convert to base function
return g(n, b)
def g(n, c):
# string slice, which will return an empty string if n:n+1 is not in range
# an empty string is falsey
if c[n:n+1]:
return c[n:n+1]
else:
# get current least significant digit
rem = c[n%len(c)]
# get the rest of the integer
div = n/len(c)
# get the converted string for the rest of the integer, append the calculated least significant digit
return g(div,c)+rem
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
iⱮ’ḅL{ṃ⁵ṙ1¤
```
[Try it online!](https://tio.run/##y0rNyan8/z/z0cZ1jxpmPtzR6lP9cGfzo8atD3fONDy05P///@qWFuZmpibGRoYG6iCOqbmRCZBhYGhkbGJqZm5h6ejk7OLqpg4A "Jelly – Try It Online")
Argument order: InputFormat, Number, OutputFormat. **Be sure to quote the arguments with proper escaping!**
[Answer]
# Pyth, 21 bytes
```
s@LeQjimx@Q1dhQl@Q1le
```
[Test suite](https://pyth.herokuapp.com/?code=s%40LeQjimx%40Q1dhQl%40Q1le&test_suite=1&test_suite_input=%221%22%2C%220123456789%22%2C%229876543210%22%0A%22985724%22%2C%229876543210%22%2C%220123456789ABCDEF%22%0A%22FF%22%2C%220123456789ABCDEF%22%2C%220123456789%22%0A%22FF%22%2C%220123456789ABCDEF%22%2C%2201234567%22&debug=0)
Explanation:
```
s@LeQjimx@Q1dhQl@Q1le | Code
s@LeQjimx@Q1dhQl@Q1leQ | with implicit variables
m | Map the function
x d | index of d in
@Q1 | the second string in the input
hQ | over the first string in the input
i | Convert the resulting list to int from base
l@Q1 | length of the second string in the input
j | Convert the int into a list in base
leQ | length of the last string in the input
@LeQ | Turn each number in the list into the character from the numbers index in the last string in the input
s | Concatenate the strings in to one string
| Implicit print
```
[Answer]
# [Haskell](https://www.haskell.org/), 119 bytes
```
n!f=init.((foldl((+).(l f*))0[i|c<-n,(i,d)<-zip[0..]f,d==c],0)#)
(0,d)#b=[b!!d]
(r,d)#b=r`divMod`l b#b++[b!!d]
l=length
```
[Try it online!](https://tio.run/##fY7BToNAEIbvPMUgHnYFNguFAgnbRKuc7MkjEgtdKBu3C4HVJsZ3R7QeSEycw2T@75vD35bjay3lNCmzYUIJTRBqOsklQjYmSEJzgzHNxechdZWDhMNx6n6IPqeEFI3DGTsUDsUWNhCdnVWxvDJNXhhouMRhz8X7ruN7CZVV2favlkzW6qjb6VQKBQxOZb97AYSec@U0ji7cTf@mn/TwqOAaxrY7A/oRGGwbrsDdzGu@0Fwbz5DAuRv4iA34HgJSqHq8BJamcKz1tlO6VnqcPKCevwrCdRQnkMTROgxWvkeNJA4jP1iQxd/t3fb@ITOy7A9bgH/1Fw "Haskell – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~100~~ 97 bytes
```
{$^c.comb[(":"~$^b.chars~[$^a.comb>>.&{index $b,$_}].perl).EVAL.polymod($c.chars xx*)].join.flip}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiUuWS85PzcpWkPJSqlOJS5JLzkjsai4LlolLhEsYWenp1admZeSWqGgkqSjEl8bq1cANEJTzzXM0UevID@nMjc/RUMlGaJPoaJCSzNWLys/M08vLSezoPZ/cWKlQpqGkqGSjpKBoZGxiamZuYUlkGNpYW5mamJsZGigpGnNBVVlaWFqbmSCKousz9HJ2cXVDUmDmxs2eRSriFcMVPofAA "Perl 6 – Try It Online")
Anonymous code block that takes 3 strings in order, input, input format and output format, then returns a string
### Explanation:
```
{ # Anonymous code block
$^c.comb[ # Split the output format into characters
(":"~$^b.chars~[$^a.comb>>.&{index $b,$_}].perl) # The radix syntax in a string e.g ":3[1,2,3]"
.EVAL # Eval'ed to produce the base 10 version
.polymod($c.chars xx*) # Converted to a list in the output base (reversed)
] # Convert the list into indexes of the output format
.join # Join the characters to a string
.flip # And unreversed
}
```
[Answer]
# VBA, 182 bytes
A declared subroutine which takes input, `n`, in the language `y` and projects that into language `z`.
```
Sub f(n,y,z)
l=Len(n)
For i=-l To-1
v=v+(InStr(1,y,Mid(n,-i,1))-1)*Len(y)^(l+i)
Next
l=Len(z)
While v
v=v-1
d=v Mod l+1
v=v\l
If d<0Then v=v+1:d=d-l
o=Mid(z,d+1,1)&o
Wend
n=o
End Sub
```
[Answer]
# JavaScript (ES6), ~~90~~ 86 bytes
Takes input as `(input_format)(output_format)(number)`.
```
s=>d=>g=([c,...n],k=0)=>c?g(n,k*s.length+s.search(c)):k?g(n,k/(l=d.length)|0)+d[k%l]:n
```
[Try it online!](https://tio.run/##lc5dC4IwFAbg@36FDIItbX6uWTCjLP@EeCHzo3LMcNJV/90QjbK66dwdznkf3kt6SxVvztd2Kess7wrWKRZkLCgZjLmBMZaJUTELsYBvSyiNaqGwyGXZnnSFVZ42/AQ5QptquJpQsGx8QHcL6VlczUWykR2vpapFjkVdwgICy3Zcj6yovwYIgrVPV8RzHdvqNxsgpL2NaWrAB7MPYZp5ebt9eDhGg0qo4/VYL7g0dL@QX7FptSh6tukRh5C/jKmgjUUo6B4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 130 129 bytes
```
v;c(r,i,s,t)char*r,*i,*t;{for(r[1]=v=0;*i;v=v*strlen(s)+index(s,*i++)-s);for(s=strlen(t),i=1;*r=t[v%s],v/=s;memmove(r+1,r,++i));}
```
[Try it online!](https://tio.run/##lVDLbsMgELz7KxBSJLA3inGclyiHvvITDofIIS1SbFdAUdUo3@7ivBP1Eg4sDDPM7pT9j7JsW89LYkCDBUfLz6WJDcQaYse368YQUzApvEh5rLkXPrbObFRNLE10vVI/xAZyktC@pbyjW3EkOApaMB4b4QrfsxL8QFheqapqvCImYWAgSTSlfNd2rih2yrpyaZUtZDGUSETbCIW1RZhhwCnLhvloPJnOwmU2nYxH@TBjKUY7ONFm09Eky2@fr4XPL69v7/NrxXz@H@HG7AF24EY7HkW6dqha6pr4Rq/ocYz9jEbZ740rWJrlMhA7PISGSKfQSKCUh/KErP5VzRqdA0GDE3QJiaMuvUNr@31vQg4OcNEWWhapvAPYPZBJys@/fJnQz5pgssA9u8BwU2ho83Ba1BjOmtN62BeOoRz9Q4LtHw "C (gcc) – Try It Online")
-1 byte using `index` instead of `strchr`.
This is a simple iterative approach, reusing some variables (and thereby abusing `sizeof(int) == sizeof(char *)` on TIO) to save bytes.
Input:
* `i` input number
* `s` source base characters
* `t` target base characters
Output:
* `r` result number (pointer to a buffer)
### Explanation:
```
v; // value of number
c(r,i,s,t)char*r,*i,*t;{
for(r[1]=v=0; // initialize value and second
// character of output to 0
*i; // loop while not at the end of
// input string
v=v*strlen(s)+index(s,*i++)-s); // multiply value with source base
// and add the value of the current
// digit (position in the base string)
for(s=strlen(t),i=1; // initialize s to the length of the
// target base string, length of
// result to 1
*r=t[v%s],v/=s; // add character for current digit
// (value modulo target base) and
// divide value by target base until
// 0 is reached
memmove(r+1,r,++i)); // move result string one place to
// the right
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~97~~ 95 bytes
Thanks to Chas Brown for -2 bytes.
```
n,s,t=input()
k=0;w='';x=len(t)
for d in n:k=len(s)*k+s.find(d)
while k:w=t[k%x]+w;k/=x
print w
```
[Try it online!](https://tio.run/##hY5ZT4NAFIXf51eMYxqhxQoUOtBmEruAu3Wpa9OYFqYWqQMOU6EafzuC@mATE1/uvefkyz0nXol5xPTci3xKEEI5UxJFkIDFSyHJICRqOyVbW@2MLCiThAxmEYc@DBhkrfDLS@RqWEvqs4D5ki@DdB4sKAxbKRGjsJKNa2k73CEZiHnABEzzIgP8QEO@pC0AoeCrckFIM@rBsgkob4/GAjoD1@E84t/AlNNJCHKkIQWpmt4wzCa27ELYFm6aRkPXVAQKYWLdWHd/851ur@@4Bei6f/lrr/@HEJCQZhkmLodh2VjTDQtjXTMxUuB6zc5E7U61nqf3/YZDDXdm7j029@f4ILAOn@yjUDle1E@eR6dsPIh2z@LN85ePC/5@mWwPRe1qSa5fH27Sjduscreq3r8h@RM "Python 2 – Try It Online")
[Answer]
# Java 10, 131 bytes
A lambda taking the parameters in order as strings and returning a string.
```
(i,f,o)->{int n=0,b=o.length();var r="";for(var c:i.split(r))n=n*f.length()+f.indexOf(c);for(;n>0;n/=b)r=o.charAt(n%b)+r;return r;}
```
[Try It Online](https://tio.run/##hVDLasMwEDzHXyEMBalxXOedVDiQPgI9lBxyLKVIjpUoddZGXpuW4G935bwO7aGwsDuz2tnV7EQpOrv1Z50VMtERiRKR5@RVaCAHp3UmNWBslIhismjYC71Co2FDohTK2CA9Qw1Zgd6lqVKzF/gCv4hlgYw7rcq57shRoE1Kg0jsGkXCmmpPeSnrzA72AAJh4Mkw9ZMYNriljJfCEBO6LreStAHRvfbzLNFIDWMQwq26Pm4rX8M6/loqGrHjAIdZwOEulMxY0WgrzBwp3EjWNtzEWBgghld1i/85sUz1muytQ@cfv70TYTY5O1qz@s4x3vtpgX5mm5gAVf7FIXc6GY57A9ezxXg0HPR73cCCoNvrD4aj8WQ6f3h8el64rPHmHykhpQ3XI@6HOCUpToOVU9U/)
## Ungolfed
```
(i, f, o) -> {
int n = 0, b = o.length();
var r = "";
for (var c : i.split(r))
n = n * f.length() + f.indexOf(c);
for (; n > 0; n /= b)
r = o.charAt(n % b) + r;
return r;
}
```
] |
[Question]
[
Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
c32-p95\32+c
```
[**Try it online!**](https://tio.run/##y00syfn/P9nYSLfA0jTG2Eg7@f//avXigpzMEnUdBfXM4qQ89VoA "MATL – Try It Online")
### Explanation
```
c % Implicitly input cell array of 2 strings. Convert to 2-row char matrix.
% This pads the shorter string with spaces
32- % Subtract 32, element-wise. Each char is interpreted as its ASCII code.
% Note that padding spaces will give 0.
p % Product of each column. Since (padding) spaces have been mapped to 0, the
% product effectively eliminates those colums. So the effect is the same as
% if string length had been limited by the shorter one
95\ % Modulo 95, element-wise
32+ % Add 32, element-wise
c % Convert to char. Implicitly display
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~80~~ ~~74~~ 71 bytes
```
lambda*t:''.join(map(lambda x,y:chr((ord(x)-32)*(ord(y)-32)%95+32),*t))
```
*Thanks to @shooqie for golfing off 3 bytes!*
[Try it online!](https://tio.run/##JYkxDoAgEMC@wmLuQHTQOGjiT1xQYsQoELhBXo9EpzatT3Q42@edzWzJl7pXrQRNAO3pjMVbefwje2SatiMguqDx4U3fcfF5@rwah7pACuI8@2As4Y5g4mpBQvSXISjjBQ "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 12 bytes
```
z⁶O_32P€‘ịØṖ
```
[Try it online!](https://tio.run/##ATIAzf9qZWxsef//euKBtk9fMzJQ4oKs4oCY4buLw5jhuZb///9bJ3NwbGl0JywgJ2lzYm4nXQ "Jelly – Try It Online")
-3 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~75~~ 70 bytes
*-3 bytes thanks to Dennis' suggestion of shooqie's suggestion. -2 bytes thanks to Zacharý's suggestion.*
```
lambda*l:''.join(chr((ord(i)-32)*(ord(j)-32)%95+32)for i,j in zip(*l))
```
[Try it online!](https://tio.run/##HcYxDsIwDADAr3hBtkNhKGIAiZ@wtERRHQU7csNQPh9Qp7u6tcV07Onx7GV6z3EK5Y54ziZKr8WJzCMJny4jh/15/@F2Pf5J5iBDBlH4SqVQmHt10QaJUDR@1uYbDoCzaUTuPw "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~60~~ 57 bytes
```
zipWith(\a b->toEnum$f a*f b`mod`95+32)
f=(-32+).fromEnum
```
[Try it online!](https://tio.run/##ddFPa8IwFADwez7F8ylUp91B3WEDexljjFEQdtgOwkztH6Np0qUJQ8XP3iV1bhTruyQkvzxe3lvTcptwXh38LnAqMkOzBB7nc@j6R5LNFtWeFe9Mr/sLCpEfaPkkTN5Lgd6kEC1zGS/v74aT8YCks74/GQ8Ht6mSuUNVTpmAGRRGv2kFPcgAv6WMEXBtRKZ2SA4@QVZGAkeAZcGZRrgIPwDcGG41OtYiGvSXvUAshachp1onCttY48y9CRMQif1qouChjzVrGoKR0eBSd5zvnAMbqf8N8b6M1EnpjcDDOrzLir3V9pO9Zh45NWf0153W7@2oErYOrejO0cxOB690YkP3e0uZiE2pVc0jKWJsobGShaWFiThbOagl5@0FpNTeEFQOWBi7J6KdRif6/FF3yy1Xp@aaSHAKnHOYOn3eXsjzBcEwCMJ6bG69kjcIwwCJf6x@AA "Haskell – Try It Online")
First line is an anonymous function taking two arguments.
This a straight forward implementation of the algorithm: `zipWith` takes both strings and applies a given function to the pairs of characters. It handles the truncation and also works for empty strings. `fromEnum` and `toEnum` are alternatives to `ord` and `chr` to switch between characters and their ASCII values which do not need a lengthy import.
**Edit:** -3 bytes thanks to Bruce Forte.
[Answer]
## C++, ~~331~~ ~~291~~ ~~282~~ ~~270~~ 268 bytes, Version 2 = ~~178~~ ~~176~~ ~~150~~ 148 bytes
Original Version :
```
#include<string>
#include<algorithm>
#define L length()
#define S std::string
S m(S a,S b){S c;int m=a.L<b.L?a.L:b.L;auto l=[m](S&s){s=s.substr(0,m);std::for_each(s.begin(),s.end(),[](char&c){c-=32;});};l(a);l(b);for(int i=0;i<m;++i){c+=a[i]*b[i]%95+32;}return c;}
```
-40 bytes thanks to Bruce Forte
-39 bytes thanks to Zacharý
Version 2, inspired by other people's answers
```
#include<string>
#define L length()
using S=std::string;S m(S a,S b){S c;for(int i=0;i<(a.L<b.L?a.L:b.L);++i)c+=(a[i]-32)*(b[i]-32)%95+32;return c;}
```
If the first version uses a lambda, it's because i wanted to test C++11 std::async function i just learnt before, so i kept it for no reasons...
More readable version :
```
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
#define L length()
#define S string
//Function code for the original version
S m(S a,S b) {
S c;
int m = a.L < b.L ? a.L : b.L;
auto l=[m](S&s){
s = s.substr(0, m);
for_each(s.begin(),s.end(),[](char&c){
c -= 32;
});
};
l(a);
l(b);
for(int i=0;i<m;++i) {
c += a[i] * b[i] % 95 + 32;
}
return c;
}
//Code for the version 2
S m2(S a,S b) {
S c;
for(int i = 0; i < (a.L < b.L ? a.L : b.L); ++i) {
c += (a[i] - 32) * (b[i] - 32) % 95 + 32;
}
return c;
}
int main() {
string a, b, c;
getline(cin, a);
getline(cin, b);
c = m(a, b);
cout << c;
}
```
[Answer]
# Dyalog APL, ~~36~~ ~~34~~ ~~33~~ ~~25~~ 24 bytes
```
{⎕UCS 32+95|×⌿32-⎕UCS↑⍵}
```
[Try it online (TryAPL)!](http://tryapl.org/?a=%7B%u2395UCS%2032+95%7C%D7%u233F32-%u2395UCS%u2191%u2375%7D%27split%27%20%27isbn%27&run)
[Try it online (TIO)!](https://tio.run/##Tc@xTsMwEAbgPU9x7WIk1KUtAwxdGBBDpgqJrUpqK7V0tYNzFgrQtRNFdEA8CQsLA2/iFwl26UW9xefv/pPsosaRbAu0VdetPdIibN@fw9vH3fUcJuPzy4uX38/w@jMZj/4xbPdh97XJUjZFDzsQdt9Ju07opjQCkoJoatQkMsH3k/YWpDVCEKwLIuXiBE6LY7kCozStlIOrsxgqPUFaHXBgwBWHD96SangyPFTkR2sl48qbyrURyRUtY/Wk60jaSN@Q67m0RkaufYl6yUgWMaJLx5FkCpiIN/f9s1KbiSkgIkwZ@ZqJfDbL@y@m/g8)
Input is a list of strings, and has trailing whitespace.
Here's how it works:
```
{⎕UCS 32+95|×⌿32-⎕UCS↑⍵}
↑⍵ - the input as a 2d array
⎕UCS - codepoints
32- - subtract 32
×⌿ - element wise product reduction ([a,b]=>a×b)
95| - Modulo 95
32+ - Add 32
⎕UCS - Unicode characters
```
[Answer]
# FSharp 275 bytes
```
let f (p : string, q : string) =
let l = if p.Length < q.Length then p.Length else q.Length
p.Substring(0,l).ToCharArray() |> Array.mapi (fun i x -> (((int(x) - 32) * (int(q.[i]) - 32)) % 95) + 32) |> Array.map (fun x -> char(x).ToString()) |> Array.fold(+) ""
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes
```
.BÇ32-`*₃%32+çJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fz@lwu7GRboLWo6ZmVWMj7cPLvf7/j1YvLsjJLEkuSqyqzElMyUwtzk3MTs1NBQlkphap66hnFiflqcdyAQA "05AB1E – Try It Online")
-1 for Emigna pointing out `₃` pushes `95`.
---
```
# ['hi', 'you']
.B # [['hi ', 'you']]
Ç # [[[104, 105, 32], [121, 111, 117]]]
32- # [[[72, 73, 0], [89, 79, 85]]]
` # [[72, 73, 0], [89, 79, 85]]
* # [[6408, 5767, 0]]
₃% # [[43, 67, 0]]
32+ # [[75, 99, 32]]
ç # [['K', 'c', ' ']]
J # ['Kc ']
```
---
```
.BÇ32-`*95%žQsèJ
```
is another.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 23 bytes
```
{z{2' e]' f-:*95%' +}%}
```
[Try it online!](https://tio.run/##S85KzP1fWPe/uqraSF0hNVZdIU3XSsvSVFVdQbtWtfZ/3f9opeKCnMwSJQWlzOKkPKVYAA "CJam – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform),100 96 95 bytes
```
(l,n)=>{for(int i=0;i<l.Length&i<n.Length;)Console.Write((char)((l[i]-32)*(n[i++]-32)%95+32));}
```
[Try it online!](https://tio.run/##NY7BSsRAEETv8xVNQOkx2SDKHmSSBfGqB9mDh8VDdhyThrFHpltBQr49G7Nal1dUQVFeNj7lMH8JcQ/7H9Hw4YzxsROBZzMaWCTaKXn4TvQGTx0x2jU@l7@690qJG9G8rFRw5g56aGHGWLFtd@N7ykisQO21oybWj4F7HS6p4T/r7ENiSTHUL5k0IPqhyxYxHuh1c3tjr5APVJarv7jblgusm@bl7f@NHgv5jKRFVZAcubBurSYzzSc "C# (.NET Core) – Try It Online")
-4 bytes thanks to @Zacharý
-1 byte by moving the increment
Uses a lambda and abuses the fact that characters are basically ints.
[Answer]
# Mathematica, 114 bytes
```
(a=Min@StringLength[x={##}];FromCharacterCode[Mod[Times@@(#-32&/@ToCharacterCode/@(StringTake[#,a]&/@x)),95]+32])&
```
**input**
>
> ["public","toll"]
>
>
>
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 52 bytes
```
[,:$#'"!MIN$take"![CS#.toarr]"!32-prod 95%32+#:''#`]
```
[Try it online!](https://tio.run/##bZExT8MwEIX3/opLUnSJ2magZcBDhcSAOoSFBalUIqnd1qqJjXMWKn8@JIU2ccSTPPjpe3enu4ry7VHwul5P2TjCMMhWz2PKjyIM1o8vUUo6t3YTBvPbmbGaw/3dzfx2EjHE6H1TP7DdaBTH8CesjJKE0BPKqigxGUEMnu1Bv85/EK6A6xKR4CMnEvYM@dn2h5mAUkg6CAssvlbCwhG0FYJLBIOL@u3w02kSVa8uhmf5M@GX1rwPHVy5t6cBRDY/@SvYf0vTQShL7iqyA6jQJfdmMq5QcutDpJUatLOt1UN4GxtuHJ9eg8HWWqeDcAFKKVh00NXx22XLZebPdHaSBNbAIE1T2MEUNs25DMQx5s0Ji@ZpR8YRJs3xZp2QsSb4BpMJcFmZ@gc "Stacked – Try It Online")
Function that takes two arguments from the stack.
## Explanation
```
[,:$#'"!MIN$take"![CS#.toarr]"!32-prod 95%32+#:''#`]
```
Let's look at the first part, assuming the top two items are `'split'` and `'isbn'`:
```
,:$#'"!MIN$take"! stack: ('split' 'isbn')
, pair top two: (('split' 'isbn'))
: duplicate: (('split' 'isbn') ('split' 'isbn'))
$#' length function literal: (('split' 'isbn') ('split' 'isbn') $#')
"! execute on each: (('split' 'isbn') (5 4))
MIN obtain the minimum: (('split' 'isbn') 4)
$take "take" function literal: (('split' 'isbn') 4 $take)
(e.g. `'asdf' 2 take` is `'as'`)
"! vectorized binary each: (('spli' 'isbn'))
```
This part performs the cropping.
Then:
```
[CS#.toarr]"! stack: (('spli' 'isbn'))
[ ]"! perform the inside on each string
string `'spli'`:
CS convert to a character string: $'spli'
#. vectorized "ord": (115 112 108 105)
toarr convert to array: (115 112 108 105)
(needed for empty string, since `$'' #.` == `$''` not `()`
```
Then, the last part:
```
32-prod 95%32+#:''#` stack: (((115 112 108 105) (105 115 98 110)))
32- subtract 32 from each character code: (((83 80 76 73) (73 83 66 78)))
prod reduce multiplication over the array: ((6059 6640 5016 5694))
95% modulus 95: ((74 85 76 89))
32+ add 32: ((106 117 108 121))
#: convert to characters: (('j' 'u' 'l' 'y'))
''#` join: ('july')
```
[Answer]
# [R](https://www.r-project.org/), 88 bytes
```
function(r,s,u=utf8ToInt)intToUtf8((((u(r)-32)*(u(s)-32))%%95+32)[0:min(nchar(c(r,s)))])
```
anonymous function; takes input as two strings; third argument is just to ensure this is a one line function and save some bytes.
The TIO link below returns an array with entries named with the first input.
[Try all test cases!](https://tio.run/##ZY5BSwMxEIXv/oo0UJLUFERb0FJ7lR56qyCIh93NbjeQncRkgqx/fp1sEQQfgffNMJl5cerYfj11GRq0HmTUSefnjN3j2R8BlQU8@1cqJSnLqNYP92pFlGZSy@XT9pbg/W43WJDQ9FWUTVmjlPpQ01CF4EbZ6UZym2rgml8f@yOuGa8zMsuMX1AhPrPHNglqf3lvaBpjNZJZMDlhLBhy7WxDEL1zZC9v9JNvmHOObcrC0@Fw4krf0OEUnMXr2SOdAIFsqBDbOM@1DFqLfRvZTpbG4lclCZ8ltOgzXOJIcPm2gaz2YMiQrpOZkgYIKEaJ/S@Hmn4A "R – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 65 bytes
64 bytes of code + `-p` flag.
```
$n=reverse<>;s/./($_=chop$n)&&chr 32+(-32+ord$&)*(-32+ord)%95/ge
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAv@q@TZFqWWpRYVp9rYWRfr6@lrqMTbJmfkF6jkaaqpJWcUKRgbaWvoAon8ohQVNU0tGFtT1dJUPz31/39fOztfLhABAA "Perl 5 – Try It Online")
[Answer]
# D, 113 bytes
```
T m(T)(T a,T b){T c;for(int i;i<(a.length<b.length?a.length:b.length);++i)c~=(a[i]-32)*(b[i]-32)%95+32;return c;}
```
This is a port of [HatsuPointerKun's C++ solution](https://codegolf.stackexchange.com/a/133871/55550), don't forget to upvote them!
[Try it online!](https://tio.run/##Ncy9DoIwFIbhmV5FF9NTQQaIgxbjTXQjDOVHPQm0pFQdCN56rQaGJ3nzneS03ks6gOQgqUokrfksaSNuxgJqR1FgASrtO313j6Je47ot523hIo6RN58LqBKrQ57xPdRr7U7HOM@E7dzT6vB7IS@DLR0UauB0JhEOo7GOTq5NAzSCRG@Lrus1DFCyiSVsDPoAA8eqpPzX71IHmlWcC7J4/wU)
[Answer]
# Java 8, ~~127~~ ~~115~~ ~~97~~ 95 bytes
```
a->b->{for(int i=0;i<a.length&i<b.length;System.out.printf("%c",(a[i]-32)*(b[i++]-32)%95+32));}
```
**Explanation:**
[Try it here.](https://tio.run/##tZNfS8MwFMXf9ymuhWnqXBD/PGi3ggiKD3vaizD3kKbZlpklNblR5thnn5lWEVlAiqaFXjg3v3Mu9M7ZM@uaSuh5@bjhijkHAyb1qgXgkKHkMA8d1KNUdOI1R2k0vamLHp8xOxof7eq5Ntr5hbB1T54Dhz5sWDcvuvlqYiyRGkH2jzPZY1QJPcXZvuwVdZkNlw7FghqPtLKhdUKSNk@OCBvJcff0JD0kxUh2Ou91@@K8Ez5ptt5kIXh4K1@okL0e4dnIEhZhLDLEwJqOxsDS7YgAnLKqUkuSuEpJTCia65D3ylq2JGlKGeeiQpJIV@ifYvYO@JlTaVIrX@go9e@Jd1AafYBhWERhG/Ph@4maDQRoIXEmLFySxl6FR9jG3ov67H2exh5P3qBwUYOHb09jjxdjyqjDzOupXTZmY@iPsqevsmpMlrr0Dm2cjkapxvSPNfyf5HZHsC9yuTVuvrG39/G/cYf2a@4ZKKXgLMqO6L/mD/J8EF/XHeL2/rq13rwB)
```
a->b->{ // Method with 2 char-array parameters and no return-type
for(int i=0; // Index-integer, starting at 0
i<a.length&i<b.length; // Loop over both arrays up to the smallest of the two
System.out.printf("%c", // Print, as character:
(a[i]-32) // Current char of `a` minus 32
*(b[i++]-32) // multiplied with current char of `b` minus 32
%95 // Take modulo-95 of that multiplied result
+32));} // And add 32 again
```
[Answer]
# C#, 166 bytes
```
using System.Linq;s=>t=>{int e=s.Length,n=t.Length,l=e>n?n:e;return string.Concat(s.Substring(0,l).Select((c,i)=>(char)((((c-32)*(t.Substring(0,l)[i]-32))%95)+32)));}
```
I'm sure there's a lot of golfing to be done but I don't have time right now.
[Try it online!](https://tio.run/##ZVDBTsMwDL3nK6JKSAl0EQJxgJJwQOI0JEQPHBCHLPO2SJkLtYuEpn57SVcmMXgX2@/52bIDzbYNNkNHEdey/iKGbSV@V2Ye8aMSIiRPJJ/ETsgMYs8xyM8mLuWjj6j0np7EEQ8dhlviNg8qj4spOidX0sqBrGPrdhFZgiUzB1zzpkTLhzRZcHiHN1C1wF2LP35z32DwrMjU3WKi1HmZtKkhQWClQhm1dSpsfKtVRphdXuhTxX/6X@PbKOiT6yt9Nia66od87uGOvIaaBOaljQz5FaCO969UQe8pcqFVEWmBxTjhv/0Z/HLvzuLI96IfvgE "C# (Mono) – Try It Online")
Full/Formatted Version:
```
using System;
using System.Linq;
class P
{
static void Main()
{
Func<string, Func<string, string>> f = s => t =>
{
int e = s.Length, n = t.Length, l = e > n ? n : e;
return string.Concat(s.Substring(0, l).Select((c, i) => (char)((((c - 32) * (t.Substring(0, l)[i] - 32)) % 95) + 32)));
};
Console.WriteLine(string.Concat(f("split")("isbn")));
Console.ReadLine();
}
}
```
[Answer]
# Common Lisp, 99 bytes
```
(lambda(a b)(map'string(lambda(x y)(code-char(+(mod(*(-(#1=char-code x)32)(-(#1#y)32))95)32)))a b))
```
[Try it online!](https://tio.run/##NcxBCoMwFATQq3ziwvmWLKp00YWH@SZFBWNCtNScPjWCqxnewJhl3kJGiPO6EzIWcYMVCA0MJ6He9nMZbz4oMYy3H20miXjAeYsGGtWzL6LLRgd3LV9YpVL5/bqCyytn9fPeKlLTdx1jUqf8AQ)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 24 bytes
```
¬íVq)®®©c -HÃ×u95 +H dÃq
```
Returns a string with trailing null-chars (`\u0000`) when the first input is longer than the second.
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=rO1WcSmurqljIC1Iw9d1OTUgK0ggZMNx&input=InNwbGl0IgoiaXNibiIKLVE=) with the `-Q` flag to show formatted output, including the null-chars.
[Run all the test cases](https://codepen.io/justinm53/full/NvKjZr?code=rO1WcSmurqljIC1Iw9d1OTUgK0ggZMNx&inputs=ImlzYm4iCiJzcGxpdCI=,IiIKIiI=,IiIKIkkgZG9uJ3QgbWF0dGVyIg==,IiAgICAgICAgICAgICAiCiJNZSBuZWl0aGVyIDooIg==,ImJ1dCBJIGRvISIKIiEhISEhISEhISI=,J3F1b3RlcycKJyIiIiIiIic=,Indvb2QiCiJodW5ncnki,InRyYXkiCiJnemlwIg==,ImluZHVzdHJ5IgoiYm9uZCI=,InB1YmxpYyIKInRvbGwi,InJvbGwiCiJkdWJsaW4i,IkdYISIKIkdYISI=,IjQgbGxsIDQiCiI0IGxsbCA0Ig==,Ik0+Pk0iCiJNPj5NIg==&flags=LVE=) using my WIP CodePen.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~95~~ 73 bytes
* Thanks @Zacharý for 4 bytes: unwanted brackets removed
```
lambda x,y:''.join(chr((ord(i)-32)*(ord(j)-32)%95+32)for i,j in zip(x,y))
```
[Try it online!](https://tio.run/##HcsxDsIwDEDRq3hBtiEwFDGAxE1YWqKojsCO3CARLh@qTv8tv7Q6mw493R/9Nb6nOMI3tBviKZsoPWcnMo8kfDwPvN@cN@@ul8OaZA4SMojCTwqtM3MvLlohEU6mEQOKxs9SvSH3Pw "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
F⌊⟦LθLη⟧℅⁺³²﹪×⁻³²℅§θι⁻³²℅§ηι⁹⁵
```
[Try it online!](https://tio.run/##dYy7CgIxFER7vyLlDWQbxUKsxEpwcQs7sQhJ3ASSXDYPH19/zeK2VjMMZ46yMimUnuiBiUHvogs1wO1s4lgsTFywpVp@55wNycUCx/aSqpgEg68ZNmvBetTVI1xdMHnWLPMlaRelh0M5RW3eMAnmOG/W/4j9IY3ZbefcE70Q9crWOKYPdU/qsv8C "Charcoal – Try It Online") Link is to verbose version of code. I actually wrote the calcualation as `(32 - ord(q)) * (32 - ord(h))` because it avoids consecutive numeric literals but I guess I could have just written `(ord(q) - ord(" ")) * (ord(h) - ord(" "))` instead.
[Answer]
# [Perl 5](https://www.perl.org/), 95 bytes
```
@a=<>=~/(.)/g;@b=<>=~/(.)/g;$#a=$#b if@a>@b;print chr 32+(-32+ord$_)*(-32+ord$b[$i++])%95 for@a
```
[Try it online!](https://tio.run/##K0gtyjH9/98h0dbGzrZOX0NPUz/d2iEJmaeinGiropykkJnmkGjnkGRdUJSZV6KQnFGkYGykraELJPKLUlTiNbXg7KRolUxt7VhNVUtThbT8IofE//8zi5PyuIoLcjJLAA "Perl 5 – Try It Online")
**Explanation:**
```
@a=<>=~/(.)/g;@b=<>=~/(.)/g; # Split the strings into 2 arrays
$#a=$#b if@a>@b; # Truncate the first if longer than the second
print chr 32+(-32+ord$_)*(-32+ord$b[$i++])%95 for@a # Multiply each character
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 19 bytes
```
(PA$* *(PA@?Zg)%95)
```
Takes the strings as command-line arguments. [Try it online!](https://tio.run/##K8gs@P9fI8BRRUtBC0g52Eela6pammr@//@/uCAns@R/ZnFSHgA "Pip – Try It Online")
### Explanation
```
(PA$* *(PA@?Zg)%95)
g is list of args; PA is string of all printable ASCII characters
Zg Zip items of g together: result is list of pairs of characters
PA@? Find index of each character in PA
( ) (Parentheses to get correct operator precedence)
$* * Map (fold on *) to the list: multiplies each pair of numbers
%95 Take list items mod 95
(PA ) Use those numbers to index into PA again
Print the resulting list of chars, concatenated together (implicit)
```
[Answer]
# [Factor](http://factorcode.org), 45
```
[ [ [ 32 - ] bi@ * 95 mod 32 + ] "" 2map-as ]
```
It's a quotation (lambda), `call` it with two strings on the stack, leaves the new string on the stack.
As a word:
```
: s* ( s1 s2 -- ps ) [ [ 32 - ] bi@ * 95 mod 32 + ] "" 2map-as ;
"M>>M" "M>>M" s* ! => ">MM>"
dup s* ! => "M>>M"
dup s* ! => ">MM>"
...
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 26 bytes
**Solution:**
```
`c$32+95!*/-32+(&/#:'x)$x:
```
[Try it online!](https://tio.run/##y9bNz/7/PyFZxdhI29JUUUtfF8jQUNNXtlKv0FSpsNJQysxLKS0uKapUslZKys9LUdL8/x8A "K (oK) – Try It Online")
**Example:**
```
`c$32+95!*/-32+(&/#:'x)$x:("split";"isbn")
"july"
```
**Explanation:**
Evaluation is performed right-to-left:
```
`c$32+95!*/-32+(&/#:'x)$x: / the solution
x: / assign input to variable x
$ / pad right to length on left
( #:'x) / count each x (return length of each char list in list)
&/ / min-over, get the minimum of these counts
-32+ / subtract 32, this automagically converts chars -> ints
*/ / multiply-over, product of the two lists
95! / modulo 95
32+ / add 32 back again
`c$ / convert to character array
```
[Answer]
# [Kotlin](https://kotlinlang.org), 65 bytes
```
{zip(it){a,b->(a-' ')*(b-' ')%95+32}.fold(""){s,i->s+i.toChar()}}
```
[Try it online!](https://tio.run/##dY69DoIwFIV3nuKGxHArlEHjIAk4uLr5BG0AvbEUQouDTZ@91p@4eZaTnG843220inS4CwXDoio425n0pcRPM@DNd4I6uAdNSJY5UUjeoOAZZGyN8t2r/S7fbnzZj6rFNGXOFMQbk1Npx@NVzMi8D/2iYRCkkYFLIOb1K6CGuRPtiXQXwaGCNP1B@Q9OUcpidMZow1jiAxmpEzMpsk8 "Kotlin – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 39 bytes
```
[ [ [ 32 - ] bi@ * 95 mod 32 + ] 2map ]
```
[Try it online!](https://tio.run/##HY4xC8IwFIR3f8WRRVB0qDioIG7SxUWcpEOaPjHYJjHvOUjpb4@J3PR93ME9tBEf0@1aX857aGZvGC@KjnoMWp4IkUS@IVonYHp/yBliHGYjRijLrVNQHHorClNRGWt03s2l7IVi8VO6o2RTYYUGrT1hgd0Wg@@KW2ZXDTqgSWNu/18cC6/TDw "Factor – Try It Online")
## Explanation:
This is a quotation (anonymous function) that takes two strings from the data stack and leaves one string on the data stack. In Factor, strings are just sequences of unicode code points and can be manipulated like any other sequence.
* Assuming a data stack that looks like `"split" "isbn"` when this function is called...
* `[ [ 32 - ] bi@ * 95 mod 32 + ]` push a quotation to the data stack (to be used later by `2map`) `"split" "isbn" [ [ 32 - ] bi@ * 95 mod 32 + ]`
* `2map` map over two sequences, combining them into one sequence with the given quotation which has stack effect `( x x -- x )`.
* At the beginning of the first iteration of `2map`, the data stack looks like this: `115 105`
* `[ 32 - ]` push a quotation to the data stack to be used later by the word `bi@`. `115 105 [ 32 - ]`
* `bi@` apply a quotation to the object on top of the data stack *and* the second-top object on the data stack `83 73`
* `*` multiply top two objects on the data stack `6059`
* `95` push `95` to the data stack `6059 95`
* `mod` reduce NOS (next on stack) modulo TOS (top of stack) `74`
* `32` push `32` to the data stack `74 32`
* `+` add top two objects on the data stack `106`
* So, at the end of the quotation to `2map`, we are left with `106`, which is the code point for `'j'`, which is the first element of the output sequence. The quotation given to `2map` will be run on each pair of elements until one of the two sequences no longer has any elements, meaning the output sequence will have the same size as the shorter of the two input sequences.
[Answer]
# [Red](http://www.red-lang.org), 81 bytes
```
func[a b][repeat i min length? a length? b[prin a/:i - 32 *(b/:i - 32)% 95 + 32]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OlEhKTa6KLUgNbFEIVMhNzNPISc1L70kw14hEc5Kii4oAkok6ltlKugqGBspaGkkwdiaqgqWpgraQFZs7P80BaXigpzMEiUFpczipDyl/wA "Red – Try It Online")
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 11 bytes
`32â-R*95%+¥`
Takes input as an array of 2 strings
prints additional trailing spaces if one string is longer
[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=MzLiLVIqOTUlK6U=&in=WyJpc2JuIiwgInNwbGl0Il0=)
## Explanation
```
32â-R*95%+¥ ; implicit input
32 ; constant 32
â ; push 32 below implicit input
- ; subtract 32 from input
R* ; multiply elements of input array
95% ; take input modulo 95
+ ; add 32
¥ ; print value as string (implicit output will print '()' for empty string)
```
] |
[Question]
[
[Originally posted (and deleted) by *@Tlink*](/q/163907), which was most likely [inspired from this StackOverflow question](https://stackoverflow.com/q/48751320).
Since it was a shame it got deleted, because it seemed like a good challenge in general, I figured I'd repost it with proper formatting and rules. (I've tried contacting *@Tlink* and get his/her permission to post it, but (s)he doesn't respond any more, which is why I decided to post it myself now.)
**Input:** Six digits.
**Output:** Either the first or last valid time in the 24-hour format (`00:00:00` through `23:59:59`). (You can choose yourself whether you output the first or last valid time.)
**Example:**
When the inputs are `1,8,3,2,6,4`, the following times can be created:
```
12:36:48 12:38:46 12:46:38 12:48:36
13:26:48 13:28:46 13:46:28 13:48:26
14:26:38 14:28:36 14:36:28 14:38:26
16:23:48 16:24:38 16:28:34 16:28:43
16:32:48 16:34:28 16:38:24 16:38:42
16:42:38 16:43:28 16:48:23 16:48:32
18:23:46 18:24:36 18:26:34 18:26:43
18:32:46 18:34:26 18:36:24 18:36:42
18:42:36 18:43:26 18:46:23 18:46:32
21:36:48 21:38:46 21:46:38 21:48:36
23:16:48 23:48:16
```
So we'll output either `12:36:48` or `23:48:16` in this case, being the first / last respectively.
## Challenge rules:
* State whether you output the first or last valid time in your answer.
* I/O is flexible. Input can be six separated integers; a string containing the six digits; an integer list/array; a single (possibly octal) number; etc. Output can be a correctly ordered list/array of digits; a String in the format `HH:mm:ss`/`HHmmss`/`HH mm ss`; every digit printed with new-line delimiter; etc. Your call.
* You are allowed to take the digits in any order you'd like, so they can already be sorted from lowest to highest or vice-versa.
* If no valid time can be created with the given digits (i.e. `2,5,5,5,5,5`), make so clear in any way you'd like. Can return `null`/`false`; `"Not possible"`; crash with an error; etc. (You cannot output an invalid time like `55:55:52`, or another valid time like `00:00:00`.) Please state how it handles inputs for which no valid time can be created.
* You are not allowed to output all possible valid times. Only the earliest/latest should be outputted/returned.
* `24` for hours (i.e. `24:00:00`), or `60` for minutes/seconds (i.e. `00:60:60`) are not valid. The ranges are `[00-23]` for hours and `[00-59]` for minutes and seconds.
## 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 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.
* Also, please add an explanation if necessary.
## Test cases:
```
Input: Earliest output: Latest output:
1,2,3,4,6,8 12:36:48 23:48:16
2,5,5,5,5,5 None possible None possible
0,0,0,1,1,1 00:01:11 11:10:00
1,1,2,2,3,3 11:22:33 23:32:11
9,9,9,9,9,9 None possible None possible
2,3,5,5,9,9 23:59:59 23:59:59
1,2,3,4,5,6 12:34:56 23:56:41
0,0,0,0,0,0 00:00:00 00:00:00
1,5,5,8,8,8 18:58:58 18:58:58
1,5,5,5,8,8 15:58:58 18:58:55
1,1,1,8,8,8 18:18:18 18:18:18
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~186~~ 174 bytes
```
D[7]={0,1,10,100,1e3,1e4,1e5};G(O,L,F,T,I,M,E){if(!F)O=L<24e4&L%10000<6e3&L%100<60?L:1e9;else{for(T=1e9,I=0;I++<F;M=G(O/10,L*10+E,F-1),T=T>M?M:T,O=(O/10)+E*D[F])E=O%10;O=T;}}
```
[Try it online!](https://tio.run/##LU7BbsIwDL3zFR4SU0KNltDSbaSBy1qE1KqX3lgPVRdYpK1Mhe1S9dszk@1ZL3rWs1/cLk5t69zL4bHWg0CJkh5BNCExIq5GtWMl5phhhXssMOWDPbK7jJc6T5aRie7zGa0IkcQm/NNJLLb5WppnZT4uZjiee1ZpanGvhdoHQZKpQlPqA/2Wz6UIUswWkmOlq02xLdYVltq7PEjnL4es5qkuKViVulLj6Gx3hc/Gduwmmv7UIrTvTQ9z0j@HmsMwAcLNtcpLOgGYBQ1SgYXELykIAsu9fcNXT/NHNp1dYLGB2dtrN0XwgbZG2LHmerbsv@coMCb64lxNfEpvrt99B0JNRufkMoxWsZNP4TKO3MrjFw "C (gcc) – Try It Online")
-12 bytes thanks to Kevin Cruijssen
Probably not optimal, but it works. Oddly enough for some reason with 7 arguments the gcc implementation on TIO requires that you actually supply them or it segfaults. On my machine that is unnecessary however.
Format: G(X,0,6) -> Y where X is the 6-digit number whose digits are to be used and Y is the 6 digit number which when taken as a time (by inserting : appropriately) is minimal.
[Answer]
# [Haskell](https://www.haskell.org/), ~~114~~ ~~96~~ 86 bytes
```
import Data.List
f l=minimum[x|x@[a,b,c,d,e,f]<-permutations l,a:[b]<"24",c<'6',e<'6']
```
Now with less strict output. Takes input as a string of digits and compares permutations against limits with list comparison. With minutes and seconds only the first digit is checked. Crashes and burns if no permutation is a valid time.
[Try it online!](https://tio.run/##FcSxCsIwEADQ3a84gtDlLFhLEUnBwdE/CB2uNcHDXBqSFDr47xHf8N6UP9b7Wlnimgo8qFD75FwODvwoHFg2Mft3vxvCGRd8oUU36VO0SbZChdeQwSPdzDxp1fUKF90MDdr/UxXiACPExKHAERyo8/XSDb2qPw "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~131~~ ~~115~~ ~~112~~ ~~109~~ ~~105~~ 88 bytes
```
lambda s:min(d for d in permutations(s)if(2,4)>d[:2]>d[4]<6>d[2])
from itertools import*
```
[Try it online!](https://tio.run/##PUxJbsMwDLz7FbwYkgofbMUyXKPpE/qB1AenkhAB1gKJAZrXu1QKZEAMh5wh0wNvMcjDnr@PffNXvUFZvAtcg40ZNLgAyWR/xw1dDIUX4SyX3Sg@9WWRK/G4fkzU5Coam6MHhyZjjHsB51PM@HbUTzSFCxvkaZxm1jGpKkj0fT8MAwmyqEi8P1EzJ6Weol6p6T9MqBul5nlm69IA5gcxpOwCAmt1q5cXsdZyvyVOVleEaMD8/piErzz7iggpluKuu2HHHw "Python 2 – Try It Online")
I/O are lists of integers
Throws an error if no times are possible
---
Alternative:
# [Python 2](https://docs.python.org/2/), 88 bytes
```
lambda s:max(d*((2,4)>d[:2]>d[4]<6>d[2])for d in permutations(s))
from itertools import*
```
[Try it online!](https://tio.run/##RU7LisMwDLz3K3QJdkoOiRuHbNjuJ@wPtDm4tUMN8QNbhfbrU7kL20GMRpoRKD7xFrzYluN5W5W7aAV5curB9Z5z0fT1jz5NYibu5@@BmpjrJSTQYD1Ek9wdFdrgM891vVtScGDRJAxhzWBdDAn3WzmgyZ9YJw79MLKGCVlAom3brutIkEVF4uuNkjlI@RblSg5/YULZSDmOI5unHWB6EkNM1iOrdKWnf2LVwp2KnJymvAfmcTURP/HfgBBDzvayGra9AA "Python 2 – Try It Online")
Returns the latest time
Returns an empty tuple for invalid times
---
Saved
* -21 bytes, thanks to ovs
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 15 bytes
Input as sorted string.
Output is the smallest time as a string.
In case of no solution, an empty list is the output.
```
œʒ2ô•3Èñ•2ô‹P}н
```
[Try it online!](https://tio.run/##MzBNTDJM/V9TVvn/6ORTk4wOb3nUsMj4cMfhjUAazNsZUHth7/9KpcP7FXTtFA7vV9L5b2hkbGJmwWVkCgJcBgYGhoaGXIaGRkbGxlyWYMBlZGxqCqRAKk3NQEqAgMvQ1NTCwgJEmYIoQ0MgDwA "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), ~~93~~ ~~89~~ 88 bytes
Expects an array of 6 digits, sorted from lowest to highest. Returns either the 6-digit string of the first valid time, or `false` if no solution exists.
```
f=(a,t='')=>t<24e4&/..([0-5].){2}/.test(t)?t:a.some((v,i)=>s=f(a.filter(_=>i--),t+v))&&s
```
[Try it online!](https://tio.run/##fY/LboMwEEX3fEVWxFYHg1@IWCX9kCiqrNSOqGioYotN1W@nTBRaRJLq3uXRPTPvtrfhcG4@Y3bq3tww@JpYiPV6TettfBbKqTRnjOyKTO8Z/RLfOYsuRBLpSzSWhe7DEdJDM@Kh9sQy37TRnclrvW2yjEJ86ilN0zAculPoWsfa7kg82XEQIEFBCdWe0lWer7gwsjSqShakAD3lSnrbBrfECsBwzBUrClNww3lyo0Y56uWk5kaMdrkkN/Cb/9Q4hff9YUIavRmbPPhaQzn7Whld3n/nktk72NtNdFeYabMyGnuf1HNSPyIxi81Lhx8 "JavaScript (Node.js) – Try It Online")
### Commented
We recursively try all permutations of the input until we find one that passes a hybrid test using both arithmetic and a regular expression.
```
f = ( // f = recursive function taking
a, t = '' // a[] = input array and t = current time
) => //
t < 24e4 & // if t is less than 240000
/..([0-5].){2}/.test(t) ? // and it matches "hhMmSs" with M and S in [0-5]:
t // return t
: // else:
a.some((v, i) => // for each digit v at position i in a[]:
s = f( // save in s the result of a recursive call with:
a.filter(_ => i--), // a copy of a[] with the current digit removed
t + v // the current digit appended to t
) // end of recursive call
) && s // end of some(); if truthy, return s
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
Takes input as a string of digits and outputs the first valid time; loops infinitely if there's no valid time.
```
á
@øXr':}a@ÐX ¤¯8
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=4QpA+FhyJzp9YUDQWCCkrzg=&input=IjAwMDExMSI=)
>
> **Warning:** Extremely slow - add `*1000` after the second `X` to speed it up somewhat. And don't forget that an invalid input will create an infinite loop and may crash your browser.
>
>
>
---
## Explanation
```
:Implicit input of string U
á :Get all permutations of U
\n :Reassign that array to U
}a :Loop until true and then return the argument that was passed
@ :By default that argument is an integer X which increments on each loop so first we'll pass X through a function
ÐX : new Date(X)
¤ : Get the time
¯8 : Slice to the 8th character to get rid of the timezone info
@ :The function that tests for truthiness
Xr': : Remove all colons in X
ø : Does U contain the resulting string?
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~77~~ ~~74~~ ~~69~~ ~~65~~ 62 bytes
```
$
:
6+Lv$`(.)(.*):
$%`$2:$1$%'
O`
0L`([01].|2[0-3])([0-5].){2}
```
[Try it online!](https://tio.run/##K0otycxLNPz/X4XListM26dMJUFDT1NDT0vTiktFNUHFyErFUEVVncs/gcvAJ0Ej2sAwVq/GKNpA1zhWE8jTNY3V06w2qv3/39DC2MjMBAA "Retina – Try It Online") Outputs the earliest time, or the empty string if no time can be found. Edit: Saved ~~5~~ 8 bytes thanks to @TwiNight. Explanation:
```
$
:
6+Lv$`(.)(.*):
$%`$2:$1$%'
```
Generate all the permutations. The `:` works its way though the string as the permutations are generated, ending up at the start.
```
O`
```
Sort the times into order.
```
0L`([01].|2[0-3])([0-5].){2}
```
Output the first valid time.
[Answer]
# [Red](http://www.red-lang.org), 157 124 bytes
Thanks to Kevin Cruijssen for reminding me to read the descritions more carefully!
```
func[s][a: 0:0:0 loop 86400[b: to-string a a: a + 1 if b/1 =#"0"[insert b"0"]if s = sort replace/all copy b":"""[return b]]]
```
[Try it online!](https://tio.run/##VY3LCsMgEEX3@YqLXZZSzYtUyE90Ky400RIIUdQs@vWpzaLYO5vhzOVMMPPxNLOQleWH3bdJRCkUB@V5sDrnMfQtpUJzJHeLKSzbCwq5onAFw2Kh7wzjhVAili2akKDzLvMhYkR0GQTjVzWZu1pXTM6/c4MTQkQwaQ8btJTy8NmcYEFY3bT9QKofqLtvCkApZYwVgLG6bpoCPM6Ujqbr/gA9Uzryj2Egxwc "Red – Try It Online")
Takes a sorted string as input. Returns `none` if it's not possible to make time.
## Explanation:
```
f: func[s][ ; the argument is a sorted string of digits
a: 0:0:0 ; time object, set to 00:00:00 h
loop 86400 [ ; loop through all seconds in 24 h
b: to-string a ; convert the time to string
a: a + 1 ; add 1 second to the current time
if b/1 = #"0" [ ; prepend "0" if necessary
insert b "0" ; (Red omits the leading 0)
]
if s = sort replace/all copy b ":" ""[ ; compare the input with the sorted time
return b ; return it if they are equal
]
]
]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
lambda s:min(x for x in range(62**3)if x%100<60>x/100%100<s==sorted('%06d'%x))
```
[Try it online!](https://tio.run/##TY5BDsIgEEX3PcVsGqAxEVoh1ViP4AXURbWgJC00wAJPX6G68GcyeTP8H2Z@h5c19aK66zL2033owR8mbXAEZR1E0AZcb54Si7qqGqIVxJJRehT0FLcJ1sF3nbcuyAGjkooBlZGQJed9zl8Qq5udaNEG1TwrAaWUMZYgPaVKsF@VPQ3nK@QUF19zUt5w3rYtuh0KCO6dOsxOmwDfX6EEhUftA/4d4wkhBcj4kHP4M59tgNl6r@@jRMsH "Python 2 – Try It Online")
Arnauld saved a byte. Thanks!
Expects a list like `['1','2','3','4','6','8']` in sorted order:
>
> You are allowed to take the digits in any order you'd like, so they can already be sorted from lowest to highest or vice-versa.
>
>
>
Outputs an integer like `123648` for 12:36:48. I hope that's acceptable.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
Œ!s€2Ḍf«¥“ç;;‘Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMXiR01rjB7u6Ek7tPrQ0kcNcw4vt7Z@1DDj4c6m////G@qYAqEFCAIA "Jelly – Try It Online")
[Posted after a request.](https://codegolf.stackexchange.com/questions/164439/the-time-anagram/164452?noredirect=1#comment397995_164452) The approach is the same as the one of the other answer, however this answer was developed independently.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~39~~ 23 bytes
Pretty sure there's a shorter way to do this, but I wanted to try using Date objects in Japt.
```
á ®¬ò q':Ãf@T<ÐXiSiKÅ
Ì
á // Get all permutations of the input array.
®¬ò q':à // [1,2,3,4,5,6] -> "12:34:56"
f@ // Filter the results, keeping those that
T< // are valid dates
ÐXiSiKÅ // when made into a date object.
Ì // Return the last remaining item, if any.
```
Takes input as a sorted array of numbers, returns the latest valid time or empty output if none exists.
Lost 10 ~~pounds~~ bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy).
[Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=4SCurPIgcSc6w2ZAVDzQWGlTaUvFCsw=&input=WzEsMiwzLDQsNiw4XQ==).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~68 67 62 56~~ 55 bytes
```
->*b{b.permutation.find{|a,b,c,d,e|c<6&&e<6&&a*9+b<22}}
```
[Try it online!](https://tio.run/##JYvLCoMwEEX3foUr09o0mLSRWGx/RKQkPqgLH8QIFuO3pxN7GIbD3Dt6UV/XPt31FatNkanR/WKk6caBtN1Qb1ZihStc48ZWeRpFjV8yzi4qZ2zfXYEou91TgTBi3AOSJAmlFAQiGJDswHdunB/iv3j6LwP@wrkQApWkl9NmVxuEwBQWK26LeCXVR@rZZ6foYcZ3dybzqE1ZBrv7AQ "Ruby – Try It Online")
Input: **Sorted** array of digits (as integers).
Output: Array of digits or `nil` if no solution found
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I'm almost certain this is not the shortest approach... will look at this again later :)
```
Œ!s2Ḍ<ẠʋÐṀ“ð<<‘ṢḢ
```
**[Try it online!](https://tio.run/##AToAxf9qZWxsef//xZIhczLhuIw84bqgyovDkOG5gOKAnMOwPDzigJjhuaLhuKL///9bOSwxLDUsOSwyLDVd "Jelly – Try It Online")**
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes
```
FirstCase[Permutations@#,{a:0|1|2,b_,c_,_,d_,_}/;a*b-4<6>d>=c]&
```
[Try it online!](https://tio.run/##RYzLCoMwEEX3@Q1BWhnxLbZWCRS6FroUkfiiLlSI6Sr67akxbeXAhcO9MwNhr3YgrK@J6JKTePR0Zncyt3nW0uHNtmYaZ6wBJ1d7cRYXqhLqEkpotlitmBiV6d/CtEmTutDFOUYZ7UeWa2baYa3QsfGcKLMwR4g74IIHPoQQrYC4C8EPqTZIHIlUNd5T6gX@qFtvv/zq73MA4fFqR7VyGkkODQ6VqBahVXwA "Wolfram Language (Mathematica) – Try It Online")
Takes a **sorted** list of digits as input. Returns `Missing[NotFound]` for invalid inputs.
### Explanation
```
Permutations@#
```
Find all of the permutations of the input. Since the input is sorted, it is guaranteed that all valid times are in increasing order.
```
FirstCase[ ... ]
```
Find the first list that matches...
```
{a:0|1|2,b_,c_,_,d_,_}
```
The first element, labeled `a`, is 0, 1, or 2, and label the second, third, and fifth elements `b`, `c`, and `d` respectively...
```
... /;a*b-4<6>d>=c
```
... such that `a*b` is less than 10, and `d` and `c` are less than 6, with `d >= c`.
The trick is that for all numbers `00` to `24`, the product of the two digits is at most 9, and the possible invalid numbers `25` to `29` (since we force the first digit to be 0, 1, or 2) have the product of least 10.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 37 bytes
```
j\:hf&&<shT24<s@T1 60<seT60mcs`Md2S.p
```
[**Test suite**](https://pyth.herokuapp.com/?code=j%5C%3Ahf%26%26%3CshT24%3Cs%40T1+60%3CseT60mcs%60Md2S.p&test_suite=1&test_suite_input=1%2C2%2C3%2C4%2C6%2C8%0A2%2C5%2C5%2C5%2C5%2C5%0A0%2C0%2C0%2C1%2C1%2C1%0A1%2C1%2C2%2C2%2C3%2C3%0A9%2C9%2C9%2C9%2C9%2C9%0A2%2C3%2C5%2C5%2C9%2C9%0A1%2C2%2C3%2C4%2C5%2C6%0A0%2C0%2C0%2C0%2C0%2C0%0A1%2C5%2C5%2C8%2C8%2C8%0A1%2C5%2C5%2C5%2C8%2C8%0A1%2C1%2C1%2C8%2C8%2C8&debug=0)
Explanation:
```
j\:hf&&<shT24<s@T1 60<seT60mcs`Md2S.pQ # Code with implicit variables
h # The first element of
.pQ # The list of all permutations of the input list
S # Sorted
mcs`Md2 # Mapped to three two digit long strings
f # Filtered on whether
<shT24 # The first number is less than 24
& <s@T1 60 # AND the second number is less than 60
& <seT60 # AND the third number is less than 60
j\: # Joined by a colon
```
[Answer]
## [Perl 5](https://www.perl.org/) with `-palF`, 73 bytes
```
$"=",";($_)=grep@F~~[sort/./g]&/([01]\d|2[0-3])([0-5]\d){2}/,glob"{@F}"x6
```
[Try it online!](https://tio.run/##LYtRC4IwFEbf9zOGhIK23buuTULwyT9hEkUigbShPgSmP721ReflcOD7bDcO5FzES57yUxxdkrIfO1vV29ZMZpzFXvTtTsSNhPZ8f2MjM9UmPjPynSy4irQfzI0vVb3yV@4coDrkmiEFmJQSABgAolKs@MFQEXmFJeVh4mFApLUOoiCAf4UDgKJj8TF2fpjn5DJ7Heov "Perl 5 – Try It Online")
Outputs like `HHmmss` and outputs a blank line for invalid entries.
Every answer I've made recently has used `glob`ing for permutations... Weird!
[Answer]
## Bash + GNU sed, 83, 72, 69 bytes
* Accepts input as 6 separate arguments;
* Returns the earliest time (if found);
* Returns nothing (empty output) if no valid combination exist.
`seq 0 86399|sed "s/^/date +%T -ud@/e;h;`printf s/%d//\; $@`/\w/d;x;q"`
**How it works**
Pre-generate all the possible time strings, for the timestamps in range 0 to 86399, using GNU-sed **e**(xecute) command + `date`.
`%seq 0 86399|sed "s/^/date +%T -ud@/e;h;"`
```
00:00:00
00:00:01
...
23:59:59
```
Generate `sed` script with 6 sequential substitution commands,
for an each input digit.
`%echo sed `printf s/%d//\; $@``
```
sed s/1//;s/2//;s/3//;s/4//;s/6//;s/8//;
```
Then, apply substitutions, remove any input lines which have at least one digit left, print the first matching line (original time string is extracted from the hold space with `x`).
```
%echo 23:45:12|sed 's/1//;s/2//;s/3//;s/4//;s/6//;s/8//;'
:5:2 //non-matching, delete
%echo 12:36:48|sed 's/1//;s/2//;s/3//;s/4//;s/6//;s/8//;'
:: //matching, print and stop
```
**Test**
```
%./timecomb 1 2 3 4 6 8
12:36:48
%./timecomb 2 5 5 5 5 5
%./timecomb 0 0 0 1 1 1
00:01:11
%./timecomb 1 1 2 2 3 3
11:22:33
%./timecomb 9 9 9 9 9 9
%./timecomb 2 3 5 5 9 9
23:59:59
%./timecomb 1 2 3 4 5 6
12:34:56
%./timecomb 0 0 0 0 0 0
00:00:00
%./timecomb 1 5 5 8 8 8
18:58:58
%./timecomb 1 5 5 5 8 8
15:58:58
%./timecomb 1 1 1 8 8 8
18:18:18
```
[Try It Online !](https://tio.run/##S0oszvj/vzi1UMFAwcLM2NKypjg1RUGpWD9OPyWxJFVBWzVEQbc0xUE/1TrDOqGgKDOvJE2hWF81RV8/xlpBxSFBP6ZcP8W6wrpQ6f///wYKIGgIggA)
[Answer]
# [Kotlin](https://kotlinlang.org), ~~396~~ ~~391~~ 389 bytes
No clue how to make this smaller. I'm thinking it is double of what's possible. Produces earliest time.
Thanks to Kevin for 7 bytes!
```
fun p(d:Array<Int>)={val s=Array(6,{0})
val f=Array(6,{1>0})
val t=Array(3,{0})
val o=Array(3,{60})
fun r(i:Int){if(i>5){var l=0>1
var e=!l
for(p in 0..2){t[p]=s[p*2]*10+s[p*2+1]
l=l||(e&&t[p]<o[p])
e=e&&t[p]==o[p]}
if(t[0]<24&&t[1]<60&&t[2]<60&&l)for(p in 0..2)o[p]=t[p]}
else
for(p in 0..5)if(f[p]){f[p]=0>1
s[i]=d[p]
r(i+1)
f[p]=1>0}}
r(0)
if(o[0]>23)0
else "${o[0]}:${o[1]}:${o[2]}"}()
```
[Try it online!](https://tio.run/##lVhrb9vIFf3OXzEbFLaU0JKoFxwlMhokaWNgES8aF8Ui8IcxOZII87UcKrLg@Len5955kIyToJUFazRzH2fum7ormywtvo2fi7e1ko1KxKasRbNLtYjLRIltmW1EvJNZpoqtWgW7pqn0ajymQzob6UbGd@oeJDgfxWU@/muvdJOWhR5Hy/l89jK43ilxneZKvCnktpZ5EFzV6TYtIPQoqlKT1oEsEpGoTOHLUNwexd@vgesuFIddGu/EQWqRg1Jk6Z0CV1roKq0JbV3mBu4nAnL1RdWbrDwIB2IUfEqLWIm0YRlS6J3M@eu2bJzCUNyqWO4172ulcggmRSDflmXS3h96xVYVqpZZKC7FJt3uCcTlaSJqRTdhPWmzE1VdVqomY@ayadJiK@iC9T5TeiQGl6dflGjqFLxxWQA4U5grM@FWNQKXGu8gA3LyVGtcRjSlsFoAed@IgR7CtkmpdHHaAIKuSjDL4ghj1coZD8Y57I7Am6g4TaCzFSPyo1bwcFEeRsMguCyqfbMSn9J7kcBDjR7BV/uGN9/jWopCQ@HeNbgRJ5nE5xeZpZBJDoZ56Hw6P9uVe3d7MZhMVvzGYV3utzsxna0WL/EewhZ/lnsRywJGLkt44AhGhnTYKVaIDVEyhl/qJvjv72VeZYjS4D87ZaCkdCP4vVYiCs/DWTgNl@E8NKLKDKFClicBmlHcKhGbRICUaLqaLVfzc4EXrc9X86Vdz5f46tbnIAui2WrqibH2xDMinrp9EE9BPCdiK2FOxLOlXc888Zw0EjF2Zk4y1nPHuGTGebuez4h4Nm2JZ3MnbcnS5u16PiXi@bSVNp@1xIRz1q5nID5nGAbnOcPw66WDwWuCcc4wHAHB8Oulg8HrOUsmGI6AYPj10sHgNWBMo9YptHZ2xto7hdbsFACOPDEbP1oGwadSHNRplrm4Uia0vbsRXY7YhDRVQ6kV1QkOFx@HYxOGlHkKSfwFtWkUvPXlgvMdgUTqUZ8a9f9GNamnjEBO64OqRyzpcnxFOb3J1H16m6mR4LR14auRvFpVsuZqnhaN2qpav6LSh4oD9Fxx0sJdRPtkB03hGFD/dDOWdS2PzArqTIkByoaGzqMo40ZmQ1Hs81tVvxKqiUfCVAqHQ0JRXcMqRF0nquai6oSKctNqhW0YmS0ftmx8@LDK85XW4w8f8pw/RJ4LDQaFKn807Ci0hDgxVbdQhzPUUEWFPc3TxkP7k2wYwy3GglRzqCRIKgCmIDYS9Z60G1SEheooIycXnJqWEApdEtmRrykz1IrkyGYv68b1IxIKN0LqLt3ulPHslzRWZwCupfUiVd2uq/vlx1yIAG0RVoWDNUhHcPg0XLi/YShygg5YcaZk7YAfYOMW9ki8hfRaNfu6gNOybLyRmVavxLOPaIPWq@rZK2iXemd0g0HVdelM6Ap1AQYbuRwunRtwz1wsVvSehnRpCWoK9@@JXEcYDcUfQI26rzk9dmjdcCqGiQSZ46o3jSSmlf3KYn3XEsyOex1iJL27bUcSevJVgTglc8OGWQqfjTMIhes0WlmWkB4jA5rGxpBOJaoZIaSW5x00N/cbshWWEybI02IPkWOtkIKJIwXdkt5DD5txjQSNTTVNVaZ9fZ5Mzqazm44qGhRod/Hypiuf960O9O9/mnmlV4uuqaLZEe@MxjgOa9y05iubYkORdHskgeiR2lz1XUmDBoamlhUlq9juJcFMUh0DGdZc3zgXaNAw4w/J1DZPy@LMTZB06EXg1shs@AuDpBL7ykciZjeGRwvvQIuT7n6KmD@lqYsGzLwrc@Sqb5HI2o5gQlYV3E2MnerKRjg@LQ00GH66fnf5cYz/V/@@DsVmX8RmxM1RzstOstq5j8ovjpT1komXs@ZYKWKmIDRI9ZPS9E5t5D5rxO9lWe3KzDofSG/TJFGFrx3OCKGoTALJBJOf4AnSGE2wL/0dyd6G@02myz4bMv2@gsEkXUqkqEwqVlrLGt0suCYx1P4oeuyE6F/vbbbY5DAnv5vMsVuYozB1zTB1LUNuxKI7V/mXb8@d4sYHH0sUdO9z@@ptBpOQ/iL641PKvWgVRT0FEXYoJwOimzKkmTuYAtHsezgYYKIoeBn6v/8VDokm/I7FjbvfK@BNb51FuPTWma8WyyfUMFlkr8p//qo8W3dfbhOyCcc5/Qk7RS3o3TeM3bTUi5Z68XPqBZsx6svm9/fU/A5m5y9NNQmej78hf0Q1SFZvaBR4fVk0F8P1A8qe0GveGizDh8njMKCtTbsVXbjNxm7OWrqy3VrSHumoB@kK0ocP6WaQXiyG0IHJZj25iAJaqfVvWYAEGVRU6yaj0XT40Hyubtb6c/V8evM8mrzg1YvoJsjW2devA3VyQgSvS/wbBmptv6/XtPEYQE3zeXLzejqn/ejm9XJCi6lZZMO@LuJZN8yo0Ix7SBZDyNqQlgf6z5D15/RmneBbgHu9iHBFOiGjPGJnMiT1JdRfTGfDCYsUz/72QDuPK/qM7Of05vHZ42D4bTwW7@8r1CeUORpM7BOmnRLstIg5DR2RU5wfs9iuqF5UHwZmKFmJjh/FWjxQk4Hwt3vMfwU9UeNpnB7C/cxn5@h4p@I7evzWqjEsoMhlfacJh6ZhQNoxj@bdWinaRydGRU5Cw7HFE2Wl7EBAfTG0fTAUJ7YLGiZDToWJNHbvZIX69k5VkoPR4V4LF4KCw80cM57ukQlPc8gF0B3Oenx2FOkecsAagP9SMXo7Rj7fZHg6RVekgTq/TU2RJowc4UyuBim8eL8SFOzG/iwMfeIAq0hIg4mNhIp@8vB3I9vjKWPjOIyp7RzEFkJP3Ej75IHOYDSJC7HwipjxH@gzSmJEgwuJnQ1rHg8w6fQc0zI5D2FMwgdi0DwNecNjtC8B6VS3LEYkd9U7pSp@iqllfEd6Ad4EFtpmh6XBOMlyYxuQPecDNyaULGvpoV3abkweq1kc/EU52G4yFXZ/6yijZkvPSKnpozbPYSdXDiksPjuCG3C7q/pNqjtBr4KiCD0lopLkKCw8/vj6VQwMspOT77W97sk1YdgeD/2pu9nP5KzXvxRkDx/JlDBIJ0YuO6GBKDPzN3mSoTs3tfTf@Ss0DqbR0IQoHvfcmXMXRSjDneC@NJk7@BF9xyB@ctIBzydTf8I4Wjv82JvBz28Om/VN5RPxip6CDin9hECpbMDfN5yVbVUka/mYpQmdU80@FbsgGLWpxmyhT92NeXTi3wJvFZ4ZuUyiROSKc@ZgCqfo8FAhopTvqwhdWeHSo/iXQseBO4fsMy5/4KUhnX5tSzACGS88Cm5nPzfiojUi@YskdeKwky5C9M96SUgvnxlsKjo3pnwSjfTq1Urqn79Qg1rujx@NdYN2ZUo1nilswap90badEUVo5MLdRIltPxT6SZqQi/DkY0ZvF93u8RyGtM2tdGHjzlz6kKHddSZ0EbKjDUczADB6uoP3Bc0CjoIHAfMl6n6h0SDAbBAE0P6HuUu/rPuHATMJ5DItBrLe@iHA/JRzYbzoOiGVJ/7Z52ozcJ@dh4KhawnurP/7htvtTPlPODozfYejM7v/QIcf0jscnWH8CUdn9O5x@BH7B6j8QN3j8IPzkPzEKWLSrDDmcjnAP25lxaDiYyamEKQ6waFI1g@@/Rc "Kotlin – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~31~~ 30 bytes
```
Y@3Xy[X1]X*!Y*t[4XX]6*<!AY)1Y)
```
[Try it online!](https://tio.run/##y00syfmf8D/SwTiiMjrCMDZCSzFSqyTaJCIi1kzLRtExUtMwUvO/S8j/aEMdEx0zHQsdIx3jWK5oBQMdEDQEwVgFLqCsKRha6FhAuCBoAeMaQWWBMJYLAA "MATL – Try It Online")
Input is 6 integers, output is the minimum hour, minutes, and seconds in an array. Crashes for inputs where no such time is possible.
*(-1 byte thanks to @Luis Mendo.)*
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 43 bytes
```
*.permutations.first:{24e4>.join&&6>.[2&4]}
```
[Try it online!](https://tio.run/##RYzLCoMwEEX3@YpBJGgZQo0x2Ir@SCniwoClPojpQkq/PWW0Vs5mDnfunVr71L5fgBso/UlMre1frnHdOMzCdHZ217dUrarEY@wGznUlbpKr@8cXbG4WCGuEAMoKAgQThXUMZrQsSlBiigo15jGySGK2Q3pGIiFI6ZBrISW94J@tm67Nn@7LGepjamVL6TUnDs0OJba08F8 "Perl 6 – Try It Online")
Expects a sorted input array. Returns `Nil` for invalid input.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╝a╣=→aá≈#8(⌂≈58
```
[Run and debug it](https://staxlang.xyz/#p=bc61b93d1a61a0f72338287ff73538&i=%22123468%22%0A%22255555%22%0A%22000111%22%0A%22112233%22%0A%22999999%22%0A%22235599%22%0A%22123456%22%0A%22000000%22%0A%22155888%22%0A%22155588%22%0A%22111888%22&a=1&m=2)
It takes a string of sorted digits for input. It returns the first permutation that satisfies a few criteria.
* lexicographically less than "24"
* all three pairs of characters are lexicographically less than "6"
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~58~~ 47 bytes
```
+,V^2`[0-5][6-9]{2}
G`([01].|2[0-3])([0-5].){2}
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9bJyzOKCHaQNc0NtpM1zK22qiWyz1BI9rAMFavxggobhyrqQGW1tMEyv3/b2BoZGxiygWmLMGUBZgyB1NmYMoMTJmBKQA "Retina – Try It Online")
Input is 6 digits in sorted order. Output is 6 digits representing earliest valid time, or empty string if no valid time exists.
EDIT: I was an idiot, -9 bytes
## Explanation
**Algorithm**
For brevity, let's define a low digit as 0-5, and a high digit as 6-9.
First, rearrange the digits so that "low-ness" or "high-ness" of each position is correct. The correct arrangement, for each number of high digits in the input:
```
# of highs arrangment
0 LLLLLL
1 LLLLLH
2 LLLHLH
3 LHLHLH
4+ Not possible
```
Since the any rearrangement would fail the final check in the input has 4+ high digits, we can ignore that case completely.
Then, sort the lows and the highs individually. Combine with the rearrangement, this gives the lowest value that satisfies the minute and second constraints. So this gives the earliest valid time, if one exists.
Finally, check if that we have valid time. If not, discard the string.
---
**Program**
```
+,V^2`[0-5][6-9]{2}
```
Matches `LHH` and swaps the first two digits in that (becomes `HLH`), and repeat that until no more `LHH` exists. This gives the correct arrangement.
Actually, I lied. No sorting is needed because 1) swapping only happens between adjacent digits and only between a low and a high; and 2) the input is sorted. So the lows and the highs individually are already in sorted order.
```
G`([01].|2[0-3])[0-5].[0-5].
```
Only keeps the string if it is a valid time
] |
[Question]
[
This question is based on the number-placement puzzle Towers (also known as Skyscrapers), which you can [play online](http://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/towers.html). Your goal is to take a solution to the puzzle and determine the clues -- the numbers of towers visible along each row and column. This is code golf, so fewest bytes wins.
**How Towers works**
The solution to a Towers puzzle is a Latin square -- a `n*n` grid in which every row and column contains a permutation of the numbers `1` through `n`. An example for `n=5` is:
```
4 3 5 2 1
5 4 1 3 2
1 5 2 4 3
2 1 3 5 4
3 2 4 1 5
```
Each row and column is labelled with a clue at each end like:
```
2 3 1 4 5
v v v v v
2 > 4 3 5 2 1 < 3
1 > 5 4 1 3 2 < 4
2 > 1 5 2 4 3 < 3
3 > 2 1 3 5 4 < 2
3 > 3 2 4 1 5 < 1
^ ^ ^ ^ ^
2 2 2 2 1
```
Each clue is a number from `1` to `n` that tells you how many towers you "see" looking along the row/column from that direction, if the numbers are treated as towers with that height. Each tower blocks shorter towers behind it. In other words, the towers you can see are the ones that are taller than any tower before them.

For example, let's look at the first row.
```
2 > 4 3 5 2 1 < 3
```
It has a clue of `2` from the left because you can see the `4` and the `5`. The `4` blocks the `3` from sight and the `5` blocks everything else. From the right, you can see `3` towers: `1`, `2`, and `5`.
**Program requirements**
Write a program or function that takes in the grid of numbers and outputs or prints the clues, going clockwise from the top left.
**Input**
An `n*n` Latin-square with `2<=n<=9`.
The format is flexible. You can use any data structure that represents a grid or list containing numbers or digit characters. You may require a separator between the rows or no separator at all. Some possibilities are a list, a list of lists, a matrix, a token-separated string like
```
43521 54132 15243 21354 32415,
```
or a string without spaces.
You're not given `n` as part of the input.
**Output**
Return or print the clues starting from the top left and going clockwise. So, first the upper clues reading rightwards, then the right clues reading downwards, then the lower clues reading leftwards, the the left clues reading upwards.
This would be `23145 34321 12222 33212` for the previous example
```
2 3 1 4 5
v v v v v
2 > 4 3 5 2 1 < 3
1 > 5 4 1 3 2 < 4
2 > 1 5 2 4 3 < 3
3 > 2 1 3 5 4 < 2
3 > 3 2 4 1 5 < 1
^ ^ ^ ^ ^
2 2 2 2 1
```
Just as for the input, you can use a list, string, or any ordered structure. The four "groups" can be separated or not, in a nested or a flat structure. But, the format must be the same for each group.
**Example test cases:**
(Your input/output format doesn't have to be the same as these.)
```
>> [[1 2] [2 1]]
[2 1]
[1 2]
[2 1]
[1 2]
>> [[3 1 2] [2 3 1] [1 2 3]]
[1 2 2]
[2 2 1]
[1 2 3]
[3 2 1]
>> [[4 3 5 2 1] [5 4 1 3 2] [1 5 2 4 3] [2 1 3 5 4] [3 2 4 1 5]]
[2 3 1 4 5]
[3 4 3 2 1]
[1 2 2 2 2]
[3 3 2 1 2]
>> [[2 6 4 1 3 7 5 8 9] [7 2 9 6 8 3 1 4 5] [5 9 7 4 6 1 8 2 3] [6 1 8 5 7 2 9 3 4] [1 5 3 9 2 6 4 7 8] [3 7 5 2 4 8 6 9 1] [8 3 1 7 9 4 2 5 6] [9 4 2 8 1 5 3 6 7] [4 8 6 3 5 9 7 1 2]]
[4 2 2 3 3 3 3 2 1]
[1 3 3 2 2 2 2 3 3]
[4 3 2 1 2 3 3 2 2]
[3 1 2 4 3 3 2 2 5]
```
For you convenience, here are the same test cases in a flat string format.
```
>> 1221
21
12
21
12
>> 312231123
122
221
123
321
>> 4352154132152432135432415
23145
34321
12222
33212
>> 264137589729683145597461823618572934153926478375248691831794256942815367486359712
422333321
133222233
432123322
312433225
```
[Answer]
## APL 19
```
≢¨∪/⌈\(⍉⍪⌽⍪⊖∘⌽∘⍉⍪⊖)
```
(golfed a bit more after ngn's suggestion, thanks)
Explanation:
```
(⍉⍪⌽⍪⊖∘⌽∘⍉⍪⊖) rotates matrix 4 times appending results
⌈\ gets maximums for each row up to current column (example: 4 2 3 5 1 gives 4 4 4 5 5)
≢¨∪/ counts unique elements for each row
```
Try it on [tryapl.org](http://www.tryapl.org/?a=%u2262%A8%u222A/%u2308%5C%28%u2349%u236A%u233D%u236A%u2296%u2218%u233D%u2218%u2349%u236A%u2296%295%205%u23744%203%205%202%201%205%204%201%203%202%201%205%202%204%203%202%201%203%205%204%203%202%204%201%205&run)
[Answer]
# Python 2, 115 bytes
```
def T(m):o=[];exec'm=zip(*m)[::-1]\nfor r in m[::-1]:\n n=k=0\n for x in r:k+=x>n;n=max(x,n)\n o+=[k]\n'*4;return o
```
There's an awful lot of list flipping going on in there.
Takes input as a nested list (e.g. call with `T([[4,3,5,2,1],[5,4,1,3,2],[1,5,2,4,3],[2,1,3,5,4],[3,2,4,1,5]])`). Output is a single flat list.
Ungolfed:
```
def T(m):
o=[]
for _ in [0]*4:
m=zip(*m)[::-1]
for r in m[::-1]:
n=k=0
for x in r:k+=x>n;n=max(x,n)
o+=[k]
return o
```
Alternative 115:
```
def T(m):o=[];exec'm=zip(*m)[::-1];o+=[len(set([max(r[:i+1])for i in range(len(r))]))for r in m[::-1]];'*4;return o
```
I have no idea why this works with a list comprehension, but chucks a `NameError` with a set comprehension...
A bit too long, but if anyone's interested — yes, it's possible to get this down to a lambda!
```
T=lambda m:[len({max(r[:i+1])for i in range(len(r))})for k in[1,2,3,4]for r in eval("zip(*"*k+"m"+")[::-1]"*k)[::-1]]
```
---
# [Pyth](https://github.com/isaacg1/pyth), 25 bytes
```
V4=Q_CQ~Yml{meS<dhkUd_Q)Y
```
Obligatory Pyth port.
Input the list via STDIN, e.g. `[[4, 3, 5, 2, 1], [5, 4, 1, 3, 2], [1, 5, 2, 4, 3], [2, 1, 3, 5, 4], [3, 2, 4, 1, 5]]`.
[Try it online](https://pyth.herokuapp.com/)... is what I would say but unfortunately, for security reasons, the online interpreter disallows the use of eval on nested brackets. Try the workaround code `JcQ5V4=J_CJ~Yml{meS<dhkUd_J)Y` instead, and input as a flattened list like `[4, 3, 5, 2, 1, 5, 4, 1, 3, 2, 1, 5, 2, 4, 3, 2, 1, 3, 5, 4, 3, 2, 4, 1, 5]`.
*(Thanks to @isaacg who helped golf out a few bytes)*
[Answer]
# CJam, ~~29~~ 27 bytes
```
q~{z_{[{1$e>}*]_&,}%pW%}4*;
```
Input like
```
[[4 3 5 2 1] [5 4 1 3 2] [1 5 2 4 3] [2 1 3 5 4] [3 2 4 1 5]]
```
Output like
```
[2 3 1 4 5]
[3 4 3 2 1]
[1 2 2 2 2]
[3 3 2 1 2]
```
## How it works
The basic idea is to have the code work along rows and rotate the grid counter-clockwise 4 times. To count the towers, I'm raising each tower as far as it doesn't make a "visual difference" (i.e., don't change it if it's visible, or pull it up to the same height of the tower in front of it), and then I'm counting distinct heights.
```
q~ "Read and evaluate the input.";
{ }4* "Four times...";
z "Transpose the grid.";
_ "Duplicate.";
{ }% "Map this block onto each row.";
[ ] "Collect into an array.";
{ }* "Fold this block onto the row.";
1$ "Copy the second-to-topmost element.":
e> "Take the maximum of the top two stack elements.";
"This fold replaces each element in the row by the
maximum of the numbers up to that element. So e.g.
[2 1 3 5 4] becomes [2 2 3 5 5].";
_&, "Count unique elements. This is how many towers you see.";
p "Print array of results.";
W% "Reverse the rows for the next run. Together with the transpose at
the start this rotates the grid counter-clockwise.";
; "Get rid of the grid so that it isn't printed at the end.";
```
[Answer]
# APL, 44
```
{{+/~0∊¨↓(∘.>⍨⍵)≥∘.<⍨⍳⍴⍵}¨↓(⌽∘⍉⍪⊢⍪⊖∘⍉⍪⊖∘⌽)⍵}
```
[Tested here.](http://www.tryapl.org/?a=%7B%7B+/%7E0%u220A%A8%u2193%28%u2218.%3E%u2368%u2375%29%u2265%u2218.%3C%u2368%u2373%u2374%u2375%7D%A8%u2193%28%u233D%u2218%u2349%u236A%u22A2%u236A%u2296%u2218%u2349%u236A%u2296%u2218%u233D%29%u2375%7D5%205%u23744%203%205%202%201%205%204%201%203%202%201%205%202%204%203%202%201%203%205%204%203%202%204%201%205&run)
[Answer]
# J, 35 chars
```
(+/@((>./={:)\)"2@(|.@|:^:(<4)@|:))
```
Example:
```
t=.4 3 5 2 1,. 5 4 1 3 2,. 1 5 2 4 3,. 2 1 3 5 4,. 3 2 4 1 5
(+/@((>./={:)\)"2@(|.@|:^:(<4)@|:)) t
2 3 1 4 5
3 4 3 2 1
1 2 2 2 2
3 3 2 1 2
```
[Try it here.](http://tryj.tk/)
[Answer]
# Haskell, 113
```
import Data.List
f(x:s)=1+f[r|r<-s,r>x]
f _=0
r=reverse
t=transpose
(?)=map
l s=[f?t s,(f.r)?s,r$(f.r)?t s,r$f?s]
```
[Answer]
# Mathematica, ~~230,120,116,113~~ 110 bytes
```
f=(t=Table;a=#;s=Length@a;t[v=t[c=m=0;t[h=a[[y,x]];If[h>m,c++;m=h],{y,s}];c,{x,s}];a=Thread@Reverse@a;v,{4}])&
```
Usage:
```
f[{
{4, 3, 5, 2, 1},
{5, 4, 1, 3, 2},
{1, 5, 2, 4, 3},
{2, 1, 3, 5, 4},
{3, 2, 4, 1, 5}
}]
{{2, 3, 1, 4, 5}, {3, 4, 3, 2, 1}, {1, 2, 2, 2, 2}, {3, 3, 2, 1, 2}}
```
[Answer]
## JavaScript, ~~335~~ ~~264~~ ~~256~~ 213
```
T=I=>((n,O)=>(S=i=>i--&&O.push([])+S(i)+(R=(j,a,x)=>j--&&R(j,0,0)+(C=k=>k--&&((!(a>>(b=I[(F=[f=>n-k-1,f=>j,f=>k,f=>n-j-1])[i]()][F[i+1&3]()])))&&++x+(a=1<<b))+C(k))(n)+O[i].push(x))(n,0,0))(4)&&O)(I.length,[],[])
```
Evaluate in the browser's JavaScript console (I used Firefox 34.0, doesn't seem to work in Chrome 39??) Test with:
```
JSON.stringify(T([[4, 3, 5, 2, 1], [5, 4, 1, 3, 2], [1, 5, 2, 4, 3], [2, 1, 3, 5, 4], [3, 2, 4, 1, 5]]));
```
Here's the current incarnation of the ungolfed code - it's getting harder to follow:
```
function countVisibleTowers(input) {
return ((n, out) =>
(sideRecurse = i =>
i-- &&
out.push([]) +
sideRecurse(i) +
(rowRecurse = (j, a, x) =>
j-- &&
rowRecurse(j, 0, 0) +
(columnRecurse = k =>
k-- &&
((!(a >> (b = input[
(offsetFtn = [
f => n - k - 1, // col negative
f => j, // row positive
f => k, // col positive
f => n - j - 1 // row negative
])[i]()
]
[
offsetFtn[i + 1 & 3]()
]))) &&
++x +
(a = 1 << b)) +
columnRecurse(k)
)(n) +
out[i].push(x)
)(n, 0, 0)
)(4) && out
)(input.length, [], [])
}
```
I intentionally didn't look at any of the other answers, I wanted to see if I could work something out myself. My approach was to flatten the input arrays to a one-dimensional array and precompute offsets to the rows from all four directions. Then I used shift right to test whether the next tower was falsy and if it was, then increment the counter for each row.
I am hoping there is lots of ways to improve this, perhaps not precalculate the offsets, but rather use some sort of overflow/modulo on the 1D input array? And perhaps combine my loops, get more functional, deduplicate.
**Any suggestions would be appreciated!**
**Update #1** : Progress, we have the technology! I was able to get rid of the precalculated offsets and do them inline with ternary operators strung together. Also was able to get rid of my if statement and convert the for loops into whiles.
**Update #2** : This is pretty frustrating; no pizza party for me. I figured going functional and using recursion would shave off many bytes, but my first few tries ended up being larger by as much as 100 characters! In desperation, I went whole-hog on using ES6 fat arrow functions to really pare it down. Then I took to replacing boolean operators with arithmetic ones and removing parens, semi-colons and spaces whereever I could. I even quit declaring my vars and polluted the global namespace with my local symbols. Dirty, dirty. After all that effort, I beat my Update #1 score by a whopping 8 characters, down to 256. Blargh!
If I applied the same ruthless optimizations and ES6 tricks to my Update #1 function, I'd beat this score by a mile. I may do an Update #3 just to see what that would look like.
**Update #3** : Turns out the fat arrow recursive approach had lots more life in it, I just needed to work with the 2 dimensional input directly rather than flattening it and get better about leveraging the closure scopes. I rewrote the inner array offset calculations twice and got the same score, so this approach may be close to minned out!
[Answer]
# Java, *only* ~~352~~ ~~350~~ 325 bytes...
```
class S{public static void main(String[]a){int n=a.length,i=0,j,k,b,c;int[][]d=new int[n][n];for(;i<n;i++)for(j=0;j<n;)d[i][j]=a[i].charAt(j++);for(i=0;i<4;i++){int[][]e=new int[n][n];for(k=0;k<n;k++)for(j=0;j<n;)e[n-j-1][k]=d[k][j++];d=e;for(j=n;j-->(k=c=b=0);System.out.print(c))for(;k<n;k++)b=d[j][k]>b?d[j][k]+0*c++:b;}}}
```
Input like `43521 54132 15243 21354 32415`
Output like: `23145343211222233212`
Indented:
```
class S{
public static void main(String[]a){
int n=a.length,i=0,j,k,b,c;
int[][]d=new int[n][n];
for(;i<n;i++)
for(j=0;j<n;)d[i][j]=a[i].charAt(j++);
for(i=0;i<4;i++){
int[][]e=new int[n][n];
for(k=0;k<n;k++)
for(j=0;j<n;)e[n-j-1][k]=d[k][j++];
d=e;
for(j=n;j-->(k=c=b=0);System.out.print(c))
for(;k<n;k++)b=d[j][k]>b?d[j][k]+0*c++:b;
}
}
}
```
***Any tips would be greatly appreciated!***
[Answer]
# Python 2 - 204 bytes
```
def f(l):n=len(l);k=[l[c]for c in range(n)if l[c]>([0]+list(l))[c]];return f(k)if k!=l else n
r=lambda m:(l[::-1]for l in m)
m=input();z=zip(*m);n=0
for t in z,r(m),r(z),m:print map(f,t)[::1-(n>1)*2];n+=1
```
This is probably a really poor golf. I thought the problem was interesting, so I decided to tackle it without looking at anyone else's solution. As I type this sentence I have yet to look at the answers on this question. I wouldn't be surprised if someone else has already done a shorter Python program ;)
**I/O Example**
```
$ ./towers.py <<< '[[4,3,5,2,1],[5,4,1,3,2],[1,5,2,4,3],[2,1,3,5,4],[3,2,4,1,5]]'
[2, 3, 1, 4, 5]
[3, 4, 3, 2, 1]
[1, 2, 2, 2, 2]
[3, 3, 2, 1, 2]
```
You may optionally include whitespace in the input. Pretty much anywhere, honestly. So long as you can `eval()` it, it'll work.
**Explanation**
The only interesting part of this program is the first line. It defines a function `f(l)` that tells you how many towers can be seen in a row, and the rest of the program is just applying that function to every possible position.
When called, it finds the length of `l` and saves it in a variable `n`. Then it creates a new variable `k` with this pretty monstrous list comprehension:
```
[l[c]for c in range(n)if l[c]>([0]+list(l))[c]]
```
It's not too bad when you break it down. Since `n==len(l)`, everything before the `if` just represents `l`. However, using `if` we can remove some elements from the list. We construct a list with `([0]+list(l))`, which is just "`l` with a `0` added to the beginning" (ignore the call to `list()`, that's only there because sometimes `l` is a generator and we need to make sure it's actually a list here). `l[c]` is only put into the final list if it's greater than `([0]+list(l))[c]`. This does two things:
* Since there's a new element at the beginning of the list, the index of each `l[c]` becomes `c+1`. We're effectively comparing each element to the element to the left of it. If it's greater, it's visible. Otherwise it's hidden and removed from the list.
* The first tower is always visible because there's nothing that can block it. Because we put 0 at the beginning, the first tower is always greater. (If we didn't do this `[0]+` nonsense and just compared `l[c]` to `l[c-1]`, Python would compare the first tower to the last one (you can index into a list from the end with `-1`, `-2`, etc.), so if the last tower was taller than the first one we'd get the wrong result.
When all is said and done, `l` contains some number of towers and `k` contains each one of those that isn't shorter than its immediate neighbour to the left. If none of them were (e.g. for `f([1,2,3,4,5])`), then `l == k`. We know there's nothing left to do and return `n` (the length of the list). If `l != k`, that means at least one of the towers was removed this time around and there may be more to do. So, we return `f(k)`. God, I love recursion. Interestingly, `f` always recurses one level deeper than is strictly "necessary". When the list that will be returned is generated, the function has no way of knowing that at first.
When I started writing this explanation, this program was 223 bytes long. While explaining things I realized that there were ways to save characters, so I'm glad I typed this up! The biggest example is that `f(l)` was originally implemented as an infinite loop that was broken out of when the computation was done, before I realized recursion would work. It just goes to show that the first solution you think of won't always be the best. :)
[Answer]
# Matlab, (123)(119)
```
function r=m(h);p=[h rot90(h) rot90(h,2) rot90(h,3)];for i=2:size(p) p(i,:)=max(p(i,:),p(i-1,:));end;r=sum(diff(p)>0)+1
```
used like this:
```
m([
4 3 5 2 1;
5 4 1 3 2;
1 5 2 4 3;
2 1 3 5 4;
3 2 4 1 5])
[2 3 1 4 5 3 4 3 2 1 1 2 2 2 2 3 3 2 1 2]
```
# C#, down to 354...
Different approach than TheBestOne used.
```
using System;
using System.Linq;
class A
{
static void Main(string[] h)
{
int m = (int)Math.Sqrt(h[0].Length),k=0;
var x = h[0].Select(c => c - 48);
var s = Enumerable.Range(0, m);
for (; k < 4; k++)
{
(k%2 == 0 ? s : s.Reverse())
.Select(j =>
(k > 0 && k < 3 ? x.Reverse() : x).Where((c, i) => (k % 2 == 0 ? i % m : i / m) == j)
.Aggregate(0, (p, c) =>
c > p%10
? c + 10 + p/10*10
: p, c => c/10))
.ToList()
.ForEach(Console.Write);
}
}
}
```
] |
[Question]
[
You are given as input two strings representing positive integers in base 10, such as `"12345"` and `"42"`. Your task is to output a string containing their product, `"518490"` in this case.
The twist is that you may not use any numerical types in your code. No `ints`, `float`s, `unsigned long`s, etc., no built-in complex number types or arbitrary precision integers, or anything along those lines. You many not use literals of those types, nor any function, method, operator etc. that returns them.
You *can* use strings, booleans, arrays, or anything else that wouldn't normally be used to represent a number. (But note that neither indexing into an array nor getting its length are likely to be possible without invoking a numeric type.) `char`s are permitted, but you may not perform any arithmetic or bitwise operations on them or otherwise treat them as anything else other than a token representing part of a string. (Lexicographical comparison of `char`s is allowed.)
You may not work around the restriction. This includes (but is not limited to) using numeric types inside an `eval` type function, implicit type conversions into numerical types, using numeric or bitwise operators on non-numeric types that support them, using numerical types stored inside container types, or calling functions or external programs that return numerical results in string form. (I reserve the right to add to this list if other workarounds appear in the answers.) You must implement the multiplication yourself using only non-numeric types.
Input and output may be by any convenient method, as long as the data enters and exits your code in the form of a string. You may assume each of the two input arguments contains only the ASCII characters `[0-9]` and will not start with `0`. Your output shouldn't have leading zeroes either.
One more thing: your code **must** correctly handle inputs up to **at least 10 characters in length**, and **must** run in under a minute on a modern computer for **all** inputs in that range. Before posting, please check that when given inputs `9999999999` and `9999999999`, your program gives an output of `99999999980000000001`, in less than a minute. This restriction exists specifically to prevent answers that work by allocating an array of size `a*b` and then iterating over it, so please bear in mind that answers of that form will not be eligible to win.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid solution (in bytes) wins.
[Answer]
# sed, 339 338 bytes
I know this is an old one, but I was browsing and this piqued my interest. Enough to actually register as a user! I guess I was swayed by "*I would quite like to see a full sed solution – Nathaniel*"...
```
s/[1-9]/0&/g
s/[5-9]/4&/g
y/8/4/
s/9/4&/g
s/4/22/g
s/[37]/2x/g
s/[26]/xx/g
s/[1-9]/x/g
:o
s/\( .*\)0$/0\1/
/x$/{
x
G
s/ .*/\n/
:a
s/\(.*\)0\(x*\)\n\(.*\)0\(x*\)\n/\1\n\3\n0\2\4/
ta
s/\n//g
:c
s/^x/0x/
s/0xxxxxxxxxx/x0/
tc
x
s/x$//
}
/ 0/bo
g
s/0x/-x/g
s/xx/2/g
y/x/1/
s/22/4/g
s/44/8/g
s/81/9/g
s/42/6/g
s/21/3/g
s/61/7/g
s/41/5/g
s/-//g
```
This sed script expects two decimal numbers as input, separated by one space
tests:
```
time test 518490 = $(./40297.sed <<<)"12345 42" || echo fail
time test 99999999980000000001 = $(./40297.sed <<<"9999999999 9999999999") || echo fail
time test 1522605027922533360535618378132637429718068114961380688657908494580122963258952897654000350692006139 = $(./40297.sed <<<"37975227936943673922808872755445627854565536638199 40094690950920881030683735292761468389214899724061") || echo fail
time test 1230186684530117755130494958384962720772853569595334792197322452151726400507263657518745202199786469389956474942774063845925192557326303453731548268507917026122142913461670429214311602221240479274737794080665351419597459856902143413 = $(./40297.sed <<<"33478071698956898786044169848212690817704794983713768568912431388982883793878002287614711652531743087737814467999489 36746043666799590428244633799627952632279158164343087642676032283815739666511279233373417143396810270092798736308917") || echo fail
```
You might recognise last two as RSA-100 (50 x 50 digits) and RSA-768 (116 x 116 digits).
Using GNU sed on a not-very-modern (2007-era Intel Core 2), the last of those takes over a minute, but it comes faster on a newer processor:
* Q6600: >1 minute
* i7-3770: 26 seconds
* i7-6700: 22 seconds
The puny 10-digit multiply specified in the question takes well under a second on any of these (despite being full of pathological nines).
I believe it's standard sed, with no extensions. POSIX guarantees hold space of 8192 bytes only, which limits us to multiplying 400x400 digit numbers, but implementations can provide more. GNU sed is limited only by available memory, so could manage something much bigger, if you're willing to wait.
And I'm confident that I have complied with the rules - that's almost a given in a language that has no numbers. :-)
## Explanation
I use a unary/decimal hybrid, converting decimal numbers into a sequence of unary:
```
42 => _xxxx_xx
```
In unary decimal, addition is easy. We iterate from least-significant to most-significant digit, concatenating the x's:
```
X=965 Y=106 SUM
_xxxxxxxxx_xxxxxx_xxxxx _x__xxxxxx
_xxxxxxxxx_xxxxxx _x_ _xxxxxxxxxxx
_xxxxxxxxx _x _xxxxxx_xxxxxxxxxxx
_xxxxxxxxxx_xxxxxx_xxxxxxxxxxx
```
We then remove whitespace, and deal with carry by converting 10
consecutive x's to one of the next unit:
```
_xxxxxxxxxx_xxxxxx_xxxxxxxxxxx 10.6.11
_xxxxxxxxxx_xxxxxxx_x 10.7.1
_x__xxxxxxx_x 1.0.7.1
```
Once we have addition, multiplication is possible. We multiply x\*y by considering the last digit of
y. Add x to the accumulator that many times, then move to the next
digit and shift x one decimal place to the left. Repeat until y is
zero.
## Expanded code
```
#!/bin/sed -f
# Convert to unary decimal. We save two or three bytes of code by
# reusing 0 as the digit separator.
s/[1-9]/0&/g
s/[5-9]/4&/g
y/8/4/
s/9/4&/g
s/4/22/g
s/[37]/2x/g
s/[26]/xx/g
s/[1-9]/x/g
# until y==0
:one
# y ends in zero => x *= 10 and y /= 10
s/\( .*\)0$/0\1/
# while y%10, acc += x, y -= 1
/x$/{
x
G
s/ .*/\n/
# Add x
:add
s/\(.*\)0\(x*\)\n\(.*\)0\(x*\)\n/\1\n\3\n0\2\4/
tadd
s/\n//g
:carry
s/^x/0x/
s/0xxxxxxxxxx/x0/
tcarry
# repeat for each unit of y
x
s/x$//
}
# y?
/ 0/bone
# convert hold space to decimal
g
s/0x/-x/g
s/xx/2/g
y/x/1/
s/22/4/g
s/44/8/g
s/81/9/g
s/42/6/g
s/21/3/g
s/61/7/g
s/41/5/g
s/-//g
```
[Answer]
# Python – ~~312~~ ~~286~~ 273
```
D={}
e=t=""
N=[e]
for c in"0123456789":D[c]=t;D[t]=c;t+="I";N+=N
B=lambda s:[D[c]for c in reversed(s)]
Y=B(input())+N
for a in B(input())+N:
for c in a:
s=[];o=e
for a,b in zip(N,Y):i=a+b+o;o=t<=i and"I"or e;s+=i.replace(t,e),;N=s
Y=[e]+Y
print e.join(B(N)).lstrip("0")
```
If (lots of) leading zeroes are allowed, the last 12 characters are not needed.
This essentially performs the standard multiplication by hand. Digits are represented as strings of repeated `I`s (like primitive Roman numerals). Numbers are represented as lists of digits in reverse order. Addition of single digits is performed by cocatenating strings and removing ten `I`s if necessary.
Here is an ungolfed version:
```
N = [""] # zero object: list with a lot of empty strings
D = {} # dictionary for conversion from and to digits
i = "" # iterates over digits
for c in "0123456789":
D[c] = i # map digit to Roman digit
D[i] = c # and vice versa
i += "I" # increments Roman digit
N += N # add leading zeros to zero
ten = "IIIIIIIIII" # Roman digit ten
# Conversion function
B = lambda s: [D[c] for c in reversed(s)]
def Add(x,y):
Sum = []
carryover = ""
for a,b in zip(x,y):
increment = a+b+carryover
carryover = "I" if ten in increment else ""
increment = increment.replace(ten,"") # take increment modulo ten
Sum += [increment]
return Sum
def M(x,y):
Sum = N[:] # Initiate Sum as zero
X = B(x)+N # Convert and add leading zeros
Y = B(y)+N
for a in X:
for c in a:
Sum = Add(Sum,p+Y)
Y = [""] + Y # multiply Y by 10
return "".join(B(Sum)).lstrip("0") # Convert back and to string, remove leading zeros.
M(input(),input())
```
[Answer]
## Ruby: ~~752~~ 698
This is just to get an answer out there, just done out of curiosity. Edited: now golfed a bit.
```
$F='0123456789'
$G="#{$F}abcdefghij"
def x(a,b);p(a=~/[13579]$/?b:"",a==""?"":x(Hash[*%w(b0 5 b1 6 b2 7 b3 8 b4 9)].to_a.inject(a.tr($F,'0011223344').chars.zip(a.tr($F,'ababababab').chars).flatten.join("")){|n,q|k,v=q;n.gsub(k,v)}.gsub(/[ab]/,'').sub(/^0*/,''),p(b,b)));end
def p(a,b);j,k=["0#{a}","0#{b}"].map{|c|c.gsub(/./,'0')};c="#{k}#{a}".chars.zip("#{j}#{b}".chars).drop_while{|z|z==%w(0 0)}.map{|m|$G.sub(/#{m.map{|n|"122333444455555666666777777788888888999999999".chars.select{|c|c==n}}.flatten.map{|c|'.'}.join("")}/,"").chars.first}.flatten.join("");d=nil;
while c!=d
d=c;c="0#{d}".gsub(/[0-9][a-j]/) {|m| m.tr($G,"123456789a#{$F}")}.sub(/^0/,'')
end;c;end
puts x(ARGV.shift,ARGV.shift)
```
Usage: I had this in a file called peasant.rb:
```
$ time ruby peasant.rb 9999999999 9999999999
99999999980000000001
real 0m0.129s
user 0m0.096s
sys 0m0.027s
```
Explanation: it's peasant multiplication, so I repeatedly halve&double. Halving is done by halving digits & marking remainders like so: 1234 -> 0b1a1b2a; then find and replace on the b's: 06a17a; then cleaning up -> 617.
Addition is done like so... first of all, I pad both strings to the same length and make pairs from the digits. Then I add the digits by constructing a string that has the length of each digit and concatenating; I remove a string of that length from the start of '0123456789abcdefghij', and then keep the first char. So, eg, "9"+"9"->"i". NB I avoid actually using length functions here to avoid number types entirely; removing the prefix is done with a regexp instead.
So now I have a string containing a mix of digits and letters. The letters represent numbers with a carry digit; I prepend 0 to the number, then repeatedly replace digit-letter patterns with the result of the carry until the addition is complete.
[Answer]
# Brainfuck (1328 bytes)
Considerations at first:
* Not sure if brainfuck is a valid answer to this questions since I'm not sure whether you consider the cell values as 'numerical types' or not. I don't think so since bf doesn't know types, but that's my own opinion, please correct me if I'm wrong.
* An implementation supporting (nearly) unlimited values is necessary.
* It might be far too slow, based on the implementation.
I only tested the program with my own interpreter, you can find it [here](https://github.com/redevined/brainfuck).
Input must be both numbers separated by a single ASCII space.
**Golfed:**
```
,>++++++[<----->-]<--[>,>++++++[<----->-]<--]>>>+<<<<[>>++++[<<---->>-]<<[>>>>[>+>+<<-]>>[<<+>>-]<<<<<<-]>>>>>[<<<<<+>>>>>-]<[>++++++++++<-]>[<<+>>-]<<<<<[->+<]>[-<+>]<<]>>>>[-]<,[>,]>>>+<<<<[>>+++++++[<<------->>-]<<+[>>>>[>+>+<<-]>>[<<+>>-]<<<<<<-]>>>>>[<<<<<+>>>>>-]<[>++++++++++<-]>[<<+>>-]<<<<<[->+<]>[-<+>]<<]>>>>[-]<<<<<[>>[>+>+<<-]>>[<<+>>-]<<<<-]>>[-]>[<+>-]<[>>+>+<<<-]>>>[<<<+>>>-]<[[-]<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]++++++++++<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<-]>[<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<->>[-]]+>-]<-]<<+>]<[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<<[<<->>-]<[-]<[>>>>>>>>+<<<<<<<<-]>>>>>>>>>[>>]+[<<]>[>[>>]<+<[<<]>-]<<<<<<<<<<[>>+>+<<<-]>>>[<<<+>>>-]+[<+>-]<<<[-]>>[<<+>>-]<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]++++++++++<[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>]<[-]<<<<[-]>>>[<<<+>>>-]<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<+>-]<]<[>+>+<<-]>>[<<+>>-]<[>+<[-]]+>[<[-]<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[[-]>>>>>>>>[>>]<[<[<<]<<<<<+>>>>>>>[>>]<-]<-<<[<<]<<<<<>++++++++++++++++++++++++++++++++++++++++++++++++[<+>-]<.[-]<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]+[<->-]<<<<<[-]>>>>[<<<<+>>>>-]<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]<[<+>-]<]<[-]]<[>>++++++[<++++++++>-]<.[-]<[-]]<[-]<[-]>>>>>>>>>>>>[>[-]>]<<[-<<]<<<<<<<<<<<<<<<<<[-]<[-]
```
**Ungolfed:**
```
,
>++++++[<----->-]<--
[ # read input until space
>,
>++++++[<----->-]<-- # decrease cell by 32 to check if it's a space
]
>>>+<<<< # set multiplier to 1
[
>>++++[<<---->>-]<< # decrease by 16 to get cell value of number
[>>>>[>+>+<<-]>>[<<+>>-]<<<<<<-] # multiply value by multiplier
>>>>>[<<<<<+>>>>>-] # copy value back
<[>++++++++++<-]>[<<+>>-] # multiply multiplier by 10
<<<<< # go back to number
[->+<]>[-<+>] # add value to next cell and move sum to previous cell
<< # go to next number
]
>>>>[-]< # delete old multiplier
,[>,] # read second number until end of input
>>>+<<<< # set new multiplier
[
>>+++++++[<<------->>-]<<+ # decrease by 48 to get cell value of number
[>>>>[>+>+<<-]>>[<<+>>-]<<<<<<-] # multiply value by multiplier
>>>>>[<<<<<+>>>>>-] # copy value back
<[>++++++++++<-]>[<<+>>-] # multiply multiplier by 10
<<<<< # go back to number
[->+<]>[-<+>] # add value to next cell and move sum to previous cell
<< # go to next number
]
>>>>[-]<<<<< # delete multiplier
[>>[>+>+<<-]>>[<<+>>-]<<<<-]>>[-]> # multiply both values
# magical algorithm for printing cell value as number taken from Cedric Mamo's code from a previous question
[<+>-]<[>>+>+<<<-]>>>[<<<+>>>-]<[[-]<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]++++++++++<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<-]>[<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<->>[-]]+>-]<-]<<+>]<[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<<[<<->>-]<[-]<[>>>>>>>>+<<<<<<<<-]>>>>>>>>>[>>]+[<<]>[>[>>]<+<[<<]>-]<<<<<<<<<<[>>+>+<<<-]>>>[<<<+>>>-]+[<+>-]<<<[-]>>[<<+>>-]<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]++++++++++<[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>]<[-]<<<<[-]>>>[<<<+>>>-]<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<+>-]<]<[>+>+<<-]>>[<<+>>-]<[>+<[-]]+>[<[-]<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[[-]>>>>>>>>[>>]<[<[<<]<<<<<+>>>>>>>[>>]<-]<-<<[<<]<<<<<>++++++++++++++++++++++++++++++++++++++++++++++++[<+>-]<.[-]<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]+[<->-]<<<<<[-]>>>>[<<<<+>>>>-]<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]<[<+>-]<]<[-]]<[>>++++++[<++++++++>-]<.[-]<[-]]<[-]<[-]>>>>>>>>>>>>[>[-]>]<<[-<<]<<<<<<<<<<<<<<<<<[-]<[-]
```
I've taken the code for the output of the value from [this answer](https://stackoverflow.com/a/13583633/2858287), thanks to the author for that!
The program *might* not be valid, but in either way I wanted to share it with you ^^
**Update:** You can now test it (only for small multiplications) here, thanks to @Sp3000's [answer](https://codegolf.stackexchange.com/a/40091/29890) to [this contest](https://codegolf.stackexchange.com/q/40073/29890) and SE's new Stack Snippets!
```
var NUM_CELLS = 30000;var ITERS_PER_SEC = 100000;var TIMEOUT_MILLISECS = 5000;function clear_output(){document.getElementById("output").value="";document.getElementById("stderr").innerHTML=""}function stop(){running=false;document.getElementById("run").disabled=false;document.getElementById("stop").disabled=true;document.getElementById("clear").disabled=false;document.getElementById("wrap").disabled=false;document.getElementById("timeout").disabled=false;document.getElementById("eof").disabled=false}function interrupt(){error(ERROR_INTERRUPT)}function error(e){document.getElementById("stderr").innerHTML=e;stop()}function run(){clear_output();document.getElementById("run").disabled=true;document.getElementById("stop").disabled=false;document.getElementById("clear").disabled=true;document.getElementById("wrap").disabled=true;document.getElementById("timeout").disabled=true;document.getElementById("eof").disabled=true;code=document.getElementById("code").value;input=document.getElementById("input").value;wrap=document.getElementById("wrap").value;timeout=document.getElementById("timeout").checked;eof=document.getElementById("eof").value;loop_stack=[];loop_map={};for(var e=0;e<code.length;++e){if(code[e]=="["){loop_stack.push(e)}else if(code[e]=="]"){if(loop_stack.length==0){error(ERROR_BRACKET);return}else{var t=loop_stack.pop();loop_map[t]=e;loop_map[e]=t}}}if(loop_stack.length>0){error(ERROR_BRACKET);return}running=true;start_time=Date.now();code_ptr=0;input_ptr=0;cell_ptr=Math.floor(NUM_CELLS/2);cells={};iterations=0;bf_iter(1)}function bf_iter(e){if(code_ptr>=code.length||!running){stop();return}var t=Date.now();for(var n=0;n<e;++n){if(cells[cell_ptr]==undefined){cells[cell_ptr]=0}switch(code[code_ptr]){case"+":if(wrap=="8"&&cells[cell_ptr]==255||wrap=="16"&&cells[cell_ptr]==65535||wrap=="32"&&cells[cell_ptr]==2147483647){cells[cell_ptr]=0}else{cells[cell_ptr]++}break;case"-":if(cells[cell_ptr]==0){if(wrap=="8"){cells[cell_ptr]=255}if(wrap=="16"){cells[cell_ptr]=65535}if(wrap=="32"){cells[cell_ptr]=2147483647}}else{cells[cell_ptr]--}break;case"<":cell_ptr--;break;case">":cell_ptr++;break;case".":document.getElementById("output").value+=String.fromCharCode(cells[cell_ptr]);break;case",":if(input_ptr>=input.length){if(eof!="nochange"){cells[cell_ptr]=parseInt(eof)}}else{cells[cell_ptr]=input.charCodeAt(input_ptr);input_ptr++}break;case"[":if(cells[cell_ptr]==0){code_ptr=loop_map[code_ptr]}break;case"]":if(cells[cell_ptr]!=0){code_ptr=loop_map[code_ptr]}break}code_ptr++;iterations++;if(timeout&&Date.now()-start_time>TIMEOUT_MILLISECS){error(ERROR_TIMEOUT);return}}setTimeout(function(){bf_iter(ITERS_PER_SEC*(Date.now()-t)/1e3)},0)}var ERROR_BRACKET="Mismatched brackets";var ERROR_TIMEOUT="Timeout";var ERROR_INTERRUPT="Interrupted by user";var code,input,wrap,timeout,eof,loop_stack,loop_map;var running,start_time,code_ptr,input_ptr,cell_ptr,cells,iterations
```
```
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;"> <div style="float:left; width:50%;"> Code: <br> <textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">,>++++++[<----->-]<--[>,>++++++[<----->-]<--]>>>+<<<<[>>++++[<<---->>-]<<[>>>>[>+>+<<-]>>[<<+>>-]<<<<<<-]>>>>>[<<<<<+>>>>>-]<[>++++++++++<-]>[<<+>>-]<<<<<[->+<]>[-<+>]<<]>>>>[-]<,[>,]>>>+<<<<[>>+++++++[<<------->>-]<<+[>>>>[>+>+<<-]>>[<<+>>-]<<<<<<-]>>>>>[<<<<<+>>>>>-]<[>++++++++++<-]>[<<+>>-]<<<<<[->+<]>[-<+>]<<]>>>>[-]<<<<<[>>[>+>+<<-]>>[<<+>>-]<<<<-]>>[-]>[<+>-]<[>>+>+<<<-]>>>[<<<+>>>-]<[[-]<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]++++++++++<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<-]>[<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<->>[-]]+>-]<-]<<+>]<[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<<[<<->>-]<[-]<[>>>>>>>>+<<<<<<<<-]>>>>>>>>>[>>]+[<<]>[>[>>]<+<[<<]>-]<<<<<<<<<<[>>+>+<<<-]>>>[<<<+>>>-]+[<+>-]<<<[-]>>[<<+>>-]<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]++++++++++<[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>]<[-]<<<<[-]>>>[<<<+>>>-]<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<+>-]<]<[>+>+<<-]>>[<<+>>-]<[>+<[-]]+>[<[-]<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[[-]>>>>>>>>[>>]<[<[<<]<<<<<+>>>>>>>[>>]<-]<-<<[<<]<<<<<>++++++++++++++++++++++++++++++++++++++++++++++++[<+>-]<.[-]<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]+[<->-]<<<<<[-]>>>>[<<<<+>>>>-]<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]<[<+>-]<]<[-]]<[>>++++++[<++++++++>-]<.[-]<[-]]<[-]<[-]>>>>>>>>>>>>[>[-]>]<<[-<<]<<<<<<<<<<<<<<<<<[-]<[-]</textarea> <br>Input: <br> <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">7 6</textarea> <p> Wrap: <select id="wrap"> <option value="8">8-bit</option> <option value="16">16-bit</option> <option value="32" selected="selected">32-bit</option> </select> Timeout: <input id="timeout" type="checkbox"></input> EOF: <select id="eof"> <option value="nochange">Same</option> <option value="0" selected="selected">0</option> <option value="-1">-1</option> </select> </p> </div> <div style="float:left; width:50%;"> Output: <br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> <p> <input id="run" type="button" value="Run" onclick="run()"></input> <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="true"></input> <input id="clear" type="button" value="Clear" onclick="clear_output()"></input> <span id="stderr" style="color:red"></span></p></div></div>
```
[Answer]
# Haskell - 180 ~~206 214~~
```
r=reverse
f=filter
z=['0'..'9']
a?f|f="1"!a
a?_=a
(a:b)!(c:d)=e:b!d?(e<a)where e=fst$last$zip(f(>=c)z++z)$f(<=a)z
a!c=a++c
a%(b:c)=foldr(!)('0':a%c)$f(<b)z>>[a]
_%b=b
a#b=r$r a%r b
```
Implements multiplication via repeated addition, and all kinds of digit magic are handled by shifting and filtering the `['0'..'9']` list. Defines an operator `#` of the type `String -> String -> String`:
```
*> :set +s
*> "9990123456789"#"9999876543210"
"99900001219316321126352690"
(0.02 secs, 9862288 bytes)
```
[Answer]
## Python, 394 349 340 chars
```
D='0123456789'
R=reversed
U=lambda x:[R for y in D if y<x]
T=U(':')
def A(a,b,r='',c=[]):
for x,y in map(None,R(a),R(b)):
d=U(x)+U(y)+c;t=T;c=[R]
if d<T:t=c=[]
r=min(k for k in D if U(k)+t>=d)+r
if c:r='1'+r
return r
a,b=input()
m=''
while b:
if list(b).pop()in'13579':m=A(m,a)
b=list(A(b,A(b,A(b,A(b,b)))));b.pop();a=A(a,a)
print m
```
Run like:
```
echo '"9999999999","9999999999"' | ./mulstr.py
```
Takes 50 milliseconds.
Uses [Russian Peasant multiplication](http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication#Russian_peasant_multiplication). When adding digits, we convert them to unary ('5' => [R,R,R,R,R]), concatenate the lists, then convert back. `U` converts to unary, using `R` as the unary digit. We compute `b/=2` as `b=b*5/10`.
[Answer]
# Haskell, 231 bytes
This defines an operator # which multiplies two string representations of natural numbers. It works by defining an elementary increment/decrement operation on strings, then uses it to build up addition and multiplication. A little extra magic gives some exponential speedups that make it all possible..
```
r=reverse
n="9876543210"
t=True
c&(x:y)|c==x=head y|t=c&y
m%[]="1";m%(c:s)|c==last m=head m:m%s|t=c&m:s
[]!y=y;x![]=x;(x:a)!('0':b)=x:a!b;x!y=(r n%x)!(n%y)
"0"?_="0";x?('0':y)|all(=='0')y="0"|t=('0':x)?y;x?y=x?(n%y)!x
x#y=r$r x?r y
```
This approach is fast enough that even on a 2008 laptop in the unoptimized ghci REPL, the test case takes just a fraction of a second:
```
λ> :set +s
λ> let test = replicate 10 '9'
(0.00 secs, 0 bytes)
λ> test
"9999999999"
(0.00 secs, 1069784 bytes)
λ> test # test
"99999999980000000001"
(0.06 secs, 13451288 bytes)
```
Here's a check that all of the two-digit products are correct:
```
λ> and [ show (x * y) == (show x # show y) | x <- [0..100], y <- [0..100] ]
True
```
[Answer]
# JavaScript (E6) 375 ~~395 411 449~~
**Edit** Golfed
**Edit** Bug fixed: missing clearing a carry flag
It can be done with just symbol manipulation in near 0 time.
In this version you could use any char instead of the digits, as long as the symbol are in ascending order.
Notes: using strings, hashmap with string key, arrays used as list. No indexing, the arrays are traversed using 'map' or rotated using push & shift.
All '+' are string concatenation.
```
M=(x,y,S=a=>a.shift()||z,R=a=>[...a].reverse(),e=R('9876543210'),d=[...e])=>
R(y)[T='map'](b=>
R(x)[T](a=>(
u=R[e[a+=b]+v],
v=R[S[a]+(u<v?'1':z)],
p[P](t=R[S(o)+u]),
t<u?v=R[v+'1']:v
),o=p,p=[])
+(v>z&&p[P](v),x+=v=z),
d[T](a=>d[T](b=>e[P='push'](R[a+b]=S(e)))+e[P](S(e))),
d[T](a=>d[T](b=>e[d[T](c=>v=c<a?(u=R[u+b])<b?R[v+'1']:v:v,v=u=z='0'),S[a+b]=v,a+b]=u)),
p=[v=z]
)&&R(p).join(o)
```
**Less Golfed** (maybe I'll add an explanation tomorrow)
```
M=(x,y)=>(
R=a=>[...a].reverse(),
// Addition table s
s={},
e=[...'9012345678'],
[for(a of(d='0123456789'))for(b of(e.push(e.shift()),d))e.push(s[a+b]=c=e.shift())],
// Multiplication table m,n
m={},n={},
[for(a of d)for(b of d)(
[for(c of(z=u=v='0',d))
c<a&&(t=s[u+b],t<u?v=s[v+'1']:v,u=t)
],m[a+b]=u,n[a+b]=v
)],
x=R(x),v=z,o=[],p=[],
[for(b of R(y))(
[for(a of x)(
u=s[m[a+b]+v],v=s[n[a+b]+(u<v?'1':z)],
p.push(t=s[(o.shift()||z)+u]),
t<u?v=s[v+'1']:v
)],
v>z?p.push(v):o,o=p,p=[],x.unshift(v=z)
)],
R(o).join('')
)
```
**Test** In FireFox/FireBug console
```
t0=-new Date
r=M('9999999999','9999999999')
t1=-new Date
console.log("Result",r, "time ms", t0-t1)
```
*Output*
```
Result 99999999980000000001 time ms 14
```
[Answer]
**JavaScript: ~~3710~~ 3604 bytes**
* Using string lookup tables with 1 digit multiplication and add with carry.
* The multiplication is done by digit x digit instead of digit x line.
Golf:
```
var M={
'00':'0','01':'0','02':'0','03':'0','04':'0','05':'0','06':'0','07':'0','08':'0','09':'0',
'10':'0','11':'1','12':'2','13':'3','14':'4','15':'5','16':'6','17':'7','18':'8','19':'9',
'20':'0','21':'2','22':'4','23':'6','24':'8','25':'10','26':'12','27':'14','28':'16','29':'18',
'30':'0','31':'3','32':'6','33':'9','34':'12','35':'15','36':'28','37':'21','38':'24','39':'27',
'40':'0','41':'4','42':'8','43':'12','44':'16','45':'20','46':'24','47':'28','48':'32','49':'36',
'50':'0','51':'5','52':'10','53':'15','54':'20','55':'25','56':'30','57':'35','58':'40','59':'45',
'60':'0','61':'6','62':'12','63':'18','64':'24','65':'30','66':'36','67':'42','68':'48','69':'54',
'70':'0','71':'7','72':'14','73':'21','74':'28','75':'35','76':'42','77':'49','78':'56','79':'63',
'80':'0','81':'8','82':'16','83':'24','84':'32','85':'40','86':'48','87':'56','88':'64','89':'72',
'90':'0','91':'9','92':'18','93':'27','94':'36','95':'45','96':'54','97':'63','98':'72','99':'81'
};
var A={
'000':'0','001':'1','002':'2','003':'3','004':'4','005':'5','006':'6','007':'7','008':'8','009':'9',
'010':'1','011':'2','012':'3','013':'4','014':'5','015':'6','016':'7','017':'8','018':'9','019':'10',
'020':'2','021':'3','022':'4','023':'5','024':'6','025':'7','026':'8','027':'9','028':'10','029':'11',
'030':'3','031':'4','032':'5','033':'6','034':'7','035':'8','036':'9','037':'10','038':'11','039':'12',
'040':'4','041':'5','042':'6','043':'7','044':'8','045':'9','046':'10','047':'11','048':'12','049':'13',
'050':'5','051':'6','052':'7','053':'8','054':'9','055':'10','056':'11','057':'12','058':'13','059':'14',
'060':'6','061':'7','062':'8','063':'9','064':'10','065':'11','066':'12','067':'13','068':'14','069':'15',
'070':'7','071':'8','072':'9','073':'10','074':'11','075':'12','076':'13','077':'14','078':'15','079':'16',
'080':'8','081':'9','082':'10','083':'11','084':'12','085':'13','086':'14','087':'15','088':'16','089':'17',
'090':'9','091':'10','092':'11','093':'12','094':'13','095':'14','096':'15','097':'16','098':'17','099':'18',
'100':'1','101':'2','102':'3','103':'4','104':'5','105':'6','106':'7','107':'8','108':'9','109':'10',
'110':'2','111':'3','112':'4','113':'5','114':'6','115':'7','116':'8','117':'9','118':'10','119':'11',
'120':'3','121':'4','122':'5','123':'6','124':'7','125':'8','126':'9','127':'10','128':'11','129':'12',
'130':'4','131':'5','132':'6','133':'7','134':'8','135':'9','136':'10','137':'11','138':'12','139':'13',
'140':'5','141':'6','142':'7','143':'8','144':'9','145':'10','146':'11','147':'12','148':'13','149':'14',
'150':'6','151':'7','152':'8','153':'9','154':'10','155':'11','156':'12','157':'13','158':'14','159':'15',
'160':'7','161':'8','162':'9','163':'10','164':'11','165':'12','166':'13','167':'14','168':'15','169':'16',
'170':'8','171':'9','172':'10','173':'11','174':'12','175':'13','176':'14','177':'15','178':'16','179':'17',
'180':'9','181':'10','182':'11','183':'12','184':'13','185':'14','186':'15','187':'16','188':'17','189':'18',
'190':'10','191':'11','192':'12','193':'13','194':'14','195':'15','196':'16','197':'17','198':'18','199':'19'
}
Array.prototype.e=function(){return(''+this)==='';}
String.prototype.s=function(){return this.split('').reverse();}
function B(a,b,c) {
var r='',s='';
a=a.s();
b=b.s();
while (!a.e()||!b.e()||c!=='0') {
x=a.e()?'0':a.shift();
y=b.e()?'0':b.shift();
s=A[c+x+y];
s=s.s();
r=s.shift()+r;
c=s.e()?'0':'1';
}
return r;
}
function m(a,b) {
var s='0',m='';
b.split('').reverse().forEach(function(e){
var z=m;
a.split('').reverse().forEach(function(f){s=B(s,M[e+f]+z,'0');z+='0';});
m+='0';
});
return s;
}
```
Ungolfed with tests:
```
var mul = {
'00':'0','01':'0','02':'0','03':'0','04':'0','05':'0','06':'0','07':'0','08':'0','09':'0',
'10':'0','11':'1','12':'2','13':'3','14':'4','15':'5','16':'6','17':'7','18':'8','19':'9',
'20':'0','21':'2','22':'4','23':'6','24':'8','25':'10','26':'12','27':'14','28':'16','29':'18',
'30':'0','31':'3','32':'6','33':'9','34':'12','35':'15','36':'28','37':'21','38':'24','39':'27',
'40':'0','41':'4','42':'8','43':'12','44':'16','45':'20','46':'24','47':'28','48':'32','49':'36',
'50':'0','51':'5','52':'10','53':'15','54':'20','55':'25','56':'30','57':'35','58':'40','59':'45',
'60':'0','61':'6','62':'12','63':'18','64':'24','65':'30','66':'36','67':'42','68':'48','69':'54',
'70':'0','71':'7','72':'14','73':'21','74':'28','75':'35','76':'42','77':'49','78':'56','79':'63',
'80':'0','81':'8','82':'16','83':'24','84':'32','85':'40','86':'48','87':'56','88':'64','89':'72',
'90':'0','91':'9','92':'18','93':'27','94':'36','95':'45','96':'54','97':'63','98':'72','99':'81'
};
var adc = {
'000':'0','001':'1','002':'2','003':'3','004':'4','005':'5','006':'6','007':'7','008':'8','009':'9',
'010':'1','011':'2','012':'3','013':'4','014':'5','015':'6','016':'7','017':'8','018':'9','019':'10',
'020':'2','021':'3','022':'4','023':'5','024':'6','025':'7','026':'8','027':'9','028':'10','029':'11',
'030':'3','031':'4','032':'5','033':'6','034':'7','035':'8','036':'9','037':'10','038':'11','039':'12',
'040':'4','041':'5','042':'6','043':'7','044':'8','045':'9','046':'10','047':'11','048':'12','049':'13',
'050':'5','051':'6','052':'7','053':'8','054':'9','055':'10','056':'11','057':'12','058':'13','059':'14',
'060':'6','061':'7','062':'8','063':'9','064':'10','065':'11','066':'12','067':'13','068':'14','069':'15',
'070':'7','071':'8','072':'9','073':'10','074':'11','075':'12','076':'13','077':'14','078':'15','079':'16',
'080':'8','081':'9','082':'10','083':'11','084':'12','085':'13','086':'14','087':'15','088':'16','089':'17',
'090':'9','091':'10','092':'11','093':'12','094':'13','095':'14','096':'15','097':'16','098':'17','099':'18',
'100':'1','101':'2','102':'3','103':'4','104':'5','105':'6','106':'7','107':'8','108':'9','109':'10',
'110':'2','111':'3','112':'4','113':'5','114':'6','115':'7','116':'8','117':'9','118':'10','119':'11',
'120':'3','121':'4','122':'5','123':'6','124':'7','125':'8','126':'9','127':'10','128':'11','129':'12',
'130':'4','131':'5','132':'6','133':'7','134':'8','135':'9','136':'10','137':'11','138':'12','139':'13',
'140':'5','141':'6','142':'7','143':'8','144':'9','145':'10','146':'11','147':'12','148':'13','149':'14',
'150':'6','151':'7','152':'8','153':'9','154':'10','155':'11','156':'12','157':'13','158':'14','159':'15',
'160':'7','161':'8','162':'9','163':'10','164':'11','165':'12','166':'13','167':'14','168':'15','169':'16',
'170':'8','171':'9','172':'10','173':'11','174':'12','175':'13','176':'14','177':'15','178':'16','179':'17',
'180':'9','181':'10','182':'11','183':'12','184':'13','185':'14','186':'15','187':'16','188':'17','189':'18',
'190':'10','191':'11','192':'12','193':'13','194':'14','195':'15','196':'16','197':'17','198':'18','199':'19'
}
Array.prototype.isEmpty = function() {
return (''+this) === '';
}
function add(a, b, c) {
var r = '', s = '';
a = a.split("").reverse();
b = b.split("").reverse();
while (!a.isEmpty() || !b.isEmpty() || c !== '0') {
x = a.isEmpty() ? '0' : a.shift();
y = b.isEmpty() ? '0' : b.shift();
s = adc[c + x + y];
s = s.split("").reverse();
r = (s.shift()) + r;
c = (s.isEmpty()) ? '0' : '1';
}
return r;
}
function mult(a, b) {
var s = '0';
var m = '';
b.split('').reverse().forEach(function(e) {
var z = m;
a.split('').reverse().forEach(function(f) {
s = add(s, mul[e + f] + z, '0');
z = z + '0';
});
m = m + '0';
} );
return s;
}
function test(a, b) {
var t0 = (new Date()).getTime();
var r = mult(a,b);
var t1 = (new Date()).getTime();
var e = t1 - t0;
console.log('mult ' + a + ' * ' + b + ' = ' + r + " (" + e + " ms)");
}
test('12345', '42');
test('9999999999', '9999999999');
```
This outputs:
```
mult 12345 * 42 = 518490 (3 ms)
mult 9999999999 * 9999999999 = 99999999980000000001 (47 ms)
```
[Answer]
## Python 2 (555)
I wouldn't normally answer my own challenge so quickly (or at all), but I wanted to prove it could be done. (Luckily some other answers did that before this one, but I couldn't help wanting to finish it.) There's some more golfing that could be done, but I think this is reasonable. It handles the `9999999999x9999999999` case in under 0.03s on my machine.
```
d="123456789";I=dict(zip('0'+d,d+'0'))
def r(x):return reversed(x)
def s(x):return''.join(x)
def i(x):
try:
h=I[x.next()]
if h!='0':h+=s(x)
else:h+=i(x)
return h
except:return'1'
def b(x,y):
for c in'0'+d:
if c==y:break
x=iter(i(x))
return x
def a(x,y):
z=''
for c in y:
x=b(x,c)
try:z+=x.next()
except:z+='0'
return z+s(x)
def n(x,y):
z='0'
for c in'0'+d:
if c==y:break
z=a(iter(z),x)
return z
def o(x,y):
x=s(x)
l='';z=''
for c in y:
z=a(iter(z),l+s(n(x,c)))
l+='0'
return z
def m(x,y):
return s(r(o(r(x),r(y))))
```
Example use: `m("12345","42")`
It works by doing long multiplication using string manipulations. Sometimes the variables are strings and sometimes they're iterators over strings, which makes it possible to get the first element without using an integer literal. Everything's stored with the digits reversed, so that the first element is the least significant digit.
Here's a function-by-function explanation:
* `r` and `s` are bookkeeping functions. (`r` is just an alias for `reversed`, which makes a reverse iterator, and `s` converts iterators into strings.)
* `i` increments the number in a string by 1, including cases like `39+1=40` and `99+1=100`.
* `b` adds `x` and `y`, but `y` must be only one digit. It works by incrementing `x` `y` times.
* `a` adds two numbers together that can both have multiple digits, by calling `b` for each digit in `y`.
* `n` multiplies `x` and `y`, but `y` must be only one digit. It works by adding `x` to itself `y` times.
* `o` multiplies `x` and `y`, where both arguments can have multiple digits. It uses classic long-multiplication
* `m` just converts its string inputs into reverse iterators and hands them to `o`, then reverses the result and converts it into a string.
[Answer]
## Scala, 470 characters
(the `⇒` are standard scala but can equivalently be replaced with `=>` if we're counting bytes)
```
def p(a: String,b: String)={type D=List[Char]
val d="0123456789".toList
def v(s: String)=s.toList.map{c⇒d.takeWhile(c.!=)}
def u(l:D, a:D):(Char,D)=l match {
case _::_::_::_::_::_::_::_::_::_::m⇒u(m,'a'::a)
case _⇒(('a'::l).zip(d).last._2,a)}
val o=(("", List[Char]())/:v(a).tails.toList.init.map{l⇒(v(b) map {_.flatMap(_⇒l.head)})++l.tail.map(_⇒Nil) reverse}.reduce(_.zipAll(_, Nil, Nil).map{t⇒t._1++t._2}))({(t,e)⇒val s=u(t._2++e,Nil);(s._1+t._1,s._2)})
u(o._2, Nil)._1+o._1}
```
Here we're emulating digits using the length of lists, being careful not to use any numeric operations - only folds, maps, zips and the like. A number is a list of these digits (order strategically reversed halfway through the computation); we multiply individual digits with `flatMap` and our rows up with `reduce`. `u` handles figuring out the carry (by directly matching against a list of >10 elements, and recursing) and converting digits back to characters, and we use a `/:` to work our way through the stack with that. The required example completes in less than a second.
[Answer]
# Haskell ~~507~~ 496
This works for arbitrarily large integers. I define custom representations for the natural numbers from 0 to 18 (the largest natural number equal to the sum of two digits), and define little-endian multiplication in terms of digit\*number multiplication, which I define in terms of number+number addition, which I define in terms of digit+digit addition. I have a reduction function that expands 10--18 values into their digital decomposition. This then just reads and reverses the two strings, translates to the custom bindings, multiplies, and translates back, reversing to get the right result.
## Edit 2
I saved a few characters by creating short local aliases for multi-character commands I use more than once, as well as removing spaces and parentheses, and by replacing `(`-`)` pairs with `$` when possible.
```
data S=Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R deriving(Enum, Ord, Eq)
p Z=id
p x=succ.p(pred x)
s Z=id
s x=pred.s(pred x)
z=s J
r[]=[]
r(x:y)|x<J=x:r y
r(x:[])=z x:[A]
r(x:y)=z x:(r$p A a:b)where(a:b)=r y
a x y=r$w(r x)(r y)
m Z _=[]
m _[]=[]
m x y=r$a y(m(pred x)y)
t[]_=[Z]
t _[]=[Z]
t(x:z)y=r$a(m x y)(Z:r(t z y))
i '0'=Z
i x=succ.i.pred$x
b Z='0'
b x=succ.b.pred$x
w[]y=y
w x[]=x
w(x:c)(y:d)=p x y:(w c d)
o=map
v=reverse
f=(o i).v
g=v.o b
main=getLine>>=putStrLn.(\[x,y]->g$t(f x)(f y)).words
```
For reference, S is the custom integer-like data type, `p` is 'plus' (digit+digit addition), `s` is subtract (for reduction), `r` is reduce (expand into digital decomposition), `a` is addition (number+number addition), `m` is multiply (digit\*number multiplication), `t` is times (number\*number multiplication), `i` is 'interpret' (convert string to list of `S`), `b` is 'back' (list of S to string), and f and g are just shortenings for golfing purposes. I didn't use numbers, even implicitly; the closest I got was using successors and predecessors, which are much higher level mathematical concepts than addition and multiplication of natural numbers.
## Edit
Forgot to include the time profile.
```
> time echo "9999999999 9999999999" | runhaskell multnonum.hs
99999999980000000001
real 0m0.246s
user 0m0.228s
sys 0m0.012s
```
Just for good measure:
```
> time echo "99999999980000000001 99999999980000000001" | runhaskell multnonum.hs
9999999996000000000599999999960000000001
real 0m0.244s
user 0m0.224s
sys 0m0.016s
```
Let's go insane!
```
> time echo "9999999996000000000599999999960000000001 9999999996000000000599999999960000000001" | runhaskell multnonum.hs
99999999920000000027999999994400000000699999999944000000002799999999920000000001
real 0m0.433s
user 0m0.424s
sys 0m0.004s
```
[confirmation](http://www.wolframalpha.com/share/clip?f=d41d8cd98f00b204e9800998ecf8427e15ls0rp036 "Confirmation")
[Answer]
# Python 2 - ~~1165, 712, 668~~ 664
```
I,T,V,N,X,J=raw_input,dict,reversed,None,zip,''.join
D='0123456789'
z,o='01'
A,B=I(),I()
r=i=""
K=map(J,X('666622222222911111551111555884444447773333333','678945672389954132987698765898967457989837654'))
P=T(X(K,map(J,X('344501110011800000440000332673322124652202211','628480244668154132507698505422648609367491852'))))
S=T(X(K,'cdef678945abi65243ed87a9cbaghcdab89egfcb6a987'))
for d in D:P[z+d]=z;S[z+d]=d
def Z(A,B,R=r):
for a,b in V(map(N,V(z+A),V(z+B))):c=(a or z)+(b or z);s=S[min(c)+max(c)];R=Z(R,o)+T(X('abcdefghi',D))[s]if s>"?"else R+s
return R
for a in V(A):
j=""
for b in V(B):r=Z(r,P[min(a+b)+max(a+b)]+i+j).lstrip(z);j+=z
i+=z
print r if r else z
```
Note that I'm not using logical indexing like `Z = [X, Y][N == "0"]`, because this could be interpreted as a boolean casted to a numeric index.
**Ungolfed:**
```
A = raw_input()
B = raw_input()
P = {'00':'00','01':'00','02':'00','03':'00','04':'00','05':'00','06':'00','07':'00','08':'00','09':'00',
'10':'00','11':'01','12':'02','13':'03','14':'04','15':'05','16':'06','17':'07','18':'08','19':'09',
'20':'00','21':'02','22':'04','23':'06','24':'08','25':'10','26':'12','27':'14','28':'16','29':'18',
'30':'00','31':'03','32':'06','33':'09','34':'12','35':'15','36':'28','37':'21','38':'24','39':'27',
'40':'00','41':'04','42':'08','43':'12','44':'16','45':'20','46':'24','47':'28','48':'32','49':'36',
'50':'00','51':'05','52':'10','53':'15','54':'20','55':'25','56':'30','57':'35','58':'40','59':'45',
'60':'00','61':'06','62':'12','63':'18','64':'24','65':'30','66':'36','67':'42','68':'48','69':'54',
'70':'00','71':'07','72':'14','73':'21','74':'28','75':'35','76':'42','77':'49','78':'56','79':'63',
'80':'00','81':'08','82':'16','83':'24','84':'32','85':'40','86':'48','87':'56','88':'64','89':'72',
'90':'00','91':'09','92':'18','93':'27','94':'36','95':'45','96':'54','97':'63','98':'72','99':'81',
}
S = {'00':'0','01':'1','02':'2','03':'3','04':'4','05':'5','06':'6','07':'7','08':'8','09':'9',
'10':'1','11':'2','12':'3','13':'4','14':'5','15':'6','16':'7','17':'8','18':'9','19':'a',
'20':'2','21':'3','22':'4','23':'5','24':'6','25':'7','26':'8','27':'9','28':'a','29':'b',
'30':'3','31':'4','32':'5','33':'6','34':'7','35':'8','36':'9','37':'a','38':'b','39':'c',
'40':'4','41':'5','42':'6','43':'7','44':'8','45':'9','46':'a','47':'b','48':'c','49':'d',
'50':'5','51':'6','52':'7','53':'8','54':'9','55':'a','56':'b','57':'c','58':'d','59':'e',
'60':'6','61':'7','62':'8','63':'9','64':'a','65':'b','66':'c','67':'d','68':'e','69':'f',
'70':'7','71':'8','72':'9','73':'a','74':'b','75':'c','76':'d','77':'e','78':'f','79':'g',
'80':'8','81':'9','82':'a','83':'b','84':'c','85':'d','86':'e','87':'f','88':'g','89':'h',
'90':'9','91':'a','92':'b','93':'c','94':'d','95':'e','96':'f','97':'g','98':'h','99':'i',
}
L = {'a':'0','b':'1','c':'2','d':'3','e':'4','f':'5','g':'6','h':'7','i':'8'}
def strSum(A, B):
R = ""
for a, b in reversed(map(None, reversed("0" + A), reversed("0" + B))):
if a == None: a = '0'
if b == None: b = '0'
s = S[a + b]
if s.isdigit():
R += s
else:
R = strSum(R, "1") + L[s]
return R
i = ""
r = "0"
for a in reversed(A):
j = ""
for b in reversed(B):
p = P[a + b] + i + j
r = strSum(r, p)
j += "0"
i += "0"
r = r.lstrip("0")
if r == "":
r = "0"
print r
```
] |
[Question]
[
[Giuga numbers](https://en.wikipedia.org/wiki/Giuga_number) ([A007850](https://oeis.org/A007850)) are composite numbers \$n\$ such that, for each prime factor \$p\_i\$ of \$n\$, \$p\_i \mid \left( \frac n {p\_i} -1 \right)\$. That is, that for each prime factor \$p\_i\$, you can divide \$n\$ by the factor, decrement it and the result is divisible by \$p\_i\$
For example, \$n = 30\$ is a Giuga number. The prime factors of \$30\$ are \$2, 3, 5\$:
* \$\frac {30} 2 - 1 = 14\$, which is divisible by \$2\$
* \$\frac {30} 3 - 1 = 9\$, which is divisible by \$3\$
* \$\frac {30} 5 - 1 = 5\$, which is divisible by \$5\$
However, \$n = 66\$ isn't, as \$\frac {66} {11} - 1 = 5\$ which is not divisible by \$11\$.
The first few Giuga numbers are \$30, 858, 1722, 66198, 2214408306, ...\$
---
Given a positive integer \$n\$, determine if it is a Giuga number. You can output either:
* Two distinct, consistent values to indicate whether \$n\$ is a Giuga number or not (e.g `True`/`False`, `1`/`0`, `5`/`"abc"`)
* Two classes of values, which are naturally interpreted as truthy and falsey values in your language (e.g. `0` and non-zero integers, and empty vs non-empty list etc.)
Additionally, you may choose to take a [black box function](https://codegolf.meta.stackexchange.com/a/13706/66833) \$f(x)\$ which returns 2 distinct consistent values that indicate if its input \$x\$ is prime or not. Again, you may choose these two values.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
---
## Test cases
```
1 -> 0
29 -> 0
30 -> 1
66 -> 0
532 -> 0
858 -> 1
1722 -> 1
4271 -> 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Æfḟɓ÷’ọȦ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//w4Zm4bifyZPDt@KAmeG7jcim/8i3NMOHxof/ "Jelly – Try It Online")
This version is mostly caird's, and I merged one of my golfs into it. Posted with their permission.
```
Æfḟɓ÷’ọȦ Main Link
Æf Take the prime factors
ḟ And filter out the original (if x is prime, this list is empty, otherwise, nothing changes)
ɓ---- Call this chain dyadically with reversed arguments: x on the left, factors on the right
÷ Divide x by each factor
’ Decrement each quotient
ọ Count divisibility of each result by the corresponding factor
Ȧ Are any and all truthy? That is, the list is all truthy and is not empty
```
This was my original solution:
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
:’ọɗÆfȦ>Ẓ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//OuKAmeG7jcmXw4ZmyKY@4bqS/8i3NMOHxof/ "Jelly – Try It Online")
Gives `1` for Guiga numbers and `0` otherwise.
```
:’ọɗÆfȦ>Ẓ Main Link (monadic)
---ɗ Last three links as a dyad
Æf Monad - get array of prime factors
:’ọ Since this is a 2,1-chain, this dyadic section is called with `x` on the left and the prime factors on the right
: - divide x by each prime factor
’ - decrement each
ọ - how many times is each result divisible by its matching prime factor?
Ȧ Check if all are true
>Ẓ 2,1-chain: check if that result is greater than whether or not x is prime (in other words, true if and only the above check was true and it is not a prime)
```
[Answer]
# [Zsh](https://www.zsh.org) `-eo extendedglob` 36 bytes
```
>`factor $1`
for x (<->~$1)$[$1/x%x]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5LDoIwGIT3nOJfVEM1BP8iDy2BgxgTVAouEAwUbXxdxA2J8RSehNsIkriaSebLzDxfl2rftFvUqV4JCVPBk81OFiUQvKWlOIJx7iz3fZ-ElCddgKAjsAVYM3AcsC0Gnu0BuozBnLlIr78iQxQglBR5LOI0K7b8XcvE8FoSRP-BSOv7FOi-ETwIUrIiaKqRWg_sh44DMxYnM6-zTOsf4JKEvDzA5D4QTTPoFw)
Outputs via exit code: zero for Giuga numbers and non-zero otherwise.
This makes *heavy* abuse of the rule
>
> Additionally, you may choose to take a black box function f(x) which returns 2 distinct consistent values that indicate if its input x is prime or not. Again, you may choose these two values.
>
>
>
The function is assumed to:
* be predefined under the name `1`
* output either `0` or `1` to standard out, for prime and non-prime respectively
* always succeed (exit with a status code of 0)
For each prime factor `x`, `$[$1/x%x]` takes the residue of the input mod `x` and tries to execute it as a command. The only number that's defined as a command is the black-box function `1`, which will succeed; otherwise, the command fails, and because of the `-e` option, Zsh exits with a non-zero status code.
---
If this is cheating, have this:
# [Zsh](https://www.zsh.org), 40 bytes
```
>`factor $1`
for x (<->~$1)(($1/x%x==1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5LDoIwGIT3nuJfVNNqCP5FHloeV0Gk4ALBQFHi6yJuSIyn8CTcRpDE1UwyX2bm-bpU-7aLkDJaSQULKZLtThUlELylpTyCdu6tcF2XBEwkfYBAEfgajCVYFpgGB8d0AG3OYcVtZNdfkSYLkI2SeSzjNCsi8a5Vojkd9cP_QDgZ-hqgruY_CDJKCerNtPE8ZGzkP2zm67E86XmdZZPhBW5IIMoDzO8j0bajfgE)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `r`, 8 bytes
```
Ǐo:?/‹ḊΠ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%C7%8Fo%3A%3F%2F%E2%80%B9%E1%B8%8A%CE%A0&inputs=2&header=&footer=)
```
Ǐo # prime factors excluding x
: # Duplicate
?/ # Input / n (vectorised)
‹ # Decremented (vectorised)
Ḋ # Is divisible by corresponding prime factor (vectorised)
Π # Take the product (0 for empty list)
```
[Answer]
# [J](http://jsoftware.com/), 22 19 bytes
```
1<q:(-:*#@[)*:@q:|]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DW0KrTR0rbSUHaI1tawcCq1qYv9rcvk56SlEW2lo62tp6WsWWtlCZbhKUotLgMakcaUmZ@QDTbFVAIkoGKLxjSwhAoYwAWMDNBVmZmgCpsZGaHosTC3QRAzNjYzQtJkYmRv@BwA "J – Try It Online")
-3 after reading [Bubbler's analysis](https://codegolf.stackexchange.com/a/230822/15469).
* `*:@q:|]` Mods input by square of its prime factors (vectorized).
* `-:` Does that match the list of prime factors?
* `*#@[` Times the length of the prime factors.
* `1<` Is that greater than 1?
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~73~~ 62 bytes
```
.+
$*
^((.)*)(?=\1*$)(?<!^\3+(..+))(?!((?<-2>\1)+)(?(2)^)\4*$)
```
[Try it online!](https://tio.run/##DYq9CoQwEAb77y0Ehd0Eg7vxF/wpfYkQtLjiGovj3j9uNcwwv8//@9ylofMqwaN2yESBHdOxJXG1ca1yip5C8GxWkZVW9yTsTUk5c@ptLKWDQBfEDuOIISrmYYZMquh1khc "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `0` for a Guiga number, `1` if not. Explanation:
```
.+
$*
```
Convert `n` to unary.
```
^((.)*)
```
Match an integer `p=\1`, but also as a count `\2`, where...
```
(?=\1*$)
```
... `p` must be a factor of `n`, ...
```
(?<!^\3+(..+))
```
... `p` must not have a nontrivial proper factor `\3`, and...
```
(?!((?<-2>\1)+)(?(2)^)\4*$)
```
... `n-p` must be zero (in which case `n` is not composite) or not divisible by `p²`, which is calculated by matching `\1` `\2` times, and then captured, so that it can be easily repeated using `\4`.
Edit: Saved 11 bytes thanks to @Deadcode pointing out that I don't need to check that `p` is at least `2`, and in fact also allowing `p=0` means that the program works for `n=0` (although not required by the question) at no extra cost.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Æfð_ọḟ>1Ȧ
```
[Try it online!](https://tio.run/##y0rNyan8//9wW9rhDfEPd/c@3DHfzvDEsv@H2x81rfn/P9pQR8HQVEfByFJHwdhAR8HMTEfB1NhIR8HC1AIoY24EZJoYmRvGAgA "Jelly – Try It Online")
```
Æfḟð_ọḷ’Ȧ
```
[Try it online!](https://tio.run/##y0rNyan8//9wW9rDHfMPb4h/uLv34Y7tjxpmnlj2/3D7o6Y1//9HG@ooGJrqKBhZ6igYG@gomJnpKJgaG@koWJhaAGXMjYBMEyNzw1gA "Jelly – Try It Online")
I already lost, but figured I'd post them since they're somewhat different 9-byters.
### How these work
The condition \$p\_i \mid \left( \frac n {p\_i} -1 \right)\$ can be translated to
$$
\frac{n}{p\_i}-1 \equiv 0 \quad(\operatorname{mod} \ p\_i) \\
\frac{n}{p\_i} \equiv 1 \quad(\operatorname{mod} \ p\_i) \\
n \equiv p\_i \quad(\operatorname{mod} \ p\_i^2)
$$
So \$n-p\_i\$ (equivalently, \$p\_i-n\$) must be divisible by \$p\_i\$ at least twice.
```
Æfð_ọḟ>1Ȧ Monadic link; input = n
Æf List of prime factors of n (= L)
ð...... Call ... as a dyadic chain, left = L, right = n
ọ How many times each of...
_ L - n
...is divisible by...
ḟ Remove any occurrences of n from L
(missing positions are treated as 0, so ọ gives 0)
>1Ȧ Test if the result is nonempty list of all 2s or above
Æfḟð_ọḷ’Ȧ Monadic link; input = n
Æfḟ Remove any occurrences of n from prime factors of n (= L)
ð..... Call ... as a dyadic chain, left = L, right = n
_ọḷ How many times each of L-n is divisible by each of L
’Ȧ Test if the result, decremented, is nonempty with all nonzero
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 50 bytes
```
->n{(2...z=n).all?{|c|z%c>0||n/c%c==1&&z/=c}&&z<n}
```
[Try it online!](https://tio.run/##DcWxDkAwEADQX7FoSM5pD6nB8SFi4BITjUgMqr69vOWd13LHlWPRuycjRPTscpy3bXiCBJ9Kr0NwpaTCbJTyJcv717k3HslogDRUGpqKoG1aMJYIarJmwn0@MrXm8QM "Ruby – Try It Online")
### So what?
```
->n{(2...z=n).all?
```
Check every number between 2 and n-1, use a temporary variable to skip over composite divisors.
```
{|c|z%c>0
```
If c is divisor of `z` then it's also a prime divisor of `n`, if not we can skip this number.
```
||n/c%c==1
```
Check if `n/c-1` can be divided by `c`
```
&&z/=c}
```
At this point, we must divide `z` by `c` before continuing. Once is enough, because if `n/c-1` can be divided by `c`, then `n` can't be divided by `c` more than once.
```
&&z<n}
```
Final check: did we divide z at least once? If not, then n is a prime number.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
e=n=input();k=w=0;i=1
while~-n:
i+=1
while n%i<1:k+=(e/i-1)%i;n/=i;w+=1
print k<1<w
```
[Try it online!](https://tio.run/##HcpLCoAgFEbheatwEiQRdRtIpXc5Qj/GTcKQJm3dHsPzceKV1l3GUjwLQ@KZGm0DZx4smKq8YvN3J0ul0L6tflBSw9ESWm58j450DSs9w@bviQckqeDI5VKMoXl6AA "Python 2 – Try It Online")
-14 bytes thanks to @ovs
[Answer]
# JavaScript (ES6), ~~59 56~~ 53 bytes
Returns a Boolean value.
```
n=>(k=2,g=j=>j%k?k++<j&&g(j):n/k%k-1?g:1+g(j/k))(n)>1
```
[Try it online!](https://tio.run/##DcpBDoMgEEDRvaeYjQRCreBSHTyLsULKmJlGm26anp2y@3n5ef2s13Y@X@@O5bGXiIUxaMLhljBjyC0tZO2clUo6m5F7aqnzSxq9rdCTMZpN8CXKqRkQ/AQMMwzOuVrWGvg2ALFOoBRswpcc@/2QVGVqfuUP "JavaScript (Node.js) – Try It Online")
### Commented
```
n => ( // n = input
k = 2, // k is the prime divisor, starting at 2
g = j => // g is a recursive function taking the quotient j
j % k ? // if k is not a divisor of j:
k++ < j && // stop if k is greater than or equal to j
g(j) // otherwise, do a recursive call with j unchanged
// and k + 1
: // else:
n / k % k // if (n / k) modulo k
- 1 ? // is not equal to 1:
g // stop the recursion and yield g, which turns the
// result into a non-numeric string and forces the
// final test to fail, whatever happened before
: // else:
1 + // add 1 to the result
g(j / k) // do a recursive call with j = j / k
)(n) // initial call with j = n
> 1 // return true if there were at least 2 prime divisors
// satisfying the Giuga test
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
f©/<0K®Öß
```
Outputs `1` as truthy and either `0`/`""` as falsey.
[Try it online](https://tio.run/##yy9OTMpM/f8/7dBKfRsD70PrDk87PP//f2MDAA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/7RDK/VtDLwPrTs87fD8/zr/ow11jCx1jA10zMx0TI2NdEwtTHUMzY2MdEyMzA1jAQ).
**Explanation:**
```
f # Get all unique prime factors of the (implicit) input
© # Store this list in variable `®` (without popping)
/ # Divide the input by each of these
< # Decrease it by 1
0K # Remove all 0s
®Ö # Check of each if it's divisible by their initial values `®`
ß # Pop and push the minimum of this list ("" for empty lists)
# (after which it is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
N⁰ḋṀ{;N⁰↔÷;?%}ᵛ1
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3@9R44aHO7of7myotgaxH7VNObzd2l619uHW2Yb//1uYWgAA "Brachylog – Try It Online")
[Answer]
# Regex (ECMAScript 2018 / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), ~~83~~ ~~79~~ ~~64~~ 49 bytes
```
^(x(x*))(?<!^\3+(x+x))(?!(?=\1*(\1\2+$))\4*$)\1*$
```
*-15 bytes (79 → 64) thanks to H.PWiz*
*-8 bytes (64 → 56) by squaring instead of doing division (thanks to H.PWiz [for the idea](https://chat.stackexchange.com/transcript/message/61553870#61553870))*
*-7 bytes (56 → 49) [thanks to H.PWiz](https://chat.stackexchange.com/transcript/message/61554305#61554305) - now beats the original .NET-only version!*
Returns a non-match for Giuga numbers.
[Try it online!](https://tio.run/##TY5Bb8IwDIXv/AqokGJTGjVABaIETjtw2WE7rkNEJRRPXdolASoBv52VSZO4WLa/5@f3pU7K5ZZqH5lqp@9OxqmVb7p4aWp495ZMwa06b@8baKAZIMJq0dtk4xCasHlMPVjJTAwgE9ko7CNmk0Ef20X/vuWupFyDGEYCMbX650hWA7Na7UoymiHP297rtfHa7lUrvZCpj35e2yrXznHnd2RuyCsD7O9iWMrlpZAld3VJHljEMKU9gJEFL7Up/AGXo@uV3Kt6BZK1su7hDsVH/In4D/QzMEuxEvMHRn@w1TlYm5Mqade1yhR63g3CMt1XFlJaSJ1SGGL7sBc0Abe6btMDIf9WPj@ARbw8Ja@Onp8teQ3gViwzbM4YhoSpkyK93fAuIhHHnWQcR8k46cySOJpN446YjuKoLUlnMpqKXw "JavaScript (Node.js) – Try It Online") - ECMAScript 2018
[Try it online!](https://tio.run/##LY7RjoIwFETf@xXXhodeoKQFCQa28UNEE7NWbcIWUvpQ@Xmkui83dyZnJjO9/HO01Wr@ptF5mF9z7vRDhw6ccpTS9cICCykiO/7sLn2VsZCFqHbsqHqZsl72ZZYg9vs0wc1I1i11ki2X5w4WJch9dDCAsbG7mP3N2JbAoIZingbjGeUUCUTIRshd7UMzYz0bTuKM@ffbyjCTuAXB3MGOHj4ji1lf3e@TuRxooKn9AJFYWphcjGI0FiW7f21zbW@KUlwll0KQuhK8rmpyqAU/NILIphR8OzXZl418Aw "Python 3 – Try It Online") - Python `import regex` (very slow)
[Try it online!](https://tio.run/##RY/RaoMwFIbvfQqVAyZmKYlWLHXSwq73BGpBXDoDWSKaolR8dqeFsZsD38fPz386M4p@aIVSK/R50YtvMVXnsxYjugbrDU1oCjFGl3fvVsYETWTayUOXvOQhKnkZEcC4PIaANwFrcH3zP8xPJ5X48nEGz5xld9OLumkRKFdqF6TuHhbPUOeg6NApaX3qZ/KOoD405qEtVdaN9gDJoS5YtWwFCHReSG2rl8lAUyX@mO9MCJ63Dg/6w2dtm1YMKJiCEDR@eXjieeylFbQ1g122XTz7Z5dqs72spBYu6GVZVk45Y04SM5rEiXNKGD2lzOFpxOh2EucYpfwX "PowerShell – Try It Online") - .NET
The commented version below is a **54 byte** version that behaves correctly with an input of zero, and returns a match for Giuga numbers. (Its length would be 52 bytes if returning a non-match for Giuga numbers.)
The underlying squaring/multiplication algorithm is explained [in this post](https://codegolf.stackexchange.com/questions/125237/its-hip-to-be-square/223201#223201).
```
^ # tail = N = input number
(?! # Negative lookahead - Assert that this cannot match
# Cycle \1 through all the prime divisors of N
(x(x*)) # \1 = conjectured non-composite divisor of N; \2 = \1-1
# tail -= \1; head = \1
(?<!^\3+(x+x)) # Assert head is not composite, i.e. is prime or <2
# Assert that tail is not divisible by \1 * \1
(?! # Negative lookahead - Assert that this cannot match
# Calculate \4 = \1 * \1; this will fail to match if the result would
# be greater than tail.
(?=
\1* # We can use this shortcut thanks to tail already being
# checked for divisibility by \1 later.
(\1\2+$) # \4 = \1 * \1
)
\4*$ # Assert that tail is divisible by \4
)
\1*$ # Assert N is divisible by \1
)
x # Prevent N == 0 from matching
```
## Regex (.NET), ~~57~~ ~~53~~ bytes
Now obsoleted by the ECMAScript 2018 / .NET version above.
## Regex (ECMAScript+`(?^=)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), 50 bytes
```
^(x(x*))(?^1!(xx+)\3+$)(?!(?=\1*(\1\2+$))\4*$)\1*$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Giuga-numbers-with-lookinto) - RegexMathEngine
This is a port using lookinto instead of variable-length lookbehind.
# Regex (ECMAScript+`(?*)`[RME](https://github.com/Davidebyzero/RegexMathEngine) / PCRE2 v10.35+), 58 bytes
```
^(?*(x(x*))(\1*$))(?!\3(xx+)\4+$)\1(?!(?=\1*(\1\2+$))\5*$)
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Giuga-numbers-with-molecular-lookahead) - RegexMathEngine
[Attempt This Online!](https://ato.pxeger.com/run?1=fVLdatswFIZd-ilOhKilxE6srMu6KiYMlo3CaIe3u7oTricnXhzZyAoYSp5kN4WxZ9izbE-z46QwlosJJB2d7-dIB3373qybx9_PXs8XGAC1EAOZEBhDY_VKWd1UWa6ZPxkPF0qts8qpvN42ZaVtylIu02TS-gH4OAtMqpXuCcZp41qm1Nur90uleACCoyUaS680pWq1Y6TJrR7fZ_nGWVxUVW5LRwIgoSBcwr80q_Odbcva_J_29QhFiHhFbRkt40jSKi7wWi37-OnN1TWX_AHKgtHqtnW20gYjHoq7OCapIRzJ7e4eEUwHURAK3ut111T1F81ISAKkS9Tn9c64XjufougWDXCN7qQHcKhsns7UzOMDjtFoxOEBCYAXADZgdBMfurzNXL5m1AZYt2-5zhzzOz-ghuMAqo-0Kmud0taiPR_E8Ydk-U5d36hlktwk8q8t3cDZGQyoxmL9Q0uu83Xdv04CNkRI6M9AjdyfinrNASSXQMYnRdW2XTHeF9p7-5O_gPkfO1eEF78uP7PFkHWsG3LOUjGkuC0G6XPWdSOeno8oTwUm2CJGEAnpFFM8fYHEo8Pj0_YzCsVFFHnn05fCm83EqyiczaYiOsJ_AA "PHP - Attempt This Online") - PCRE2 v10.40+
This is a port using molecular lookahead instead of variable-length lookbehind. It is far, far faster, since it does not place a divisibility test after an is-prime test (and to do so would not be better golf, as far as I can tell); on my PC it can test every number from \$0\$ to \$66200\$ in 5.2 minutes (whereas the ECMAScript 2018 version takes weeks or maybe more) and can even test \$2214408306\$ in 6.4 minutes.
```
^ # tail = N = input number
(?! # Negative lookahead - Assert that this cannot match
# Cycle \1 through all the prime divisors of N
(?*(x(x*))(\1*$)) # Cycle \1 through all of the divisors of N, including N
# itself; \2 = \1-1; \3 = N-\1 == tool to make tail = \1
(?!\3(xx+)\4+$) # Assert \1 is prime or \1 < 2.
\1 # tail -= \1
# Assert that tail is not divisible by \1 * \1
(?! # Negative lookahead - Assert that this cannot match
# Calculate \5 = \1 * \1
(?=
\1* # We can use this shortcut thanks to tail already being
# checked for divisibility by \1 later.
(\1\2+$) # \5 = \1 * \1
)
\5*$ # Assert that tail is divisible by \5
)
)
x # Prevent N == 0 from matching
```
### \$\large\textit{Full programs}\$
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~63~~ ~~59~~ 55 bytes
```
.+
$*
^(.+)(?<!^\2+(.+.))(\1)*$(?<=(?!\B\1*$)(?>(?<-3>.)*))
```
Takes its input in decimal. Outputs `1` if input is a Guiga number, `0` if not.
[Try it online!](https://tio.run/##Fcg9CsMwDAbQ/btFwAHJBlHJ@YUEj72EMMnQoUuH0vu7yfje9/V7f87W0/NokhAiKglJZKayddVzIklyq6Oyu0ZydUuB2YcY@IrQmsJW5AemCWM2LOMCnc0w2Kx/ "Retina 0.8.2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes
```
YfG-t?6MU\~A
```
[Try it online!](https://tio.run/##y00syfmfoJCpUBLlp2CvUKGnEKsQ4fE/Ms1dt8TezDc0ps7xfyxQwkNBXTVFIbNYIVHBPbM0PVEhrzQ3KbVIXSHSRaEWIZuXX4JNBdBMF4WoCoWQ2P@GXEaWXMYGXGZmXKbGRlwWphZchuZGRlwmRuaGXAb6BgA "MATL – Try It Online")
1 for Giuga number, either 0 or an empty vector for non-Giuga number - both of which MATL considers falsy.
*(note: had previously posted a 9 byte version which was wrong)*
**Explanation**:
\$p\_i \mid \left( \frac n {p\_i} -1 \right) \Longrightarrow p\_i^2 \mid \left( n - {p\_i} \right) \Longrightarrow p\_i^2 \mid \left( {p\_i} - n \right)\$
1. `Yf` - get the prime factors of the input (if `1` is the input, `Yf` returns an empty vector; primes return themselves)
2. `G-` - subtract the input from each factor (let's call this S = \${p\_i} - n \$)
3. `t?` - is it truthy? (for `1` this is an empty vector; for primes it's a 0; either way, falsey)
4. `6M` - If so, bring back a copy of the list of factors
5. `U` - square each one
6. `\` - compute the mod of S with respect to these squares
7. `~A` - And check if that is all 0s
If the check at step 3 failed, that falsy S is left on the stack. If it succeeded, the result of the final step is left on the stack.
---
Alternate 12 byter: `_tYf+t5MU\~*` [Try it online!](https://tio.run/##y00syfmfoJCpUBLlp2CvUKGnEKsQ4fE/viQyTbvE1Dc0pk7rv72Ch4K6aopCZrFCooJ7Zml6okJeaW5SapG6QqSLQi1CNi@/BJsKoIkuClEVCiGx/w25jCy5jA24zMy4TI2NuCxMLbgMzY2MuEyMzA25DPQNAA "MATL – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
k f<U £/XÉ vXÃâ ¥1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ayBmPFUgoy9YySB2WMPiIKUx&input=WzEsMjksMzAsNjYsNTMyLDg1OCwxNzIyLDQyNzFdLW0)
```
k - prime factors
f<U - filter out U(input)
£..Ã - map X-> :
/XÉ > U/X-1
vX > divisible by X?
â - get unique elements
¥1 - is [1] ?
```
] |
[Question]
[
## Background
Define a **run** in a list as a maximal contiguous subsequence of identical values. For example, the list
```
0 0 0 1 1 0 3 3 3 2 2
```
has five runs of lengths 3, 2, 1, 3, 2 respectively. (Think of run-length encoding.)
Then define a **cut operation** as removing one item from each run of a list. Applied to the list above, the result will be `0 0 1 3 3 2`.
Finally, the **cut resistance** of a list is the number of cut operations needed to reduce it to an empty list. The cut resistance of the list above is 3:
```
0 0 0 1 1 0 3 3 3 2 2
0 0 1 3 3 2
0 3
(empty)
```
Note that the cut resistance can be higher than the maximal run length, since multiple runs may fuse in the way:
```
1 0 0 1 1 0 0 1 0 0 1 0 0 1 0 1 0
0 1 0 0 0
0 0
0
(empty)
```
Related OEIS sequence: [A319416](http://oeis.org/A319416) (cut resistance of n written in binary)
## Task
Given a (possibly empty) list of nonnegative integers, compute its cut resistance.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
0 0 0 1 1 0 3 3 3 2 2 => 3
1 0 0 1 1 0 0 1 0 0 1 0 0 1 0 1 0 => 4
1 2 3 4 5 99 100 101 => 1
4 4 4 4 4 4 3 3 3 3 2 2 1 2 2 3 3 3 3 4 4 4 4 4 4 => 7
(empty) => 0
```
[Answer]
# [J](http://jsoftware.com/), 20 bytes
```
1-~&#(#~2=/\_&,)^:a:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DXXr1JQ1lOuMbPVj4tV0NOOsEq3@a3KlJmfkKxgr2CqkAdWCoCEQGgBFQNBIwQiiwASswBBJgQEGCcQQxYZQxUZAE0wUTBUsLRUMDYDyBoYQeXOwvAkSNEbYB9ZnBBdBUgXRbADWrK7@HwA "J – Try It Online")
Using the `0 0 0 1 1 0 3 3 3 2 2` example:
1. `(......_&,)` Prepend infinity `_`:
```
_ 0 0 0 1 1 0 3 3 3 2 2
```
2. `(..2=/....)` Are consecutive pairs equal? Returns 0-1 list of same length as input:
```
_ 0 0 0 1 1 0 3 3 3 2 2 <-- Before
0 1 1 0 1 0 0 1 1 0 1 <-- After
```
3. `(#~.......)` Apply the above mask as a filter to the input. This drops the first member of every group:
```
0 0 1 3 3 2
```
4. `^:a:` Repeat until we reach a fixed point, returning all intermediate results (0-padded on the right):
```
0 0 0 1 1 0 3 3 3 2 2
0 0 1 3 3 2 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
```
5. `1-~&#` Subtract 1 from `1-~` the above result, after applying the "length of" verb to both lists `&#`. Since the length of 1 is 1, it remains unchanged, while the result above becomes 4:
```
4 - 1
3
```
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
f=lambda l:l>[]and-~f([x for x in l[1:]if x==l.pop(0)])
```
[Try it online!](https://tio.run/##dY3BCoMwEETv/Yo9JmBLEu1BIf2RkIPFBgPbGCRSe@mvpzFiKZbCYxl2dmb9M/SDEzEaie392rWADV6Ubl13fBmiZjDDCDNYB6h4o62BWUo8@cETRjWNj97iDXjjR@sCGGKdnwKhNCpWwArPJFFuiIQ@KP5zwf6LZa4ZkTuqAs4F1HVy2GIzntwq778pd29zkdhKPuyDqUu/AQ "Python 2 – Try It Online")
False for 0.
**57 bytes**
```
f=lambda l:l>[]and-~f([a for a,b in zip(l,l[1:])if a==b])
```
[Try it online!](https://tio.run/##dY3BCsMgEETv/Yo9KlhQkx4ipD8iHpRUIlgjwVLaQ3/dGkNKSSk8lmFnZzY@0jgFnrPtvb6aQYMX/iyVDsPxZZHUYKcZNDHgAjxdRJ54yYTCzoLue6Nwvo/OX4CJOLuQwCIX4i0hjLOkBFZYpYhmgxfUQbKfC/pfLHPN8NrREjgR6Lri0MWmrLht3X/T7N7WIr6VfNgHS5d6Aw "Python 2 – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 13 bytes
Same as Jonah's, scan of x at where equal each-prior.
```
#1_{x@&=':x}\
```
Using `0 0 0 1 1 0 3 3 3 2 2` as example:
`=':` means equal each prior
```
=': 0 0 0 1 1 0 3 3 3 2 2
0 1 1 0 1 0 0 1 1 0 1 / zeros in the result correspond to the first item of the run
```
then indexing into the argument with this mask effectively drops the first item of each run. the indices are:
```
&=': 0 0 0 1 1 0 3 3 3 2 2 / where equal each-prior?
1 2 4 7 8 10
0 0 0 1 1 0 3 3 3 2 2@1 2 4 7 8 10 / indexing
0 0 1 3 3 2
```
we can turn this into a function and repeat until the result stops changing
```
{x@&=':x}\0 0 0 1 1 0 3 3 3 2 2
(0 0 0 1 1 0 3 3 3 2 2
0 0 1 3 3 2
0 3
!0)
```
drop 1 and take the length
```
#1_{x@&=':x}\0 0 0 1 1 0 3 3 3 2 2
3
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NStkwvrrCQc1W3aqiNuZ/moIBGBoCoYGCMRgaASFXGlgAJmGAQQIxWI0RUIOJgqmCpaWCoQFQ2MAQKGyCBI2RTDUEkzARJFVAPQbKBv8B "K (ngn/k) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.Γ〨˜}g
```
[Try it online](https://tio.run/##yy9OTMpM/f9f79zkc5sfNa05tOL0nNr0//@jDXUMgNBQB0ajkkAcCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vXOTz21@1LTm0IrTc2rT/@v8j4420AFBQyA00DEGQyMdo1idaEMkcQMMEojBaoyA6k10THUsLXUMDYDCBoZAYRMdBDRGGKpjCCZhIkiqgHpiYwE).
**Explanation:**
```
.Γ # Continue until the result no longer changes,
# collecting all intermediate results in a list
γ # Split the list into chunks of equal adjacent elements
۬ # Remove the last value of each chunk
˜ # Flatten the list of lists
}g # After the cumulative fixed-point loop, pop and push the length
# (which is output implicitly as result)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 38 bytes
```
f=s=>s+s?f(s.filter(t=>s===(s=t)))+1:0
```
[Try it online!](https://tio.run/##ZY/RCoMwDEXf@xV5s05XW3UMN@o@pAqKq@IoKrb4@10tDIXlkgRybgj5tFuru3VczHWa39Lanmte6ki/eqxJPyojV2zchHOONTdhGEbsQe2zmyc9K0nUPOAGCQq7mBOFzCuFtAZeQoYEO0H6V116Y74bU7eZww2KAhh1jDLPGBI5HMqOG8B8/U1OLr94R8J3ihqyykW1ncRJJcilqpMhBvdZj@XWKmwODI4EcRDuYb8 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 42 bytes
```
f=s=>s+s?f(s.filter(t=>s[++i]==t,i=0))+1:0
```
[Try it online!](https://tio.run/##ZY/RCoMwDEXf@xV5s05XW3UMN@o@pAqKq@IoVmzx910tDIXlkgRybgj5tGtrumWc7XXSb7ltPTe8NJF59diQflRWLti6iYiisebcxiOnYRixB92enZ6MVpIoPeAGCQq7mBOFzCuFtAZeQoYEO0H6V116Y74bU7eZww2KAhh1jDLPGBI5HMqOG8B8/U1OLr94R8J3ihqyyFm1ncRJJcilqpMhBvddj@XaKmwPDI4EcRDusX0B "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
f[]=0
f(h:t)=1+f[x|(x,y)<-zip(h:t)t,x==y]
```
[Try it online!](https://tio.run/##dY5BCsIwEEX3PcUsXLQYIUkjUnFOErooaGiwtkWzSMW7x3SkYluERxjC@3@mrh7XS9OEYHSJPDFpfXQZiq3R/pV6NmSn3dP29OuYRxzKcKtsCwjnLgHo77Z1sAEDmjP4IIg45BMyUgIi5POIWEX4/2F8qUStSiRtUQz2DIoiqnz0uSBdzHVF4i/54lJaJafWL8sglR/CGw "Haskell – Try It Online")
`f a=1+f[x|(x,y)<-zip a$tail a,x==y]` is the same length.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
tl.uqF#C,t
```
[Try it online!](https://tio.run/##K6gsyfj/vyRHr7TQTdlZp@T/fxMdBTRkjISMwMgQxkCWQtcIAA "Pyth – Try It Online")
There's a bug in the parser related to this use of `qF#`, because if I append three variables at the end (e.g. `NNQ`), it [crashes the parser](https://tio.run/##K6gsyfj/vyRHr7TQTdlZp8TPL/D/fxMdBTRkjISMwMgQxkCWQtf4L7@gJDM/r/i/bgoA "Pyth – Try It Online"). This is because `qF` should be treated as having arity 1, but it's being treated as having arity 2. However, it works fine as is,
because the rest of the program is implicit, so the parser completes before anything goes wrong.
Explanation:
```
tl.uqF#C,t
.u Repeatedly apply the following function until the result stops changing:
t Remove the first element of the input (tail)
, Pair with the input
C Transpose, resulting in all 2 element sublists.
# Filter on
qF the two elements being equal.
l Length
t Subtract 1 for the empty list.
```
Note that the intermediate lists look like:
```
[1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0]
[[0, 0], [1, 1], [0, 0], [0, 0], [0, 0]]
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
[]
```
[Try it online!](https://tio.run/##K6gsyfj/P0uvtNBN2Vmn5P//aEMdBQMwMgQjOBsrA0TGAgA "Pyth – Try It Online")
This occurs because the program doesn't both to select one element from each pair of numbers. Instead, the pair itself is used as the element of the list in the next iteration. This saves 2 bytes.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes
```
If[#!={},#0[Join@@Rest/@Split@#]+1,0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMtWlnRtrpWR9kg2is/M8/BISi1uETfIbggJ7PEQTlW21DHIFbtf0BRZl6Jgr5Dur5DdbWBDggaAqGBjjEYGukY1epUGyKJG2CQQAxWYwRUb6JjqmNpqWNoABQ2MAQKm@ggoDHCUB1DMAkTQVIF1FNb@/8/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 32 bytes
```
$\++while s/\b(\d+ )(\1*)/$2/g}{
```
[Try it online!](https://tio.run/##K0gtyjH9rxKvZ6uuoJ6ZpqivoKJv/V8lRlu7PCMzJ1WhWD8mSSMmRVtBUyPGUEtTX8VIP722@v9/QwUDIDRUgNGoJAj/yy8oyczPK/6vWwAA "Perl 5 – Try It Online")
Requires a trailing space on the input. (Though I did put some code in the header to add it if it isn't already there so that testing is easier.)
[Answer]
# [Prolog](https://github.com/mthom/scryer-prolog), 115 bytes
```
a([_],[]).
b(_,[],E,E).
b(A,[B|C],D,E):-A=B,b(A,C,[B|D],E);b(B,C,D,E).
c(A,B):-A=[],B=0;A=[P|L],b(P,L,[],C),!,c(C,D),B is D+1.
```
Clear version:
```
% Cut operation.
% Cut operation.
% Previous A, Head B, Tail C, List D, List E.
b(_, [], E, E).
b(A, [B|C], D, E) :-
A = B,
b(A, C, [B|D], E)
; b(B, C, D, E).
% Count cut.
% List A, Number of cut B.
c(A, B) :-
A = [],
B = 0
; A = [P|L],
b(P, L, [], C),!,
c(C, D),
B is D + 1.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
←V¬¡Ψf=
```
[Try it online!](https://tio.run/##yygtzv7//1HbhLBDaw4tPLcizfb////RhjogaASGxkAIZsUCAA "Husk – Try It Online")
## Explanation
It's not often that I get to use the higher order modifier function `Ψ`, but here it's very convenient.
```
←V¬¡Ψf= Implicit input: a list.
¡ Iterate (producing an infinite list)
f filtering by condition:
Ψ the next element
= is equal to this one.
The last element is always discarded.
V 1-based index of first result that is
¬ falsy (for lists, this means empty).
← Decrement.
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 18 bytes
```
≢1↓{⍵⊇⍨⍸2=/¯1,⍵}⍡≡
```
`{⍵⊇⍨⍸2=/¯1,⍵}` - dfn that finds the next stage
`⍡≡` iterate until reaching a fixpoint
`≢2↓` drop the first two elements, then take the length
-2 bytes thanks to Marshall
-1 byte thanks to Bubbler
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R24RHnYuMHrVNrn7Uu/VRV/uj3hWPencY2eofWm@oAxSqfdS78FHnwv@P@qYC1aYpGIChIRAaKBiDoZGCERdM1hBJ1gCDBOL/AA "APL (dzaima/APL) – Try It Online")
[Answer]
# T-SQL, 125 bytes
I am [using table as input](https://data.stackexchange.com/stackoverflow/query/1244049/cut-resistance-of-a-list)
```
DECLARE @ INT=1u:SET
@-=1DELETE x FROM(SELECT*,lag(a,1,-1)over(order by i)b
FROM t)x
WHERE a<>b
IF @@rowcount>0GOTO u
PRINT-@
```
The posted code is using a permanent table as input. **[Try it online](https://data.stackexchange.com/stackoverflow/query/1244049/cut-resistance-of-a-list)** is using a table variable spending 1 additional byte
[Answer]
# [R](https://www.r-project.org/), ~~56~~ 55 bytes
```
f=function(x)`if`(sum(x|1),1+f(x[-cumsum(rle(x)$l)]),0)
```
[Try it online!](https://tio.run/##ZY3BCoMwDIbve44dEpZBUt3Bg08yBkKxIKiDaqEH372LMrVj/OQn5P@S@GTD7NupTq52YbRz9x4hYtO5BqYwQFwESW4O4vNuw7COfN8qce3xhcT43QcLTKtExVRsMmQQLwcgGcB/rvULG71Q0oOqioQ1Z8nzkk4V5z@SzfdJRuXL2qcP "R – Try It Online")
*Edit: recursive function is 1 byte shorter, and returns `0` for empty input*
([original](https://tio.run/##K/r/v8K2ODkxT0PTujwjMydVo7g0V6OixlBTs7rCtiJaN7k0FyRSBJSp0FTJ0Yy1drN10zastXb7b6KAgMZQaASEhmASJoKk6j8A), non-recursive version returned FALSE for empty input)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 68 bytes
```
([]){{}({}()<>)<>([])}<>({()<{(({}<>)<>[({})]){{}<>{}(<>)}{}}<>>}{})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6ulYDiDRt7IAIJFALpKqB/GoNoDhYNBrI0ASrtLEDKgWK1VbXAtl2QErz/39DBQMgNFSA0agkEAMA "Brain-Flak – Try It Online")
```
([]){{}({}()<>)<>([])}<> # add 1 to everything so I don't have to handle 0
({()< # until stack is "empty", counting iterations:
{ # for each number
(
({}<>) # copy to other stack
<>[({})]) # and compare to next number (or zero if at end)
{{}<>{}(<>)}{} # if not equal, remove newly added number
}<> # switch stacks for next iteration
>}{}) # output number of iterations
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~108~~ ~~104~~ 101 bytes
* Saved ~~four~~ seven bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
*o,*O,r;e(int*s){for(r=1;~*s;r++)for(o=s;~*o;*O=-1){for(;*o==*++o;);for(O=--o;~*O;)*O++=O[1];}s=~-r;}
```
[Try it online!](https://tio.run/##dVHda8IwEH/vX3F0CEmaQqOO4UIme3AwGBQ296Q@SG2l0DbSdMNN6r/eXVo/hm7hCHe938flGvnrKGoapjkLeSljkhYVM3SX6JKUSsg9M7L0PGprrQzWWrJQ@aKDSKaVYp6nJZW2xo6vERRKykLPU@FMLGRt1N4vZd3crOIkLWKYTmAHaATVbAEKc@fYeZuSeLuh4AuoJeRxHm2@SMah4kBM@h3rBCrwQFBgcKjtxJRKmDtwcazDWlfoEJPsT8SGVPh9UyIyIW5vBWMFeJOeofPC5ZbNAQfif3BbZWW7MAbXfERRbIwL9@A@PT6/vL9OXJSunU@drtDHzsIyCjvnZLdDgAPtFrHlCQkZLhp9zvNwwCGQJs@sGvYP0Ek7VjRfpgVpdTsLfG2@zDIdkWCb4DkvqtPB3Qf8EKINTAbH6LeBf2FAW6i4ggb/J92N5OGJ3G9VhxxuOYxGCAksLhAtTHSwIb@MwdVE4pj8bl0TUfSuE8UsoE7d/AA "C (gcc) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `grouping.extras`, 78 bytes
```
[ 0 swap [ [ ] group-by values [ rest ] map-concat [ 1 + ] dip ] until-empty ]
```
[Try it online!](https://tio.run/##ZVDLasMwELz7K6bn4iDFLiXNB5Recik9mRxUdZua2LIirduakG9312oDgjJoWObBsno3locwvzw/7R4fcAjD6Ft3WNE3BxNhYhxsRKTTSM5SNl0TRwqOOvSGP@ADMU8@tI6xLc4FcIZK0AKFKmEtuOAGVfJ15qt/vLwlW/9l19KvcYfNBlqJrXSydbLrDFW2TCe@Knlq6d6n7jKp4jI3sjB@GY9GsP/9j/J1wqfpRjm/QaDIYvTGl3Zw1rBoGrcivbVeeHTcdiX1nifsZ4khsrHH1fwD "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves an integer on the data stack as output.
* `0 swap` Tuck away our cut resistance value for safe keeping.
* `[ ... ] until-empty` Keep doing something to a sequence until it's empty. This is shorter than having to call `dup`, `empty?`, `drop`, and the like.
* `[ ] group-by values` Group the runs of a sequence. This is shorter than `[ = ] monotonic-split`.
* `[ rest ] map-concat` Cut the runs and glue 'em back together.
* `[ 1 + ] dip` Increment the cut resistance value.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
≬ĠvṪfİL
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiazEoHbhuapmxLBMIiwiIiwiWzAsIDAsIDAsIDEsIDEsIDAsIDMsIDMsIDMsIDIsIDJdIl0=)
```
İL # Count number of times until the result repeats
≬---- # By applying the following
Ġ # Group consecutive elements
vṪ # Remove the last item from each group
f # Flatten
```
[Answer]
# [Python 2](https://docs.python.org/2/), 63 bytes
Takes in a string \$ s \$, a space-separated string of the numbers. It returns `False` for the *empty* case.
```
f=lambda s:s>''and-~f(re.sub(r'(\d+ )(\1*)',r'\2',s))
import re
```
[Try it online!](https://tio.run/##ZYzLCoMwEEX3@YrZJWmtJGopCvojtZS0KgZ8hCQi3fTX7SiUCuUwdzH3zJiXb8chWpYm71T/qBS4zBWUqqE6vRtm69BND2YpK6sjcFbKA6eBpWVEA8c50b0ZrQdbL3OruxpkRuCpXA05WDXf9WAmz3joTKc9o3kBlBMwVg8eGraKV3Hji4AViQiINyIE7ZjIXSX@ch3UEtQivErgDGkKUmAj5NpIksCPePddbvnd7C08uxAM8QE "Python 2 – Try It Online")
---
## [Python 2](https://docs.python.org/2/), 65 bytes
Same as above, but returns `0` for the *empty* case, in case returning false is disallowed.
```
f=lambda s:len(s)and-~f(re.sub(r'(\d+ )(\1*)',r'\2',s))
import re
```
[Try it online!](https://tio.run/##ZYzRCoIwFIbv9xTnbltZbGqEgb1IRsycONA5tkV006vbUYiE@Dj/xfm/c9wrdqNNp6ktezXUjYJw6rVlgSvb7N4t83ofHjXzlFXNFjir5IbTxNMqpUngnJjBjT6C19OzM70GeSJwV0FDCV49b8a6R2R8H1xvIqPlGSgn4LyxEVo2ixdx5ZOAGYkIyBZSBO2MyFUl/nIe1HLUUrzK4QBFAVJgI@TcSJLDj2z1XS753awtPDsSDPEB "Python 2 – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 109 bytes
```
: f ( s -- n ) 0 swap [ dup empty? ]
[ [ = ] monotonic-split [ 1 tail ] map concat
[ 1 + ] dip ] until drop ;
```
[Try it online!](https://tio.run/##ZU89a8MwFNz9K25sKApSkg5xKB0ylCxZSqeQQdhyKmpLqvRMCcG/3X02iTFUhx7oPnS8ShfkY//5cTi@5/g20ZkajaYvJPPTGleYhBRqS2TdZdl458k7WyBEQ3QN0TrCLjscc@xbEtEkm0hzSvhKaFHzq89R4QkJQsBhAYn0qwNOKNsA0wS6vuGcnZh4xRlTgxhbmVUgbetB4lThXaEpG9hnpkobeLaO2FBGH7Drbxn43LhmgGJIrEesGN1dVTNV/pvD7TBZVxze4AXbLZRkVarpn80M61mPGueDmbseyS7reLnqvtey/wM "Factor – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~27~~ 25 bytes
*-2 bytes thanks to @Neil*
```
1`\b
=
}`(\d+ )(\1*)
$2
=
```
[Try it online!](https://tio.run/##K0otycxL/K@qkaDCpcCl4Z7w3zAhJonLlqs2QSMmRVtBUyPGUEuTS8WIy/b/fwMFEDQEQgMFYzA0AkIuQyRhAwwSiIEqjICKTRRMFSwtFQwNgIIGhlwmCghojGSeIZiEiSCr4lIAAA "Retina 0.8.2 – Try It Online")
Similar to @Xcali's Perl solution, and similarly requires a trailing space in the input.
```
1`\b
=
```
Replace the first word-boundary with a `=` character. The first time this is executed, it will match the start of the input. On subsequent runs, it will match the empty space between a `=` and the first number in the list
```
(\d+ )(\1*)
$2
```
Replace sequences of repeated integers with everything but the first integer.
```
}`
```
Execute the preceding two stages in a loop until the input stops changing
```
=
```
Count the number of `=`'s
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 by golfing a 9-byter suggested by clapp
```
EƝTịµƬL’
```
**[Try it online!](https://tio.run/##y0rNyan8/9/12NyQh7u7D209tsbnUcPM////RxvqKBiAkSEYwdlYGSAyFgA "Jelly – Try It Online")**
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~118~~ \$\cdots\$ ~~94~~ 92 bytes
Saved ~~2~~ ~~5~~ 7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
*t;k;c;f(l,n)int*l;{for(k=0;n;++k)for(t=l,c=-1;t-l<n;)c-*t?c=*t,wmemcpy(t,t+1,n--):++t;c=k;}
```
[Try it online!](https://tio.run/##vVHbaoNAEH3vVwxCgroj9UpJN7YPpV@R5CFstBWNCbrQtOK3242rqbFUsEhklL3MuTnMeGOsqnROY8poqCaYalHK9YQW4SFTY9@kKSUk1s477ifIfMOi3EiWKdWYofNn5uscP/bBnh0/VY6cWJgahvZICKfMj2lZBZhjRO/22yhVNSjuQDxCA3iQ89xabcCHwkSQZdUlFk5btqiSXqNsibJ@ocy/F@dvn8e58Ni1lovgISwWots8Q0yrj3Alwq17u@X0LNeCdkt8qT6wz@9J/s5xcDoGjMtjSSCIH37CsPdtpmfyXlmfXu31afEiXk9B6O4dRQBqxDETvKGqFIomKcRwQY0EgUkhgiXk0VdwCFU5IO2@2QqQRoGQqB1i7XA@b@mEXMPXFZntFGwmHW2a@/LKRtnCcuGgVcUBE017iwfjCWY7mOXrVHjIEbJV888CQja@n59lxwe3pwpujwlu44CJ2wR3pgrujAnu4ICJ2wR3pwrujgnu4oCJ2wT3pgrujQnu4YCJ/wQvq28 "C (gcc) – Try It Online")
**Commented code**
```
*t;k;c;f(l,n)int*l;{
for(k=0; /* initialise cut operation counter */
n; /* loop until there're no numbers left
in array */
++k) /* increment cut operation counter after
every loop */
for(t=l, /* save the pointer to the start of
the array */
c=-1; /* initialise c to something that won't
match first number */
t-l<n;) /* loop until our temp pointer is past
the end of the array */
c-*t? /* should we do a cut operation? */
c=*t, /* save our cuurent number so we do a cut
operation at next different number */
wmemcpy(t,t+1,n--) /* shift array down one element
and reduce number of elements by 1 */
:++t; /* if we're not doing a cut operation
bump pointer */
c=k; /* return k */
}
```
[Answer]
## Clojure, 72 bytes
```
#(count(take-while seq(iterate(fn[c](mapcat rest(partition-by + c)))%)))
```
Damn these function names are long :D
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
Wθ«≔Φθ∧λ⁻κ§θ⊖λθ⊞υω»ILυ
```
[Try it online!](https://tio.run/##XYvLCoMwEEXX5itmOYF00cfOlbQUCi24Fxeig4bGKSaxFkq/PY2Fgjicxb2cO3VX2fpRmRCmThsCHCS8RZI5p1vGszaeLA4KMm7QKLhpHh3eY/cXbug1qxPVlnpiT3Ei51MwyFQk@eg6HBVMsXxEbjV7PFbO45W49VHFaRpCURwUrNgv2P3Y/sNSrR/LMmye5gs "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Wθ«
```
Repeat until the input list is empty.
```
≔Φθ∧λ⁻κ§θ⊖λθ
```
Filter out the first term and any terms equal to their predecessor, i.e. the first of every run.
```
⊞υω
```
Keep track of the number of iterations.
```
»ILυ
```
Output the number of iterations.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Ê©ÒßUòÎcÅ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yqnS31XyzmPF&input=WzAgMCAwIDEgMSAwIDMgMyAzIDIgMl0)
```
Ê©ÒßUòÎcÅ :Implicit input of array U
Ê :Length
© :Logical AND with
Ò :Negate the bitwise NOT of
ß :Recursive call with argument
Uò : Partition U between elements where
Î : The sign of their difference is truthy (not 0)
c : Flatten after
Å : Slicing off the first element of each partition
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes
```
←LU¡mhg
```
[Try it online!](https://tio.run/##yygtzv7//1HbBJ/QQwtzM9L///8fbaADgoZAaKBjDIZGOkaxAA "Husk – Try It Online")
A different method, which is ~~slightly longer~~ now the same length.
## Explanation
```
←LU¡mhg
g group runs of consecutive equal elements
¡ apply function infinitely, collecting it's results
mh drop the last element from each run
U cut at fixed point
←L Get length, decrement.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, 43 bytes
Similar to the other regex-based answers.
```
$.+=1while gsub(/(\d+ )(\1*)/,'\2')!=""
p$.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5ejlLsgqWlJWm6Fje1VfS0bQ3LMzJzUhXSi0uTNPQ1YlK0FTQ1Ygy1NPV11GOM1DUVbZWUuApU9CBaoDoX3DQyUUBAYyg0AkJDMAkTQVYF0QoA)
] |
[Question]
[
Integers are tedious to represent in [Brain-Flak](https://esolangs.org/wiki/Brain-Flak). There are 8 operators:
```
() Evaluates to 1, but does not push anything on any stack
[] Evaluates to an indeterminate value for the purposes of this question
{} Removes the top of the stack and evaluates to it
<> Switches to or back from the alternate stack and evaluates to zero
(foo) Pushes the value of the expression foo to the stack and evaluates to it
[foo] Evaluates to the negation of foo
{foo} Evaluates the expression foo until the top of the stack is zero
<foo> Evaluates to zero but executes foo anyway
```
`foo` may consist of multiple operators, in which case they are evaluated and summed. For example `(()())` pushes `2` to the stack (and evaluates to `2` too).
Obviously, the `(()...())` mechanism is not useful in Code Golf as large numbers would take `n*2+2` bytes to represent. Your challenge is therefore to write a program or function that will output in as few bytes as possible a Brain-Flak program that will push a given positive integer `n` to the active stack. This program must not make any assumptions about the existing contents of the stacks, so it must not leave the stacks exchanged or add or remove extra values from the stacks.
Although your program or function must be capable of returning a working Brain-Flak program for all inputs from 1 to 1,000,000 the winner will be the program or function that generates the smallest set of appropriate Brain-Flak programs for all 1061 prime numbers between 1,000 and [10,000](http://aleph0.clarku.edu/~djoyce/numbers/primes.html). You should note the total size of your outputs for those 1061 inputs as part of your submission. Your program or function may accept the integer and return the (string) Brain-Flak program in any of the usual acceptable I/O formats. Ties will be broken using the size of your program or function.
[Answer]
# Python 2, ~~59394~~ ~~59244~~ ~~58534~~ ~~58416~~ ~~58394~~ 58250
Ok here is my solution.
```
import re
import math
cache = {0:"<()>"}
def find(x,i,j):
return i*((x**2+x)/2)+(j+1)*((x**2-x)/2)
def solve(x, i, j):
a = (i + j + 1)/2.
b = (i - j - 1)/2.
c = -x
return (-b + math.sqrt(b**2 - 4*a*c))/(2*a)
def size(i,j=0):
return 4*(i+j)+14
def polynomials(n):
upperBound = int(4*math.log(n,2))
i = 0
answers = []
while size(i) < upperBound:
for j in range(i):
sol = int(solve(n, i-j, j)+.5)
if find(sol, i-j, j) == n:
answers.append((sol, i-j, j))
i += 1
return answers
def complement(character):
dict = {"(":")","{":"}","<":">","[":"]",")":"(","}":"{",">":"<","]":"["}
return dict[character]
def findMatch(snippet, index):
increment = 1 if snippet[index] in "({<[" else -1
stack = []
if snippet[index] in "(){}<>[]":
stack.append(snippet[index])
while len(stack) > 0 and index + increment < len(snippet):
index += increment
if snippet[index] in "(){}<>[]":
if complement(snippet[index]) == stack[-1]:
stack = stack[:-1]
else:
stack.append(snippet[index])
return index
def isPrime(n):
return not [0 for x in range(2,int(n**.5)+1) if n%x==0] and n>1
def getPrimeFactors(n):
return [x for x in range(2,n/2) if n%x==0 and isPrime(x)]
def divHardcode(n,m):
assert n%m == 0
assert m != 1
assert n != 1
binary = bin(m)[3:]
return (binary.count("1")+len(binary))*"("+getBF(n/m)+")"*binary.count("1")+binary.replace("1","){}{}").replace("0","){}")
def isTriangular(n):
#Triangles must be between sqrt(2n) and cbrt(2n)
if n < 0: return isTriangular(-n)
for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
if (x**2+x) == 2*n:
return True
return False
def getTriangle(n):
if n < 0: return -getTriangle(-n)
#Triangles must be between sqrt(2n) and cbrt(2n)
for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
if (x**2+x) == 2*n:
return x
#If we don't find one we made a mistake
assert False
def getSimpleBF(n):
if n in cache:return cache[n]
if n < 0:
# There is room for better solutions here
return "["+getSimpleBF(-n)+"]"
elif n == 0:
return ""
elif n < 6:
return "()"*n
#Non-edge cases
solutions = []
factors = getPrimeFactors(n)
if n >= 78 and isTriangular(n):
solutions.append(
min([push(getTriangle(n))+"{({}[()])}{}","<"+push(getTriangle(n)+1)+">{({}[()])}{}"],key=len)
)
polynomialSolutions = polynomials(n)
for polynomial in polynomialSolutions:
solutions.append("<%s>{%s({}[()])%s}{}"%(push(polynomial[0]),"({})"*polynomial[1],"({})"*polynomial[2]))
#Mod 3 tricks
if n % 3 == 2:
solutions.append(("((%s)()){}{}")%getBF(n/3))
elif n % 3 == 1:
solutions.append(("((%s)()()){}{}")%getBF(n/3-1))
#Basic solutions
if isPrime(n):
solutions.append(getSimpleBF(n-1) + "()")
else:
#TODO multithread
solutions += map(lambda m:divHardcode(n,m),factors)
return min(solutions,key=lambda x:len(unpack(x)))
def getBF(n):
if n in cache: return cache[n]
result = getSimpleBF(n)
index = n - 1
while index > n-(len(result)/2):
score = getSimpleBF(index)+getSimpleBF(n-index)
if len(score) < len(result):result = score
index -= 1
index = n + 1
while index < n+(len(result)/2):
score = getSimpleBF(index)+getSimpleBF(n-index)
if len(score) < len(result):result = score
index += 1
cache[n] = result
return result
def unpack(string):
reMatch = re.match("\(*<",string)
if reMatch:
location =reMatch.span()
return string[location[1]:findMatch(string,location[1]-1)] +string[:location[1]-1] + string[findMatch(string,location[1]-1)+1:]
return string
def push(n):
return unpack("("+getBF(n)+")")
def kolmo(string):
code = push(ord(string[-1]))
stringVector = map(ord,string)
for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
code = "("+code+getBF(y-x)+")"
code = code.replace("<()>)",")")
return code
def kolmo(stringVector):
code = push(stringVector[-1])
for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
code = "("+code+getBF(y-x)+")"
code = code.replace("<()>)",")")
return code
if __name__ == "__main__":
import primes
sum = 0
for prime in primes.nums:
print push(prime)
sum += len(push(prime))
print sum
```
The relevant function is `push(n)`. To call it simply call push on the integer you wish to represent.
# Explanation
The main optimization done by the program is multiplication hard-coding. The idea of multiplication hardcoding is pretty simple. You push the a number and then pop and push it to create a new value. For example to multiply by two you can use the following code `((n){})` where n code producing a specific number. This works because both `(n)` and `{}` have a value of n.
This simple idea can be made more complex for larger numbers. Take for instance 5 it was discovered a while ago that the best way to multiply by five was `(((n)){}){}{}`. This code makes two copies of the n multiplies one by 4 and adds the two. Using the same strategy I make every multiplication based on a number's binary representation. I won't get into the details of how this works right now but I do this by chopping off the first one of the binary representation and replacing 0 with `){}` and 1 with `){}{}`. It then makes sure that n is pushed the appropriate number of times and balances all the parentheses. (If you want to know how this is done you can look at my code). If you want to know why this works just ask me in a comment. I don't think anyone actually reads all the updates to my post so I left the explanation out.
When the algorithm attempts to find a multiplication hardcode it attempts all of a numbers prime factors. It ignores composite factors because at one point composite factors could always be expressed more concisely as its own prime factors it is not known if this is still true.
The other byte saving mechanism is a polynomial solution finder. There are certain forms of polynomials that are easy to represent with decrementing loops. These polynomials include, but are not limited to, polygonal numbers. This optimization finds polynomials that fit the form and creates the code that makes them.
## Output
[paste-bin](http://pastebin.com/KKyRb6YR)
[Answer]
# Brain-Flak, 64664
[Try it Online!](http://brain-flak.tryitonline.net/#code=KHt9PAogKCgoKCgpKCkoKSgpKCkpe30pe30pe30oKSkgIzQxCj4pCnsKICgoe30pWygpKCkoKSgpKCkoKV0pCiAoWyh7fTwoKCkpPildKDw-KSl7KHt9KCkpPD59e308Pnt9e308Pigoe30pKXsoPHt9KHt9PD4pPil9e30oe308PikKIHsoKDwgI0lGCiAge30gCiAgeyh7fVsoKV08ICNGT1IKICAgKCgoKCgpKCkoKSgpKCkpe30pe30pe30oKSkgIzQxCiAgICgoe30pWygpXSkgICAgICAgICAgICAgICAgICM0MAogID4pfXt9CiA-KSl9e30KICgoe30pKQogI01PRDIKIHsoPAogICh7fTwoKCkpPikoezwoe31bKCldPD4pPjw-KCgpW3t9XSk8Pjwoe308Pik-fXt9PCh7fTw-KT48Pik8Pih7fTw-KQogIHsoKDx7fSh7fTwgI0lGCiAgIHt9CiAgICgoKCgpKCkoKSgpKCkpKHt9KSh7fSkoe30pe30pKHt9KSh7fSkoe30pe30pICAjMTI1CiAgICgoe30pWygpKCldKSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAjMTIzCiAgICgoKCgoKSgpKCkoKSgpKXt9KXt9KXt9KCkpICAgICAgICAgICAgICAgICAgICAjNDEKICAgPD4KICAgKCgoKCgpKCkoKSgpKCkpe30pe30pe30pICAgICAgICAgICAgICAgICAgICAgICM0MAogICA8PgogICA-KQogICAKICA-KSl9e317fQogPil9e30KICNNT0QyIChudW1iZXIgMikKICgoe30pKQogKHt9KCgpKSl7KHt9WygpXTw-KTw-KCgpW3t9XSk8Pih7fTw-KX17fQogKCh7fSk8KFt7fV17fSk-KQogewogICh7fVsoKV08PD4KICAgICgoKCgoKSgpKCkoKSgpKXt9KXt9KXt9KSAjNDAKICAgICgoe30pKCkpICAgICAgICAgICAgICAgICAjNDEKICAgPD4-KQogfXt9Cn17fQo8Pnsoe308Pik8Pn08PigoKCgoKSgpKCkoKSgpKXt9KXt9KXt9KQ&input=OTc&args=LUE&debug=on)
Here is my annotated code
```
({}<
((((()()()()()){}){}){}()) #41
>)
{
(({})[()()()()()()])
([({}<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){(<{}({}<>)>)}{}({}<>)
{((< #IF
{}
{({}[()]< #FOR
((((()()()()()){}){}){}()) #41
(({})[()]) #40
>)}{}
>))}{}
(({}))
#MOD2
{(<
({}<(())>)({<({}[()]<>)><>(()[{}])<><({}<>)>}{}<({}<>)><>)<>({}<>)
{((<{}({}< #IF
{}
(((()()()()())({})({})({}){})({})({})({}){}) #125
(({})[()()]) #123
((((()()()()()){}){}){}()) #41
<>
((((()()()()()){}){}){}) #40
<>
>)
>))}{}{}
>)}{}
#MOD2 (number 2)
(({}))
({}(())){({}[()]<>)<>(()[{}])<>({}<>)}{}
(({})<([{}]{})>)
{
({}[()]<<>
((((()()()()()){}){}){}) #40
(({})()) #41
<>>)
}{}
}{}
<>{({}<>)<>}<>((((()()()()()){}){}){})
```
## Explanation
This only implements two rules as of now:
* If n is divisible by two return `(n/2){}`
* If n is not divisible by two return `n-1()`
It also hardcodes all the numbers smaller than 6.
[Answer]
## Perl, ~~59222~~ ~~59156~~ 58460 characters
* `n()` (11322660 characters)
* `(n){}()` (64664 characters)
* `((n)){}{}` (63610 characters)
* `((n)()){}{}` (63484 characters) - this is a novel calculation
* `(n){({}[()])}{}` (60748 characters)
* `n[m]` (62800 characters)
* `(n){m({}[l])}{}` (58460 characters) - this is a novel calculation
The formula for that last calculation is `n(n/l+1)/2+mn/l`. I've tried some other calculations but they are no longer helpful for the given output. The program actually generates all the values up to 9999 but then lists the given prime numbers and their total length.
```
@primes = (<list of the 4-digit prime numbers here>);
@numbers = ();
for ($i = 1; $i < 10000; $i++) {
$numbers[$i] = "()" x $i; # default calculation
}
for ($i = 2; $i < 10000; $i++) {
for ($j = 1; $j < 8; $j++) {
&try($i, "$numbers[$i+$j]\[$numbers[$j]]");
}
&try($i + 1, "$numbers[$i]()");
&try($i * 2, "($numbers[$i]){}");
&try($i * 3, "(($numbers[$i])){}{}");
&try($i * 3 + 2, "(($numbers[$i])()){}{}");
for ($l = 1; $l * $l < $i; $l++) {
unless ($i % $l) {
for ($j = 0; ($k = (($i + $j + $j) * $i / $l + $i) / 2) < 10000; $j++) {
&try($k, "($numbers[$i]){$numbers[$j]({}[$numbers[$l]])}{}");
}
}
}
}
$len = 0;
foreach (@primes) {
print "($numbers[$_])\n";
$len += 2 + length $numbers[$_];
}
print "$len\n";
sub try {
($n, $s) = @_;
$numbers[$n] = $s if (length($numbers[$n]) > length $s);
}
```
[Answer]
# Lua 5.3, 57522
I actually started working on this back when the question was posted, but forgot about it until the Brain-Flak anniversary.
```
-- 64 gives all results through 10000 (should run in about 1 second)
-- 78 gives all results through 100000 (should run in about 20 seconds)
-- 90 gives all results through 1000000 (should run in about 200 seconds)
-- Note: Timings may not be accurate, as the are not updated every time new cases are added.
local k_max_len = 64
local k_limit = 10000
local pre = os.clock()
local function compute_multiplier_helper(prefix, suffix, m)
if m == 2 then
prefix[#prefix + 1] = "("
suffix[#suffix + 1] = "){}"
elseif m % 2 == 0 then
prefix[#prefix + 1] = "("
compute_multiplier_helper(prefix, suffix, m // 2)
suffix[#suffix + 1] = "){}"
else
suffix[#suffix + 1] = ")"
compute_multiplier_helper(prefix, suffix, m - 1)
prefix[#prefix + 1] = "("
suffix[#suffix + 1] = "{}"
end
end
local function compute_multiplier(m)
local prefix = {}
local suffix = {}
compute_multiplier_helper(prefix, suffix, m)
return table.concat(prefix), table.concat(suffix)
end
local multipliers = {}
for m = 2, k_limit do
-- Including all factors, not just primes.
-- This did improve a few numbers, although none in the ppcg test set.
local prefix, suffix = compute_multiplier(m)
local mult = {prefix = prefix, suffix = suffix, m = m, cost = #prefix + #suffix}
table.insert(multipliers, mult)
end
table.sort(multipliers, function(a, b) return a.cost < b.cost end)
local poly_multipliers = {}
poly_multipliers[1] = {m = 1, s = "({})", l = 4}
for m = 2, k_limit do
local prefix, suffix = compute_multiplier(m)
local s = prefix .. "({})" .. suffix
assert(#s <= 4 * m)
poly_multipliers[m] = {m = m, s = s, l = #s}
end
poly_multipliers[k_limit + 1] = {m = 0, s = "", l = 0}
table.sort(poly_multipliers, function(a, b) return a.l < b.l end)
local pcache = {}
local plen_cache = {}
local function register_push(prefix, suffix, value, pvalue)
if value > 1500000 or value < -1500000 then return end
local old_res = pcache[value]
if old_res == nil then
local res = {prefix = prefix, suffix = suffix, value = value, pvalue = pvalue}
pcache[value] = res
local length = #prefix + #suffix
local lcache = plen_cache[length]
if lcache == nil then
lcache = {}
plen_cache[length] = lcache
end
lcache[#lcache + 1] = res
end
end
local function get_pushes(length)
return ipairs(plen_cache[length] or {})
end
register_push("", "()", 1, 0)
register_push("", "<()>", 0, 0)
local function triangle(n)
return (n * (n + 1)) // 2
end
local function process(length)
-- basic
for _, res in get_pushes(length - 2) do
register_push(res.prefix, res.suffix .. "()", res.value + 1, res.pvalue)
register_push(res.prefix, "[" .. res.suffix .. "]", -res.value, res.pvalue)
end
-- multiplication by constant (precomputed)
for _, mult in ipairs(multipliers) do
local cost = mult.cost
if length - cost >= 4 then
local m, prefix, suffix = mult.m, mult.prefix, mult.suffix
for _, pus in get_pushes(length - cost) do
local name = prefix .. pus.suffix .. suffix
register_push(pus.prefix, name, pus.value * m, pus.pvalue)
end
else
break
end
end
-- residue 2 mod3 trick (Neil)
-- ((n)()){}{}
-- (n) -- push n
-- ( ()) -- push n + 1
-- {}{} -- (n + 1) + (n + 1) + n
if length - 10 >= 2 then
for _, res in get_pushes(length - 10) do
local name = "((" .. res.suffix .. ")()){}{}"
register_push(res.prefix, name, 3 * res.value + 2, res.pvalue)
end
end
-- residue 1 mod3 trick (Wheat Wizard)
-- ((n)()()){}{}
-- (n) -- push n
-- ( ()()) -- push n + 2
-- {}{} -- (n + 2) + (n + 2) + n
-- not useful, but fast...
if length - 12 >= 2 then
for _, res in get_pushes(length - 12) do
local name = "((" .. res.suffix .. ")()()){}{}"
register_push(res.prefix, name, 3 * res.value + 4, res.pvalue)
end
end
-- residue 2 mod5 trick (tehtmi)
-- (((n)){}()){}{}
-- (n) -- push n
-- ( ) -- push n
-- ( {}()) -- push 2n + 1
-- {}{} -- (2n + 1) + (2n + 1) + n
-- [[
if length - 14 >= 2 then
for _, res in get_pushes(length - 14) do
local name = "(((" .. res.suffix .. ")){}()){}{}"
register_push(res.prefix, name, 5 * res.value + 2, res.pvalue)
end
end
-- ]]
-- residue 4 mod5 trick (tehtmi)
-- (((n)()){}){}{}
-- (n) -- push n
-- ( ()) -- push n + 1
-- ( {}) -- push 2n + 2
-- {}{} -- (2n + 2) + (2n + 2) + n
-- [[
if length - 14 >= 2 then
for _, res in get_pushes(length - 14) do
local name = "(((" .. res.suffix .. ")()){}){}{}"
register_push(res.prefix, name, 5 * res.value + 4, res.pvalue)
end
end
-- ]]
-- residue 6 mod7 trick (tehtmi)
-- ((((n)())){}{}){}{}
-- (n) -- push n
-- ( ()) -- push n + 1
-- ( ) -- push n + 1
-- ( {}{}) -- push 3n + 3
-- {}{} -- (3n + 3) + (3n + 3) + n
-- [[
if length - 18 >= 2 then
for _, res in get_pushes(length - 18) do
local name = "((((" .. res.suffix .. ")())){}{}){}{}"
register_push(res.prefix, name, 7 * res.value + 6, res.pvalue)
end
end
--]]
-- residue 4 mod7 trick (tehtmi)
-- ((((n))()){}{}){}{}
-- (n) -- push n
-- ( ) -- push n
-- ( ()) -- push n + 1
-- ( {}{}) -- push 3n + 2
-- {}{} -- (3n + 2) + (3n + 2) + n
-- [[
if length - 18 >= 2 then
for _, res in get_pushes(length - 18) do
local name = "((((" .. res.suffix .. "))()){}{}){}{}"
register_push(res.prefix, name, 7 * res.value + 4, res.pvalue)
end
end
--]]
-- residue 2 mod7 trick (tehtmi)
-- ((((n))){}{}()){}{}
-- (n) -- push n
-- ( ) -- push n
-- ( ) -- push n
-- ( {}{}()) -- push 3n + 1
-- {}{} -- (3n + 1) + (3n + 1) + n
-- [[
if length - 18 >= 2 then
for _, res in get_pushes(length - 18) do
local name = "((((" .. res.suffix .. "))){}{}()){}{}"
register_push(res.prefix, name, 7 * res.value + 2, res.pvalue)
end
end
--]]
-- triangle numbers (?)
--(n){({}[()])}{}
--(n) -- push n
-- { } -- sum and repeat
-- ( ) -- push
-- {}[()] -- top - 1
-- {} -- pop 0
if length - 14 >= 2 then
for _, res in get_pushes(length - 14) do
if res.value > 0 then
local code = "{({}[()])}{}"
register_push(res.prefix .. "(" .. res.suffix .. ")", code, triangle(res.value - 1), res.pvalue + res.value)
register_push(res.prefix, "(" .. res.suffix .. ")" .. code, triangle(res.value), res.pvalue)
register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, triangle(res.value) + res.pvalue, 0)
end
end
end
-- negative triangle numbers (tehtmi)
--(n){({}())}{}
--(n) -- push n
-- { } -- sum and repeat
-- ( ) -- push
-- {}() -- top + 1
-- {} -- pop 0
if length - 12 >= 2 then
for _, res in get_pushes(length - 12) do
if res.value < 0 then
local code = "{({}())}{}"
register_push(res.prefix .. "(" .. res.suffix .. ")", code, -triangle(-res.value - 1), res.pvalue + res.value)
register_push(res.prefix, "(" .. res.suffix .. ")" .. code, -triangle(-res.value), res.pvalue)
register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, -triangle(-res.value) + res.pvalue, 0)
end
end
end
-- cubic (tehtmi)
-- (n){(({}[()])){({}[()])}{}}{}
-- (n^3-3*n^2+8*n-6)/6
-- (-6 + n*(8 + n*(-3 + n)))/6
--[[ superceded by negative cubic because
it is the same cost of -ncubic(-n)
if length - 28 >= 2 then
for _, res in get_pushes(length - 28) do
if res.value > 0 then
local code = "{(({}[()])){({}[()])}{}}{}"
local v = res.value + 1
v = (-6 + v*(8 + v*(-3 + v)))//6
register_push(res.prefix .. "(" .. res.suffix .. ")", code, v - res.value, res.pvalue + res.value)
register_push(res.prefix, "(" .. res.suffix .. ")" .. code, v, res.pvalue)
register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, v + res.pvalue, 0)
end
end
end
--]]
-- negative cubic (tehtmi)
-- (n){(({}())){({}())}{}}{}
-- (n^3-3*n^2+8*n-6)/6
-- (-6 + n*(8 + n*(-3 + n)))/6
-- [[
if length - 24 >= 2 then
for _, res in get_pushes(length - 24) do
if res.value < 0 then
local code = "{(({}())){({}())}{}}{}"
local v = -res.value + 1
v = (-6 + v*(8 + v*(-3 + v)))//6
v = -v
register_push(res.prefix .. "(" .. res.suffix .. ")", code, v - res.value, res.pvalue + res.value)
register_push(res.prefix, "(" .. res.suffix .. ")" .. code, v, res.pvalue)
register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, v + res.pvalue, 0)
end
end
end
--]]
-- polynomial (Wheat Wizard, modified by tehtmi)
-- <(n)>{A({}[()])B}{} where A, B are ({})({})({})... repeated a, b times
-- <(n)> -- push n (without adding)
-- { } -- repeat until top is zero
-- A -- top * a
-- ({}[()]) -- top = top - 1; += top - 1
-- B -- (top - 1) * b
-- {} -- pop 0
-- triangular numbers are with a = b = 0
-- from B and base:
-- (n - 1) * (B + 1) * (n - 2) * (B + 1) * ...
-- (B + 1) * (1 + ... + n - 1)
-- (B + 1) * n * (n - 1) / 2
-- from A:
-- n * A + (n - 1) * A + ...
-- A * (1 + ... n)
-- A * (n + 1) * n / 2
-- total: (B + 1) * n * (n - 1) / 2 + A * (n + 1) * n / 2
-- [(A + B + 1) * n^2 + (A - B - 1) * n] / 2
-- S := 4 * (A + B)
-- [[
if length - 18 >= 2 then
for S = 4, length - 14, 4 do
for _, res in get_pushes(length - 14 - S) do
if res.value > 0 then
for _, A in ipairs(poly_multipliers) do
if A.l > S then
break
end
for _, B in ipairs(poly_multipliers) do
if A.l + B.l < S then
-- continue
elseif A.l + B.l > S then
break
else
local a = A.m
local b = B.m
local logic = "{" .. A.s .. "({}[()])" .. B.s .. "}{}"
local v = res.value
v = ((a + b + 1) * v * v + (a - b - 1) * v) // 2
register_push(res.prefix .. "(" .. res.suffix .. ")", logic, v, res.pvalue + res.value)
register_push(res.prefix, "(" .. res.suffix .. ")" .. logic, v + res.value, res.pvalue)
register_push("", res.prefix .. "(" .. res.suffix .. ")" .. logic, v + res.value + res.pvalue, 0)
end
end
end
end
end
end
end
--]]
-- negative polynomial (tehtmi)
-- <(n)>{A({}())B}{}
-- [[
if length - 16 >= 2 then
for S = 4, length - 12, 4 do
for _, res in get_pushes(length - 12 - S) do
if res.value < 0 then
for _, A in ipairs(poly_multipliers) do
if A.l > S then
break
end
for _, B in ipairs(poly_multipliers) do
if A.l + B.l < S then
-- continue
elseif A.l + B.l > S then
break
else
local a = A.m
local b = B.m
local logic = "{" .. A.s .. "({}())" .. B.s .. "}{}"
local v = -res.value
v = ((a + b + 1) * v * v + (a - b - 1) * v) // -2
register_push(res.prefix .. "(" .. res.suffix .. ")", logic, v, res.pvalue + res.value)
register_push(res.prefix, "(" .. res.suffix .. ")" .. logic, v + res.value, res.pvalue)
register_push("", res.prefix .. "(" .. res.suffix .. ")" .. logic, v + res.value + res.pvalue, 0)
end
end
end
end
end
end
end
--]]
-- addition
-- [[
if length >= 4 then
for part1 = 4, length // 2, 2 do
for _, res1 in get_pushes(part1) do
for _, res2 in get_pushes(length - part1) do
register_push(res2.prefix .. res1.prefix, res1.suffix .. res2.suffix, res1.value + res2.value, res1.pvalue + res2.pvalue)
end
end
end
end
--]]
-- pseudo-exponentiation (tehtmi)
-- (n)<>(m){({}[()])<>(({}){})<>}{}<>{}
-- (n)<>(m) -- push n and m on opposite stacks
-- { } -- sum and repeat
-- ({}[()]) -- top(m) - 1
-- <>(({}){})<> -- n = 2*n; += n
-- {} -- pop 0
-- <> -- swap to result
-- {} -- pop and add n
-- [[
if length - 34 >= 4 then
local subl = length - 34
for part1 = 2, subl - 2, 2 do
for _, res2 in get_pushes(part1) do
local b = res2.value
if b > 0 and b < 55 then -- overflow could be a problem, so bound...
for _, res1 in get_pushes(subl - part1) do
-- 2n + 4n + 8n + ... + (2^m)*n + 2^m * n
-- n( 2 + 4 + 8 + .. 2^m + 2^m)
-- n( 3 * 2^m - 2 )
local a = res1.value
local body = "(" .. res1.suffix .. ")<>" .. res2.prefix .. "(" .. res2.suffix .. "){({}[()])<>(({}){})<>}{}<>{}"
local v = a * (3 * (1 << b) - 2) + b * (b - 1) // 2 + a + b + res2.pvalue
register_push(res1.prefix, body, v, res1.pvalue)
register_push("", res1.prefix .. body, v + res1.pvalue, 0)
end
end
end
end
end
--]]
end
--print(os.clock(), "seconds (startup)")
local start = os.clock()
for i = 2, k_max_len - 2, 2 do
--print(i)
process(i)
end
plen_cache = nil
local final = {}
for i = 1, k_limit do
if pcache[i] ~= nil then
final[i] = pcache[i].prefix .. "(" .. pcache[i].suffix .. ")"
end
end
pcache = nil
-- hard coded to 10000 for ppcg test
local sieve = {}
for i = 1, 10000 do sieve[i] = true end
for i = 2, 10000 do
for j = i * i, 10000, i do
sieve[j] = false
end
end
--print(os.clock() - start, "seconds (calculation)")
--local bf = require("execute2")
local count = 0
local sum = 0
local sum2 = 0
local maxlen = 0
local pcount = 0
for i = 1, k_limit do
local res = final[i]
final[i] = nil
--print(i, #res, res)
--local ev = res and bf.eval1(bf.compile(res)) or -1; assert( res == nil or ev == i, string.format("Failed %d %s %d", i, res or "", ev))
if sieve[i] and i > 1000 then
sum = #res + sum
pcount = pcount + 1
end
if res then
sum2 = #res + sum2
maxlen = math.max(maxlen, #res)
count = count + 1
end
end
print("sum", sum)
--print("coverage", count / k_limit, "missing", k_limit - count)
--print("sum2", sum2)
--print("maxlen", maxlen)
assert(pcount == 1061)
```
Similar idea to the other answers where known-useful functions are used to build up larger numbers from good representations of simpler numbers.
One difference is that instead of solving subproblems in terms of smaller numbers, I'm solving subproblems in terms of numbers with shorter representations. I think this makes it more elegant to take advantage of negative numbers as well as handling the case where smaller numbers are represented in terms of larger numbers.
Also, trying to find all numbers that can be represented in a certain size rather trying to represent a particular number as shortly as possible actually simplifies certain calculations. Instead of working a formula in reverse to see whether it can be applied to a number, the formula can be worked forwards and applied to every number.
Another difference is that known solutions are stored in two pieces -- an (optional) "prefix" and a "suffix" (more like an infix). The valuation of the prefix is expected to be ignored when calculating the given number -- the prefix just contains code that sets up the suffix to run (generally by pushing one or more things to the stack). So, given a prefix and a suffix, the corresponding number can be pushed onto the stack with `prefix(suffix)`.
This split basically solves the same problem as the `unpack` function in Wheat Wizard's answer. Instead of wrapping code with `<...>` only to undo this later, such code is simply added to the prefix.
In a few cases, the prefix actually does get evaluated (mainly for the pseudo-exponentiation operation), so its valuation is also stored. However, this doesn't really cause a big problem, as the generator isn't trying to construct specific numbers. It seem to theoretically imply that there could be two pieces of code of the same length and generating the same number that wouldn't be redundant in the cache due to having different prefix valuations. I didn't bother accounting for this though, as it doesn't seem to matter much (at least in this domain).
I imagine it would be easy to whittle down the byte count just by adding more cases, but I've had enough for the moment.
I've run to 1000000, but only done sanity checking up to 100000.
[Pastebin of output on given primes.](https://pastebin.com/rQ4bvbGk)
[Answer]
## Python, ~~59136~~ 58676 characters
**Brainflak number golfing function:**
```
m=11111
R=range(0,m)
R[1]="()"
R[2]="()()"
l=2
def a(v,r):
if v>0 and v<m:
if isinstance(R[v],int) or len(r)<len(R[v]):
R[v]=r
if v<R[0]:
R[0]=v
def s(v,k):
S=0
while v>0:
S+=v
v-=k
return S
p=lambda r:"("+r+")"
w=lambda r:"{({}["+r+"])}{}"
def q(r,v):
for i in range(1,v):
r="("+r+")"
for i in range(1,v):
r+="{}"
return r
def e(r,v,k):
for i in range(0,k):
r=q(r,v)
return r
while l<m:
R[0]=l+1
a(l*2,q(R[l],2))
a(l*3,q(R[l],3))
a(l*5,q(R[l],5))
a(l*7,q(R[l],7))
for i in range(1,l):
a(l+i,R[l]+R[i])
a(l-i,R[l]+"["+R[i]+"]")
if l%i==0:
t=s(l-i,i)
a(s(l,i),p(R[l])+w(R[i]))
a(l+2*t,p(R[l])+q(w(R[i]),2))
a(l+4*t,p(R[l])+e(w(R[i]),2,2))
a(l+8*t,p(R[l])+e(w(R[i]),2,3))
a(l+16*t,p(R[l])+e(w(R[i]),2,4))
a(l+32*t,p(R[l])+e(w(R[i]),2,5))
a(l+64*t,p(R[l])+e(w(R[i]),2,6))
a(l+128*t,p(R[l])+e(w(R[i]),2,7))
a(l+3*t,p(R[l])+q(w(R[i]),3))
a(l+9*t,p(R[l])+e(w(R[i]),3,2))
a(l+27*t,p(R[l])+e(w(R[i]),3,3))
a(l+5*t,p(R[l])+q(w(R[i]),5))
a(l+6*t,p(R[l])+q(q(w(R[i]),3),2))
a(l+10*t,p(R[l])+q(q(w(R[i]),5),2))
a(l+15*t,p(R[l])+q(q(w(R[i]),5),3))
a(l+12*t,p(R[l])+q(q(q(w(R[i]),3),2),2))
a(l+18*t,p(R[l])+q(q(q(w(R[i]),3),3),2))
a(l+20*t,p(R[l])+q(q(q(w(R[i]),5),2),2))
a(l+24*t,p(R[l])+q(q(q(q(w(R[i]),3),2),2),2))
a(l+36*t,p(R[l])+q(q(q(q(w(R[i]),3),3),2),2))
a(l+40*t,p(R[l])+q(q(q(q(w(R[i]),5),2),2),2))
l=R[0]
f=lambda v:p(R[v])
```
**Prime number iteration:**
```
def isPrime(v):
i=2
while i*i<=v:
if v%i==0:
return False
i+=1
return True
for i in range(1000,10000):
if isPrime(i):
print f(i)
```
**Output:**
[Pastebin](http://pastebin.com/uZY846bz)
**Explanation:**
We pre-populate a list *R* of Brain-flak representation evaluating to individual integers over a larger than necessary range [1,*m*-1] to define our function *f*. The representations are formed by taking the lowest unused representation (indexed by *l*) and forming many new representations from it, keeping only the shortest. The lowest unused representation assumes that all number 1 to *l* have been assigned a representation, and that these representations have already been used to produce new numbers. If a value less than *l* gets a shorter representation we must go back and reproduce numbers beginning form that point. The function *f* produces a program saving the number to the stack by adding parenthesis.
I didn't know any Brainflak when I began this, and greatly appreciate [Eamon Olive's answer](https://codegolf.stackexchange.com/a/89737/46756) for pointing out the formula for triangle numbers. Mostly I've generalized the summation and been relentless about checking sums and differences. Adding lots of multiples of sums has had a great effect.
For those who care, here is the [scratch code](http://pastebin.com/aueB36NJ) I used to see which formulas were worth it.
**Representation Formulas:**
1. Multiplication by small primes:
`(X){}`
`((X)){}{}`
`((((X)))){}{}{}{}`
`((((((X)))))){}{}{}{}{}{}`
2. Addition *X*+*Y*:
`XY`
3. Subtraction *X*-*Y*:
`X[Y]`
4. Summation to and including *X* of increment *Y*:
`(X){({}[Y])}{}`
5. Multiples of summations to *X* of increment *Y*, plus *X*:
`(X)({({}[Y])}{}){}`
`(X)(({({}[Y])}{})){}{}`
`(X)(({({}[Y])}{}){}){}`
etc...
[Answer]
# ruby, 60246 bytes
```
$brain_flak = Hash.new{|h, k|
a = []
a.push "()"*k
if k > 1
if k > 10
# Triangle Numbers:
n = (Math.sqrt(1+8*k).to_i-1)/2
if (n*n+n)/2 == k
a.push "("+h[n]+"){({}[()])}{}"
a.push h[n+n]+")({({}[()])}{}"
end
end
(k**0.51).to_i.downto(2){|i|
# multiplication:
if k%i==0
a.push "("*(i-1) + h[k/i] + ")"*(i-1)+"{}"*(i-1)
end
}
(k/2).downto(1){|i|
# Addition
a.push h[k-i] + h[i]
}
end
h[k] = a.min_by{|x|x.length}
}
$brain_flak[0] = "<><>"
def get_code_for (i)
"(#{$brain_flak[i]})"
end
```
I use a hash. I finds the best golf for a given number and uses the smaller ones to find the larger ones.
Recursive hashes are so much fun!
[Answer]
# Python, 64014 characters
I didn't know anything about brainflak before this challenge and only fiddled around with it a bit on tryitonline, so there could be obvious shortcuts I missed. This is a quite boring solution, just splits the input into `x=x/2+x%2` or `x=x/3+x%3`, whichever is shorter.
```
k=lambda x:"(("+o(x/3)+")){}{}"+(x%3)*"()"if x>3else"()"*x
m=lambda x:"("+o(x/2)+"){}"+(x%2)*"()"if x>6else"()"*x
o=lambda x:min(k(x),m(x),key=len)
b=lambda x:"("+o(x)+")"
```
Call it like so: `b(42)`
## [output on pastebin](http://pastebin.com/JpTT9pFA)
[Answer]
## Lua, 64664 bytes
Program prints the total length of the programs and the program for the 203rd prime (theres a line you can change to change which one is printed, or uncomment a line to print all the programs)
Right now the only optimization is x = 2\*n + 1
Hopefully I will have time to add some more optimizations to lower the score.
```
local primeS = [[<INSERT PRIMES HERE>]]
local primes = {}
for num in primeS:gmatch("%d+") do
table.insert(primes, num+0)
end
local progs = {}
progs[0] = ""
progs[1] = "()"
progs[2] = "()()"
local function half(n)
if progs[n] then return progs[n] end
local p = ""
local div = math.floor(n/2)
local rem = n%2 == 1 and "()" or ""
return "("..progs[div].."){}"..rem
end
for i = 3, 10000 do
local bin = half(i)
progs[i] = progs[i-1] .. "()"
if #bin < #progs[i] then
progs[i] = bin
end
if i % 1000 == 0 then
print(i)
end
end
local n = 203 -- This is the program it outputs
print(n..", ("..progs[203]..")")
local len = 0
for i,v in ipairs(primes) do
len = len + #progs[v] + 2
--print(v.." ("..progs[v]..")\n")
end
print("Total len: "..len)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 64664, 35 bytes
```
?*"()"¹+*"()"%2¹`+"){}":'(₀½-%2¹¹<6
```
[Try it online!](https://tio.run/##yygtzv7/315LSUNT6dBObTCtanRoZ4K2kmZ1rZKVusajpoZDe3VBYod22pj9///f0MjAGAA "Husk – Try It Online")
Husk is a golfing language so making a high scoring solution is a little hard, simply because long Husk code quickly becomes unwieldy. I just gave this a shot to practice my Husk.
This implements the same algorithm as [my Brain-Flak solution from earlier](https://codegolf.stackexchange.com/a/98054/56656).
] |
[Question]
[
Given a positive integer `n`, output the `N`-dimensional identity "matrix", which is the `N^N` array with `1` where all the components of the indices are equal and `0` otherwise. `N^N` means N-by-N-by-N-by-...
```
1 -> [1]
2 -> [[1,0],[0,1]]
3 -> [[[1,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,1,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,1]]]
4 -> [[[[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]],[[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]],[[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]],[[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]]]]
```
For example, if `a` is the `4`-dimensional identity "matrix", then the only entries with `1` would be `a[0][0][0][0]`, `a[1][1][1][1]`, `a[2][2][2][2]`, and `a[3][3][3][3]`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# Octave, 29 bytes
```
@(n)accumarray((x=1:n)'+!x,1)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPMzE5uTQ3sagosVJDo8LW0CpPU11bsULHUPN/Yl6xhrHmfwA "Octave – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
×=¥þ’¡`Ṡ
```
[Try it online!](https://tio.run/##ARsA5P9qZWxsef//w5c9wqXDvuKAmcKhYOG5oP///zM "Jelly – Try It Online")
Ooh, looks like I get to outgolf @Dennis in his own language again :-)
This is a 1-argument function (because Jelly's default output format for nested lists is a little ambiguous, meaning that it arguably doesn't fulfil the spec as a full program).
## Explanation
```
×=¥þ’¡`Ṡ
¡ Repeatedly apply the following operation,
’ {input-1} times in total:
þ For each element of the current value {perhaps made into a range}
` and of {the range from 1 to the} {input}:
= Compare corresponding elements, giving 0 for equal or 1 for unequal
× ¥ then multiply by one of the elements
Ṡ then replace each element with its sign
```
In order to understand this, it helps to look at the intermediate steps. For an input of 3, we get the following intermediate steps:
1. `[1,2,3]` (input, made into a range implicitly by the `þ`)
2. `[[1,0,0],[0,2,0],[0,0,3]]` (make a table with `[1,2,3]`, compare for equality to get `[[1,0,0],[0,1,0],[0,0,1]]`, then multiply by one of the values we compared)
3. `[[[1,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,2,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,3]]]` (the same idea again)
4. `[[[1,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,1,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,1]]]` (replace each element with its sign using `Ṡ`)
Note the fact that the input starts out 1-dimensional means that we have to loop (input-1) times in order to add (input-1) dimensions, producing an input-dimensional list.
Fun fact: this program contains five quicks in a row, `¥þ’¡``. (A quick is a modifier to a "link", or builtin, used to modify its behaviour or combine it with another link.)
[Answer]
## Mathematica, 30 bytes
```
Array[Boole@*Equal,#~Table~#]&
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 10 bytes
```
1=≢∘∪¨⍳⍴⍨⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdMyU1r@S/oe2jzkWPOmY86lh1aMWj3s2Perc86l3xqG8qSMl/BTAAq@Qy5ELmGaHwjFF4JgA "APL (Dyalog Unicode) – Try It Online")
`1=` [is] 1 equal to
`≢` the number
`∘` of
`∪` unique elements
`¨` in each of
`⍳` the indices in an array with the dimensions of
`⍴⍨` the self-reshape (*N* copies of *N*) of
`⎕` the input (*N*) [?]
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ðṗE€ṁ+þ’¡
```
[Try it online!](https://tio.run/##AR8A4P9qZWxsef//w7DhuZdF4oKs4bmBK8O@4oCZwqH///80 "Jelly – Try It Online")
### How it works
Achieving the task directly seems to be difficult (I haven't found a way), but contructing arrays of the same numbers and arrays of the same shape is quite easy.
`ð` makes the chain dyadic, and the integer input **n** serves as both left and right argument for the chain. It's possible to use a monadic chain instead, but the parsing rules for dyadic ones save three bytes here (two after accouting for `ð`).
The *Cartesian power* atom `ṗ`, with left and right argument equal to **n**, constructs the array of all vectors of length **n** that consist of elements of **[1, ..., n]**, sorted lexicographically.
When **n = 3**, this yields
```
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3, 1], [1, 3, 2], [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 3, 1], [3, 3, 2], [3, 3, 3]]
```
The *equal each* quicklink `E€` tests the elements of all constructed vectors for equality.
When **n = 3**, we get
```
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
```
which are the elements of the 3-dimensional identity matrix, in a flat array.
The dyadic quicklink `+þ’¡` is called with left argument and right argument **n**. The quick `¡` calls the decrement atom `’`, which yields **n-1**, then calls the *add table* quicklink `+þ` **n-1** times.
Initially, the arguments of `+þ` are both **n**. After each call, the right argument is replaced by the left one, and the left one is replaced by the return value of the call.
The *table* quick calls the *add* atom `+` for each elements of its left argument and each element of its right argument, constructing a table/matrix of the return value. The initial integer arguments **n** are promoted to the ranges **[1, ... n]**.
When **n = 3**, after promotion but before the first iteration, both arguments are
```
[1, 2, 3]
```
Adding each integer in this array to each integer in this array yields
```
[[2, 3, 4], [3, 4, 5], [4, 5, 6]]
```
In the next invocation, we add each of these arrays to the integers in **[1, 2, 3]**. Addition vectorizes (adding an integer to an array adds it to each element), so we get
```
[[[3, 4, 5], [4, 5, 6], [5, 6, 7]],
[[4, 5, 6], [5, 6, 7], [6, 7, 8]],
[[5, 6, 7], [6, 7, 8], [7, 8, 9]]]
```
This array has the same shape as the 3-dimensional identity matrix, but not the correct elements.
Finally, the *mold* atom `ṁ` discards the integer entries of the result to the right and replaces them in order with the elements in the result to the left.
[Answer]
# [Python](https://docs.python.org/2/), 70 bytes
```
f=lambda n,l=[]:[f(n,l+[i])for i in(len(l)<n)*range(n)]or+(l==l[:1]*n)
```
[Try it online!](https://tio.run/##DcYxDoAgDAXQqzC26qJuRk5CGDCKNqkfQnDw9OjwkpffeiVMrUWr4d72YDCodX5xkf71TjzHVIwYAenx4xXclYDzILBPpSe1Vt0y@g7cchFUE0mQn0rMbf4A "Python 2 – Try It Online")
A recursive solution. Thinking of the matrix as a list of matrices one dimension smaller, it iterates over that list to go down the tree. It remembers the indices picked in `l`, and when `n` indices have been picked, we assign a `1` or `0` depending on whether they are all the same.
---
# [Python 2](https://docs.python.org/2/), 73 bytes
```
n=input();r=0
exec'r=eval(`[r]*n`);'*n+('n-=1;r'+'[n]'*n+'=1;')*n
print r
```
[Try it online!](https://tio.run/##FchLCoAgFAXQuato9vwQ9BmKKxHBCCEhbvKwqNVbDc8pT90OTK3BZZSzSmXZDSLdaSV26Vp2GT0HjagsaRhJ6N1omQx5hH/oIykNUTijdtza/AI "Python 2 – Try It Online")
An improvement on [totallyhuman's method](https://codegolf.stackexchange.com/a/127921/20260) of making a matrix of zeroes and then assigning ones to the diagonal.
---
# [Python 2](https://docs.python.org/2/), 88 bytes
```
n=input()
t=tuple(range(n))
print eval('['*n+'+(i0'+'==i%d'*n%t+')'+'for i%d in t]'*n%t)
```
[Try it online!](https://tio.run/##HcgxCoAwDADA3Vd0kSRmEZ37EnEQrBoosZRU8PW1ON6l165bp1rVi6ZiSJ15KykGzJueAZWoS1nUXHi2iLDAoAyMMgKD99LvLXpjoObjzq6NE3W2/k@1zh8 "Python 2 – Try It Online")
Some nonsense with `eval`, generating a nested list, and string-format substitution. The string to be evaluated looks like:
```
[[[+(i0==i0==i1==i2)for i0 in t]for i1 in t]for i2 in t]
```
[Answer]
# Python 2 + [NumPy](http://www.numpy.org/), ~~80~~ ~~72~~ 70 bytes
Now tied with the top Python answer!
```
from numpy import*
n=input()
a=zeros((n,)*n)
a[[range(n)]*n]=1
print a
```
[**Try it online**](https://tio.run/##DcctEoAgEAbQzimIwFjUzEkYAsEfAh876xLw8quvPZpyd2yqJ/dmMRpNWxt1lmAQK2iI86bE9@D@OIfFB/xPiQuuw8HngBxXQ1whtqjuHw)
*Saved 8 bytes thanks to Andras Deak, and 2 by officialaimm*
[Answer]
# [Python 2](https://docs.python.org/2/), ~~99~~ ~~93~~ 90 bytes
*Thanks to Rod for ~~some~~ even more help that got it working and also shaved 6 bytes off! -3 bytes thanks to xnor.*
```
n=input()
r=eval(`eval('['*n+'0'+']*n'*n)`)
for i in range(n):exec'r'+`[i]`*n+'=1'
print r
```
[Try it online!](https://tio.run/##HctBCsMgEEbhvadwNxo3aciq4ElEMIRpMhD@yGBLe3qbdvP4Nq9@2n5i6h1RUJ/NeaORX8vhyr@UaECgkQLlAZd98eZxqhUrsLpgYwd/5zevpBRKklx@Q7yRqSpoVnufvw "Python 2 – Try It Online")
[Answer]
## JavaScript (ES6), 67 bytes
```
f=(n,d=n-1,i)=>[...Array(n)].map((_,j)=>d?f(n,d-1,j-i?n:j):j-i?0:1)
```
Explanation: `i` is used to keep track of whether the cell is on the main diagonal or not. Initially it's undefined, so on the first recursive call we always pass the first dimension, while on subsequent recursive calls we only pass it on if the current dimension index is equal to all previous dimensions, otherwise we pass an index of `n` which indicates that all of the recursive cells should be zero.
[Answer]
# [Brainfuck](https://github.com/TryItOnline/tio-transpilers), 61 bytes
```
>,[->+>+<<]>[-<<+>>]>-[->+.-<<<<[->+>+<<]>[-<+>]>[->>.<<]>]+.
```
## Ungolfed
The numbers after the angle brackets indicate the cell the head is over.
```
>, read n to 1
[->+>+<<] move 1 to 2 and 3
>2[-<<+>>]>3 move 2 to 0
(tape: n 0 0 n 0)
-[ while cell 3 {
- dec 3
>4+.-<3 print \x1
<<<0[->+>+<<] move 0 to 1 and 2
>1[-<+>]>2 move 1 to 0
(tape: 0 0 n rows_left 0)
[ while cell 2 {
- dec 2
>>4.<< print \x0
]>3 }
] }
+. print \x1
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v/fTida107bTtvGJtYuWtfGRtvOLtZOFySmB@TZ2KDIatuBKDs7PRA/Vlvv/39mAA "brainfuck – Try It Online")
Input is a binary number. Output is a matrix stored in row-major order.
[Answer]
# [R](https://www.r-project.org/), ~~64~~ 49 bytes
*-15 bytes thanks to Jarko Dubbeldam*
```
x=array(0,rep(n<-scan(),n));x[seq(1,n^n,l=n)]=1;x
```
Reads from stdin and returns an array, printing as matrices. `seq` generates a sequence evenly spaced from `1` to `n^n` with length `l=n`, which does the trick quite nicely to index where the 1s go.
[Try it online!](https://tio.run/##K/r/v8I2sagosVLDQKcotUAjz0a3ODkxT0NTJ09T07oiuji1UMNQJy8uTyfHNk8z1tbQuuK/yX8A "R – Try It Online")
### old version:
```
n=scan();x=rep(0,n^n);x=array(x,rep(n,n));x[matrix(1:n,n,n)]=1;x
```
Reads `n` from stdin; returns an array, printing the results as matrices. I struggled with this for a while until I read the docs for `[`, which indicate that a matrix can be used to index an array, where each row of the matrix represents the set of indices. Neat!
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTusK2KLVAw0AnLy4PxEksKkqs1KjQAQnm6eRpAsWicxNLijIrNAytgAJAoVhbQ@uK/yb/AQ "R – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~16~~ 15 bytes
```
i.@#~=i.*]#.#&1
```
[Try it online!](https://tio.run/##y/r/P03B1kohU89Buc42U08rVllPWc2Qiys1OSNfIU3B@P9/AA "J – Try It Online")
[Answer]
## Python 3 + numpy, ~~81~~ 77 bytes
```
from numpy import*
f=lambda n:all([a==range(n)for a in indices((n,)*n)],0)+0
```
I'm not *entirely* sure that the above fits all guidelines: it returns an ndarray with the given properties. I know anonymous functions are usually fine, but an interactive shell will actually print
```
>>> f(2)
array([[1, 0],
[0, 1]])
```
If the array fluff makes the above invalid, I have to throw in a `print()` for something like 7 additional bytes.
[Try it online!](https://tio.run/##DcI9DsMgDAbQPafwaJMMkdgqcZIqg/NDiwQfyKVDTk/79Nrd3xV@jGi1EL6l3ZRKq9bdFEPWsp9KeGjO/NQQTPG6GBKrkVLC/5mO68OMRRxkW1aZ19EsoXNkLzJ@)
[Answer]
# Pyth, 14 bytes
```
ucGQtQms!t{d^U
```
[Test suite](https://pyth.herokuapp.com/?code=ucGQtQms%21t%7Bd%5EU&test_suite=1&test_suite_input=1%0A2%0A3%0A4&debug=0)
Explanation: `^U`, which is implicitly `^UQQ`, where `Q` is the input, calculates all possible Q element lists of the range `0 ... n-1`. `ms!t{d` maps the ones with all elements equal to 1, and the rest to 0. This gives the flattened output
`ucGQtQ` executes the following, Q - 1 times: Chop the input into lists of size Q.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 166 bytes
```
n=>{var c=new int[n];int i=0,d;for(;i<n;c[i++]=n);var m=System.Array.CreateInstance(typeof(int),c);for(i=0;i<n;i++){for(d=0;d<n;c[d++]=i);m.SetValue(1,c);};return m;}
```
[Try it online!](https://tio.run/##hVFda8IwFH33V1wKg4R2pXW@xQhD2NjYYCBsD9KHkKYu0CaSRkWkv90l1foxp7uUNr333HPOzeX1PddGbMEFL1ldw4fRM8Oqns9s2reP2jIrOSy1zOGdSYXwoXQE@Zisayuq@Gmh@FAqG3WJR2PYegQF0N5W0dFmyQxwqsQKHGqqMuI@IGkS5aTQBhE5VIRPZRhmVGHi0RU9pYrHRjArXpRzprhAdj0XukCOBUcctxyOraVxJHjjE7lL5C1v7nklJlU8EfaTlQuBUt/WECPswiioSLMlvbPJvAfmpYFCgQaYXFTnuna1bqYMNpBE3QPNOX71LUsByLVMkwyGMMBn5fNLPbnYsVa1LkX8ZaQVb1IJFEwDCN2CjFSz@FW73QRREHkz2OWDzFnygNZ6/NyN68u/RvDh/Tz4FrQ/hZBiuIPBJVQWBxClkOALwOUMnUL/oNC/pXCq0r@mcl2pU0sPaul/aqeK6V4RdjsKw79bmt7tzPFvd2q2Pw "C# (.NET Core) – Try It Online")
At first I thought it could not be done with a lambda expression in C#... ^\_\_^U
[Answer]
# Common Lisp, ~~147~~ 133 bytes
```
(defun i(n)(flet((m(x)(fill(make-list n)x)))(let((a(make-array(m n):initial-element 0)))(dotimes(i n)(incf(apply #'aref a(m i))))a)))
```
[Try it online!](https://tio.run/##JcxBCgMxCAXQqwhd9LsYKHTX28iMAamxIZPCzOlT2y4E9T9d3fY2JzYt7yBDMIrrACqObM0dVZ66JBsUfDAzfrn899K7nKgZPSxsmPiirlVj0O1rt9ewqjssBSzWAmnNT7pcpWuh/EKWjiVrorVueZn6nuMH)
The usual super-lengthy lisp. Reduced 12 bytes thank to @ceilingcat!
Explanation:
```
(defun i (n)
(flet ((m (x) (fill (make-list n) x))) ; function to build a list of n values x
(let ((a (make-array (m n) :initial-element 0))); build the array with all 0
(dotimes (i n) ; for i from 0 to n-1
(incf (apply #'aref a (m i)))) ; add 1 to a[i]..[i]
a))) ; return the array
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
ẋÞm⁽≈€
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwi4bqLw55t4oG94omI4oKsIiwiIiwiMiJd)
My first submission, thanks to emanresu for help with the lambda.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 22 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
.^κ.H/ 0* 1.H≤Οčr.H{.n
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=LiU1RSV1MDNCQS5ILyUyMDAqJTIwMS5IJXUyMjY0JXUwMzlGMW5yLkglN0Iubg__,inputs=NA__)
[Leaves the output on the stack](https://codegolf.meta.stackexchange.com/a/8507/59183), viewable in the console. If the numbers in the output were allowed to be strings, then the `r` could be removed.
Just as a fun test of how SOGL does in challenges it was completely not made for :p
```
input: x
.^ push x^x
κ subtract x (x^x)-x
.H/ divide by x ((x^x) - x)/x
0* get that many zeroes
1 push "1"
.H push x-1
≤ pull the first item from the stack to the top
Ο encase (x-1 times the zeroes, separated, started and ended with 1s)
č chop to a char-array
r convert each character to a number
.H{ repeat x-1 times:
.n in the top array, for each group of x contents, encase that in an array
```
[Answer]
## Clojure, 92 bytes
```
#(reduce(fn[v i](assoc-in v(repeat % i)1))(nth(iterate(fn[v](vec(repeat % v)))0)%)(range %))
```
Nice that [assoc-in](https://clojuredocs.org/clojure.core/assoc-in) works also with vectors, not only with hash-maps.
] |
[Question]
[
Jack and Jane decided to play a game of chess to while away time. Unfortunately, Jack is rather bad at visualizing. He finds it tough to figure the moves possible for a given piece other than a pawn, of course!
Your challenge is to help find Jack the possible options for a given piece (other than a pawn).
In case one has forgotten, the various pieces are denoted by:
* K: King
* Q: Queen
* N: Knight
* B: Bishop
* R: Rook
As an example, in the following image the Knight is located at `d4` and can move to `c2`, `b3`, `b5`, `c6`, `e6`, `f5`, `f3`, `e2`. For a given input:
```
Nd4
```
you would produce:
```
Nc2 Nb3 Nb5 Nc6 Ne6 Nf5 Nf3 Ne2
```

Rules:
* The order of the output doesn't matter as long as all the possible moves are listed
* The possible moves can be separated by whitespaces, newlines or any other delimiter
* The input can be passed to the program as a parameter or via `STDIN`
* Whitespace in the program shall be counted, so make optimum use of it
This is code golf. (Please avoid making use of any tools/utilities specifically designed for the purpose.) The shortest answer wins!
[Answer]
# Python, ~~217~~ ~~212~~ ~~220~~ ~~217~~ 213 characters
Tied the 213-byte Mathematica solution
```
R=range(8)
def f((p,x,y)):
for a in R:
for b in R:
A,B=abs(a-ord(x)+97),abs(b-ord(y)+49);C=max(A,B);r=(A+B==3and C<3,C<2,A*B<1,A==B,0)
if(r['NKRBQ'.index(p)],any(r[1:]))[p=='Q']*C:print p+chr(a+97)+chr(b+49)
```
I started off by generating all valid moves but that grew too large so the approach is quite similar to the Mathematica one.
```
>>> f("Nd4")
Nb3
Nb5
Nc2
Nc6
Ne2
Ne6
Nf3
Nf5
>>> f("Qa1")
Qa2
Qa3
Qa4
Qa5
Qa6
Qa7
Qa8
Qb1
Qb2
Qc1
Qc3
Qd1
Qd4
Qe1
Qe5
Qf1
Qf6
Qg1
Qg7
Qh1
Qh8
```
[Answer]
## Mathematica, ~~278~~ ~~272~~ ~~264~~ ~~260~~ ~~215~~ 213 characters
```
f=(FromCharacterCode@Flatten[Table[c=Abs[#2-x];d=Abs[#3-y];b=c==d;r=#2==x||#3==y;If[Switch[#-75,0,c~Max~d<2,-9,b,7,r,6,b||r,3,!r&&c+d==3],{p,x,y},##&[]],{x,97,104},{y,49,56}]&@@ToCharacterCode@#,1]~DeleteCases~#)&
```
Ungolfed version:
```
f[pos_] := (
{piece, u, v} = ToCharacterCode@pos;
board = Flatten[Table[{piece, i + 96, j + 48}, {i, 8}, {j, 8}], 1];
DeleteCases[
FromCharacterCode[
Cases[board, {_, x_, y_} /; Switch[p,
75, (* K *)
ChessboardDistance[{x, y}, {u, v}] < 2,
66, (* B *)
Abs[u - x] == Abs[v - y],
82, (* R *)
u == x || v == y,
81, (* Q *)
Abs[u - x] == Abs[v - y] || u == x || v == y,
78, (* N *)
u != x && v != y && ManhattanDistance[{x, y}, {u, v}] == 3
]
]
],
pos (* remove the input position *)
]
)&
```
Example usage:
```
f["Nd4"]
> {"Nb3", "Nb5", "Nc2", "Nc6", "Ne2", "Ne6", "Nf3", "Nf5"}
```
The ungolfed version creates a full board, and then selects correct positions with `Cases`, whereas the golfed version drops invalid moves immediately in the `Table` command by issuing `##&[]`, which simply vanishes.
[Answer]
# Haskell ~~225 220 208 205 200~~ 182
```
f=fromEnum
m[p,a,b]=[[p,c,r]|c<-"abcdefgh",r<-"12345678",let{s=abs$f a-f c;t=abs$f b-f r;g"K"=s<2&&t<2;g"Q"=g"B"||g"R";g"N"=s+t==3&&(s-t)^2<2;g"B"=s==t;g"R"=s<1||t<1}in s+t>0&&g[p]]
```
~~It's going to be difficult to touch Mathematica when that has chess moves built in :rollseyes: (well played m.buettner)~~ I take it all back. Beating Mathematica by 31!
Latest edit: replaced case with a function, inlined filter into comprehension, to beat the entry in R ;)
usage:
```
ghci> m "Nd4"
["Nb3","Nb5","Nc2","Nc6","Ne2","Ne6","Nf3","Nf5"]
```
Ungolfed (corresponds to 208 char version before 'u' was inlined):
```
f=fromEnum -- fromEnum is 'ord' but for all enum types,
-- and it's in the prelude, so you don't need an extra import.
u piece dx dy= -- piece is the character eg 'K', dx/dy are absolute so >=0.
dx+dy > 0 && -- the piece must move.
case piece of
'K'->dx<2&&dy<2 -- '<2' works because we already checked dx+dy>0
'Q'->dx<1||dy<1||dx==dy -- rook or bishop move. see below.
'N'->dx+dy == 3 && -- either 2+1 or 3+0. Exclude the other...
(dx-dy)^2 < 2 -- 1^2 or 3^2, so valid move is '<2', ie '==1'
'B'->dx==dy -- if dx==dy, dx/=0 - we checked that.
-- other moves with dx==dy are along diagonal
_->dx<1||dy<1 -- use _ not 'R' to save space, default case is
-- the rook. '<1' saves chars over '==0'.
-- Again, dx==dy==0 edge case is excluded.
m[piece,file,rank]= -- the move for a piece. 'parse' by pattern match.
filter( -- filter...
\[_,newfile,newrank]-> -- ...each possible move...
u piece -- ...by, as everyone noticed, converting char..
(abs$f file-f newfile) -- differences to absolute dx, dy differences,..
(abs$f rank-f newrank)) -- and then using special routines per piece.
[[piece,newfile, newrank] -- the output format requires these 3 things.
|newfile<-"abcdefgh",newrank<-"12345678"] -- and this just generates moves.
```
[Answer]
# GolfScript, ~~94~~ 93 characters
My first ever GolfScript program! This took me many an hour of fumbling around not really knowing what I was doing, but I persisted and I think I managed to learn the language basics and golf it fairly well.
[Fully golfed](http://golfscript.apphb.com/?c=Ik5kNCIKCnt9Lzgsezk3Ky4zJC0uKjo%2BOCx7NDkrLjQkLS4qOl4yJCsuWzM8Pl4qND0%2BXj0%2BXiohLjIkfF0iS05CUlEiOCQ%2FPSp7WzUkMyRAXSIiK3B9ezt9aWZ9Lzs7fS9dOw%3D%3D):
```
{}/8,{97+.3$-.*:>8,{49+.4$-.*:^2$+.[3<>^*4=>^=>^*!.2$|]"KNBRQ"8$?=*{[5$3$@]""+p}{;}if}/;;}/];
```
[Commented and nicer source](http://golfscript.apphb.com/?c=Iy0xIC0xIC0xIC0xIC0xIC0xIC0xIC0xCiMjU1RBQ0sgRFVNUDogWzckNyQ3JDckNyQ3JDckNyRdcAoKIk5kNCIKCnt9LyAgICAgICAgICAgICAgIyB0SW4gZkluIHJJbgo4LHs5NysgICAgICAgICAgICMgICAgICAgICAgICAgZlRzdAogIC4zJC0uKjo%2BICAgICAgICMgICAgICAgICAgICAgICAgICBmRGlmXjIgOiA%2BCiAgOCx7NDkrICAgICAgICAgIyAgICAgICAgICAgICAgICAgICAgICAgICByVHN0IAogICAgLjQkLS4qOl4gICAgICMgICAgICAgICAgICAgICAgICAgICAgICAgICAgICByRGlmXjIgOiBeCiAgICAyJCsuICAgICAgICAgIyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBePisKICAgIFszPCAgICAgICAgICAjIFRoZXNlICAgICMgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBbdmFsaWRLCiAgICAgPl4qND0gICAgICAgIyBjaGVja3MgICAjICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB2YWxpZE4KICAgICA%2BXj0gICAgICAgICAjIGRvIG5vdCAgICMgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB2YWxpZEIKICAgICA%2BXiohICAgICAgICAjIGFjY291bnQgICMgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdmFsaWRSCiAgICAgLjIkfF0gICAgICAgIyBmb3IgbnVsbCAjICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB2YWxpZFFdCiAgICAiS05CUlEiOCQ%2FPSAgIyBtb3ZlOyAgICAjICAgICAgICAgICAgICAgICAgICAgICAgICB2YWxpZAogICAgKiAgICAgICAgICAgICMgKiBkb2VzLiAgIyAgICAgICAgICAgICAgICAgICAgICAgICAgdmFsaWROb3ROdWxsCiAgICB7WzUkMyRAXSIiK3B9ezt9aWYgICMgcHJpbnQ%2FICMgIGZEaWZeMgogIH0vOzsgICAgICAgICAgICMgICAgICAgIHJJbgp9L107):
```
{}/ # tIn fIn rIn
8,{97+ # fTst
.3$-.*:> # fDif^2 : >
8,{49+ # rTst
.4$-.*:^ # rDif^2 : ^
2$+. # ^>+
[3< # These # [validK
>^*4= # checks # validN
>^= # do not # validB
>^*! # account # validR
.2$|] # for null # validQ]
"KNBRQ"8$?= # move; # valid
* # * does. # validNotNull
{[5$3$@]""+p}{;}if # print? # fDif^2
}/;; # rIn
}/];
```
It may look like Claudiu's answer, which is because I referenced his answer, as well as my (unsubmitted) C solution, while making mine. He provided a good specimen of a (relatively) complex, working GolfScript program, and it helped me learn a lot about the language. So thanks, Claudiu!
Being new to GolfScript still, if you guys have any feedback, I'd appreciate hearing it!
[Answer]
# Bash, 238
```
B={19..133..19}\ {21..147..21};K=1\ {19..21};N='18 22 39 41';R={1..7}\ {2..14..2}0;Q=$B\ $R
a=${1%??};b=$[20#${1:1}-200];c=`eval{,} echo '$'$a`;d=({a..h})
for i in $c -${c// / -};do echo $a${d[$[(i+=b)/20]]}$[i%20];done|grep '[a-h][1-8]$'
```
# How it works
* The idea is to represent every field on the board by a numeric value, taking its coordinates as a base-20 number and subtracting 200. This way, `a1` becomes `20 * 10 + 1 - 200 = 1`, `h8` becomes `20 * 17 + 8 - 200 = 148`, etc.
Now, the possible moves of the Bishop can be represented by (positive or negative) multiples of 19 – same amount of steps up (+20) and to the left (-1) – or 21 – same amount of steps up (+20) and to the right (+1).
The figure's placement after the move is simply the sum of its original position and the movement. After adding those numbers, we have to check if their sum corresponds to a valid field on the board.
Since the base (20) is more than twice as big as the highest possible number (8), the sum cannot wrap around the board, e.g., moving *Bh1* seven steps to the right and up will result in an invalid board position.
* The line
```
B={19..133..19}\ {21..147..21};K=1\ {19..21};N='18 22 39 41';R={1..7}\ {2..14..2}0;Q=$B\ $R
```
enumerates all possible moves of the pieces that are represented by positive numbers.
* The commands
```
a=${1%??};b=$[20#${1:1}-200];c=`eval{,} echo '$'$a`;d=({a..h})
```
stores the piece's identifier in variable *a*, the original position's numeric representation in *b* and the letters *a* to *h* in the array *d*.
After brace expansion, `eval{,} echo '$'$a` becomes `eval eval echo '$'$a` (doubly evil), which evaluates to, e.g., `eval echo $K`, which evaluates to `echo 1 19 20 21`.
* `for i in $c -${c// / -};do …; done` loops over all possible movements and their negative counterparts.
* `echo $a${d[$[(i+=b)/20]]}$[i%20]` gives the final position after the movement.
* `grep '[a-h][1-8]$'` makes sure that we have a valid board position.
[Answer]
# Golfscript, ~~144~~ 135 characters
Instead of continuing to try golfing my [Python solution](https://codegolf.stackexchange.com/a/25057/4800), I translated it into Golfscript:
```
{}/49-:y;97-:x;:N;8,{.x-abs:A
8,{.y-abs:B@[\]$1=:C[B
A+3=\3<&2C>B
A*1<B
A=]81N={(;{|}*}{"NKRB"N?=}if
C*{[N
2$97+@49+]''+p}{;}if
A}/;;}/
```
Straightforward translation without much golfing so it can most likely be whittled away further. Takes input from stdin without a newline, [try it here](http://golfscript.apphb.com/?c=OyJOZDQiCgp7fS80OS06eTs5Ny06eDs6TjsKOCx7CiM1IAogICNhCiAgLngtYWJzOkEKICAjYSBBCjgsewojMyAKICAjYSBBIGIgCiAgLnktYWJzOkIKICAjYSBBIGIgQgogIEBbXF0kMT06QwogICNhIGIgQwogIFtCIEErMz1cMzwmCiAgIDJDPgogICBCIEEqMTwKICAgQiBBPV0KICA4MU49CiAgeyg7e3x9Kn0KICB7Ik5LUkIiTj89fWlmCiAgQyp7W04gMiQ5NytANDkrXScnK3B9ezt9aWYgQQp9Lwo7Owp9Lw%3D%3D) (1st two lines are to mimic stdin).
[Answer]
## C ~~634~~ ~~632~~ ~~629~~ ~~625~~ 600 chars
```
#define F for(;i<4;i++){
#define B ;}break;
#define O x=X,y=Y,
P,X,Y,c,r,x,y,i=0, N[8][2]={{-2,1},{-1,2},{1,2},{2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}},S[4][2]={{1,0},{0,1},{-1,0},{0,-1}},D[4][2]={{-1,1},{-1,-1},{1,1},{1,-1}};
C(){return((0<=c)&(c<8)&(0<r)&(r<9))?printf("%c%c%d ",P,c+'a',r):0;}
M(int*m){c=m[0]+x,r=m[1]+y;C()?x=c,y=r,M(m):0;}
main(int a,char**v){char*p=v[1];P=*p,X=p[1]-97,Y=p[2]-48; switch(P){case 75:F c=S[i][1]+X,r=S[i][0]+Y,C(),c=D[i][1]+X,r=D[i][0]+Y,C()B case 81:F O M(D[i]),O M(S[i])B case 78:for(;i<8;i++){c=N[i][1]+X,r=N[i][0]+Y,C()B case 66:F O M(D[i])B case 82:F O M(S[i])B}}
```
Any suggestions on how to improve this? This is my first time submitting an answer.
[Answer]
## Haskell, ~~300~~ 269 chars
Thanks to bazzargh for help with losing 31 characters...
```
import Data.Char
f x=filter(x#)[x!!0:y|y<-[v:[w]|v<-"abcdefgh",w<-"12345678"],y/=tail x]
a%b=abs(ord a-ord b)
x#y=let{h=(x!!1)%(y!!1);v=(x!!2)%(y!!2);m=max h v;n=min h v}in case(x!!0)of{'N'->m==2&&n==1;'K'->m==1;'B'->h==v;'R'->n==0;'Q'->('R':tail x)#y||('B':tail x)#y}
```
Same algorithm as the Mathematica version. Sample output from ghci:
```
*Main> f "Nd4"
["Nb3","Nb5","Nc2","Nc6","Ne2","Ne6","Nf3","Nf5"]
*Main> f "Ni9"
["Ng8","Nh7"]
```
(You didn't ask for sanity checking!)
[Answer]
# Haskell , 446 chars
```
import Data.Char
a=[-2,-1,1,2]
b=[-1,1]
d=[1..8]
e=[-8..8]
g=[-1..1]
h 'N' c r=[(c+x,r+y)|x<-a,y<-a,3==(sum$map abs[x, y])]
h 'B' c r=[(c+x*z,r+y*z)|x<-b,y<-b,z<-d]
h 'R' c r=[(c+x,r)|x<-e]++[(c,r+y)|y<-e]
h 'Q' c r=h 'B' c r++h 'R' c r
h 'K' c r=[(c+x,r+y)|x<-g,y<-g]
l s=ord s-96
m n=chr$n+96
k ch (c,r)=ch:m c:[intToDigit r]
f (x,y)=all(`elem`[1..8])[x, y]
i n c r=map(k n).filter(/=(c,r)).filter f$h n c r
j s=i(s!!0)(l$s!!1)(digitToInt$s!!2)
```
Called using the `j` function
```
j "Nd4"
```
I haven't worked with Haskell in a few months, so it didn't end up being as short as most of the other solutions, but I'm sure there are some optimizations to made, mainly with `h`. I might shorten it in a bit.
[Answer]
# q & k [311 262 chars]
There is a potential of reducing some more characters. I will be reducing it in next iteration.
```
k)o:{n:#m:&(#x)##y;((),x)[m],'n#y}
k)a:`$"c"$(o/)c:+(97;49)+/:!8
k)r:{{|x@<x}'?,/{o[x]y}'[x](|"c"$c)}
k)k:{"c"$(6h$x)+/:(o/)2 3#-1 0 1}
k)n:{"c"$(6h$x)+/:(|:'t),t:o[-1 1;2 2]}
k)b:{"c"$(6h$x)+/:(n,'n),n,'|n:-8+!17}
k)q:{,/(r;b)@\:x}
d:{(`$("rknbq"!(r;k;n;b;q))[x]y)except`$y}
g:{a inter d[x 0]@1_x}
```
### Usage
Rook
```
g"ra1"
`a2`a3`a4`a5`a6`a7`a8`b1`c1`d1`e1`f1`g1`h1
```
King
```
g"ka1"
`a2`b1`b2
```
Knight
```
g"na1"
`b3`c2
```
Bishop
```
g"ba1"
`b2`c3`d4`e5`f6`g7`h8
```
Queen
```
g"qa1"
`a2`a3`a4`a5`a6`a7`a8`b1`b2`c1`c3`d1`d4`e1`e5`f1`f6`g1`g7`h1`h8
```
[Answer]
# R, 203 chars
```
f=function(p,x,y){x=which((l=letters)==x);X=rep(1:8,8);Y=rep(1:8,rep(8,8));A=abs(X-x);L=abs(Y-y);B=A==L;R=!A|!L;i=switch(p,N=A+L==3&A&L,R=R,B=B,Q=R|B,K=(R|B)&A<2&L<2)&A+L>0;paste(p,l[X[i]],Y[i],sep="")}
```
Ungolfed version:
```
f = function(p,x,y) {
x = which(letters == x) # Gives index between 1 and 8.
X = rep(1:8, 8) # 1,2,...,7,8,1,2,.... (8x8).
Y = rep(1:8, rep(8,8)) # 1,1,...2,2,.....,8,8 (8x8).
dx = abs(X-x)
dy = abs(Y-y)
B = (dx == dy) # Bishop solutions
R = (!dx | !dy) # Rock solutions
i = switch(p,
N=dx+dy==3 & dx & dx, # Sum of dist. is 3, dx and dy must be <> 0.
R=R,
B=B,
Q=R|B, # Queen is merge of rock and bishop.
K=(R|B) & dx<2 & dy<2 # King's distance is < 2.
) & (dx+dy > 0) # Exclude start field.
paste(p, letters[X[i]], Y[i], sep="")
}
```
Usage:
```
> f('N', 'a', 3)
[1] "Nb1" "Nc2" "Nc4" "Nb5"
```
The solution is even good readable. However I added some parentheses and comments for readers unfamiliar with R code (on the ungolfed version).
[Answer]
## Haskell (hypothetical), 248 chars
```
import Data.Char
f x=filter(o x)[x!!0:y|y<-[v:[w]|v<-"abcdefgh",w<-"12345678"],y/=tail x]
d a b=abs(ord a-ord b)
h x y=(c*(d(x!!1)(y!!1))-(d(x!!2)(y!!2)))+200*c
where c=d (x!!0)'A'
o x y=elem(chr(h x y))"ਲ਼ੁߏߚߙÈേെൄൃ൙൪ൻඌඝථ౿౾౽౼౻౺౹ಐಏಠಞರಭೀ಼ೋೠ೩"
```
Unfortunately, every Haskell compiler I can get my hands on right now has problems with Unicode string literals. Here's the (longer) version that actually works:
```
import Data.Char
f x=filter(o x)[x!!0:y|y<-[v:[w]|v<-"abcdefgh",w<-"12345678"],y/=tail x]
d a b=abs(ord a-ord b)
h x y=(c*(d(x!!1)(y!!1))-(d(x!!2)(y!!2)))+200*c
where c=d (x!!0)'A'
o x y=elem(chr(h x y))"\2611\2625\1999\2010\2009\200\3399\3398\3397\3396\3395\3394\3393\3417\3434\3451\3468\3485\3502\3519\3199\3198\3197\3196\3195\3194\3193\3216\3215\3232\3230\3248\3245\3264\3260\3280\3275\3296\3290\3312\3305"
```
The definition `h x y=...` is a hash function; valid moves will hash to character numbers that are in the 41-character string. This gets rid of the need for a "case" statement or equivalent.
I'm not planning to work further on this right now. It would be fun to see if someone can use a hash function in a more concise language to make a shorter solution.
] |
[Question]
[
## The challenge
Write a function that takes two positive integers \$n\$ and \$k\$ as arguments and returns the number of the last person remaining out of \$n\$ after counting out each \$k\$-th person.
This is a code-golf challenge, so the shortest code wins.
## The problem
\$n\$ people (numbered from \$1\$ to \$n\$) are standing in a circle and each \$k\$-th is counted out until a single person is remaining (see the corresponding [wikipedia article](http://en.wikipedia.org/wiki/Josephus_problem)). Determine the number of this last person.
E.g. for \$k=3\$ two people will be skipped and the third will be counted out. I.e. for \$n=7\$ the numbers will be counted out in the order \$3 \, 6 \, 2 \, 7 \, 5 \, 1\$ (in detail \$\require{cancel}1 \, 2 \, \cancel{3} \, 4 \, 5 \, \cancel{6} \, 7 \, 1 \, \cancel{2} \, 4 \, 5 \, \cancel{7} \, 1 \, 4 \, \cancel{5} \, 1 \, 4 \, \cancel{1} \, 4\$) and thus the answer is \$4\$.
## Examples
```
J(7,1) = 7 // people are counted out in order 1 2 3 4 5 6 [7]
J(7,2) = 7 // people are counted out in order 2 4 6 1 5 3 [7]
J(7,3) = 4 // see above
J(7,11) = 1
J(77,8) = 1
J(123,12) = 21
```
[Answer]
## Minsky Register Machine (25 non-halt states)
Not technically a function, but it's in a computing paradigm which doesn't have functions per se...
This is a slight variation on the main test case of my first [MRM interpretation challenge](https://codegolf.stackexchange.com/questions/1864/simulate-a-minsky-register-machine-i):

Input in registers `n` and `k`; output in register `r`; it is assumed that `r=i=t=0` on entry. The first two halt instructions are error cases.
[Answer]
## Python, 36
I also used the formula from wikipedia:
```
J=lambda n,k:n<2or(J(n-1,k)+k-1)%n+1
```
Examples:
```
>>> J(7,3)
4
>>> J(77,8)
1
>>> J(123,12)
21
```
[Answer]
### Mathematica, ~~38~~ 36 bytes
Same Wikipedia formula:
```
1~f~_=1
n_~f~k_:=Mod[f[n-1,k]+k,n,1]
```
[Answer]
## GolfScript, 17 bytes
```
{{@+\)%}+\,*)}:f;
```
Takes `n k` on the stack, and leaves the result on the stack.
## Dissection
This uses the recurrence `g(n,k) = (g(n-1,k) + k) % n` with `g(1, k) = 0` (as described in the Wikipedia article) with the recursion replaced by a fold.
```
{ # Function declaration
# Stack: n k
{ # Stack: g(i-1,k) i-1 k
@+\)% # Stack: g(i,k)
}+ # Add, giving stack: n {k block}
\,* # Fold {k block} over [0 1 ... n-1]
) # Increment to move from 0-based to 1-based indexing
}:f;
```
[Answer]
## C, 40 chars
This is pretty much just the formula that the above-linked wikipedia article gives:
```
j(n,k){return n>1?(j(n-1,k)+k-1)%n+1:1;}
```
For variety, here's an implementation that actually runs the simulation (99 chars):
```
j(n,k,c,i,r){char o[999];memset(o,1,n);for(c=k,i=0;r;++i)(c-=o[i%=n])||(o[i]=!r--,c=k);
return i;}
```
[Answer]
## dc, 27 bytes
```
[d1-d1<glk+r%1+]dsg?1-skrxp
```
Uses the recurrence from the Wikipedia article. Explanation:
```
# comment shows what is on the stack and any other effect the instructions have
[ # n
d # n, n
1- # n-1, n
d # n-1, n-1, n
1<g # g(n-1), n ; g is executed only if n > 1, conveniently g(1) = 1
lk+ # g(n-1)+(k-1), n; remember, k register holds k-1
r% # g(n-1)+(k-1) mod n
1+ # (g(n-1)+(k-1) mod n)+1
]
dsg # code for g; code also stored in g
? # read user input => k, n, code for g
1- # k-1, n, code for g
sk # n, code for g; k-1 stored in register k
r # code for g, n
x # g(n)
p # prints g(n)
```
[Answer]
## J, 45 characters
```
j=.[:{.@{:]([:}.]|.~<:@[|~#@])^:(<:@#)>:@i.@[
```
Runs the simulation.
Alternatively, using the formula (31 characters):
```
j=.1:`(1+[|1-~]+<:@[$:])@.(1<[)
```
I hope Howard doesn't mind that I've adjusted the input format slightly to suit a dyadic verb in J.
Usage:
```
7 j 3
4
123 j 12
21
```
[Answer]
### GolfScript, ~~32~~ 24 bytes
```
:k;0:^;(,{))^k+\%:^;}/^)
```
*Usage:*
Expects the two parameters *n* and *k* to be in the stack and leaves the output value.
(thanks to Peter Taylor for suggesting an iterative approach and many other tips)
The old (recursive) approach of 32 chars:
```
{1$1>{1$(1$^1$(+2$%)}1if@@;;}:^;
```
This is my first GolfScript, so please let me know your criticisms.
[Answer]
## R, 48
```
J=function(n,k)ifelse(n<2,1,(J(n-1,k)+k-1)%%n+1)
```
Running Version with examples: <http://ideone.com/i7wae>
[Answer]
### Groovy, 36 bytes
```
def j(n,k){n>1?(j(n-1,k)+k-1)%n+1:1}
```
[Answer]
## Haskell, 68
```
j n=q$cycle[0..n]
q l@(i:h:_)k|h/=i=q(drop(k-1)$filter(/=i)l)k|1>0=i
```
Does the actual simulation. Demonstration:
>
> GHCi> j 7 1
>
> 7
>
> GHCi> j 7 2
>
> 7
>
> GHCi> j 7 3
>
> 4
>
> GHCi> j 7 11
>
> 1
>
> GHCi> j 77 8
>
> 1
>
> GHCi> j 123 12
>
> 21
>
>
>
[Answer]
### Scala, 53 bytes
```
def?(n:Int,k:Int):Int=if(n<2)1 else(?(n-1,k)+k-1)%n+1
```
[Answer]
## C, 88 chars
Does the simulation, doesn't calculate the formula.
Much longer than the formula, but shorter than the other C simulation.
```
j(n,k){
int i=0,c=k,r=n,*p=calloc(n,8);
for(;p[i=i%n+1]||--c?1:--r?p[i]=c=k:0;);
return i;
}
```
Notes:
1. Allocates memory and never releases.
2. Allocates `n*8` instead of `n*4`, because I use `p[n]`. Could allocate `(n+1)*4`, but it's more characters.
[Answer]
## C++, 166 bytes
### Golfed:
```
#include<iostream>
#include <list>
int j(int n,int k){if(n>1){return(j(n-1,k)+k-1)%n+1;}else{return 1;}}
int main(){intn,k;std::cin>>n>>k;std::cout<<j(n,k);return 0;}
```
### Ungolfed:
```
#include<iostream>
#include <list>
int j(int n,int k){
if (n > 1){
return (j(n-1,k)+k-1)%n+1;
} else {
return 1;
}
}
int main()
{
int n, k;
std::cin>>n>>k;
std::cout<<j(n,k);
return 0;
}
```
[Answer]
### Ruby, 39 bytes
```
def J(n,k)
n<2?1:(J(n-1,k)+k-1)%n+1
end
```
Running version with test cases: <http://ideone.com/pXOUc>
[Answer]
# Q, 34 bytes
```
f:{$[x=1;1;1+mod[;x]f[x-1;y]+y-1]}
```
Usage:
```
q)f .'(7 1;7 2;7 3;7 11;77 8;123 12)
7 7 4 1 1 21
```
[Answer]
## Ruby, 34 bytes
```
J=->n,k{n<2?1:(J(n-1,k)+k-1)%n+1}
```
[Answer]
# Powershell, 56 bytes
```
param($n,$k)if($n-lt2){1}else{((.\f($n-1)$k)+$k-1)%$n+1}
```
Important! The script calls itself recursively. So save the script as `f.ps1` file in the current directory. Also you can call a script block variable instead script file (see the test script below). That calls has same length.
Test script:
```
$f = {
param($n,$k)if($n-lt2){1}else{((&$f($n-1)$k)+$k-1)%$n+1}
}
@(
,(7, 1, 7)
,(7, 2, 7)
,(7, 3, 4)
,(7, 11, 1)
,(77, 8, 1)
,(123,12, 21)
) | % {
$n,$k,$expected = $_
$result = &$f $n $k
"$($result-eq$expected): $result"
}
```
Output:
```
True: 7
True: 7
True: 4
True: 1
True: 1
True: 21
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 6 bytes
```
+~/\,@0%+_@
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq7Xr9GN0HAxUteMdICJQiTXRSoZGSjpAwlgpFioGAA)
Uses the formula as described on Wikipedia:
\$J(n,k) = g(n,k) + 1\$, where
$$\begin{align}g(1,k) &= 0 \\ g(n,k) &= (g(n-1,k)+k) \bmod n\end{align}$$
```
+~/\,@0%+_@
+~ Add 1
/ fold right
\ reverse
, range from 1 to
@ n
0 with initial value 0
% modulo
+ add
_ k
@ accumutalor
item
```
[Answer]
# Haskell, 29
Using the formula from wikipedia.
```
1#_=1
n#k=mod((n-1)#k+k-1)n+1
```
[Answer]
# JavaScript (ECMAScript 5), 48 bytes
Using ECMAScript 5 since that was the latest version of JavaScript at the time this question was asked.
```
function f(a,b){return a<2?1:(f(a-1,b)+b-1)%a+1}
```
## ES6 version (non-competing), 33 bytes
```
f=(a,b)=>a<2?1:(f(a-1,b)+b-1)%a+1
```
## Explanation
Not much to say here. I'm just implementing the function the Wikipedia article gives me.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
L[Dg#²<FÀ}¦
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fJ9olXfnQJhu3ww21h5b9/29oZMxlaAQA "05AB1E – Try It Online")
```
L # Range 1 .. n
[Dg# # Until the array has a length of 1:
²<F } # k - 1 times do:
À # Rotate the array
¦ # remove the first element
```
[Answer]
# [8th](http://8th-dev.com/), 82 bytes
**Code**
```
: j >r >r a:new ( a:push ) 1 r> loop ( r@ n:+ swap n:mod ) 0 a:reduce n:1+ rdrop ;
```
**SED** (Stack Effect Diagram) is: `n k -- m`
**Usage and explanation**
The algorithm uses an array of integers like this: if people value is 5 then the array will be [1,2,3,4,5]
```
: j \ n k -- m
>r \ save k
>r a:new ( a:push ) 1 r> loop \ make array[1:n]
( r@ n:+ swap n:mod ) 0 a:reduce \ translation of recursive formula with folding using an array with values ranging from 1 to n
n:1+ \ increment to move from 0-based to 1-based indexing
rdrop \ clean r-stack
;
ok> 7 1 j . cr
7
ok> 7 2 j . cr
7
ok> 7 3 j . cr
4
ok> 7 11 j . cr
1
ok> 77 8 j . cr
1
ok> 123 12 j . cr
21
```
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
1+1{1([:|/\+)/@,.1|.!.0#
```
[Try it online!](https://tio.run/##FcexCoAgFEbh3af4q6Gk0K4OhiH0HgkNkURLQ2P17HYbPjjnyOlC8OjBMrV0UzP7R8dW6qlT9KhC9VWWolSoU/A1Orwe6RJiW/cTi0EzJi0jHIgZZv/mcRhAxrL8AQ "J – Try It Online")
An iterative approach based on the dynamic programming solution.
## Explanation
```
1+1{1([:|/\+)/@,.1|.!.0# Input: n (LHS), k (RHS)
# Make n copies of k
1|.!.0 Shift left by 1 and fill with zero
1 ,. Interleave with 1
/@ Reduce using
+ Addition
|/\ Cumulative reduce using modulo
1{ Select value at index 1
1+ Add 1
```
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
1+(}:@|.^:({:@])i.)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbU1aq0cavTirDSqrRxiNTP1NP9rcqUmZ@QrGCqkKZhDmEYIpjGCaYikwgLEhImDlBsaGf8HAA "J – Try It Online")
### How it works
```
1+(}:@|.^:({:@])i.) Left: k, Right: n
i. Generate [0..n-1]
^: Repeat:
}:@|. Rotate left k items, and remove the last item
({:@]) n-1 (tail of [0..n-1]) times
1+ Add one to make the result one-based
```
[Answer]
# [Dart](https://www.dartlang.org/), 33 bytes
```
f(n,k)=>n<2?1:(f(n-1,k)+k-1)%n+1;
```
[Try it online!](https://tio.run/##Tc1BCsIwEAXQfU8xi0oTOhUnFSrW1pWnCFkEpbQUo4TETcnZYxC0bj7/DQP/pq2LcWAGZ9715iTOdGSJFaVDOVfEN6akNt71ZBhfMoCXtuCgA5k6gGyQsFH4hfhHjfsVQIT0Y4OHVSRqJIGCVLJqs5RuOzzsRV9HxvxnFuBpJ@NYkS8D83Kn0EtSPEDXQ754KVQoeJseQ8oQ3w "Dart – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 bytes
```
_é1-V Å}h[Uõ] Ì
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=X+kxLVYgxX1oW1X1XSDM&input=MTIzCjEy)
A byte could be saved by [0-indexing k](https://ethproductions.github.io/japt/?v=1.4.6&code=X+lWbinFfWhbVfVdIMw=&input=MTIzCjEx), but it isn't actually an index so I decided against that.
Explanation:
```
[Uõ] :Starting with the array [1...n]
_ }h :Repeat n-1 times:
é1-V : Rotate the array right 1-k times (i.e. rotate left k-1 times)
Å : Remove the new first element
Ì :Get the last value remaining
```
[Answer]
# Japt `-h`, 10 bytes
```
õ
£=éVn1¹v
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9QqjPelWbjG5dg==&input=NzcsOAotaA==)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytes
```
{¯1↓⍺⌽⍵}⍣{1=≢⍺}∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rQesNHbZMf9e561LP3Ue/W2ke9i6sNbR91LgIK1T7qmPGod/P/tEdtEx719j3qan7Uu@ZR75ZD640ftU181Dc1OMgZSIZ4eAb/N1RIUzDnMgKTxmDSECJkASKBPJCUoZExAA "APL (Dyalog Unicode) – Try It Online")
Takes input as `k f n`.
## Explanation
```
{¯1↓⍺⌽⍵}⍣{2=≢⍵}∘⍳
∘⍳ list from 1..n
⍣ (f⍣g) → apply f repeatedly till g is true
{¯1↓⍺⌽⍵} f: rotate list through k elements, drop last
{1=≢⍺} g: is the length = 1, for the previous iteration?
```
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 bytes
```
1+{⍺>1:⍺|⍵+⍵∇⍨⍺-1⋄0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///31C7@lHvLjtDKyBZ86h3qzYQP@pof9S7Aiiga/iou8Wg9n/ao7YJj3r7HnU1P@pd86h3y6H1xo/aJj7qmxoc5AwkQzw8g/8bKqQBNSmYcxnBGMYwhiFczgLKAIpBlRkaGQMA "APL (Dyalog Unicode) – Try It Online")
Recursive function.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
RṙṖ¥ƬṖṪ
```
[Try it online!](https://tio.run/##y0rNyan8/z/o4c6ZD3dOO7T02Bog9XDnqv@Hlyv9/x9trqOAQEBsaGQc@z/aUEfBSEfBGMgFsixAorEA "Jelly – Try It Online")
## How it works
```
RṙṖ¥ƬṖṪ - Main link. Takes n on the left and k on the right
R - Range; Yield [1, 2, ..., n]
¥Ƭ - Do the following to a fixed point and collect intermediate steps:
ṙ - Rotate k steps to the left
Ṗ - Remove the last element
Ṗ - Remove the empty list (the fixed point)
Ṫ - Return the single element left over
```
] |
[Question]
[
# Background
One of the commonly meme'd aspects of javascript is its incredibly loose type coercion that allows for `+!![]+[+[]] == '10'` this technique can also be used to create letters as seen in the following example:
```
[[][[]]+[]][+[]][-~[]] == 'n'
[undefined+[]][+[]][-~[]] // [][[]] -> undefined
['undefined'][+[]][-~[]] // undefined+[] -> 'undefined'
['undefined'][0][-~[]] // +[] -> 0
'undefined'[-~[]] // ['undefined'][0] -> 'undefined'
'undefined'[1] // -~[] -> -(-1) -> 1
'n'
```
Some examples of js coercions:
```
[][[]] = undefined // out of bounds array access returns undefined
+[][[]] = NaN // the unary + operator coerces to numbers +undefined is NaN
+[] = 0 // empty arrays coerce to the number 0
~[]/[] = -Infinity // ~ coerces any value to a number then does bitwise negation and / coerces the second value to a number
[]+{} = '[Object object]' // plus coerces both values into strings if it can't do numeric addition
![] = false // ! coerces empty arrays to false
!![] = true // negation of previous coercion
+!![] = 1 // number coercion of true
-~[] = 1 // ~ coerces [] to 0 and the bitwise negation of 0 is -1, -(-1)=1
true+[] = 'true' // adding an empty array to a primitive coerces it to a string
'true'[+[]] = 't' // strings are treated as arrays by js
'true'[-~[]] = 'r'
```
[Here's a reference table of js coercions using different operators](https://delapouite.com/ramblings/javascript-coercion-rules.html)
Note: blue shaded cells in the table are strings while yellow cells are literals.
# Task
Given a string with only the letters `abcdefijlnorstuy` , convert it to valid javascript containing only the characters `[]+-~/{}!` that evaluates to the original string. **Note that this is not JSFuck** but is instead focused purely on a subset of strings that can be (relatively) concisely translated.
# Input
Any lowercase string that can be written with the letters `abcdefijlnorstuy` (can include spaces)
# Output
Valid javascript containing only the characters `[]+-~/{}!` that will evaluate to the original word in a js environment.
# Examples
```
f('u') -> [[][[]]+[]][+[]][+[]]
f('a') -> [+[][[]]+[]][+[]][-~[]]
f('t') -> [-~[]/[]+[]][+[]][-~[]-~[]-~[]-~[]-~[]-~[]]
f('o') -> [[]+{}][+[]][-~[]]
f('l') -> [![]+[]][+[]][-~[]-~[]]
f('r') -> [!![]+[]][+[]][-~[]]
f('defined') -> [[][[]]+[]][+[]][-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]+[[][[]
]+[]][+[]][-~[]-~[]-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]-~[]-~[]]+[[][[]]+[]][
+[]][-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]]
f('aurora borealis') -> [+[][[]]+[]][+[]][-~[]]+[[][[]]+[]][+[]][+[]]+[!![]+[]][
+[]][-~[]]+[[]+{}][+[]][-~[]]+[!![]+[]][+[]][-~[]]+[+[][[]]+[]][+[]][-~[]]+[[]+{
}][+[]][-~[]-~[]-~[]-~[]-~[]-~[]-~[]]+[[]+{}][+[]][-~[]-~[]]+[[]+{}][+[]][-~[]]+
[!![]+[]][+[]][-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]+[+[][[]]+[]][+[]][-~[]]+[![]
+[]][+[]][-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]-~[]-~[]]+[![]+[]][+[]][-~[]-~[
]-~[]]
f('code tennis') -> [[]+{}][+[]][-~[]-~[]-~[]-~[]-~[]]+[[]+{}][+[]][-~[]]+[[][[]
]+[]][+[]][-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]+[[]+{}][+[]][-~[]-~[]-~[]-~[
]-~[]-~[]-~[]]+[-~[]/[]+[]][+[]][-~[]-~[]-~[]-~[]-~[]-~[]]+[[][[]]+[]][+[]][-~[]
-~[]-~[]]+[[][[]]+[]][+[]][-~[]]+[[][[]]+[]][+[]][-~[]]+[[][[]]+[]][+[]][-~[]-~[
]-~[]-~[]-~[]]+[![]+[]][+[]][-~[]-~[]-~[]]
f('js bad') -> [[]+{}][+[]][-~[]-~[]-~[]]+[![]+[]][+[]][-~[]-~[]-~[]]+[[]+{}][+[
]][-~[]-~[]-~[]-~[]-~[]-~[]-~[]]+[[]+{}][+[]][-~[]-~[]]+[+[][[]]+[]][+[]][-~[]]+
[[][[]]+[]][+[]][-~[]-~[]]
f('obfuscate') -> [[]+{}][+[]][-~[]]+[[]+{}][+[]][-~[]-~[]]+[[][[]]+[]][+[]][-~[
]-~[]-~[]-~[]]+[[][[]]+[]][+[]][+[]]+[![]+[]][+[]][-~[]-~[]-~[]]+[[]+{}][+[]][-~
[]-~[]-~[]-~[]-~[]]+[+[][[]]+[]][+[]][-~[]]+[-~[]/[]+[]][+[]][-~[]-~[]-~[]-~[]-~
[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]
```
# Rules
Lowest byte count wins.
The solution can be written in any language, but the generated code must evaluate in either chrome, firefox, or a node.js repl.
Don't abuse any common loopholes.
[Answer]
# JavaScript (ES6), ~~139~~ 135 bytes
```
s=>[...s].map(c=>`[{},!![,[][[],![,~[]/[`.split`,`.some(s=>i=~eval(S=`[${s}]+[]][+[]]`).search(c))&&S+`[${'-~[]'.repeat(~i)}]`).join`+`
```
[Try it online!](https://tio.run/##XY/BbsMgDIbveQoqTQWUlD3AlNz6BD0yJFzqbEQUIkgqTVX66pmzbpcdPsv@f9uyB7hBcdmP0yGmC659u5a200qpYtQVRuHazur70ux2utFGa9NQ8tDmVVtVxuAn21CSrihozrcPvEEQp9bql3tZTK2N0VuwUhWE7D6Fk3K/P9VbAz/QIq4yjgiTeHi5bH1D8tHWdn3TFWN85g0HYiISEYhMfPFmsy/Y@4iXZwFzThnYOWWE4MtTdPQWmzDGP2Eo7Ay/E@ncz8XBhLwylepTPgKdWFjbsTv5LsWSAqqQPkRGklkvipT/nJ@XyZasZvw9clktcv0G "JavaScript (Node.js) – Try It Online")
### How?
The following code snippets are used:
```
code | string | used for
------------------+-------------------+-------------------------------------
[[{}]+[]][+[]] | '[object Object]' | space, 'b', 'c', 'e', 'j', 'o', 't'
[!![]+[]][+[]] | 'true' | 'r', 'u'
[[][[]]+[]][+[]] | 'undefined' | 'd', 'f', 'i', 'n'
[![]+[]][+[]] | 'false' | 'a', 'l', 's'
[~[]/[]+[]][+[]] | '-Infinity' | 'y'
```
We pick the appropriate character in the resulting string with `[-~[]-...-~[]]`.
We can't access index \$0\$ this way, so we make sure that the snippets are ordered in such a way that this is never required. For instance, '*u*' is taken from '*true*' rather than from '*undefined*'.
[Answer]
I have a solution which works if you have infinite time and memory. I'm not 100% sure whether that's allowed within the rules here; I searched on [codegolf.meta.SE](https://codegolf.meta.stackexchange.com/) and didn't find anything saying that code-golf answers have to run in a reasonable length of time using a reasonable amount of memory. I also didn't find it forbidden in the "common loopholes" thread. If it makes my solution invalid, please let me know.
# JavaScript (ES6), ~~112, 110, 107~~ 106 bytes
```
s=>{for(q=[''];;c=q.shift(),q.push(...[...'[]+-~/{}!'].map(x=>c+x)))try{return eval(c)===s?c:d}catch(e){}}
```
It isn't restricted to string inputs, and can find short solutions in reasonable times, but unfortunately it's not feasible to solve for non-empty strings, even just single-characters like `'o'`. Here it is working on some inputs for which it is feasible.
```
> f(0)
"+[]"
> f(1)
"-~[]"
> f(-1)
"~[]"
> f(true)
"!+[]"
> f(false)
"![]"
> f('')
"[]+[]"
```
### How?
It's a breadth-first search. `q` is the queue, `c` is the current string. The breadth-first search algorithm will iterate through every possible string formed from the given alphabet, in order of length, so if a solution exists, it will be found.
We try evaluating `c` with the `eval` function, and return it if it evaluates to `s`. This comparison is done with `===` to avoid e.g. returning `+[]` which evaluates to 0 when we're looking for an expression which evaluates to the empty string. The variable `c` is uninitialised on the first iteration of the loop, but that's OK because it's only used within the `try` block.
We need `try`/`catch` because most candidate strings have syntax errors; as a bonus, instead of guarding the `return` with an `if` statement, we can return the non-existent name `d` because the error will get caught, allowing the loop to continue searching. This saves one byte, but it means the function stops working if you declare a variable named `d`, which is mildly amusing.
[Answer]
# [Python 2](https://docs.python.org/2/), 125 bytes
Using a single code snippet.
```
print[]
for c in input():print'+[{}+!![]+![]+~[]/[]+[][[]]][+[]]['+'-~[]'*(ord('#2??;"?4?9 &?/5%03!$B'[ord(c)%59%21])-31)+']'
```
[Try it online!](https://tio.run/##HYlBCsIwFET3niKJxt8YSm1qF9VFwGt8/qK2igVJSmwXInr1mAozzGPe@Jru3pkYxzC4CWl184F1bHAp4zxl6vgXoPH90Zwj6aVfpCINEiIRYQJC0JCnH3aZD30Ga2PtSdiDbdjWFrXcV3xzBlxcp2TdSFOSyqtSaSCIUbRz8KFlFx@u7WN4ivgD "Python 2 – Try It Online")
[Try the output in JS!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvE/OpZLO7q6VltRMTpWG4TromP1gVR0bHR0bGxsNJARG60LFKQmpped9LCHWDsGk1sGU1ySon@oh/VwzmuDxd7B6qbY/5r/AQ)
---
# [Python 2](https://docs.python.org/2/), ~~167~~ 150 bytes
*Saved 2 bytes thanks to @JonathanAllan*
```
print[]
for c in input():i=ord(".@C1A83J42/K70DIY"[ord(c)*91%211%23]);print'+['+"[{} !![ [][[] ![ ~[]/[".split()[i/9-5]+']+[]][+[]]['+'-~[]'*(i%9)+']'
```
[Try it online!](https://tio.run/##HUxRC4IwGHzvV8yBzDnUnEVZBEW9VL8gPr4Hs6KBuDH1IaL@@lrC3XHcHWde/VO30jljVdsDTh7akpqo1sMMfcRXaqPtLaLpdp/vlsVpJrPzYno4Xij885rHZR7K3LNAvh5fmAAmKLw/JAiAAAIg8eYLmAFNO9Mo/wsqK5M5CoYCEGEUJljiVyyOVFhyXzHnaDVYbSty1fZeNaqj7gc "Python 2 – Try It Online")
[Try the output in JS!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvE/OpZLO1oxOlY7OjY2Gkzo1gFJkCCGKG4ZkGh0dS1RpuC0ENMAXBi3alIdgt9O3GGDK2iiY4GIgC9wGgCW/K/5HwA)
### How?
This is based on the same code snippets as [my JS answer](https://codegolf.stackexchange.com/a/198474/58563), but a lookup string is used to retrieve the snippet ID and the position of the character.
Given the ASCII code \$c\$ of the character to be converted, the position in the lookup string is given by:
$$i=((c\times91)\bmod211)\bmod23$$
Given the ASCII code \$n\$ of the \$i\$-th character in the lookup string `".@C1A83J42/K70DIY"`:
* the snippet ID is \$\lfloor(n-45)/9\rfloor=\lfloor n/9\rfloor-5\$
* the position of the character is \$(n-45)\bmod9=n\bmod9\$
This is summarized in the following table.
```
char. | ASCII code | -45 | //9 | mod 9 | character lookup | output
-------+------------+-----+-----+-------+----------------------+--------
'.' | 46 | 1 | 0 | 1 | '[object Object]'[1] | 'o'
'@' | 64 | 19 | 2 | 1 | 'undefined'[1] | 'n'
'C' | 67 | 22 | 2 | 4 | 'undefined'[4] | 'f'
'1' | 49 | 4 | 0 | 4 | '[object Object]'[4] | 'e'
'A' | 65 | 20 | 2 | 2 | 'undefined'[2] | 'd'
'8' | 56 | 11 | 1 | 2 | 'true'[2] | 'u'
'3' | 51 | 6 | 0 | 6 | '[object Object]'[6] | 't'
'J' | 74 | 29 | 3 | 2 | 'false'[2] | 'l'
'4' | 52 | 7 | 0 | 7 | '[object Object]'[7] | ' '
'2' | 50 | 5 | 0 | 5 | '[object Object]'[5] | 'c'
'/' | 47 | 2 | 0 | 2 | '[object Object]'[2] | 'b'
'K' | 75 | 30 | 3 | 3 | 'false'[3] | 's'
'7' | 55 | 10 | 1 | 1 | 'true'[1] | 'r'
'0' | 48 | 3 | 0 | 3 | '[object Object]'[3] | 'j'
'D' | 68 | 23 | 2 | 5 | 'undefined'[5] | 'i'
'I' | 73 | 28 | 3 | 1 | 'false'[1] | 'a'
'Y' | 89 | 44 | 4 | 8 | '-Infinity'[8] | 'y'
```
[Answer]
# Prolog (SWI), 269 bytes
It's not a particularly short solution, but made this challenge interesting because it is able to use backtracking to automatically select which string and index into that string to use for each character.
```
`fals`^`![]+[]`.
`[object `^`[]+{}`.
`und`^`[][[]]+[]`.
`-Infinity`^`~[]/[]+[]`.
`tr`^`!![]+[]`.
[]-`[]`.
[H|T]-S:-B^C,nth0(I,B,H),length(L,I),foldl([_,V]>>append(`-~[]+`,V),L,` +[]`,J),T-U,append([`[`,C,`][+[]][`,J,`]+`,U],S).
S/W:-S+A,A-B,W+B.
A+B:-string_codes(A,B).
```
[Try it online!](https://tio.run/##ZVJNb@MgFLz7V7C@BJSHveeoihRXrZqqUg7ul8S6Bds4sZcFC3CraLf717M4TaMoe@K9mTcDDJTCbXaV8BcXk6vV9QTNkZfOJ73a8UYox1/4N1ZMWcGTiDNTdrLyKIAB@/0xYoOu9y1jxdcYXeqm1a3fBuIvK9Kj3tvR7ujHCso/i5s/9wXNZzR7uQTtN9/xEjK4IaCkXvsNvoMlgcaoWmH2Co/FfC76Xuoacxr8pxweCdwBR6Mt3BK4pw9wmGCccbgEXrBAFqG@DXVQPBSQkyTK06cZzacLWNAMnqZZEi2m2Yw6b1u9fq1MLR1eQEaS3ZhKOBZaETSjaJnmgN5t6yVeAYoro51RMlFmjWNywuSnTUx@6DhsGnKOUtP7tLcmKKh7b9Oy1WlYe/UVf3iItJZvqR6U@pzuxJtwlW17T13f1tL@Mvqn3O6lnUNm8P3gk87tTLg5nhz7ySELeCYQob0/jkVZ1bJpO6S0sc4P2xjQKT@SWtZnqBissQKVxkqhWnfGjnGFUuv/mHC8UpybmbIZXPh58oBXyjiJn0mCkugf "Bash – Try It Online")
# Ungolfed Code
```
% Declaration of strings we can generate with their corresponding JS.
base_str(`undefined`,`[[][[]]+[]][+[]]`).
base_str(`[object Object]`, `[]+{}`).
base_str(`Infinity`, `[-~[]/[]+[]][+[]]`).
base_str(`NaN`, `[+[][[]]+[]][+[]]`).
base_str(`true`, `!![]+[]`).
base_str(`false`, `![]+[]`).
% Construct JS used to index into strings
wtf_index(0,`+[]`).
wtf_index(1,`-~[]`).
wtf_index(N, S0) :-
N > 1,
wtf_index(1, S1),
M is N - 1,
wtf_index(M, S2),
append([S1,`+`,S2],S0).
% Construct JS used for single char
wtf_char(C, WC) :-
% Find known string with desired character at some index
base_str(S, WS),
nth0(I, S, C),
% JS for this index
wtf_index(I, WI),
% JS to select index from string
append([`(`,WS,`)[`,WI,`]`],WC).
% Map wtf_char over string, reducing to single string
wtf_list([], `[]`).
wtf_list([H|T], WS) :-
wtf_char(H, WH),
wtf_list(T, WT),
append(WH, [0'+|WT], WS).
wtf_str(S, W) :-
string_codes(S, SC),
wtf_list(SC, WC),
string_codes(W, WC).
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 104 bytes
```
s=>[...s].map(c=>(p=`[{}+!![]+![]+~[]/[]+[][[]]][+[]]`)+`[${'-~[]'.repeat(eval(p).search(c))}]`).join`+`
```
[Try it online!](https://tio.run/##XY/RasQgEEXf8xUuFFSyaz@gJG/9Cis4MZM2IaviJAslpL@eznbblz4cdO5x4DrBDSiUMS@XmHo8huagprXGGHLmClmFplW58Xbb69PJuvrOl3XPfFhnrXPO8sV5XXv7tMkLO2kKZoRF4Q1mlbUhhBI@VNB654dmSmP0tT9ebCWEXOVZArMwiZmZwnzK8133OIwR@8cAa0kFRJcKwjzSIwzcWywY418wkejgdyN1w0oBFpSVq8yQyitwExJNKzb2IUVKM5o5vauCHItBkdb/zM8/WGtRC/kWpa52fXwD "JavaScript (Node.js) – Try It Online")
**Explanation**
Each letter is converted to a string of the form
```
[{}+!![]+![]+~[]/[]+[][[]]][+[]][x]
```
Where `x` is a number of `-~[]`
`[{}+!![]+![]+~[]/[]+[][[]]][+[]]` evaluates to the string `[object Object]truefalse-Infinityundefined`, which contains all of our letters. We then index into it by using this snippet:
```
`[${'-~[]'.repeat(eval(p).search(c))}]`
```
It evaluates `[{}+!![]+![]+~[]/[]+[][[]]][+[]]` (stored in variable p), then finds the first index of the current letter we are processing. We repeat the string `+~-[]` (evaluates to 1) that number of times. That is wrapped around with square brackets, and appended to `p`.
Finally, everything is joined with `+`.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 156 bytes
```
x=>string.Join('+',x.Select(l=>"[{}+!![]+![]+~[]/[]+[][[]]][+[]]["+new StringBuilder().Insert(0,"-~[]",$"[object {0,8}ru fals{0,9}y nd fi".IndexOf(l))+"]"))
```
[Try it online!](https://tio.run/##TY0xT8MwEIVn@iuuFlJtJQ0di0o7MCCBkBg6MFgeHOcMrixbsh0IisJfD3azMNy7d09336m4VdHMT71TDzEF4z7qpZ30cR6Op2VoXrxxdFNt6qE5o0WVqD2eCB@nar3moir1y8VdblxwLoTg2QhOKoffcL4yHntjOwyUNc8uYkh0V5NtPiL1LeG@vWQojLt6P4UetLQx@/vpB1wH2pB80@HwpqllrCKCMDYfVtoHlOqTfskACWMC4yD/42IEIkkNJBXxRWyRUKRDbRx2xco@@CChLRhrYomU7zCznFvGS4RWXnd9q/uoZEIyMRhXN@/BJHzNJFo@s8P/RC9ZDqf5Dw "C# (Visual C# Interactive Compiler) – Try It Online")
**Explanation**
Each letter is converted to a string of the form
```
[{}+!![]+![]+~[]/[]+[][[]]][+[]][x]
```
Where `x` is a number of `-~[]`
`[{}+!![]+![]+~[]/[]+[][[]]][+[]]` evaluates to `[object Object]truefalse-Infinityundefined`, which contains all the letters. We index into the string `$"[object {0,8}ru fals{0,9}y nd fi"`, which expands to
```
[object 0ru fals 0y nd fi
```
We take the current letter and get the first index of it in that string. We then repeat the string `-~[]` that number of times, and replace the `x` with that.
Repeating a string is rather verbose in C#, as there is no builtin for it. Instead, a `StringBuilder` is created, and taking advantage of the `StringBuilder.Insert(int, string, int)` overload (which inserts the string `n2` times at index `n1`) to created a `StringBuilder` containing a repeated string. It is implicitly converted to a string due to the magic of the `+` operator.
```
new StringBuilder().Insert(0,"+-~[]",$"[object {0,8}ru fals{0,9}y nd fi".IndexOf(l))
```
Finally, the converted strings are joined together with `+`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 95 bytes
```
≔⪪“<≦ω≕ε…(Bς´B⌈YWγ№Φξ⌕IY¦l ”,ηFS«≔⊟Φ⁵№§ηκιζ⊞υ⪫[]⁺⁺§⪪“"∧|⌊AuüQ⁷~⊙<⁷≕u?ψμ”,ζ×+[]][²×-~[]⌕§ηζι»⪫υ+
```
[Try it online!](https://tio.run/##TY/LasMwEEXX8VeoWo2IQqHQVVehEEhXhnQnaeHYTqxUHRk9SuuQ/Lo7Me4DNFdwZ3TnqO6qUPvKjeM6RntE2PXOJuAaNTZSY@UiachSa8SDvdkav8jy@1NbJ8YlHS4k68RTcfCBwRb7nHYpWDyCEOxcLObk0vewsS61AR4le/YZE6zTFpv2EzrJ3ijECkE6UNSizLGDLNmLtwhcGVpUuhxhkp9nM6wyShkj7xTVTa7K3NN1vvzSDVSv9r2NwJc0qqjxIP681XVasLHY/EcaZiTiuRQl/SjBhENYfMnJHsdTZPuqKcbVh/sG "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪“<≦ω≕ε…(Bς´B⌈YWγ№Φξ⌕IY¦l ”,η
```
Split the compressed string `"\n\nd,\nals,\nru,\\nnfi\n\n\ny,\nobject "` on commas. This is the array `["undefined", "false", "true", "Infinity", "[object Object]"]` keeping only the space and unique letters and truncated at the last remaining letter to improve the compression.
```
FS«
```
Loop over the input string.
```
≔⊟Φ⁵№§ηκιζ
```
Find the entry that contains the current input character.
```
⊞υ⪫[]⁺⁺§⪪“"∧|⌊AuüQ⁷~⊙<⁷≕u?ψμ”,ζ×+[]][²×-~[]⌕§ηζι
```
Split the compressed string `"[][[]],![],!![],~[]/[],{}"` on commas and take the matching entry, then concatenate it with `"+[]]["` doubled and a suitable number of repetitions of `"-~[]"` before finally wrapping everything inside a final set of `[]`.
```
»⪫υ+
```
Join everything together with `+`s.
] |
[Question]
[
## Background
[**Set**](https://en.wikipedia.org/wiki/Set_(card_game)) is a card game. The deck consists of 81 unique cards that vary in four features: number of shapes (one, two, or three), shape (diamond, squiggle, oval), shading (solid, striped, or open), and color (red, green, or purple).
For convenience, let's write a card as a 4-tuple of numbers from 1 to 3, e.g.
* `1111` = one red solid diamond
* `1122` = one red striped squiggle
* `1223` = one green striped oval
* `2312` = two purple solid squiggle
Given several cards (usually 12), the objective of the game is to find a "set" of three cards such that
* They all have the same number or have three different numbers.
* They all have the same shape or have three different shapes.
* They all have the same shading or have three different shadings.
* They all have the same color or have three different colors.
i.e. the cards are either **all the same or all different in each of the four features**.
Here are some examples of sets:
```
1111, 1112, 1113
1111, 2222, 3333
2312, 3321, 1333
```
Here are some examples of non-sets:
```
1111, 1122, 1123
2131, 3221, 1213
```
A [**cap set**](https://en.wikipedia.org/wiki/Cap_set) is a collection of cards that doesn't contain any Set. It was proven in 1971 that [the maximum number of cards without a Set is 20.](https://www.quantamagazine.org/set-proof-stuns-mathematicians-20160531) Interestingly, finding the largest cap set for the generalized game of Set is still an open problem in mathematics.
The Wikipedia page shows an example of 20-cap set, and here is the 20 cards in the number notation:
```
1111, 1113, 1131, 1133,
1312, 1332, 1321, 1323,
3311, 3313, 3331, 3333,
3112, 3132, 3121, 3123,
1222, 2122, 2322, 3222
```
There are 682344 20-cap sets in total, but under affine transformations on 4-dimensional finite space, they all reduce to essentially one cap set.
## Task
Output any of the 20-cap sets in the game of Set.
## Input and output
Your program/function is not allowed to take input.
The output is a collection (list, set, ...) of 20 cards which is a cap set. Each card should be represented as a 4-tuple (or equivalent ordered collection) whose elements are one of three distinct values (not necessarily 1, 2, 3). Flexible output applies in the following ways:
* Nested or flattened list
* Ordering of cards doesn't matter
* You may choose to output the same set or different set across runs
* For string/text output, it's fine as long as we can clearly identify the structure (20 chunks of four items) of the output
[Verification script example in Python](https://tio.run/##VZFNjoMwDIX3nMKsClVGKvGuUrY9QXcIjVJ@1EiQoCSVgMszdmhnNCw@2X5@jmXmNT6dxX0fvJvAxN5H58YAZpqdj@es6wcYilb7LpTXDAbnQYuHaMFYaN30MFZH42w4WgQgd4EJ36GPoODuXz3lbFvEKja2bWYu0ozUCmaARak1VxtQ16rUlquFw02pJVfr9W/aTY@Bx5HlqF3B9/Hl7Ud5Z/zqnhYiU12fJz0XxkYBIfpiKcvmWIiXqWlcRZ9gIhNTjChYwUpShpgoq8SkILKHiExM8eEhgbpJSGQP8ZgmJdVklYhMgsyaJps9rVd87gzadjD29p0qJS@pdLo/Df2ZABrk5avVM9AJTnyqX8W6@F8t9x8) using the example shown above.
## Scoring and winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest valid code in bytes wins.
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
tail[t|t@[a,b,c,d]<-mapM(:[1,2])[0,0,0,0],mod(a*a+b*b+c*d)3<1]
```
[Try it online!](https://tio.run/##HcJBDkQwFADQq3RhQX3JMDshcQEn6HTx2xoavzR06ey@RN5b8FwnIqb@xwk9qXSlQSEYsOB0VwWMY96qGhpdqA@8NITd5SixNNKUVrri29WaA/pN9CIefksiE8S3/RPOJ1c2xgc "Haskell – Try It Online")
Defines a cap-set as all \$(a,b,c,d)\$ from \$\{0,1,2\}^4\$ where $$a^2+b^2+cd=0\bmod3,$$ except not \$(0,0,0,0)\$.
I found this formula by looking at [Wikipedia's example](https://en.wikipedia.org/wiki/Cap_set#/media/File:Set_isomorphic_cards.svg) and coming up with progressively simpler formulas linking the allowed inner coordinates \$(a,b)\$ to the outer coordinates \$(c,d)\$.
---
# [Haskell](https://www.haskell.org/), 46 bytes
```
[t|t<-mapM(:"12")"0000",sum[1|'0'<-t!!0:t]==2]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfYxvzP7qkpsRGNzexwFfDSsnQSElTyQAIlHSKS3OjDWvUDdRtdEsUFQ2sSmJtbY1i/@cmZuYp2CoUFGXmlSioKOT8/5eclpOYXvxfN7mgAAA "Haskell – Try It Online")
This uses a modified condition giving a different but equivalent cap set:
$$a^2+b^2+c^2 - d^2=0\bmod3,$$ still without \$(0,0,0,0)\$.
This is equivalent to \$a^2+b^2+c^2 + d^2 + d^2 =0\bmod3,\$, so we can duplicate an element and check that the give-element list of squares adds to zero modulo 3. Since squares modulo 3 are 0 or 1, this is further equivalent to this condition:
>
> There are exactly \$2\$ zeroes among \$[a,b,c,d,d]\$.
>
>
>
This automatically excludes the all-zero point. Of course, duplicating $d$ was arbitrary -- choosing another element gives a different but equivalent cap-set.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~13~~ ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2Ý4ãʒĆ0¢<
```
Port of the found formula of *@xnor*, as mentioned in [his comment](https://codegolf.stackexchange.com/questions/195685/20-cards-with-no-set#comment465676_195685) as well as his [Haskell answer](https://codegolf.stackexchange.com/a/195689/52210), so make sure to upvote him!
-2 bytes by using *@xnor*'s updated formula (thanks for letting me know).
-2 bytes thanks to *@xnor* again by simply counting whether there are exactly 2 zeroes in \$[a,b,c,d,a]\$.
Also outputs a list of lists with values in the range \$[0,3]\$.
[Try it online.](https://tio.run/##yy9OTMpM/f/f6PBck8OLT0060mZwaJHN//8A)
**Explanation:**
Will leave quartets \$[a,b,c,d]\$ for which there are exactly 2 zeroes in the list \$[a,b,c,d,a]\$.
```
2Ý # Push the list [0,1,2]
4ã # Create all possible quartets using the values in this list
# by taking the cartesian power of 4
ʒ # Filter the remaining quartets by:
Ć # Enclose the quartet; appending its own head: [a,b,c,d] → [a,b,c,d,a]
0¢ # Count the amount of 0s in this list
< # And decrease it by one
# (Since only 1 is truthy in 05AB1E, the filter with count(0)-1 will only
# leave quartets where the [a,b,c,d,a].count(0) is exactly 2)
# (after which the filtered list is output implicitly as result)
```
[Answer]
# JavaScript (ES6), ~~73~~ 67 bytes
```
_=>[...'11138272726454626454'].map(i=>3333-(t-=i).toString(3),t=80)
```
[Try it online!](https://tio.run/##HcTRCoMwDEDRzzEBG@zqnC/xJ3wcMopT6dBGavD3q@weuD9/@mNMYVcT5TvlmfOHuzcRFdZa1z5et6Z@1s3/xUCb3yFw5@4MqOGApNJrCnEBh6VyW2EeJR6yTrTKAjMg5gs "JavaScript (Node.js) – Try It Online")
Outputs the following set, as an array of integers:
```
1112, 1113, 1121, 1131, 1223, 1232, 1323, 1332, 2123, 2132,
2222, 2233, 2322, 2333, 3123, 3132, 3222, 3233, 3322, 3333
```
[Test it online!](https://tio.run/##VZFNjoMwDIX3nMKsClVGKvGuUrY9QXcIjVJ@1EiQoCSVgMszdmhnNFlYz/b3jEnmNT6dxX0fvJvAxN5H58YAZpqdj@es6wcYilb7LpTXDAbnQYuHaMFYaN30MFZH42w4EAHIFJjwHfoICu7@1VPOtkWsYmPbZuYizUgomAEWpdZcbUDUqtSWq4XlptSSq/X6N@2mx8DjyHLUruD7@PL203ln/NU9LUSmuj5Pei6MjQJC9MVSls2xEC9T07iqqqTgiBxlxRE5SskVidzFpJG1rFhLKglySzqUSeQaJo2sMVHIFGBiMDGYGEIwa5ps9rRY8blh0LaDsbfvVCl5SaXT/WnoTQJokJevVs9AP3/iS/rtWBf/d8v9Bw)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~46~~ 36 bytes
```
{grep *[0,^*].Bag{0}==2,[X] ^3 xx 4}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAQSvaQCdOK1bPKTG92qDW1tZIJzoiViHOWKGiQsGk9n9xYqVCmobmfwA "Perl 6 – Try It Online")
Uses [xnor's *updated* formula](https://codegolf.stackexchange.com/a/195689/76162).
### Explanation:
```
{ } # Anonymous code block
grep # Filter from
,[X] # The cross product of
^3 xx 4 # 0,1,2 four times
*[0,^*] # Duplicating the first element
.Bag{0} # Where the number of zeroes
==2 # Is equal to 2
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21~~ 19 bytes
*-2 bytes thanks to Bubbler*
```
((3=1⊥5⍴×)¨⊆⊢),⍳4/3
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGIBaQ1tAwtjV81LXU9FHvlsPTNQ@teNTV9qhrkabOo97NJvrG//8DAA "APL (Dyalog Unicode) – Try It Online")
This uses [xnor's formula](https://codegolf.stackexchange.com/a/195689/76162), finding all cards from the permutation that when the first attribute is duplicated, has exactly 2 zeroes (this code being 0-indexed). The output is slightly weird, since some cards are grouped together, but you can still make out the individual cards.
### Explanation
```
,⍳4/3 ⍝ Generate all length 4 permutations of 0,1,2
( )¨ ⍝ For each permutation, e.g 0,1,2,1
× ⍝ Get the sign, e.g 0,1,1,1
5⍴ ⍝ Reshape to size 5 e.g 0,1,1,1,0
1⊥ ⍝ Base 1 (or sum) e.g 3
3= ⍝ Is equal to 3 e.g 1
⊆⊢ ⍝ And partition the ones that return true
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~78..52~~ 49 bytes
```
"U
".bytes{|r|p ($.+=r).to_s 4}
```
[Try it online!](https://tio.run/##KypNqvz/XymUiY2Jm4eZiVlGQQZI8nAD@Up6SZUlqcXVNUU1BQoaKnratkWaeiX58cUKJrX//wMA "Ruby – Try It Online")
### How
The sequence can be DPCM-encoded.
If we consider a card as a single base-4 integer (1111 through 3333), we can take any sequence, sort it, and use a single ASCII character to encode the difference between successive elements. The first character represents the first value of the sequence. All values are relatively small, and the decoding is still simple enough to be golfed.
Thanks Value Ink for -3 bytes ("to print the unprintable")
In theory, with a different encoding, every value can be encoded as a single byte, and this would bring the byte count down to 43, but with UTF-8 it's impossible (or at least, I can't figure it out).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
UB0E²⁰⮌⍘Σ…”)″&:igK⁶Mψ”ι³
```
[Try it online!](https://tio.run/##HYlBCoMwEADvfUXIaQMpSJKD4E3PQmlesMRFpamRGIW@fhscGBiYsGAOCSOzp9Jj@Mw5ndsEspGqe7zyuhUYcQfTaPGmi/JB0ONBvtQ1gz@/MPxCpGFJO8jWOlt1xhh3l22lFqtSWlhV6Zj5ecU/ "Charcoal – Try It Online") Link is to verbose version of code. Outputs the given set, but with digits decremented and sorted in order of reverse of string. Explanation:
```
UB0
```
Pad all lines to the same length using `0`.
```
E²⁰
```
Loop `i` from 0 to 19 and implicitly print each result on its own line.
```
⮌⍘Σ…”)″&:igK⁶Mψ”ι³
```
Convert the digital sum of the `i`th prefix of the compressed string `8343834422244383438` to base 3 and print it backwards.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
print eval('[[a,b,c,d]'+'for %s in 0,1,2'*4%tuple('abcd')+'if(a*a+b*b+c*d)%3<1]')[1:]
```
A full program which performs [xnor's algorithm](https://codegolf.stackexchange.com/a/195689/53748).
**[Try it online!](https://tio.run/##BcFLCoAgEADQq7iR8TOLrFbRTcTF@ImEMCkLOr29V7@2n2XsvV65NJZeOgRYS@gxYHSgYTsvxm@WCxvQ4Ahq5u2pRxJAPkSQGvImSJH2yuugouTTahxIaxbX@w8 "Python 2 – Try It Online")**
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
for c in"P}nF-Z>a9*)V=.Q":n=ord(c);print n/50,n%3,n%4,n%5
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFZITNPKUCkNk/STTdK0C5RzFJLM8xWL5BNySrPNr8oRSNZ07qgKDOvRCFP39RAJ0/VGIhNgNj0/38A "Python 2 – Try It Online")
Using ideas from Bubbler and Jo King, we can cut a few bytes from the below. The decompression method `n/50,n%3,n%4,n%5` turns an ASCII value into a 4-tuple. While not every set can be obtained this way using `n` from 0 to 127, there's enough wiggle room in the choice of cap-set to find one within the obtainable subset. We also avoid problematic characters that need escaping such as `\0` or `\n`, though unprintables can't be avoided.
---
**[Python 2](https://docs.python.org/2/), 65 bytes**
```
for c in'RSTW_ahjq"(,15;=CGLP':print[ord(c)/B%3for B in 27,9,3,1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFZITNPPSg4JDw@MSOrUElDx9DU2tbZ3SdA3aqgKDOvJDq/KEUjWVPfSdUYpNwJqFzByFzHUsdYxzD2/38A "Python 2 – Try It Online")
String compression looks like the way to go for Python. We compress each of the 20 elements as a value from 0 to 80, which we represent as a character. Since we only need the values to be correct modulo 81, we can keep the string within the printable ASCII range. Python 3 could save a few bytes using a bytestring.
An alternative compression method would be 81 bits marking which of the 81 cards are present. Even though the 81 bits needed for this are less than the \$20 \log\_2(81)\approx 127\$ bits for the method used, the latter [wins out easily](https://tio.run/##FcYxCoAwDADAr2SpKAhNUsW49CPi4GC1S5TioK@Puhx3Ptd@KJudJes1Tep5aNWPLnyGXxfmdBRQyApl0W2thZqcAG8iFGFh/tIjC3XYrTFqRbPZCw) for how concisely the string can be written and decoded.
For comparison, here's a solution using [the formula I found](https://codegolf.stackexchange.com/a/195689/20260).
**79 bytes**
```
n=81
while n:
t=a,b,c,d=n/27,n/9%3,n/3%3,n%3;n-=1
if(a*a+b*b+c*d)%3<1:print t
```
[Try it online!](https://tio.run/##FcRLCoAgFADAvadwI5Qaoi4qy8P4KRTiJSFEp7eaxZSnphNUa2Anie6Ujw2DQbhaxz0PPFoQauQgZqK/9T/RCwxWIpz3zlHHPPUs0NgTvUpTrgwV19Ze "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 using more of xnor's ideas
```
3ṗ4ṁ5ỊS⁼ʋƇ2
```
A niladic Link which yields a list of lists of integers.
**[Try it online!](https://tio.run/##AR4A4f9qZWxsef//M@G5lzThuYE14buKU@KBvMqLxocy//8 "Jelly – Try It Online")**
### How?
Cards being `[a, b, c, d]` where \$a,b,c,d \in [1,3]\$ this method picks cards for which there are exactly two `1`s in `[a, b, c, d, a]`.
```
3ṗ4ṁ5ỊS⁼ʋƇ2 - Link: no arguments
3 - literal three
4 - literal four
ṗ - (implicit range(x)) Cartesian power -> [[1,1,1,1],[1,1,1,2],...,[3,3,3,3]]
2 - set the right argument to two
Ƈ - filter keep if:
ʋ - last four links as a dyad:
ṁ5 - mould like 5 ([a,b,c,d] -> [a,b,c,d,a])
Ị - insignificant? (abs(x)<=1) (vectorises)
S - sum
⁼ - equals (2)?
```
---
Previous
```
3ṗ4Ṗ2œ?ḋƊ3ḍƊƇ
```
A niladic Link which yields a list of lists of integers.
**[Try it online!](https://tio.run/##ASIA3f9qZWxsef//M@G5lzThuZYyxZM/4biLxooz4biNxorGh/// "Jelly – Try It Online")**
### How?
A method which works in a similar vein as [xnor's](https://codegolf.stackexchange.com/a/195689/53748).
With cards being `[a, b, c, d]` where \$a,b,c,d \in [1,3]\$ this method picks cards for which \$3 \mid (a^2+b^2+2cd)\$ (except `[3,3,3,3]`)
```
3ṗ4Ṗ2œ?ḋƊ3ḍƊƇ - Link: no arguments
3 - literal three
4 - literal four
ṗ - (implicit range(x)) Cartesian power -> [[1,1,1,1],[1,1,1,2],...,[3,3,3,3]]
Ṗ - pop off the rightmost (remove [3,3,3,3])
Ƈ - filter keep those for which:
Ɗ - last three links as a monad:- i.e. f([a,b,c,d])
Ɗ - last three links as a monad - i.e. g([a,b,c,d]):
2 - literal two 2
œ? - nth permutation [a,b,d,c]
ḋ - dot product a*a+b*b+c*d+d*c
3 - literal three 3
ḍ - divides? (a*a+b*b+c*d+d*c)%3 == 0?
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 32 bytes
Just an inefficient Brachylog answer passing by, both in speed and bytes. But it works in the generalized case and will give every possible set if you let it run several years!
```
l₂₀{l₄ℕᵐ<ᵛ³}ᵐ{cᵐ≠&}¬{⊇l₃\{=|≠}ᵐ}&≜
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@dR20zTahBp8qhl6sOtE2webp39qG2acS2QnQzEjzoXqB1aU/2oqz3nUVNzTLVtDVAEJFmr9qhzzv//Uf8B) … or don't; this will just give you a 5 cap set, the maximum for TIO's time limit. The version uses up/down arrows for ease of use. First number is size of cap set, second is number of properties per card, and third is variations of each property. The 6 cap set I found locally: `[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 0]]`.
### How it works
```
l₂₀{l₄ℕᵐ<ᵛ³}ᵐcᵐ≠&¬{⊇l₃\{=|≠}ᵐ}&≜ (the implicit input we are looking for)
l₂₀ is a list of 20 cards,
{ }ᵐ where each card
l₄ has 4 elements,
ℕᵐ numbers >= 0 – to be precise
<ᵛ³ that are also lower than 3
(so [0,0,0,0] up to [2,2,2,2])
cᵐ if each card is concatenated to a string,
≠ they would be different. (sadly ≠
doesn't work on lists.)
&¬{ } the following doesn't hold for the input:
⊇l₃ take any list of 3 cards,
\ transpose it
([[0,1,2],[3,2,1],[0,0,0],[2,2,2]])
{ }ᵐ each of the row's elements are …
=|≠ either equal or different to each other
&≜ actually get some numbers for the list
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~108~~ ~~104~~ 100 bytes
Saved 4 bytes thanks to @JonathanAllan!
Saved 4 bytes thanks to @xnor!
Blatant rip of @xnor's algorithm:
```
lambda:[(a,b,c,d)for a,b,c,d in product(*[(0,1,2)]*4)if(a*a+b*b+c*d)%3<1][1:]
from itertools import*
```
[Try it online!](https://tio.run/##LcY7DgIhEADQ3lPQmMzMUohrtXFPghR8JJIsDBmx8PTY@KrXv@PFbZ15f8zD15D8ZsHroKNOmFnU/6o01YXTJw4gCxdt9BUd3bBk8OSXQGGJlPC83o2zZnOnLFxVGU8ZzMdbldpZBs0upQ3IgDh/ "Python 3 – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 68 bytes
```
BigInt("3aglhdjjb0zmp3uvkpxvwio58",36).toString(3).grouped(4).toList
```
[Try it online!](https://tio.run/##LcvRCsIgFIDhVxGvFIYErui27oK66gncFNO542GerbHo2a2g2//jL71JpuYuup7YzQRgbiUHtrATInsxnAJQAlHPwV@ABNfGp4eNsdttI@p5GXBdniHvj7zRB6ko3@m7eKGl8lOe0VnR/vI1FKpqHP7MGy7lu34A "Scala – Try It Online")
Just storing the 20-cap set as a 80-digit base-3 number (using 0, 1, 2 for notation - since it's stated in the question that it's not necessary to use exactly 1, 2, 3), constructing it from base-36 to save space, and splitting the string to 4-character slices, finally getting a list of 20 cards (represented as strings like "1111", "0222" etc.). A couple more bytes probably can be golfed, using a smaller number.
] |
[Question]
[
Given a strictly positive integer, return the shortest possible Roman numeral using only the additive rule. Output must consist of zero or more of each of the characters `MDCLXVI` in that order. The number `14` must therefore give `XIIII` rather than `XIV`.
The characters' numeric values are `M`=1000, `D`=500, `C`=100, `L`=50, `X`=10, `V`=5, `I`=1.
### Examples
`3` → `III`
`4` → `IIII`
`9` → `VIIII`
`42` → `XXXXII`
`796` → `DCCLXXXXVI`
`2017` → `MMXVII`
`16807` → `MMMMMMMMMMMMMMMMDCCCVII`
[Answer]
# [Plain English](https://github.com/Folds/english), ~~1059~~ ~~1025~~ ~~678~~ ~~641~~ ~~451~~ 399 bytes
Saved 34 bytes by removing an error trap. Then saved 384 bytes by golfing. Then saved 190 bytes by combining the division operation with the append operation ("z") into a new operation ("p"). Then saved 52 bytes by golfing.
```
A s is a string.
To p a r remainder a s a x string a n number:
If the x is "", exit.
Divide the r by the n giving a q quotient and the r.
Fill a t s with the x's first's target given the q.
Append the t to the s.
To convert a r number to a s:
p the r the s "M" 1000.
p the r the s "D" 500.
p the r the s "C" 100.
p the r the s "L" 50.
p the r the s "X" 10.
p the r the s "V" 5.
p the r the s "I" 1.
```
Here is the ungolfed version of the final code, plus an error trap for a negative number:
```
A roman numeral is a string.
To process a remainder given a roman numeral and a letter string is a number:
If the letter is "", exit.
Divide the remainder by the number giving a quotient and the remainder.
Fill a temp string with the letter's first's target given the quotient.
Append the temp string to the roman numeral.
To convert a number to a roman numeral:
If the number is negative, exit.
Put the number in a remainder.
Process the remainder given the roman numeral and "M" is 1000.
Process the remainder given the roman numeral and "D" is 500.
Process the remainder given the roman numeral and "C" is 100.
Process the remainder given the roman numeral and "L" is 50.
Process the remainder given the roman numeral and "X" is 10.
Process the remainder given the roman numeral and "V" is 5.
Process the remainder given the roman numeral and "I" is 1.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~25~~ 22 bytes
```
'MDCLXVI'/⍨(0,6⍴2 5)∘⊤
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBHVfF2efiDBPdf1HvSs0DHTMHvVuMVIw1XzUMeNR1xKuR31TgYrSgBSZzP//jblMuEyMuMwtzbiMDAzNuQzNLAzMAQ "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~57~~ 42 bytes
Converts to unary, then greedily replaces bunches of `I`s with the higher denominations in order.
```
.*
$*I
I{5}
V
VV
X
X{5}
L
LL
C
C{5}
D
DD
M
```
[**Try it online**](https://tio.run/##K0otycxL/K@q4Z7wX0@LS0XLk8uz2rSWK4wrLIwrgisCxPbh8vHhcuZyBrFduFxcuHz/ayZwccUkcP035jLhMjHiMrc04zIyMDTnMjSzMDAHAA)
*Saved 15 bytes thanks to Martin*
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
f=lambda n,d=5,r='IVXLCD':r and f(n/d,7-d,r[1:])+n%d*r[0]or'M'*n
```
[Try it online!](https://tio.run/##BcGxCsIwEADQ3a@4RdLWKyaxNhqIiy6CriKUDJEQDOilHF38@vje/FvehXStyX3C9xUDEEa3R3bi@njezhdhGQJFSA1tI5o@Ik/K@nZD69jxJH1hcRcd1VQYMmSCaYcDDhrNcUQtlUE1HqTxdgUzZ1ogo@hPAlOT2/oH "Python 2 – Try It Online")
Rather than creating the output string from the start by greedily taking the largest part, this creates it from the end. For instance, the number of `I`'s is `n%5`, then the number of `V`'s is `n/5%2`, and so on. This is mixed base conversion with successive ratios of 5 and 2 alternating.
Here's an iterative equivalent:
**[Python 2](https://docs.python.org/2/), 68 bytes**
```
n=input();s='';d=5
for c in'IVXLCD':s=n%d*c+s;n/=d;d^=7
print'M'*n+s
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERD07rYVl3dOsXWlCstv0ghWSEzT90zLMLH2UXdqtg2TzVFK1m72DpP3zbFOiXO1pyroCgzr0TdV10rT7v4/39DMwsDcwA "Python 2 – Try It Online")
The `M`'s need to be handled separately because any number of them could be present as there's no larger digit. So, after the other place values have been assigned, the value remaining is converted to `M`'s.
For comparison, a greedy strategy (69 bytes):
**[Python 2](https://docs.python.org/2/), 69 bytes**
```
f=lambda n,d=1000,r='MDCLXVI':r and n/d*r[0]+f(n%d,d/(d%3*3-1),r[1:])
```
[Try it online!](https://tio.run/##BcG9CsIwEADg3ae4paSpV5qf0mohLroIuooQOkSOYECvJXTx6eP3rb/tvbApJbpP@L4oACM5rZTC7MT9cr49H1cxZQhMwB012at5H2uuCKmrqbKNbbXE7PU0yxKXDAkSg7fYY29wPA5olB5RDwc1ztMO1px4g4SiPQmMdZLlDw "Python 2 – Try It Online")
The current digit value `d` is divided by either 2 or 5 to produce the next digit. The value of `d%3` tell us which one: if `d%3==1`, divide by `2`; and if `d%3==2`, divide by 5.
[Answer]
## Mathematica, 81 bytes
```
Table@@@Thread@{r=Characters@"MDCLXVI",#~NumberDecompose~FromRomanNumeral@r}<>""&
```
Explicitly using the values and deriving the corresponding numerals seems to be one byte longer:
```
Table@@@Thread@{RomanNumeral[n={1000,500,100,50,10,5,1}],#~NumberDecompose~n}<>""&
```
[Answer]
# Excel, ~~236~~ ~~193~~ 161 bytes
~~43 bytes saved thanks to @[BradC](https://codegolf.stackexchange.com/users/70172/bradc)~~
At this point, the answer really belongs totally to @[BradC](https://codegolf.stackexchange.com/users/70172/bradc). Another 32 bytes saved.
```
=REPT("M",A1/1E3)&REPT("D",MOD(A1,1E3)/500)&REPT("C",MOD(A1,500)/100)&REPT("L",MOD(A1,100)/50)&REPT("X",MOD(A1,50)/10)&REPT("V",MOD(A1,10)/5)&REPT("I",MOD(A1,5))
```
Formatted:
```
=REPT("M",A1/1E3)
&REPT("D",MOD(A1,1E3)/500)
&REPT("C",MOD(A1,500)/100)
&REPT("L",MOD(A1,100)/50)
&REPT("X",MOD(A1,50)/10)
&REPT("V",MOD(A1,10)/5)
&REPT("I",MOD(A1,5))
```
[Answer]
# [Perl 5](https://www.perl.org/), 66 bytes
65 bytes of code + `-p` flag.
```
$s=1e3;for$@(MDCLXVI=~/./g){$\.=$@x($_/$s);$_%=$s;$s/=--$|?2:5}}{
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAv@qxTbGqYaW6flF6k4aPi6OPtEhHna1unr6adrVqvE6NmqOFRoqMTrqxRrWqvEq9qqFFurFOvb6uqq1NgbWZnW1lb//29uaQYA "Perl 5 – Try It Online")
Without changing the byte count, `MDCLXVI=~/./g` can be replaced by `M,D,C,L,X,V,I`; and `--$|?2:5` by `$|--*3+2`.
Much longer ([99 bytes](https://tio.run/##K0gtyjH9r6xYAKQVdAv@q8Tb@ipUaKjE6xumGmvquYDZqkC2vqmBgaaeM4QPZOsbgvg@UHkg3xTIjYBJA2U19cJgkvqmmnqeUCnN/9YKKvEKerYKSjF5Sv@NuUy4TIy4LM24jAwMzbkMzSwMzAE)), there is:
```
$_=M x($_/1e3).D x($_%1e3/500).C x($_%500/100).L x($_%100/50).X x($_%50/10).V x($_%10/5).I x($_%5)
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~35~~ 28 bytes
*-7 bytes thanks to Martin Ender*
```
q~{5md\2md\}3*]W%"MDCLXVI".*
```
[Try it online!](https://tio.run/##S85KzP3/v7Cu2jQ3JcYIiGuNtWLDVZV8XZx9IsI8lfS0/v83MjA0BwA "CJam – Try It Online")
### Explanation
```
q~ e# Read and eval input (push the input as an integer).
{ e# Open a block:
5md\ e# Divmod the top value by 5, and bring the quotient to the top.
2md\ e# Divmod that by 2, and bring the quotient to the top.
}3* e# Run this block 3 times.
]W% e# Wrap the stack in an array and reverse it. Now we've performed the mixed-base
e# conversion.
"MDCLXVI" e# Push this string.
.* e# Element-wise repetition of each character by the numbers in the other array.
e# Implicitly join and print.
```
[Answer]
# C#, 127 bytes
```
f=n=>n>999?"M"+f(n-1000):n>499?"D"+f(n-500):n>99?"C"+f(n-100):n>49?"L"+f(n-50):n>9?"X"+f(n-10):n>4?"V"+f(n-5):n>0?"I"+f(n-1):""
```
A purely hard coded ternary statement using recursion.
Full/Formatted version:
```
using System;
class P
{
static void Main()
{
Func<int, string> f = null;
f = n => n > 999 ? "M" + f(n - 1000)
: n > 499 ? "D" + f(n - 500)
: n > 99 ? "C" + f(n - 100)
: n > 49 ? "L" + f(n - 50)
: n > 9 ? "X" + f(n - 10)
: n > 4 ? "V" + f(n - 5)
: n > 0 ? "I" + f(n - 1)
: "";
Console.WriteLine(f(3));
Console.WriteLine(f(4));
Console.WriteLine(f(42));
Console.WriteLine(f(796));
Console.WriteLine(f(2017));
Console.WriteLine(f(16807));
Console.ReadLine();
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ ~~26~~ 25 bytes
```
¸5n3×Rvćy‰ì}"MDCLXVI"Ss×J
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K4NW4zw5dSdsSHeeKAsMOsfSJNRENMWFZJIlNzw5dK//8yNjc5 "05AB1E – Try It Online")
**Explanation**
```
¸ # wrap input in a list
5n # push 5**2
3× # repeat it 3 times
Rv # for each digit y in its reverse
ć # extract the head of the list
# (div result of the previous iteration, initially input)
y‰ # divmod with y
ì # prepend to the list
} # end loop
"MDCLXVI"S # push a list of roman numerals
s× # repeat each a number of times corresponding to the result
# of the modulus operations
J # join to string
```
[Answer]
# JavaScript (ES6), ~~81~~ ~~75~~ 69 Bytes
Saved 6 bytes thanks to @Neil for porting @Jörg Hülsermann's answer
Saved 6 bytes thanks to @Shaggy
```
n=>'MDCLXVI'.replace(/./g,(c,i)=>c.repeat(n/a,n%=a,a/=i%2?5:2),a=1e3)
```
**Test cases:**
```
f=
n=>'MDCLXVI'.replace(/./g,(c,i)=>c.repeat(n/a,n%=a,a/=i%2?5:2),a=1e3)
const testCases = [3, 4, 42, 796, 2017, 16807]
testCases.forEach(testCase => console.log(f(testCase)))
```
[Answer]
# [///](https://esolangs.org/wiki////), 50 bytes
```
/1/I//IIIII/V//VV/X//XXXXX/L//LL/C//CCCCC/D//DD/M/
```
[Try it online!](https://tio.run/##XcExCsAgEACwJwXfoItg18O1Q6FDN//PiWuT9d3rfVamotMPQYTJPAzGUKmHRmsuWX5yAw "/// – Try It Online")
Takes input in unary, and I'm (ab)using the footer field on TIO for input so output is preceded by a newline.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~100 97 96 94 93 91~~ 90 bytes
* saved 4+2 bytes: use of `def`; array as default parameter reduced an indentation space; unwanted variable declaration removed
* @shooqie saved 1 byte `a%=` shorthand
* saved 2 bytes: rearranged and braces in `(a//i)` got removed
* @Wondercricket saved 1 byte: move the array from default parameter to within the function which removed `[]` at the cost of one indentation space, thus saving 1 byte.
```
def f(a):
b=1000,500,100,50,10,5,1
for i in b:print(end=a//i*'MDCLXVI'[b.index(i)]);a%=i
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1HTikshydbQwMBAxxSIDcE0kNIx1THkUkjLL1LIVMjMU0iyKijKzCvRSM1LsU3U18/UUvd1cfaJCPNUj07Sy8xLSa3QyNSM1bROVLXN/J@mYW5ppvkfAA "Python 3 – Try It Online")
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 69 ~~74~~ ~~80~~ bytes
```
/.UI,..N&..0\0&/52"IVXLCDM"U,r%ws;rr3tu;pw..u;qrUosv!s.u\psq,!@Us(0;U
```
[Try it online!](https://tio.run/##Sy5Nyqz4/19fL9RTR0/PT01PzyDGQE3f1EjJMyzCx9nFVylUp0i1vNi6qMi4pNS6oFxPr9S6sCg0v7hMsVivNKaguFBH0SG0WMPAOvT/f3NLSwA "Cubix – Try It Online")
```
/ . U I
, . . N
& . . 0
\ 0 & /
5 2 " I V X L C D M " U , r % w
s ; r r 3 t u ; p w . . u ; q r
U o s v ! s . u \ p s q , ! @ U
s ( 0 ; U . . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
```
[Watch It Running](https://ethproductions.github.io/cubix/?code=ICAgICAgICAvIC4gVSBJCiAgICAgICAgLCAuIC4gTgogICAgICAgICYgLiAuIDAKICAgICAgICBcIDAgJiAvCjUgMiAiIEkgViBYIEwgQyBEIE0gIiBVICwgciAlIHcKcyA7IHIgciAzIHQgdSA7IHAgdyAuIC4gdSA7IHEgcgpVIG8gcyB2ICEgcyAuIHUgXCBwIHMgcSAsICEgQCBVCnMgKCAwIDsgVSAuIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgICAuIC4gLiAuCiAgICAgICAgLiAuIC4gLgogICAgICAgIC4gLiAuIC4KICAgICAgICAuIC4gLiAuCg==&input=NzA2Cg==&speed=15)
I have managed to compress it a bit more, but there is still some pesky no-ops, especially on the top face.
* `52"IVXLCDM"U` put the necessary divisors and characters on the stack. The 5 and 2 will be used to reduce the div/mod value and the characters will be discarded after use.
* `UIN0/&0\&,/U` u-turns onto the top face and starts a long tour to get the input and push 1000 onto the stack. An initial divide is done and a u-turn onto the `r` of the next snippet. This was an area I was looking at to make some savings.
* `,r%ws;rr` beginning of the divmod loop. integer divide, rotate the result away mod, then rearrange top of stack to be reduced input, current divisor and divide result.
* `3tus` bring the current character to the top and swap it with the divide result.
* `!vsoUs(0;U` this is the print loop. while the div result is more than 0, swap with character output, swap back, decrement, push a 0 and drop it. On 0 redirect over the pop stack (remove divide result) and around the cube.
* `\u;pwpsq,!@Urq;u` with a bit of redirection, this removes the character from the stack, brings the 5 and 2 to the top, swaps them and pushes one back down. The remaining is used to reduce the divisor. Halt if it reduces to 0, otherwise push the 5 or 2 to the bottom and re-enter the loop.
[Answer]
# Mathematica, 130 bytes
```
(f=#~NumberDecompose~{1000,500,100,50,10,5,1};""<>{Flatten@Table[Table[{"M","D","C","L","X","V","I"}[[i]],f[[i]]],{i,Length@f}]})&
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~109~~ 90 bytes
```
lambda n,r=[1000,500,100,50,10,5,1]:''.join(n%a/b*c for a,b,c in zip([n+1]+r,r,'MDCLXVI'))
```
[Try it online!](https://tio.run/##Hcq9DoIwFIbh3as4iynIp7bIj5LgoouJroYEGQqGeIwW0rDozVdwePMsb/8ZHp0JXZvf3Eu/67smA5uXSkqJeEz9HUEMVWVCrJ4dG8/M9bpeNNR2ljRqNMSGvtx7pQlUFVhYiMvxcC6uJ@H7btp4WsoNIkQh0l2CUKoUKtnKtMpm1Fs2AzHEci/Qeuy7Hw "Python 2 – Try It Online")
[Answer]
# [PHP](https://php.net/), 70 bytes
```
for($r=1e3;$a=&$argn;)$a/$r<1?$r/=++$i%2?2:5:$a-=$r*print MDCLXVI[$i];
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkZGBormT9Py2/SEOlyNYw1dhaJdFWDSxpramSqK9SZGNor1Kkb6utrZKpamRvZGVqpZKoa6tSpFVQlJlXouDr4uwTEeYZrZIZa/3/PwA "PHP – Try It Online")
[Answer]
# T-SQL, 164 bytes
```
SELECT REPLICATE('M',n/1000)+IIF(n%1000>499,'D','')
+REPLICATE('C',n%500/100)+IIF(n%100>49,'L','')
+REPLICATE('X',n%50/10)+IIF(n%10>4,'V','')
+REPLICATE('I',n%5)
FROM t
```
Line breaks added for readability only.
This version is a lot longer (230 characters), but feels much more "SQL-like":
```
DECLARE @ INT,@r varchar(99)=''SELECT @=n FROM t
SELECT'I's,1v INTO m
INSERT m VALUES('V',5),('X',10),('L',50),('C',100),('D',500),('M',1000)
L:
SELECT @-=v,@r+=s
FROM m WHERE v=(SELECT MAX(v)FROM m WHERE v<=@)
IF @>0GOTO L
SELECT @r
```
Makes a table *m* with all the char-value mappings, and then loops through finding the largest value <= the number, concatenating the matching character.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 34 bytes
```
"IVXLCD"£%(U/=Y=v *3+2Y)îXÃw i'MpU
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=IklWWExDRCKjJShVLz1ZPXYgKjMrMlkp7ljDdyBpJ01wVQ==&input=MTk5OQ==)
```
"IVXLCD"£ %(U/=Y=v *3+2Y )îXÃ w i'MpU
"IVXLCD"mXY{U%(U/=Y=Yv *3+2,Y)îX} w i'MpU : Ungolfed
: Implicit: U = input number
"IVXLCD"mXY{ } : Map each char X and its index Y in this string to:
Y=Yv *3+2 : Set Y to 5 for even indexes, 2 for odd.
U/= : Divide U by this amount.
U%( ,Y) : Modulate the old value of U by 5.
îX : Repeat the character that many times.
: This returns e.g. "IIVCCCD" for 16807.
w : Reverse the entire string.
i'MpU : Prepend U copies of 'M' (remember U is now the input / 1000).
: Implicit: output result of last expression
```
[Answer]
## JavaScript (ES6), 65 bytes
A recursive function.
```
f=(n,a=(i=0,1e3))=>n?a>n?f(n,a/=i++&1?5:2):'MDCLXVI'[i]+f(n-a):''
```
### How?
The second recursive call `f(n-a)` really should be `f(n-a,a)`. By omitting the 2nd parameter, `a` and `i` are reinitialized (to 1000 and 0 respectively) each time a new Roman digit is appended to the final result. This causes more recursion than needed but doesn't alter the outcome of the function and saves 2 bytes.
### Test cases
```
f=(n,a=(i=0,1e3))=>n?a>n?f(n,a/=i++&1?5:2):'MDCLXVI'[i]+f(n-a):''
console.log(f(3))
console.log(f(4))
console.log(f(9))
console.log(f(42))
console.log(f(796))
console.log(f(2017))
console.log(f(16807))
```
[Answer]
# [J](http://jsoftware.com/), ~~26~~ 23 bytes
3 bytes saved thanks to Adám.
```
'MDCLXVI'#~(_,6$2 5)&#:
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjYKBgBcS6egrOQTo@bv/VfV2cfSLCPNWV6zTidcxUjBRMNdWUrf5rcpUkg7QYK5goWCqYGCmYW5opGBkYmisYmlkYmHOlJmfkK2hYK6RpKhkolCT/BwA "J – Try It Online")
~~Similar to the APL answer~~ basically the same thing.
```
'MDCLXVI'#~(_,6$2 5)&#:
( )&#: mixed base conversion from decimal
6$2 5 2 5 2 5 2 5
_, infinity 2 5 2 5 2 5
this gives us e.g. `0 0 0 0 1 0 4` for input `14`
'MDCLXVI'#~ shape each according to the number of times on the right
this is greedy roman numeral base conversion
```
[Answer]
## Batch, 164 bytes
```
@set/pn=
@set s=
@for %%a in (1000.M 500.D 100.C 50.L 10.X 5.V 1.I)do @call:c %%~na %%~xa
@echo %s:.=%
@exit/b
:c
@if %n% geq %1 set s=%s%%2&set/an-=%1&goto c
```
Takes input on STDIN.
[Answer]
# Oracle SQL, 456 bytes
```
select listagg((select listagg(l)within group(order by 1)from dual start with trunc((n-nvl(n-mod(n,p),0))/v)>0 connect by level<=trunc((n-nvl(n-mod(n,p),0))/v)))within group(order by v desc)from (select 2849n from dual)cross join(select 1000v,null p,'m'l from dual union select 500,1000,'d'from dual union select 100,500,'c'from dual union select 50,100,'l'from dual union select 10,50,'x'from dual union select 5,10,'v'from dual union select 1,5,'i'from dual)
```
Outputs:
```
mmdcccxxxxviiii
```
Please note the actual size of the line is 460bytes, because it includes the input number (2849).
Ungolfed:
```
select listagg(
(select listagg(l, '') within group(order by 1)
from dual
start with trunc((n-nvl(p*trunc(n/p),0))/v) > 0
connect by level <= trunc((n-nvl(p*trunc(n/p),0))/v) )
) within group(order by v desc)
from (select 2348 n
from dual
) cross join (
select 1000v, null p, 'm' l from dual union
select 500, 1000, 'd' from dual union
select 100, 500, 'c' from dual union
select 50, 100, 'l' from dual union
select 10, 50, 'x' from dual union
select 5, 10, 'v' from dual union
select 1, 5, 'i' from dual
)
```
How it works:
I calculate how many of each letter I need, by calculating the most I can get to with the higher value one (infinity for M), and then doing an integer division between the current letter's value and the result of that.
E.g. 2348, how many `C`s do I need? `trunc((2348-mod(2348,500))/100)` = 3.
Then, I `listagg` that letter together 3 times (exploiting `CONNECT BY` to generate the 3 rows I need).
Finally, I `listagg` everything together.
Kinda bulky, but most of it is the `select from dual`s in the conversion table and I can't really do much about that...
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~119~~ 118 bytes
```
n->{String s="";for(int v[]={1,5,10,50,100,500,1000},i=7;i-->0;)for(;n>=v[i];n-=v[i])s+="IVXLCDM".charAt(i);return s;}
```
[Try it online!](https://tio.run/##LU9Na4NAEL3nVwyCoHRd1jSJTbYKpaUQaE6BUhAPW6PppmYUd7UE8bfbVXOYeY838@bjIlrhlVWGl9PvUDXfhUwhLYRScBASuwXAXVRaaANtKU9wNSXnqGuJ5zgBUZ@VO3YCXMw02mhZ0LzBVMsS6R71@50/z5YIcghhQC/qZgFUaFk8L2tHooY2TsLOJ2viM7JmJo8wIeuJDAMuPS9i3B37OUZhG8uEozehqx5Ca//59fH6drBo@iPqF@1Il9eZbmoExfuBT4caM0zbcAeY/YGhcdI9khXZktWSBNsNWTI/IP7miQW9C/N7AMeb0tmVlo2mlTld545l@@y0A1vZaBFAAjkVVVXcHHTdeVe/GKNfDP8 "Java (OpenJDK 8) – Try It Online")
Saved a byte thanks to @TheLethalCoder
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 50 46 bytes
```
NνA⁰χWφ«W¬‹νφ«§MDCLXVIχA⁻νφν»A⁺¹χχA÷φ⎇﹪χ²¦²¦⁵φ
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nnXn9r7fs/BR44bz7e/3bD/fdmg1kDq05lHDznN7QbxDy31dnH0iwjxB8kB1u0HC5/Ye2g3m7Tq083w7WOYwUO@jvvb3O1edbz@06dAyEH7UuPV82///ZhYG5gA "Charcoal – Try It Online")
Explanation:
```
Nν Take input as number and assign it to ν
A⁰χ Let χ=0
Wφ« While φ>0 (φ has a predefined value of 1000)
W¬‹νφ« While v>=φ
§MDCLXVIχ Take the char from string "MDCLXVI" at position χ
A⁻νφν» Let ν=ν-φ
A⁺¹χχ Increment χ
A÷φ⎇﹪χ²¦²¦⁵φ If χ is odd, divide φ by 5, else divide φ by 2
```
* 4 bytes saved thanks to Neil, while I am still trying to figure out how to proceed with the second part of his comment.
[Answer]
# C++, 272 Bytes
```
#include <cstdio>
#include <map>
std::map<int,char> m = {{1000,'M'},{500,'D'},{100,'C'},{50,'L'},{10,'X'},{5,'V'},{1,'I'}};
int main(){unsigned long x;scanf("%d",&x);for(auto i=m.rbegin();i!=m.rend();++i)while(x>=i->first){printf("%c", i->second);x=x-i->first;}return 0;}
```
[Answer]
# C, 183 Bytes
```
#include <stdio.h>
int v[]={1000,500,100,50,10,5,1};
char*c="MDCLXVI";
int main(){int x;scanf("%d",&x);for(int i=0;i<sizeof v/sizeof(int);i++)for(;x>=v[i];x-=v[i])putc(c[i],stdout);}
```
Same algorithm as before, just using plain c arrays instead of an std::map, partially inspired by @xnor's answer and using a string to store the letters.
[Answer]
## Common Lisp, 113 bytes
This is an anonymous function, returning the result as a string.
```
(lambda(value)(setf(values a b)(floor v 1000))(concatenate 'string(format()"~v,,,v<~>"a #\M)(format nil"~@:r"b)))
```
Ungolfed, with descriptive variable names and comments:
```
(defun format-roman (value)
;; Get "value integer-divided by 1000" and "value mod 1000"
(setf (values n_thousands remainder) (floor value 1000))
(concatenate 'string
;; Pad the empty string n_thousands times, using "M" as the
;; padding character
(format () "~v,,,v<~>" n_thousands #\M)
;; Format the remainder using "old-style" Roman numerals, i.e.
;; numerals with "IIII" instead of "IV"
(format nil "~@:r" remainder)))
```
CL has built-in Roman numeral formatter. Sadly it doesn't work for numbers larger than 3999.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
NςA²ξFMDCLXVI«×ι÷ςφA﹪ςφςA÷φξφA÷χξξ
```
Originally based on @CarlosAlego's answer. A port of @xnor's Python solution is also 34 bytes:
```
NθA⁵ξFIVXLCD«←×ι﹪θξA÷θξθA÷χξξ»←×Mθ
```
Edit: A port of @xnor's other Python solution turns out to be 33 bytes!
```
NθFMDCLXVI«×ι÷θφA﹪θφθA÷φ⁺׳﹪φ³±¹φ
```
[Try it online!](https://tio.run/##TYy9CsIwGEXn9ik@OiWQglJQwUnsErClg4hrbZMaSBObny7is8eIBR3vuZzT3VvT6VaGQNXDu9qPN2bQhPcp1wZQVpXH0/VCMwzPNGmMUA6dxcgsEgSocqWYRc/QRIBjHKXkYK0YFKp076X@cgLT3/OTOIFGerv0CgKLFHmBo1WzoXUMrfFn8Jh4hbDZrbYhn0Nu5Rs "Charcoal – Try It Online") Link is to verbose version of code. Note that I've used `⁺׳﹪φ³±¹` instead of `⁻׳﹪φ³¦¹` because the deverbosifier is currently failing to insert the separator.
] |
[Question]
[
A Stack Exchange script determines which five comments on questions or answers are initially seen on the main page of sites through the number of upvotes on them; the five comments with the highest number of votes are displayed. Your task is to recreate this behavior.
Write a full program or function taking input through STDIN, command-line args, or function arguments and prints or returns the top five comment scores. Input will be an array of integers representing the number of upvotes on the comments of some post. For instance, an input of
```
0, 2, 5, 4, 0, 1, 0
```
means that the first comment has no votes, the second one has two votes, the third has five, the fourth had four, etc. The order of the comment scores should remain the same in the output.
If the input contains five or fewer comment scores, then the output should contain nothing more than the ones given. If two or more comment scores are the same, the first score(s) should be displayed. You may assume that the input array will contain at least one comment score.
The numbers in the output should be easily distinguished (so 02541 for case 1 is invalid). Otherwise there are no restrictions on output format; the numbers may be separated by a space or newline, or they may be in list format, etc.
Test cases:
```
[0, 2, 5, 4, 0, 1, 0] -> [0, 2, 5, 4, 1]
[2, 1, 1, 5, 3, 6] -> [2, 1, 5, 3, 6]
[0, 4, 5] -> [0, 4, 5]
[1, 1, 5, 1, 1, 5] -> [1, 1, 5, 1, 5]
[0, 2, 0, 0, 0, 0, 0, 0] -> [0, 2, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 0] -> [0, 0, 0, 0, 1]
[5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7] -> [5, 8, 7, 6, 7]
[6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2] -> [6, 69, 22, 37, 5]
```
The last example was taken from [this Stack Overflow question](https://stackoverflow.com/questions/271526/avoiding-null-statements).
If possible, please provide a link in your post where your submission can be run online.
This is code golf, so the shortest code in bytes wins. Good luck!
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
NỤḣ5Ṣị
```
[Try it online!](http://jelly.tryitonline.net/#code=TuG7pOG4ozXhuaLhu4s&input=&args=WzAsIDIsIDUsIDQsIDAsIDEsIDBd) or [verify all test cases at once](http://jelly.tryitonline.net/#code=TuG7pOG4ozXhuaLhu4sKw4figqw&input=&args=WzAsIDIsIDUsIDQsIDAsIDEsIDBdLCBbMiwgMSwgMSwgNSwgMywgNl0sIFswLCA0LCA1XSwgWzEsIDEsIDUsIDEsIDEsIDVdLCBbMCwgMiwgMCwgMCwgMCwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAxLCAwLCAwLCAwLCAwXSwgWzUsIDQsIDIsIDEsIDAsIDgsIDcsIDQsIDYsIDEsIDAsIDddLCBbNiwgMywgMiwgMCwgNjksIDIyLCAwLCAzNywgMCwgMiwgMSwgMCwgMCwgMCwgNSwgMCwgMSwgMiwgMCwgMCwgMSwgMCwgMCwgMSwgMCwgMCwgMCwgMCwgMSwgMl0).
### How it works
```
NỤḣ5Ṣị Main link. Input: A (list)
N Negate (multiply by -1) all elements of A.
Ụ Grade the result up.
This consists in sorting the indices of A by their negated values.
The first n indices will correspond to the n highest vote counts,
tie-broken by order of appearance.
ḣ5 Discard all but the first five items.
Ṣ Sort those indices.
This is to preserve the comments' natural order.
ị Retrieve the elements of A at those indices.
```
[Answer]
# Python 2, 58 bytes
```
x=input()[::-1]
while x[5:]:x.remove(min(x))
print x[::-1]
```
Test it on [Ideone](http://ideone.com/CaBy06).
### How it works
`list.remove` removes the first occurrence if its argument from the specified list. By reversing the list **x**, we essentially achieve that it removes the *last* occurrence instead.
Thus, it suffices to keep removing the comment with the minimal amount of upvotes until a list of no more than five comments is reached. Afterwards, we reverse the list once more to restore the original order.
[Answer]
## Pyth, 11 bytes
```
_.-_Q<SQ_5
```
We calculate the multiset intersection of the input (`Q`) with the five greatest elements in `Q` (in the order they appear in `Q`), then take the first five of those.
```
_ .- Reverse of multiset difference
_ Q of reversed Q
< with all but last 5 elements of sorted Q
S Q
_ 5
```
Try it [here](http://pyth.herokuapp.com/?code=_.-_Q%3CSQ_5&input=%5B5%2C+4%2C+2%2C+1%2C+0%2C+8%2C+7%2C+4%2C+6%2C+1%2C+0%2C+7%5D&debug=0).
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 16 bytes
```
tn4>?t_FT#S5:)S)
```
This uses [current release (10.2.1)](https://github.com/lmendo/MATL/releases/tag/10.2.1), which is earlier than this
challenge.
[**Try it online!**](http://matl.tryitonline.net/#code=dG40Pj90X0ZUI1M1OilTKQ&input=WzYsIDMsIDIsIDAsIDY5LCAyMiwgMCwgMzcsIDAsIDIsIDEsIDAsIDAsIDAsIDUsIDAsIDEsIDIsIDAsIDAsIDEsIDAsIDAsIDEsIDAsIDAsIDAsIDAsIDEsIDJd)
### Explanation
```
% implicitly get input
t % duplicate
n % number of elements
4>? % if greater than 4...
t % duplicate
_ % unary minus (so that sorting will correspond to descending order)
FT#S % sort. Produce the indices of the sorting, not the sorted values
5:) % get first 5 indices
S % sort those indices, so that they correspond to original order in the input
) % index the input with those 5 indices
% implicitly end if
% implicitly display
```
[Answer]
# JavaScript, ~~74 65 62~~ 61 bytes
3 bytes off thanks @user81655. 1 byte off thanks @apsillers.
```
f=a=>5 in a?f(a.splice(a.lastIndexOf(Math.min(...a)),1)&&a):a
```
```
f=a=>5 in a?f(a.splice(a.lastIndexOf(Math.min(...a)),1)&&a):a
document.write('<pre>' +
'[0, 2, 5, 4, 0, 1, 0] -> ' + f([0, 2, 5, 4, 0, 1, 0]) + '<br>' +
'[2, 1, 1, 5, 3, 6] -> ' + f([2, 1, 1, 5, 3, 6]) + '<br>' +
'[0, 4, 5] -> ' + f([0, 4, 5]) + '<br>' +
'[1, 1, 5, 1, 1, 5] -> ' + f([1, 1, 5, 1, 1, 5]) + '<br>' +
'[0, 2, 0, 0, 0, 0, 0, 0] -> ' + f([0, 2, 0, 0, 0, 0, 0, 0]) + '<br>' +
'[0, 0, 0, 0, 1, 0, 0, 0, 0] -> ' + f([0, 0, 0, 0, 1, 0, 0, 0, 0]) + '<br>' +
'[5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7] -> ' + f([5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7]) + '<br>' +
'[6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2] -> ' + f([6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2]) + '<br>' +
'</pre>')
```
[Answer]
# Python 3, 76
Saved 9 bytes thanks to Kevin reminding me that I can abuse if statements in a list comp.
Saved 5 bytes thanks to DSM.
Pretty simple solution right now. Grab the top 5 scores and then parse through the list adding them to the result as we find them.
```
def f(x):y=sorted(x)[-5:];return[z for z in x if z in y and not y.remove(z)]
```
Here are my test cases if anyone wants them:
```
assert f([0, 2, 5, 4, 0, 1, 0]) == [0, 2, 5, 4, 1]
assert f([2, 1, 1, 5, 3, 6]) == [2, 1, 5, 3, 6]
assert f([0, 4, 5]) == [0, 4, 5]
assert f([0, 2, 0, 0, 0, 0, 0, 0]) == [0, 2, 0, 0, 0]
assert f([0, 0, 0, 0, 1, 0, 0, 0, 0]) == [0, 0, 0, 0, 1]
assert f([5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7]) == [5, 8, 7, 6, 7]
assert f([6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2]) == [6, 69, 22, 37, 5]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
Code:
```
E[Dg6‹#Rß\R
```
Explanation:
```
E # Evaluate input
[ # Infinite loop
D # Duplicate top of the stack
g # Get the length
6‹# # If smaller than 6, break
R # Reverse top of the stack
ß\ # Extract the smallest item and remove it
R # Reverse top of the stack
# Implicit, print the processed array
```
Uses CP-1252 encoding.
[Answer]
## CJam, 16 bytes
```
{ee{1=~}$5<$1f=}
```
An unnamed block (function) that takes an array and returns an array.
[Test suite.](http://cjam.aditsu.net/#code=%7Bee%7B1%3D~%7D%245%3C%241f%3D%7D%3AF%3B%0A%0AqN%2F%7B%22%20-%3E%20%22%2F0%3D~%7D%25%0A%0A%7BFp%7D%25&input=%5B0%202%205%204%200%201%200%5D%20-%3E%20%5B0%202%205%204%201%5D%0A%5B2%201%201%205%203%206%5D%20-%3E%20%5B2%201%205%203%206%5D%0A%5B0%204%205%5D%20-%3E%20%5B0%204%205%5D%0A%5B1%201%205%201%201%205%5D%20-%3E%20%5B1%201%205%201%205%5D%0A%5B0%202%200%200%200%200%200%200%5D%20-%3E%20%5B0%202%200%200%200%5D%0A%5B0%200%200%200%201%200%200%200%200%5D%20-%3E%20%5B0%200%200%200%201%5D%0A%5B5%204%202%201%200%208%207%204%206%201%200%207%5D%20-%3E%20%5B5%208%207%206%207%5D%0A%5B6%203%202%200%2069%2022%200%2037%200%202%201%200%200%200%205%200%201%202%200%200%201%200%200%201%200%200%200%200%201%202%5D%20-%3E%20%5B6%2069%2022%2037%205%5D)
### Explanation
```
ee e# Enumerate the array, pairing each number with its index.
{ e# Sort by...
1= e# The original value of each element.
~ e# Bitwise NOT to sort from largest to smallest.
}$ e# This sort is stable, so the order tied elements is maintained.
5< e# Discard all but the first five.
$ e# Sort again, this time by indices to recover original order.
1f= e# Select the values, discarding the indices.
```
[Answer]
# Bash + GNU utilities, 36
```
nl|sort -nrk2|sed 5q|sort -n|cut -f2
```
I/O formatted as newline-separated lists via STDIN/STDOUT.
[Try it online.](https://ideone.com/NM42WP)
[Answer]
## Python, 68 bytes
```
lambda l,S=sorted:zip(*S(S(enumerate(l),key=lambda(i,x):-x)[:5]))[1]
```
[Example run.](https://ideone.com/CQThNt)
A lump of built-ins. I think the best way to explain is to run through an example.
```
>> l
[5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7]
>> enumerate(l)
[(0, 5), (1, 4), (2, 2), (3, 1), (4, 0), (5, 8), (6, 7), (7, 4), (8, 6), (9, 1), (10, 0), (11, 7)]
```
`enumerate` turns the list into index/value pairs (technically an `enumerate` object).
```
>> sorted(enumerate(l),key=lambda(i,x):-x)
[(5, 8), (6, 7), (11, 7), (8, 6), (0, 5), (1, 4), (7, 4), (2, 2), (3, 1), (9, 1), (4, 0), (10, 0)]
>> sorted(enumerate(l),key=lambda(i,x):-x)[:5]
[(5, 8), (6, 7), (11, 7), (8, 6), (0, 5)]
```
The pairs are sorted by greatest value first, keeping the current order of index for ties. This puts at the front the highest-scored comments, tiebroken by earlier post. Then, the 5 best such comments are taken.
```
>> sorted(_)
[(0, 5), (5, 8), (6, 7), (8, 6), (11, 7)]
>> zip(*sorted(_))[1]
(5, 8, 7, 6, 7)
```
Put the top five comments back in posting order, and then remove the indices, keeping only the scores.
[Answer]
## PowerShell v4, ~~120~~ 97 bytes
```
param($a)$b=@{};$a|%{$b.Add(++$d,$_)};($b.GetEnumerator()|sort Value|select -l 5|sort Name).Value
```
Experimenting around, I found an alternate approach that golfed off some additional bytes. However, it seems to be specific to PowerShell v4 and how that version handles sorting of a hashtable -- it seems, by default, that in v4 if multiple Values have the same value, it takes the one with a "lower" Key, but you're not guaranteed that in v3 or earlier, even when using the [ordered](http://www.jonathanmedd.net/2011/09/powershell-v3-bringing-ordered-to-your-hashtables.html) keyword in v3. I've not fully vetted this against PowerShell v5 to say if the behavior continues.
This v4-only version takes input as `$a`, then creates a new empty hashtable `$b`. We loop through all the elements of the input `$a|%{...}` and each iteration add a key/value pair to `$b` (done by pre-incrementing a helper variable `$d` as the key for each iteration). Then we `sort` `$b` based on `Value`, then `select` the `-l`ast `5`, then `sort` by `Name` (i.e., the key), and finally output only the `.Value`s of the resultant hash.
If fewer than 5 elements are entered, it will just sort on value, select the last five (i.e., all of them), re-sort on key, and output.
---
### Older, 120 bytes, works in earlier versions
```
param($a)if($a.Count-le5){$a;exit}[System.Collections.ArrayList]$b=($a|sort)[-5..-1];$a|%{if($_-in$b){$_;$b.Remove($_)}}
```
Same algorithm as Morgan Thrapp's [answer](https://codegolf.stackexchange.com/a/70298/42963), which is apparently an indication that great minds think alike. :)
Takes input, checks if the number of items is less-than-or-equal-to 5, and if so outputs the input and exits. Otherwise, we create an ArrayList `$b` (with the exorbitantly lengthy `[System.Collections.ArrayList]` cast) of the top five elements of `$a`. We then iterate over `$a` and for each element if it's in `$b` we output it and then remove it from `$b` (and here's why we need to use ArrayList, as removing elements from an Array isn't a supported feature in PowerShell, since they're technically fixed size).
Requires v3 or greater for the `-in` operator. For an answer that works in earlier versions, swap `$_-in$b` for `$b-contains$_` for a total of **126 bytes**.
[Answer]
## Haskell, 62 bytes
```
import Data.List
map snd.sort.take 5.sortOn((0-).snd).zip[0..]
```
Usage example: `map snd.sort.take 5.sortOn((0-).snd).zip[0..] $ [5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7]` -> `[5,8,7,6,7]`.
How it works: augment each element with it's index, sort descending, take first 5 elements, sort by index and remove index.
[Answer]
# PHP 5, ~~107~~ 102
Saved 5 bytes thanks to @WashingtonGuedes
```
function p($s){uasort($s,function($a,$b){return$a<=$b;});$t=array_slice($s,0,5,1);ksort($t);return$t;}
```
# Ungolfed
```
function p($scores) {
// sort the array from high to low,
// keeping lower array keys on top of higher
// array keys
uasort($scores,function($a, $b){return $a <= $b;});
// take the top 5
$top_five = array_slice($scores,0,5,1);
// sort by the keys
ksort($top_five);
return $top_five;
}
```
[Try it.](http://sandbox.onlinephpfunctions.com/code/282e6d99da6a81c38543502303474a5e4fc66261)
[Answer]
# Ruby, 82 ~~87~~ ~~89~~ bytes
`$><<eval($*[0]).map.with_index{|x,i|[i,x]}.sort_by{|x|-x[1]}[0,5].sort.map(&:last)`
to call:
`ruby test.rb [1,2,2,3,4,5]`
original submission - 56 bytes but fails on certain test cases & didn't support $stdin and $stdout
~~`_.reduce([]){|a,x|a+=_.sort.reverse[0..4]&[x]if !a[4];a}`~~
Explanation
```
$><< # print to stdout
eval($*[0]) # evals the passed in array in stdin ex: [1,2,3,4]
.map.with_index # returns an enumerator with indices
{|x,i|[i,x]} # maps [index,value]
.sort_by{|x|-x[1]} # reverse sorts by the value
[0,5] # selects the first 5 values
.sort # sorts item by index (to find the place)
.map{|x|x[1]} # returns just the values
```
[Answer]
# Java 7, 155 bytes
```
import java.util.*;List c(int[]f){LinkedList c=new LinkedList();for(int i:f)c.add(i);while(c.size()>5)c.removeLastOccurrence(Collections.min(c));return c;}
```
**Ungolfed & test-code:**
[Try it here.](https://ideone.com/mtH8hn)
```
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
class Main{
static List c(int[] f){
LinkedList c = new LinkedList();
for (int i : f){
c.add(i);
}
while(c.size() > 5){
c.removeLastOccurrence(Collections.min(c));
}
return c;
}
public static void main(String[] a){
System.out.println(Arrays.toString(c(new int[]{ 0, 2, 5, 4, 0, 1, 0 }).toArray()));
System.out.println(Arrays.toString(c(new int[]{ 2, 1, 1, 5, 3, 6 }).toArray()));
System.out.println(Arrays.toString(c(new int[]{ 0, 4, 5 }).toArray()));
System.out.println(Arrays.toString(c(new int[]{ 1, 1, 5, 1, 1, 5 }).toArray()));
System.out.println(Arrays.toString(c(new int[]{ 0, 2, 0, 0, 0, 0, 0, 0 }).toArray()));
System.out.println(Arrays.toString(c(new int[]{ 0, 0, 0, 0, 1, 0, 0, 0, 0 }).toArray()));
System.out.println(Arrays.toString(c(new int[]{ 6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2 }).toArray()));
}
}
```
**Output:**
```
[0, 2, 5, 4, 1]
[2, 1, 5, 3, 6]
[0, 4, 5]
[1, 1, 5, 1, 5]
[0, 2, 0, 0, 0]
[0, 0, 0, 0, 1]
[6, 69, 22, 37, 5]
```
[Answer]
# Julia, 48 bytes
```
!x=x[find(sum(x.<x',2)+diag(cumsum(x.==x')).<6)]
```
[Try it online!](http://julia.tryitonline.net/#code=IXg9eFtmaW5kKHN1bSh4Jy4-eCwyKStkaWFnKGN1bXN1bSh4Jy49PXgpKS48NildCgpmb3IgeCBpbiAoCiAgICBbMCwyLDUsNCwwLDEsMF0sCiAgICBbMiwxLDEsNSwzLDZdLAogICAgWzAsNCw1XSwKICAgIFsxLDEsNSwxLDEsNV0sCiAgICBbMCwyLDAsMCwwLDAsMCwwXSwKICAgIFswLDAsMCwwLDEsMCwwLDAsMF0sCiAgICBbNSw0LDIsMSwwLDgsNyw0LDYsMSwwLDddLAogICAgWzYsMywyLDAsNjksMjIsMCwzNywwLDIsMSwwLDAsMCw1LDAsMSwyLDAsMCwxLDAsMCwxLDAsMCwwLDAsMSwyXQopCiAgICAheCB8PiBwcmludGxuCmVuZA&input=)
### How it works
The comment **c1** has higher precedence than the comment **c2** iff one of the following is true:
* **c1** has more upvotes than **c2**.
* **c1** and **c2** have the same amount of upvotes, but **c1** was posted earlier.
This defines a total ordering of the comments, and the task at hand is to find the five comments that have the highest precedences.
Instead of sorting the comments by precedence (which would alter their order, for each comment **c**, we count the comments that have a greater or equal precedence. We keep **c** if and only if this count is **5** or less.
To partially sort the comments by number of upvotes, we do the following. Let **x** be the column vector containing the vote counts. Then `x'` transposes **x** ‐ thus creating a row vector ‐ and `x.<x'` creates a Boolean matrix that compares each element of **x** with each element of **xT**.
For **x = [0, 2, 5, 4, 0, 1, 0]**, this gives
```
< 0 2 5 4 0 1 0
0 false true true true false true false
2 false false true true false false false
5 false false false false false false false
4 false false true false false false false
0 false true true true false true false
1 false true true true false false false
0 false true true true false true false
```
By summing across rows (via `sum(...,2)`), we count the number of comments that have strictly *more* upvotes than the comment at that index.
For the example vector, this gives
```
4
2
0
1
4
3
4
```
Next, we count the number of comments with an equal amount of upvotes have been posted earlier than that comment. We achieve this as follows.
First we build an equality table with `x.==x'`, which compraes the elements of **x** with the elements of **xT**. For our example vector, this gives:
```
= 0 2 5 4 0 1 0
0 true false false false true false true
2 false true false false false false false
5 false false true false false false false
4 false false false true false false false
0 true false false false true false true
1 false false false false false true false
0 true false false false true false true
```
Next, we use `cumsum` to calculate the cumulative sums of each columns of of the matrix.
```
1 0 0 0 1 0 1
1 1 0 0 1 0 1
1 1 1 0 1 0 1
1 1 1 1 1 0 1
2 1 1 1 2 0 2
2 1 1 1 2 1 2
3 1 1 1 3 1 3
```
The diagonal (`diag`) holds the count of comments that have an equal amount of upvotes and occur no later than the corresponding comment.
```
1
1
1
1
2
1
3
```
By adding the two row vectors we produced, we obtain the priorities (**1** is the highest) of the comments.
```
5
3
1
2
6
4
7
```
Comments with priorities ranging from **1** to **5** should be displayed, so we determine their indices with `find(....<6)` and retrieve the corresponding comments with `x[...]`.
[Answer]
# Python 3.5, 68 bytes
```
f=lambda x,*h:x and x[:sum(t>x[0]for t in x+h)<5]+f(x[1:],*h,x[0]+1)
```
No match for [my Python 2 answer](https://codegolf.stackexchange.com/a/70343), but only three bytes longer than its port to Python 3, and I think it's different enough to be interesting.
I/O is in form of tuples. Test it on [repl.it](https://repl.it/CZyo).
] |
[Question]
[
The goal of this challenge is to (eventually) output *every* possible halting program in a language of your choice. At first this may sound impossible, but you can accomplish this with a very careful choice of execution order.
Below is an ASCII diagram to illustrate this. Let the columns represent a numbering of every possible program (each program is a finite number of symbols from a finite alphabet). Let each row represent a singular step in execution of that program. An `X` represent the execution performed by that program at that time-step.
```
step# p1 p2 p3 p4 p5 p6
1 X X X X X X
2 X X X X X
3 X X X X
4 X X X X
5 X X X
6 X X
7 X X
8 X X
9 X X
∞ X X
```
As you can tell, programs 2 and 4 don't halt. If you were to execute them one-at-a-time, your controller would get stuck in the infinite loop that is program 2 and never output programs 3 and beyond.
Instead, you use a [dovetailing](http://en.wikipedia.org/wiki/Dovetailing_(computer_science)) approach. The letters represent a possible order of execution for the first 26 steps. The `*`s are places where that program has halted and is outputted. The `.`s are steps that haven't been executed yet.
```
step# p1 p2 p3 p4 p5 p6
1 A C F J N R V
2 B E I M Q * Z
3 D H * P U
4 G L T Y
5 K O X
6 * S .
7 W .
8 . .
9 . .
∞ . .
```
## Requirements for the target language
The target language (the one being parallel-interpreted) must be Turing-complete. Other than that, it can be *any* language that's Turing-complete, including Turing-complete subsets of much larger languages. You are also free to interpret things like cyclic tag system rules. You are also allowed to create a language to test, as long as you can show why it is Turing-complete.
As an example, if you choose to test brainfuck, then it is best to test just the `[]-+<>` subset, since input is not supported and output is just thrown away (see below).
When it comes to the "controller" program (which you are golfing), there's no special requirements. Normal language restrictions apply.
## How to create an infinite list of programs
The majority of programming languages can be represented as a series of symbols from a finite alphabet. In this case, it is relatively easy to enumerate a list of every possible program in order of increasing length. The alphabet you use should be representative of the *requirements* of the target language. In most cases, this is printable ASCII. If your language supports Unicode as an additional feature, you should not test every possible combination of Unicode characters, just ASCII. If your language only uses `[]-+<>` then don't test out the various combinations of "comment" ASCII characters. Languages like APL would have their own special alphabets.
If your language is best described in some non-alphabetic way, like Fractran or Turing Machines, then there are other equally valid methods of generating a list of all possible valid programs.
## Interpreting an ever-growing list of programs
The key part of this challenge is to write a parallel interpreter for a growing list of programs. There are some basic steps for this:
* Add a finite number of programs to the list
* Interpret each program on the list individually for a finite period of time. This can be accomplished by performing one instruction step for each. Save all of the states.
* Remove all terminating/error-throwing programs from the list
* Output the cleanly halted\* programs
* Add some more programs to the list
* Simulate each program in turn, picking up execution of older programs where it left off
* Remove all terminating/error-throwing programs from the list
* Output the cleanly halted\* programs
* repeat
**\*You should only output programs that halt cleanly.** This means that there were no syntax errors or uncaught exceptions thrown during execution. Programs which ask for input should also be terminated without outputting them. If a program produces output, you shouldn't terminate it, just throw the output away.
## More rules
* You must not spawn new threads to contain the tested programs, as this offloads the work of parallelization onto the host OS / other software.
* Edit: To close potential future loopholes, you are not allowed to `eval` (or any related function) a part of the *tested* program's code. You *can* `eval` a codeblock from the interpreter's code. (The BF-in-Python answer is still valid under these rules.)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
* The language you write your submission in **does not** need to be the same as the language you are testing/outputting.
* You should assume that your available memory is unbounded.
* When proving Turing-completeness, you may assume that input is hardcoded into the program, and output can be read off the program's internal state.
* If your program outputs itself, it is probably wrong or a polyglot.
[Answer]
# Brainfuck in Python, 567 bytes
A relatively simple solution, as Brainfuck is hardly the most difficult language to write an interpreter for.
This implementation of Brainfuck has the data pointer starting at 0, only allowed to take a positive value (considered an error if it tries to go to the left of 0). The data cells can take on values from 0 to 255 and wrap. The 5 valid instructions are `><+[]` (`-` is unnecessary due to the wrapping).
I think the output is all correct now, however it is difficult to be sure that it is printing every possible solution so I may be missing some.
```
o="><+]["
A="[]if b%s1<0else[(p,a+1,b%s1,t+[0],h)]"
C="[(p,h[a]+1,b,t,h)if t[b]%s0else(p,a+1,b,t,h)]"
I=lambda s,i:i*">"if""==s else o[o.find(s[0])+i-5]+I(s[1:],i*o.find(s[0])>3)
s="";l=[]
while 1:
s=I(s,1)
r=[];h={}
for i in range(len(s)):
if s[i]=="[":r+=[i]
if s[i]=="]":
if r==[]:break
h[r[-1]]=i;h[i]=r[-1];r=r[:-1]
else:
if r==[]:
l+=[(s,0,0,[0],h)];i=0
while i<len(l):
p,a,b,t,h=l[i]
if a>=len(p):print p;l[i:i+1]=[]
else:l[i:i+1]=eval([A%("+","+"),A%("-","-"),"[(p,a+1,b,t[:b]+[(t[b]+1)%256]+t[b+1:],h)]",C%">",C%"=="][o.find(p[a])]);i+=1
```
The first few ouputs:
```
>
+
>>
+>
><
>+
++
[]
>>>
+>>
```
And a list of the first 2000: <http://pastebin.com/KQG8PVJn>
And finally a list of the first 2000 outputs with `[]` in them: <http://pastebin.com/iHWwJprs>
(all the rest are trivial as long as they're valid)
Note that the output is not in a sorted order, though it may appear that way for many of them, as the programs that take longer will be printed later.
[Answer]
# [Bitwise Cyclic Tag](http://esolangs.org/wiki/Bitwise_Cyclic_Tag) in CJam, ~~98~~ ~~87~~ ~~84~~ 77 bytes
```
L{Z):Z2b1>_,,1>\f{/([\:~]a2*}+{)~[\({1+(:X+\_0=Xa*+}{0+\1>}?_{]a+}{];p}?}%1}g
```
Since this is an infinite loop, you can't directly test this in the online interpreter. However, [here is an alternative version](http://cjam.aditsu.net/#code=L%7BZ)%3AZ2b1%3E_%2C%2C1%3E%5Cf%7B%2F(%5B%5C%3A~%5Da2*%7D%2B%7B)~%5B%5C(%7B1%2B(%3AX%2B%5C_0%3DXa*%2B%7D%7B0%2B%5C1%3E%7D%3F_%7B%5Da%2B%7D%7B%5D%3Bp%7D%3F%7D%25%7Dl~*&input=50) that reads the number of iterations from STDIN for you to play around with. To test the full program, you'll need [the Java interpreter](https://sourceforge.net/projects/cjam/files/cjam-0.6.5/).
BCT is a minimalist variant of [Cyclic Tag Systems](http://en.wikipedia.org/wiki/Tag_system#Cyclic_tag_systems). A program is defined by two binary strings: a (cyclic) list of instructions and an initial state. To make my life easier when printing the programs, I have defined my own notation: each of the strings is given as a CJam-style array of integers, and the entire program is surrounded in `[[...]]`, e.g.
```
[[[0 0 1 1] [0 1 1 1 0]]]
```
I'm also disallowing empty initial states or empty instruction lists.
Instructions in BCT are interpreted as follows:
* If the instruction is `0`, remove the leading bit from the current state.
* If the instruction is `1`, read another bit off the instruction list, call that `X`. If the leading bit from the current state is `1`, append `X` to the current state, otherwise do nothing.
If the current state ever becomes empty, the program halts.
The first few halting programs are
```
[[[0] [0]]]
[[[0] [1]]]
[[[0 0] [0]]]
[[[0] [0 0]]]
[[[0 0] [1]]]
[[[0] [0 1]]]
[[[0 1] [0]]]
[[[0] [1 0]]]
[[[0 1] [1]]]
[[[0] [1 1]]]
```
If you want to see more, check out the version in the online interpreter I linked above.
## Explanation
Here is how the code works. To keep track of the dovetailing we will always have an array on the stack which contains all the programs. Each program is pair of an internal representation of the program code (like `[[0 1 0] [1 0]]`) as well as the current state of the program. We'll only use the latter to do the computation, but we'll need to remember the former to print the program once it halts. This list of programs is simply initialised to an empty array with `L`.
The rest of the code is an infinite loop `{...1}g` which first adds one or more programs to this list and the computes one step on each program. Programs that halt are printed and removed from the list.
I'm enumerating the programs by counting up a binary number. The leading digit is stripped off to ensure that we can get all programs with leading 0s as well. For each such truncated binary representation, I push one program for each possible splitting between instructions and initial state. E.g. if the counter is currently at `42`, its binary representation is `101010`. We get rid of leading `1` and push all non-empty splittings:
```
[[[0] [1 0 1 0]]]
[[[0 1] [0 1 0]]]
[[[0 1 0] [1 0]]]
[[[0 1 0 1] [0]]]
```
Since we don't want empty instructions or states, we start the counter at 4, which gives `[[[0] [0]]]`. This enumeration is done by the following code:
```
Z):Z e# Push Z (initially 3), increment, and store in Z.
2b1> e# Convert to base 2, remove initial digit.
_, e# Duplicate and get the number of bits N.
,1> e# Turn into a range [1 .. N-1].
\ e# Swap the range and the bit list.
f{ e# Map this block onto the range, copying in the bit list on each iteration.
/ e# Split the bit list by the current value of the range.
( e# Slice off the first segment from the split.
[
\:~ e# Swap with the other segments and flatten those.
] e# Collect both parts in an array.
a2* e# Make an array that contains the program twice, as the initial state is the
e# same as the program itself.
}
+ e# Add all of these new programs to our list on the stack.
```
The rest of the code maps a block onto the list of programs, which performs one step of the BCT computation on the second half of these pairs and removes the program if it halts:
```
)~ e# Remove the second half of the pair and unwrap it.
[ e# We need this to wrap the instructions and current state back in an array
e# again later.
\( e# Bring the instruction list to the top and remove the leading bit.
{ e# If it's a 1...
1+ e# Append a 1 again (the instructions are cyclic).
(:X+ e# Remove the next bit, store it in X and also append it again.
\_0= e# Bring the current state to the top, get its first bit.
Xa*+ e# Append X if that bit was 1 or nothing otherwise.
}{ e# Else (if it's a 0...)
0+ e# Append a 0 again (the instructions are cyclic).
\1> e# Discard the leading bit from the current state.
}?
_ e# Duplicate the current state.
{ e# If it's non-empty...
]a+ e# Wrap instructions and state in an array and add them to the program
e# pair again.
}{ e# Else (if it's empty)...
];p e# Discard the instructions and the current state and print the program.
}?
```
[Answer]
# subleq OISC in Python, ~~317~~ 269 bytes
```
import collections
g=0
P={}
while 1:
P[g]=[[0],collections.defaultdict(int,enumerate(list(int(x)for x in reversed(str(g)))))]
g+=1
for o,[a,p]in P.items():
i=a[0]
p[i+p[i+1]]-=p[i+p[i]]
if p[i+p[i+1]]<=0:a[0]+=p[i+2]
else:a[0]+=3
if a[0]<0:print o;del P[o]
```
<https://esolangs.org/wiki/Subleq>
A subleq program is an extensible list of integers (p) and an instruction pointer (i). This subleq variant uses relative addressing, which the wiki talk page suggests is required for turing completeness with bounded values. Each tick, the operation `p[i+p[i+1]]-=p[i+p[i]]` is performed, and then `i+=p[i+2]` if the operation result was <=0, otherwise `i+=3`. If i is ever negative, the program halts.
This implementation tests every program whose initial state is comprised of one-digit non-negative integers (0-9) with an initial instruction pointer of 0.
```
Output:
21 (which represents the program [1 2 0 0 0 0 0...]
121
161
221
271
351
352
461
462
571
572
681
682
791
792
```
The output is reversed, for golfing reasons. The spec above could be restated in reverse, but then would not match the code used in the implementation, so I've not described it that way.
EDIT: The first program that exhibits simple unbounded growth is 14283, which decrements the value at memory location 6 and writes an explicit 0 (as opposed to the implicit 0 in every cell) to the next negative cell, every three ticks.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) → [Post correspondence problem](https://en.wikipedia.org/wiki/Post_correspondence_problem), 10 bytes
```
≜;?{~c}ᵐ\d
```
[Try it online!](https://tio.run/##ASgA1/9icmFjaHlsb2cy/@KGsOKCgeG6ieKKpf/iiZw7P3t@Y33htZBcZP// "Brachylog – Try It Online")
Function which is a generator that generates all possible Post correspondence problems for which brute-forcing solutions eventually halts. (Brute-forcing solutions to the Post correspondence problem is known to be a Turing-complete operation.) The TIO link contains a header that converts a generator to a full program, and prints each output immediately as it's generated (thus, when TIO kills the program due to consuming more than 60 seconds of execution time, the output produced so far is visible).
This uses a formulation of the problem in which the strings are given as strings of digits, leading zeroes are not permitted except for `0` itself, solutions to the problem involving leading zeroes are not accepted, and a string of digits can be represented as either the number, or minus the number. Clearly, none of this has any impact on the Turing-completeness of the language (because there's no need for a Post correspondence problem to use the digit zero at all).
This program works via generating all possible solutions to problems, then working backwards to find the original programs that are solved by them. As such, an individual program can be output many times. It's unclear whether this invalidates the answer or not; note that all halting programs will eventually be output at least once (in fact, infinitely many times, as any program which has solutions has infinitely many solutions), and non-halting programs will never be output.
## Explanation
```
≜;?{~c}ᵐ\d
≜ Brute-force all numbers:
;? Pair {the number} with {itself}
{ }ᵐ For each pair element:
~c Brute-force a partition of that element into substrings
\ such that the two elements each have the same number of substrings
\ and group together corresponding substrings
d and remove duplicated pairs {to produce a possible output}
```
[Answer]
# [SK combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) in [Haskell](https://www.haskell.org/), 249 bytes
```
data C=H|S|K|C:$C deriving(Eq,Show)
n(a:$b)=m a*n b
n a=m a
m S=1
m K=1
m(S:$a)=n a
m _=0
f H=[S,K,S:$H,K:$H,S:$H:$H]
f a=[S:$b:$c:$d|b:$d:$(c:$e)<-[a],d==e,n b*n c*n d>0]++[K:$a:$H|n a>0]++do b:$c<-[a];[d:$c|d<-f b]++[b:$d|n b>0,d<-f c]
l=H:(f=<<l)
```
[Try it online!](https://tio.run/##HU5BasMwELzrFXvQwWpkcHtUvbmYgsGEHnQ0JqwtOzGRlTQJ6UVvr7sySKNhZndGZ3pcRu/X1dGToMI62tjEysgK3HifX3M4ZV8/2p6vv0qEjIzsFS5AbwF6EYASFwtYfGdsEmbWSFIYNv2IhZigxtbqRrNR6yZBYnw69og9DjVyMNJFfp2RGfNRlXlLnXaIo@YyLhz4un3R7XYtp/BX6sgtm@CukCK2lc@WI4boynyCPg2nUJ7s94XexKETHmuTTViWXq0LzQEXuh2OcLvP4Ql@/RsmT6fHmn9//AM "Haskell – Try It Online")
### How it works
The call-by-value evaluation rules for the SK combinator calculus are as follows:
(a) S*xyz* ↦ *xz*(*yz*), for *x*, *y*, *z* in normal form;
(b) K*xy* ↦ *x*, for *x*, *y* in normal form;
(c) *xy* ↦ *x*′*y*, if *x* ↦ *x*′;
(d) *xy* ↦ *xy*′, for *x* in normal form, if *y* ↦ *y′*.
Since we are only interested in halting behavior, we expand the language slightly by introducing a symbol H that is not in normal form, but to which all normal forms “evaluate”:
(a) S*xyz* ↦ *xz*(*yz*), for *x*, *y*, *z* in normal form;
(b′) K*x*H ↦ *x*, for *x* in normal form;
(c) *xy* ↦ *x*′*y*, if *x* ↦ *x*′;
(d) *xy* ↦ *xy*′, for *x* in normal form, if *y* ↦ *y′*;
(e) S ↦ H;
(f) K ↦ H;
(g) SH ↦ H;
(h) KH ↦ H;
(i) SHH ↦ H.
We consider any application H*x* to be a run-time error to be treated as if it were an infinite loop, and we order evaluations such that no H is produced by (e)–(i) except in a context where it will be ignored (top level, any K*x*☐, any ignored K☐, any ignored S*x*☐ for *x* in normal form, any ignored S☐H). This way we do not affect the halting behavior of the usual terms lacking H.
The benefits of these modified rules are that every normalizable term has a unique evaluation path to H, and that every term has a finite number of possible preimages under ↦. So instead of using the dovetailing approach, we can do a much more efficient breadth-first search of all reverse evaluation paths from H.
`n` checks whether a term is in normal form, `f` finds all possible preimages of a term, and `l` is a lazy infinite list of normalizable terms produced by breadth-first search from H.
[Answer]
# slashes in Python, ~~640~~ 498 bytes
```
g=2
P={}
while 1:
b=bin(g)[3:]
P[b]=[[0],['',''],[b]]
g+=1
for d,[a,b,c]in P.items():
s=c[0]
if a[0]:
if s.count(b[0]):s=s.replace(b[0],b[1],1)
else:a[0]=0
else:
if s[0]=='0':
if len(s)==1:del P[d];continue
s=s[2:]
else:
b[0]=b[1]=''
a[0]=1
t=p=0
while t<2:
p+=1
if p>=len(s):break
if s[p]=='0':
if p+1>=len(s):break
b[t]+=s[p+1]
p+=1
else:t+=1
if t<2:del P[d];continue
c[0]=s
if len(s)==0:print d;del P[d]
```
<https://esolangs.org/wiki////>
A slashes program is a string, in this interpreter limited to the characters '/' and '\'. In this implementation, / is '1' and \ is '0' to allow for some golfing with the use of python's bin(x). When the interpreter encounters a \, the next character is output and both characters are removed. When it encounters a /, it looks for search and replace patterns as /search/replace/ including escaped characters within the patterns (\\ represents \ and \/ represents /). That replace operation is then performed on the string repeatedly until the search string is no longer present, then interpretation continues from the beginning again. The program halts when it is empty. A program will be killed if there is an unclosed set of /patterns or a \ with no character after it.
```
Example output and explanations:
01 outputs '1' and halts
00 outputs '0' and halts
0101 outputs '11' and halts
0100 ...
0001
0000
010101
010100
010001
010000 ...
101110 replaces '1' with '', leaving '00', which outputs '0' and halts
```
[Answer]
# [Treehugger](https://esolangs.org/wiki/Treehugger) in Java, ~~1,299~~ ~~1,257~~ ~~1,251~~ ~~1,207~~ ~~1,203~~ ~~1,201~~ ~~1,193~~ ~~1,189~~ 934 bytes
```
import java.util.*;class M{static class N{N l,r;byte v;}static class T extends Stack<N>{{push(new N());}int i,h;char[]s;}static void s(T t){if(t.i<t.s.length){int i=1,c=94-t.s[t.i],C;N P=t.peek(),T=c>33?P.l:P.r,S=new N();if(c==34|c==32)t.push(T==null?c>33?P.l=S:(P.r=S):T);if(c==0)do t.pop();while(t.size()<1);if(c==3&(P.v+=c<52&c>48?50-c:0)==0|c==1&P.v!=0)for(;i>0;i-=C*C<2?C:0)C=t.s[t.i+=c-2]-92;else++t.i;}else t.h=1;}static char[]n(char[]a){var b="<^>[+-]";int q=a.length,i=q,j;for(;i-->0;a[i]=60)if((j=b.indexOf(a[i]))<6){a[i]=b.charAt(j+1);return a;}a=Arrays.copyOf(a,q+1);a[q]=60;return a;}public static void main(String[]a){var z=new ArrayList<T>();for(char[]c={};;){T t=new T();if(b(t.s=c))z.add(t);c=n(c.clone());for(T u:z)try{s(u);if(u.h>0){z.remove(u);System.out.println(u.s);break;}}catch(Exception e){z.remove(u);break;}}}static boolean b(char[]c){int i=0;for(var d:c)if((i+=d>90&d<94?92-d:0)<0)return 0>0;return i==0;}}
```
Thanks to ceilingcat for saving ~250 bytes
[Answer]
## "Purple without I/O" in Ceylon, 662
```
import ceylon.language{l=variable,I=Integer,m=map,S=String}class M(S d){l value t=m{*d*.hash.indexed};l I a=0;l I b=0;l I i=0;I g(I j)=>t[j]else 0;value f=m{97->{a},98->{b},65->{g(a)},66->{g(b)},105->{i},49->{1}};value s=m{97->((I v)=>a=v),98->((I v)=>b=v),65->((I v)=>t=m{a->v,*t}),66->((I v)=>t=m{b->v,*t}),105->((I v)=>i=v)};I&I(I)x{throw Exception(d);}I h(I v)=>f[v]?.first else x;shared void p(){(s[g(i)]else x)(h(g(i+1))-h(g(i+2)));i+=3;}}shared void run(){value a='!'..'~';{S*}s=expand(loop<{S*}>{""}((g)=>{for(c in a)for(p in g)p+"``c``"}));l{M*}r={};for(p in s){r=[M(p),*r];for(e in r){try{e.p();}catch(x){print(x.message);r=r.filter(not(e.equals));}}}}
```
[Purple](http://esolangs.org/wiki/Purple) is a self-modifying one-instruction language which was [asked to interpret here](https://codegolf.stackexchange.com/q/65411/2338). As input and output are not relevant for this task, I removed the `o` symbol's meaning from the interpreter, such that the (potentially) valid symbols are just `a`, `b`, `A`, `B`, `i` and `1` (the last one just for reading, not for writing).
But as Purple is self-modifying (and using its source code as data), potentially also programs containing other than those characters are useful, so I **opted to allow all printable (non-whitespace) ASCII characters in the code (other ones might be useful as well, but are not as easily printed).**
(You can modify the interpreter to instead take as string of allowed characters as a command line argument – switch the commented line defining `a` below. Then the length becomes 686 bytes.)
My "parallel" interpreter thus creates all finite strings from those characters (in increasing length and lexicographical order) and tries each of them.
Purple will halt without error whenever the command to be read from the tape for execution is not valid – thus there are no invalid programs and many, many halting ones. (Most halt even at the first step, only some of the programs with length 3 come to the second step (and will halt then), the first non-halting ones have length 6.
I think the very first non-halting program in the order tried by my interpreter is `aaaiaa`, which in the first step sets the `a` register to 0 (which it already was), and the second and every following step sets the instruction pointer back to 0, causing it to execute `iaa` again.
I reused part of the code written for [my interpreter of "standard" Purple](https://codegolf.stackexchange.com/a/65492/2338), but due to the removal of input and output, my parallel interpreter becomes even slightly shorter than that, while including the additional logic for executing multiple programs at once.
Here is a commented and formatted version:
```
// Find (enumerate) all halting programs in (a non-I/O subset of) Purple.
//
// Question: https://codegolf.stackexchange.com/q/51273/2338
// My answer: https://codegolf.stackexchange.com/a/65820/2338
// We use a turing-complete subset of the Purple language,
// with input and output (i.e. the `o` command) removed.
import ceylon.language {
l=variable,
I=Integer,
m=map,
S=String
}
// an interpreting machine.
class M(S d) {
// The memory tape, as a Map<Integer, Integer>.
// We can't modify the map itself, but we
// can replace it by a new map when update is needed.
l value t = m {
// It is initialized with the code converted to Integers.
// We use `.hash` instead of `.integer` because it is shorter.
*d*.hash.indexed
};
// three registers
l I a = 0;
l I b = 0;
l I i = 0;
// get value from memory
I g(I j) =>
t[j] else 0;
// Map of "functions" for fetching values.
// We wrap the values in iterable constructors for lazy evaluation
// – this is shorter than using (() => ...).
// The keys are the (Unicode/ASCII) code points of the mapped
// source code characters.
value f = m {
// a
97 -> { a },
// b
98 -> { b },
// A
65 -> { g(a) },
// B
66 -> { g(b) },
// i
105 -> { i },
// 1
49 -> { 1 }
};
// Map of functions for "storing" results.
// The values are void functions taking an Integer,
// the keys are the ASCII/Unicode code points of the corresponding
// source code characters.
value s = m {
// a
97 -> ((I v) => a = v),
// b
98 -> ((I v) => b = v),
// Modification of the memory works by replacing the map with
// a new one.
// This is certainly not runtime-efficient, but shorter than
// importing ceylon.collections.HashMap.
// A
65 -> ((I v) => t = m { a->v, *t }),
// B
66 -> ((I v) => t = m { b->v, *t }),
// i
105 -> ((I v) => i = v)
};
// Exit the interpretation, throwing an exception with the machine's
// source code as the message. The return type is effectively `Nothing`,
// but shorter (and fits the usages).
I&I(I) x {
throw Exception(d);
}
// accessor function for the f map
I h(I v) =>
f[v]?.first else x;
// a single step
shared void p() {
(s[g(i)] else x)(h(g(i + 1)) - h(g(i + 2)));
i += 3;
}
}
// the main entry point
shared void run() {
// the alphabet of "Purple without I/O".
value a = '!'..'~';
//// possible alternative to use a command line argument:
// value a = process.arguments[0] else '!'..'~';
// an iterable consisting of all programs in length + lexicographic order
{S*} s =
// `expand` creates a single iterable (of strings, in this case)
// from an iterable of iterables (of strings).
expand(
// `loop` creates an iterable by applying the given function
// on the previous item, repeatedly.
// So here we start with the iterable of length-zero strings,
// and in each iteration create an iterable of length `n+1` strings
// by concatenating the length `n` strings with the alphabet members.
loop<{S*}>{ "" }((g) =>
{
for (c in a)
for (p in g)
p + "``c``"
}));
// This is a (variable) iterable of currently running machines.
// Initially empty.
l {M*} r = {};
// iterate over all programs ...
for(p in s) {
// Create a machine with program `p`, include it
// in the list of running machines.
//
// We use a sequence constructor here instead of
// an iterable one (i.e. `r = {M(p, *r)}` to prevent
// a stack overflow when accessing the deeply nested
// lazy iterable.
r = [M(p), *r];
// iterate over all running machines ...
for(e in r) {
try {
// run a step in machine e.
e.p();
} catch(x) {
// exception means the machine halted.
// print the program
print(x.message);
// remove the machine from the list for further execution
r = r.filter(not(e.equals));
}
}
// print(r.last);
}
}
```
] |
[Question]
[
The sequence [A109648](https://oeis.org/A109648) starts with the following numbers
```
53, 51, 44, 32, 53, 49, 44, 32, 52, 52, 44, 32,
51, 50, 44, 32, 53, 51, 44, 32, 52, 57, 44, 32,
52, 52, 44, 32, 51, 50, 44, 32, 53, 50, 44, 32,
53, 50, 44, 32, 52, 52, 44, 32, 51, 50, 44, 32,
53, 49, 44, 32, 53, 48, 44, 32, 52, 52, 44, 32,
51, 50, 44, 32, 53, 51, 44, 32, 53, ...
```
and has the description of
>
> Sequence is its own ASCII representation (including commas and spaces).
>
>
>
This is the unique sequence with the property. Your task is compute this sequence.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules and [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") [I/O methods](https://codegolf.stackexchange.com/tags/sequence/info) apply. The shortest code in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
```
f=lambda n:ord(`map(f,n*[n/4])+[5]`[1+n])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNzXTbHMSc5NSEhXyrPKLUjQSchMLNNJ08rSi8_RNYjW1o01jE6INtfNiNaEa1CpsDbjKMzJzUhUqbIwMDKwKijLzShLSNCo0E7SVdJR0rCu0bQ2tIaph1gAA)
Thanks to @loopywalt
Uses Python's string representation of tuples to get the `,` parts of the sequence (`44, 32`).
## [Python 2](https://docs.python.org/2/), 42 bytes
```
f=lambda n:ord("5"[n:]or`f(n/4),1`[1+n%4])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN7XSbHMSc5NSEhXyrPKLUjSUTJWi86xi84sS0jTy9E00dQwTog2181RNYjWhOpQqbA24yjMyc1IVDK0KijLzSoBKKzQTtJV0lHSsK7RtDa0hKmF2AAA)
Here are some variations, but I've not been able to get any of them shorter:
```
f=lambda n:ord(`5*(n<1)or f(n/4),1`[1+n%4])
f=lambda n:ord(`0**n*5or f(n/4),1`[1+n%4])
f=lambda n:ord(`[5][n:]or[f(n/4)]*n`[1+n])
f=lambda n:ord(`[5]+[n and f(n/4)]*n`[1+n])
f=lambda n:ord(`0**n*-5or[f(n/4)]*n`[1+n])
f=lambda n:ord(`-~-n*"5"or[f(n/4)]*n`[1+n])
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
```
f=n=>n?[...f(n>>2)+'',28,16][n%4]^48:53
```
[Try it online!](https://tio.run/##FcrRCoIwFADQX7kvsntxDS0LEzbpO8ximMZE72RK0NcvezovZ7Qfu3bBLduB/auPcdCsDdeNUmpANuZIqRDyWMr80jacFO2jKKvzKXaeVz/1avJv/OdbCPaLeZZRq2a7ID4lOAJtYMDdFNBBAnkGWmu4Qg1C3llAtQuCSI3eMQpBagtuRqL4Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~58~~ ~~57~~ ~~55~~ 48 bytes
-1 (-2) thanks to [alephalpha](https://codegolf.stackexchange.com/questions/240278/an-ascii-self-referential-sequence/240290?noredirect=1#comment542669_240290)
```
Nest[Rest@*ToCharacterCode@*ToString,!5,#][[#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCQ6CEg4aIXkO2ckFiUml6QWOeenpIIEgkuKMvPSdRRNdZRjo6OVY2PV/gcARUr0HdLqHIuKEivrDA3@AwA "Wolfram Language (Mathematica) – Try It Online")
Returns the \$n\$th element, 1-indexed.
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes
```
If[#<1,53,Join[48+IntegerDigits@#0@‚åä#/4‚åã,{44,32}][[#~Mod~4+1]]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMtWtnGUMfUWMcrPzMv2sRC2zOvJDU9tcglMz2zpNhB2cDhUU@Xsr7Jo55unWoTEx1jo9rY6GjlOt/8lDoTbcPY2Fi1/wFFmXklDo5FRYmV0Wk6RgY6BrH/AQ "Wolfram Language (Mathematica) – Try It Online")
Implements the formula given on the OEIS page.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
≔⊗⊖⊗Nθ≔5ηW‹Lηθ≔⪫Eη℅κ, η…ηθ
```
[Try it online!](https://tio.run/##LYy7DsIwDEV3viLq5EhFKgNTJ1QWEK9fSFOrjkidkqQgvj6kpR6ubOvco0l57ZRN6RCC6RmObmotdnBE7XFAjvO@/k48TvE2DS16kHlK8ZL1Zi0W@6IUlO8PGYsCLhhCDu4jAS2oFCt6dobhqkagUtx9Z1hZeM66bCjk3/LwhiM0X22xIbeg2VCntKuqtH3bHw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` elements, joined with comma and space. Explanation:
```
≔⊗⊖⊗Nθ
```
Calculate the length of the desired output.
```
≔5η
```
Start with the initial `5`, whose ASCII code starts with itself.
```
W‹Lηθ
```
Until the string is long enough...
```
≔⪫Eη℅κ, η
```
... join its ASCII codes with comma space.
```
…ηθ
```
Output the desired number of terms.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
5?(‛, jC)Ẏ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI1PyjigJssIGpDKeG6jiIsIiIsIjMiXQ==)
Outputs the first n terms, although it actually calculates the first n^3 terms.
```
5 # Starting with 5
?( ) # input times...
‚Äõ, j # Join by `, `
C # Get charcodes
Ẏ # At end, get first n
```
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 24 bytes
```
q=53:tl(Or<ic", "(sh<q))
```
This defines `q` an infinite list representing the sequence.
If you want the actual string of the sequence you can do that for 1 more byte:
```
q=ic", "$sh<Or<('5':tl q)
```
## Explanation
So here we define `q` in terms of itself.
A naive answer might look like:
```
q=Or<ic", "(sh<q)
```
Which takes `q` maps `show` across it to convert all the numbers to strings, intercalates `", "` with `ic`, to get the string and maps `Or` to get the char points.
However if we define this the resulting list is just an infinite loop and never manages to produce the first element. So we need to tell it what the first element is. To do this we take what we had, chop off the first element and put the correct answer in it's place.
This allows Haskell to skip to the second element when calculating this list which it can calculate in terms of the first element just fine. And from there every successive element can be calculated just fine.
[Answer]
# [J](http://jsoftware.com/), 40 37 bytes
```
$_2".@}.[:,0&(]', ',~"#.3":"+@u:":)&5
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/VeKNlPQcavWirXQM1DRi1XUU1HXqlJT1jJWslLQdSq2UrDTVTP9rcqUmZ@QrpClYcAG1G3CZGusomBrqKJiY6CgYGwHZQL6JJRIfiqF8LpBaUwNU9Sj6QdgcoV7zPwA "J – Try It Online")
-3 thanks to Bubbler's idea of taking first `n` terms with `$` instead of returning the nth term
Inspired by [emanrasu A's answer](https://codegolf.stackexchange.com/a/240280/15469)
Yikes.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▓░δΓ╙öâ'╜Ä
```
[Run and debug it](https://staxlang.xyz/#p=b2b0ebe2d3948327bd8e&i=5)
freezes at 10.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 76 bytes
```
f(n){char*s=calloc(n,8),*t=s;for(*s=53;n--;)t+=sprintf(t,"%d, ",*s++);n=*s;}
```
[Try it online!](https://tio.run/##pVLLasMwELznKxaBQbJlSOOYJqjqpfQrkhyMLCemjhIkQQ3Bv153/UgaX0pDBQs7q5lhtSsV75Vq24IadlGHzIZOqqyqTooavmI89NKJ4mQp1tNEmDgWzEfSnW1pfEE9J0HOgfDQRRETRoZONC1ewTErDWVwmQGe3hh0fdbK6xwkkDThkD5xWC45JAvMES/Xd3iMG0ZuOp/yJ/ounh/U/4b/oJ/02@HVP/pHTMQwrJNxfhyZOmj1oe1mhzO7kG39vtjW6zeMlCD/DiekGdTOZianvjxqOmdsqOH@gHZLKU2ua7SaizF9gQXmUdQj1pOHjXWnUxhk944scN5W2tDrFkfvK9EisftE06rG6lWwMbufy/H/kCDJIX6FIIfAbQ0@ynCw/PZuK6XejZ7NrGm/VFFle9fGn98 "C (gcc) – Try It Online")
Inputs a \$0\$-based index \$n\$.
Returns the \$n^\text{th}\$ element.
[Answer]
# [R](https://www.r-project.org/), ~~83~~ ~~79~~ ~~74~~ 59 bytes
```
function(n){x=5
for(i in 1:n)x=utf8ToInt(toString(x))
x[n]}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPs7rC1pQrLb9II1MhM0/B0CpPs8K2tCTNIiTfM69EoyQ/uKQoMy9do0JTk6siOi@29n9mXklIfihQhUZxYkFBTqWGoZWhgU6apuZ/AA "R – Try It Online")
Credit to Dominic van Essen for -4 bytes
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), ~~63~~ ~~35~~ 28 bytes
*Edit: -28 and then -7 more bytes (!) thanks to Razetime*
```
{ùï©‚Üë{-‚üú@¬®‚àæ‚àæ‚üú", "¬®‚Ä¢Fmt¬®ùï©}‚çüùï©‚•ä5}
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=QVNDSUlfc3JzIOKGkCB78J2VqeKGkXst4p+cQMKo4oi+4oi+4p+cIiwgIsKo4oCiRm10wqjwnZWpfeKNn/CdlanipYo1fQoKQVNDSUlfc3JzIDgg)
Outputs first n elements of sequence for input n. But, to get this, calculates the first 4^n elements. So times-out (or crashes) on the online REPL for even moderate n.
Ungolfed, commented ([try it here](https://mlochbaum.github.io/BQN/try.html#code=TG9nMTAg4oaQIDEw4oq44ouG4oG8ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICMgYmFzZSAxMCBsb2dhcml0aG0KTjJkIOKGkCBOdW1iZXJfdG9fZGlnaXRzIOKGkCB7KDEw4ouG4oy94oaV4oyITG9nMTAg8J2VqSkoMTB8wrfijIrDtynLnPCdlal9ICMgZ2V0IGJhc2UgMTAgZGlnaXRzCk4ycyDihpAgTnVtYmVyX3RvX3N0cmluZyDihpAgJzAn4oq4K8KoIE4yZCAgICAgICAgICAgICAgICAgICMgc3RyaW5nIHJlcHJlc2VudGF0aW9uClMyYSDihpAgU3RyaW5nX3RvX0FTQ0lJIOKGkCBA4oq4KC3LnCnCqCAgICAgICAgICAgICAgICAgICAgICAjIEFTQ0lJIGNvZGVzIG9mIHN0cmluZwoKQVNDSUlfc3JzIOKGkCB78J2VqeKGkXtTMmHiiL7CtCjiiL7in5wiLCAiKeKImE4yc8Ko8J2VqX3ijZ/wnZWpIOKfqDXin6l9ICAjIHN0YXJ0IHdpdGgg4p+oNeKfqSwKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIyByZXBlYXQgaW5wdXQgdGltZXM6CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICMgIGdldCBzdHJpbmcgcmVwcmVzZW50YXRpb25zLAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAjICBqb2luICIsICIgdG8gZWFjaCwKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIyAgam9pbiBpdCBhbGwgdG9nZXRoZXIsIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAjICBhbmQgY29udmVydCB0byBBU0NJSSBjb2RlczsKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIyBmaW5hbGx5IGdldCBpbnB1dCBlbGVtZW50cy4KQVNDSUlfc3JzIDgg)):
```
Log10 ← 10⊸⋆⁼ # base 10 logarithm
N2d ‚Üê Number_to_digits ‚Üê {(10‚ãÜ‚åΩ‚Üï‚åàLog10 ùï©)(10|¬∑‚åä√∑)Àúùï©} # get base 10 digits
N2s ← Number_to_string ← '0'⊸+¨ N2d # string representation
S2a ← String_to_ASCII ← @⊸(-˜)¨ # ASCII codes of string
ASCII_srs ‚Üê {ùï©‚Üë{S2a‚à欥(‚àæ‚üú", ")‚àòN2s¬®ùï©}‚çüùï© ‚ü®5‚ü©}
⟨5⟩} # start with ⟨5⟩,
‚çüùï© # repeat input times:
N2s¬®ùï©} # get string representations,
(‚àæ‚üú", ")‚àò # join ", " to each,
∾´ # join it all together,
{S2a # and convert to ASCII codes;
{ùï©‚Üë # finally get input elements.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 40 bytes
```
->n{a=*5
n.times{a=(a*", ").bytes}
a[n]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtFWy5QrT68kMze1GMjRSNRS0lFQ0tRLqixJLa7lSozOi639X6CQFm1oEPsfAA "Ruby – Try It Online")
a lambda that returns the n-th element
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 83 bytes
```
a@1={53};a[n_]:=a[n]=Join[a[n-1],ToCharacterCode@StringTake[ToString@a[n-1],{n+1}]]
```
[Try it online!](https://tio.run/##LYqxCgIxEAV/xV6FC2KjBCLprA5MtyzyOIMXzCUQtjvu29eAVm9meAtkjgskTVCfI9otZwIrnLHr@bRdQeXJF9uH7b2mQp2Ohg@h@hkNk8Tm6yu6h7RU3gGfSKH@xP2va9mbjVnHHsXtQGYYWPUL "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) + `-pa`, 42 bytes
```
$_=53;$_.=", ".ord+(/./g)[++$;]while"@F">$
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbU2FolXs9WSUdBSS@/KEVbQ19PP10zWltbxTq2PCMzJ1XJwU3JTuX/fyNTs3/5BSWZ@XnF/3ULEnMA "Perl 5 – Try It Online")
## Explanation
Naiive approach, builds the string from `53` and appends the `ord`inal values. 0-indexed, prints up to the `n`th term.
Uses `$;` to store the counter to save a byte at the end from the `-p` flag.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 49 bytes
```
f(n)=if(n,Vec(Vecsmall(Str(f(n-1)))[2..n+1]),[5])
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P00jT9M2E0jqhKUmawBxcW5iTo5GcEmRBlBQ11BTUzPaSE8vT9swVlMn2jRW839BUWZeCVDSyEBT8z8A "Pari/GP – Try It Online")
1-indexed. Based on the PARI/GP code on the OEIS page.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@Zq,ú2)cY}h#5ìL
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFpxLPoyKWNZfWgjNexM&input=MTA)
[Answer]
# Excel VBA, ~~69~~ 50 bytes
Saved 19 bytes thanks to a total re-write by Taylor Raine
```
?"53";:t=3:Do:k=", "&Asc(t):t=Mid(t &k,2):?k;:Loop
```
The function is typed directly into the immediate window and output is in the same window. It will run until it's stopped (`ESC`) or it hits a software / hardware limitation like running out memory.
Colons are line line breaks in VBA. Here's a version with some nicer formatting and comments.
```
?"53"; ' Print "53" without a line break at the end
t = 3 ' Seed the value for t
Do ' Start a loop
k = ", " & Asc(t) ' Store the ASCII value for the first character in t
t = Mid(t & k, 2) ' Set t be everything in t & k except the first character
?k; ' Print the value of k without a line break at the end
Loop ' Go back to "Do"
```
[Answer]
# APL+WIN, 60 bytes
Prompts for required term number. Index origin = 0
```
i←0⋄s←53 51 44 32⋄⍎∊(n←⎕)⍴⊂'s←s,(⎕av⍳⍕s[i←i+1]),44 32⋄'⋄s[n]
```
TIO examples generate the first column of the tabular form of the series as depicted in the question.
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tfyaI@ai7pRhImxormBoqmJgoGBsBRR719j3q6NLIA0oA9Wg@6t3yqKtJHaSuWEcDKJJY9qh386PeqcXRIDMytQ1jNXVgetVBJkbnxf4H2sH1P43LgCuNy9AISBiZAAljMyBhYgEkzAy4AA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 17 bytes
```
↑¹!¡ȯmcJ", "ms;53
```
[Try it online!](https://tio.run/##yygtzv7//1HbxEM7FQ8tPLE@N9lLSUdBKbfY2tT4////RgYA "Husk – Try It Online")
---
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
↑¹!¡ȯJ", "mosc"5
```
With output as character string (ASCII values represent sequence A109648)
[Try it online!](https://tio.run/##yygtzv7//1HbxEM7FQ8tPLHeS0lHQSk3vzhZyfT///@mBgA "Husk – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
5Δ„, ýÇI£
```
Outputs the first \$n\$ results.
[Try it online.](https://tio.run/##yy9OTMpM/f/f9NyURw3zdBQO7z3c7nlo8f//hgYA)
**Explanation:**
```
5 # Start with a 5
Δ # Loop until the result no longer changes:
„, ý # Join with ", " delimiter
Ç # Convert it to a list of its codepoint integers
I£ # Only leave the first input amount of values
# (after the loop, the resulting list is output implicitly)
```
] |
[Question]
[
I noticed that it seems nobody has posted a non-ASCII ([related](https://codegolf.stackexchange.com/questions/52615/print-the-american-flag)) USA flag challenge yet, so what better time than the 4th of July?
## The Challenge
Draw the current (as of 2022) flag of the United States of America.
Here is the flag:
[](https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg)
### Specifications
[](https://upload.wikimedia.org/wikipedia/commons/a/ab/Flag_of_the_United_States_specification.svg)
* Hoist (height) of the flag: A = 1.0
* Fly (width) of the flag: B = 1.9
* Hoist (height) of the canton ("union"): C = 0.5385 (A × 7/13, spanning seven stripes)
* Fly (width) of the canton: D = 0.76 (B × 2/5, two-fifths of the flag width)
* E = F = 0.0538 (C/10, one-tenth of the height of the canton)
* G = H = 0.0633 (D/12, one twelfth of the width of the canton)
* Diameter of star: K = 0.0616 (L × 4/5, four-fifths of the stripe width, the calculation only gives 0.0616 if L is first rounded to 0.077)
* Width of stripe: L = 0.0769 (A/13, one thirteenth of the flag height)
The colors used are (as RGB tuples and hex codes):
* White: `255,255,255` or `#FFFFFF`;
* Old Glory Red: `179,25,66` or `#B31942`;
* Old Glory Blue: `10,49,97` or `#0A3161`.
Source: [Wikipedia](https://en.wikipedia.org/wiki/Flag_of_the_United_States#Design)
### Rules
* The image must be sized at a 19:10 ratio, and at least 760 by 400 pixels (if it is a raster image).
* If your language does not allow to use arbitrary RGB colors you may use any colors reasonably recognizable as "white", "red", and "blue".
* The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed in a window.
* Your program must create the image and not just load it from a website.
* Built-in flag images, flag-drawing libraries, [horrendously upscaling a flag emoji](https://chat.stackexchange.com/transcript/message/60681392#60681392) or any [other emoji](https://codegolf.stackexchange.com/a/245345/73593) are prohibited.
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
Since the flag can change at any time following the admission of one or more new states, let's make our programs futureproof! **-10 bonus points**
if your program can draw other star dispositions by accepting as an **optional** argument a list of star coordinates (which may be a number different than 50) in any coordinate system of your choice (inspired by this [challenge](https://codegolf.stackexchange.com/questions/28784/the-star-spangled-code-challenge)).
* If such optional argument is not provided, your program **must** draw the flag as previously described.
* If an empty list is passed as a parameter, you can either draw no stars, or treat it as if no argument has been given (and hence draw the standard flag).
* The other parts of the flag (the stripes and the blue background) must be the same in any case.
---
[Sandbox](https://codegolf.meta.stackexchange.com/a/24946/73593)
[Answer]
# PostScript, ~~193~~ ~~185~~ ~~170~~ 158 bytes - 10 = 148
```
00000000: 2f73 7b92 4e38 2e32 3392 6c92 3e37 926c /s{.N8.23.l.>7.l
00000010: 3630 9201 92ad 3020 3492 6b34 7b31 3434 60....0 4.k4{144
00000020: 9288 3020 3492 637d 9283 9242 924d 7d92 ..0 4.c}...B.M}.
00000030: 3328 0a31 61b3 1942 297b 3235 3592 367d 3(.1a..B){255.6}
00000040: 9249 929d 3088 1488 787b 3092 3e32 3437 .I..0...x{0.>247
00000050: 880a 9280 7d92 4892 9d30 883c 3938 2e38 ....}.H..0.<98.8
00000060: 8846 9280 3192 9692 1a30 923d 7b31 8801 .F..1....0.={1..
00000070: 327b 2f69 923e 9233 6920 3288 0b7b 6988 2{/i.>.3i 2..{i.
00000080: 0239 7b31 9258 737d 9248 7d92 487d 9248 .9{1.Xs}.H}.H}.H
00000090: 7d7b 7b7b 737d 9265 7d92 a37d 9255 }{{{s}.e}..}.U
```
Untokenized version:
```
/s{ % y x s -
gsave % star of radius 4 at (x,y)
8.23 mul exch 7 mul 60 add % scale and translate position
translate % move origin
0 4 moveto 4{144 rotate 0 4 lineto}repeat % draw star
fill % fill it
grestore
}def
<0a3161b31942>{255 div}forall % push blue, red color values
setrgbcolor % red
0 20 120{0 exch 247 10 rectfill}for % stripes
setrgbcolor % blue
0 60 98.8 70 rectfill % rectangle
1 setgray % white
count 0 eq{ % if stack empty: standard stars
1 1 2{/i exch def
i 2 11{i 2 9{1 index s}for}for % grid of stars, offset i=1,2
}for
}{ % if stack not empty
{{s}loop}stopped % place stars until stack empty
}ifelse
```
If called without arguments, produces the standard flag.
[](https://i.stack.imgur.com/508jK.png)
Takes optional arguments from the stack, which can be inserted from the command line like this:
`gs -c '3 2 5 4' -- usflag.ps`
That plots two stars at (2,3) and (4,5), where (1,1) is the position of the bottom-left star in the standard flag, and the horizontal and vertical units are chosen so that H=1 and F=1.
[](https://i.stack.imgur.com/4Lkng.png)
### Without custom star placement: 131 bytes
Removing the custom star placement code saves 27 bytes:
```
00000000: 280a 3161 b319 4229 7b32 3535 9236 7d92 (.1a..B){255.6}.
00000010: 4992 9d30 8814 8878 7b30 923e 3234 3788 I..0...x{0.>247.
00000020: 0a92 807d 9248 929d 3088 3c39 382e 3888 ...}.H..0.<98.8.
00000030: 4692 8031 9296 3188 0132 7b2f 6992 3e92 F..1..1..2{/i.>.
00000040: 3369 2032 880b 7b69 8802 397b 3192 5892 3i 2..{i..9{1.X.
00000050: 4e38 2e32 3392 6c92 3e37 926c 3630 9201 N8.23.l.>7.l60..
00000060: 92ad 3020 3492 6b34 7b31 3434 9288 3020 ..0 4.k4{144..0
00000070: 3492 637d 9283 9242 924d 7d92 487d 9248 4.c}...B.M}.H}.H
00000080: 7d92 48 }.H
```
which only draws the standard flag, and is equivalent to
```
<0a3161b31942>{255 div}forall % push blue, red color values
setrgbcolor % red
0 20 120{0 exch 247 10 rectfill}for % stripes
setrgbcolor % blue
0 60 98.8 70 rectfill % rectangle
1 setgray % white
1 1 2{/i exch def i 2 11{i 2 9{
1 index
gsave % star of radius 4 at (x,y)
8.23 mul exch 7 mul 60 add % scale and translate position
translate % move origin
0 4 moveto 4{144 rotate 0 4 lineto}repeat % draw star
fill % fill it
grestore
}for}for}for
```
[Answer]
# BBC BASIC, ~~210~~ 199 bytes
```
V.19;45840;25,66
F.i=0TO13j=1ANDi+1PLOT101-j,1852*j,i*75N.V.19;2576;49,97,25881;741;450;
F.i=9TO107V.29,i DIV9*61.75;i MOD9*52.5+502;
MOVE0,30F.j=1TO5k=j*88/35MOVE0,0PLOT88-i MOD2,SINk*30,COSk*30N.N.
```
The golfed code contains many of the following obfuscations:
* Abbreviated keywords
* Commands like PLOT and MOVE rendered as lower level VDU commands where expedient for golfing reasons.
* Many pairs of 8-bit VDU codes (terminated by comma) are replaced by 16-bit VDU codes (terminated by semicolon.)
The following are all equivalent: `MOVE x,y`, `PLOT 4,x,y`, `VDU 25,4,x,y`. The value 4 in the plot statement can take many values for everything from moving to drawing rectangles and triangles. BBC basic keeps track of the last two positions of the graphics cursor to facilitate these operations.
**Interpreter**
Download interpreter at <https://www.bbcbasic.co.uk/bbcwin/download.html>
This interpreter has several differences from the original BBC basic. Firstly the default screen mode is black on white, with the white background being set to `255,255,255` by default.
Secondly, the palette reprogramming `VDU 19`operates quite differently. Original BBC basic could display (depending on mode) up to 16 different logical colours at a time (to save memory) and these could be assigned to any 18-bit physical colour. Reprogramming the palette would immediately change all existing pixels of that logical colour to the new physical colour. With this interpreter, full 24-bit colour is supported and only pixels drawn after the `VDU 19` are affected.
**Explanation**
I selected a value of L=75 and scaled the flag accordingly, in order to make most dimensions integers.
Hopefully the comments below are fairly self explanatory. We draw the stripes first, leaving the cursor at top left to conveniently draw the blue canton by specifying its bottom right corner.
Stars are plotted in the background colour (white.) The origin is changed to the centre of each star prior to plotting for convenience. Stars are plotted on a 9x11 checkerboard grid. Only odd number stars are plotted. For the even number stars, the cursor still moves to trace out the star, but nothing is plotted.
BBC basic keeps track of the last two coordinates visited by the cursor. The stars are drawn as a series of five thin triangles by defining the current point, centre of the star, and the previous point 144 degrees away.
**Ungolfed code**
```
VDU19,0,16,179,25,66 :REM Change foreground colour to red
FORi=0TO13 :REM Iterate 14 times from bottom to top
j=1ANDi :REM j=0 at bottom of red stripe, j=1 at top
PLOT100+j,1852*(1-j),i*75 :REM If j=0 move to bottom right of stripe
NEXT :REM If j=1 draw a rectangle from bottom right to top left
VDU19,0,16,10,49,97 :REM Change foreground colour to blue
PLOT101,741,450 :REM Draw blue canton from top left to bottom right
FORi=9TO107 :REM Iterate through 99 possible star positions in checkerboard
VDU29,i DIV9*61.75;i MOD9*52.5+502.5;:REM Reset the origin to centre of star on 9x11 grid
MOVE0,30 :REM Move cursor to top of star
FORj=1TO5 :REM Iterate through star points
k=j*88/35 :REM k = j * (4/5*PI = 4/5 * 22/7 = 144 degrees)
MOVE0,0 :REM Move to centre of star
PLOT84+i MOD2*3,30*SIN k,30*COS k :REM If i is odd draw a triangle linking the latest point to the last 2
NEXT :REM cursor positions, namely the centre and the previous point
NEXT :REM If i is even draw nothing.
```
[](https://i.stack.imgur.com/pOtiw.png)
[Answer]
# [Scratch](https://scratch.mit.edu/), ~~588~~ 535 bytes
[Try it online!](https://scratch.mit.edu/projects/711617098/)
```
define(W)(H
repeat(H
change y by(1
pen down
set x to(W
set x to(-190
pen up
define(X)(Y)(Q
set[y v]to(Y
repeat(Q
set[x v]to(X
change[y v]by(21
repeat((Q)+(1
pen up
go to x(x)y(y
set pen color to[#fff
pen down
set[c v]to[
repeat(5
point in direction(
move(1)steps
turn cw(162)degrees
change[c v]by(2
repeat(5
move(c)steps
turn cw(144)degrees
end
change[x v]by(-5
when gf clicked
go to x(-190)y(-93
set pen color to[#b31942
erase all
repeat(7
[190][15
change y by(16
end
set y to(
set pen color to[668001
[-38][108
(-52)(-8)(5
(-64)(2)(4
```
@att saved 42 bytes by forgoing the -10 byte bonus, and combined the star placement and generation scripts. att also removed the function (custom block) names and converted a hex color to [Scratch's RGB system](https://en.scratch-wiki.info/wiki/Computer_Colors#RGB_Colors).
## Explanation
```
define(W)(H custom rectangle function
repeat(H loop for each px of height
change y by(1 moves up 1px
pen down applies pen
set x to(W moves horizontally a specified amount
set x to(-190 resets x-position
pen up stops applying pen
define(X)(Y)(Q custom star & placement function
set[y v]to(Y sets starting y to a specified amount
repeat(Q loop for each row of stars
set[x v]to(X sets starting x to a specified amount
change[y v]by(21 increases y value by 21px
repeat((Q)+(1 loop for each star in the width
pen up stops applying pen
go to x(x)y(y goes to coordinate specified by vars
set pen color to[#fff sets pen color to white
pen down applies pen
set[c v]to[ sets a counter to null (implicit 0)
repeat(5 loop enough to fill star
point in direction( resets facing angle
move(1)steps move 1px in the facing angle
turn cw(162)degrees rotates 162 degrees
change[c v]by(2 increases the counter 'c'
repeat(5 loop for each point of the star
move(c)steps moves 'c'px in the facing angle
turn cw(144)degrees rotates 144 degrees
end syntax
change[x v]by(-5 increases the x position
when gf clicked syntax
go to x(-190)y(-93 resets position
set pen color to[#b31942 sets color to Old Glory Red*
erase all clears stage
repeat(7 loop for each stripe
[190][15 draw a red stripe
change y by(16 skip over a white stripe
end syntax
set y to( resets y position
set pen color to[668001 sets color to Old Glory Blue*
[-38][108 draws the canton
(-52)(-8)(5 draws a 6 by 5 array of stars
(-64)(2)(4 draws a 5 by 4 array of stars
*The project uses HSB approximations of the specified colors.
This code uses HEX values and base-10 equivalents.
```
[Answer]
# Desmos, 305 bytes
```
l=[0...9]
a=[1...13]
b=[1...5]
P(x,y)=polygon(x+WcosR,y+WsinR)
W=[1,2/(3+\sqrt5)][mod(l,2)+1]120
R=l\pi/5+\pi/2
0<=x<=7410\{3a-3<=.01y<=3a\}
0<=x<=2964\{18<=.01y<=39\}
w=hsv(0,0,1)
v=rgb(10,49,97)
r=[w,rgb(179,25,66)][mod(a,2)+1]
[P(494i-247,4110-420j)fori=[1...6],j=b]
[P(494i,3900-420j)fori=b,j=[1...4]]
```
[Try it on Desmos!](https://www.desmos.com/calculator/6idahimq2n)
-35 bytes thanks to Aiden Chow
[Answer]
# [R](https://www.r-project.org), 398 bytes
```
\(w='#FFFFFF',r='#B31942',g=\(x,y,d)polygon(x,y,,,F,d),c=7/13,l=c/7,f=c/10,b=1.9,d=.76,h=d/12,z=rep,x=c(z(1:6,5)-.5,z(1:5,4))*2*h,y=1-c(z(1:5,,,6)-.5,z(1:4,,,5))*f*2,p=\(x,y,s=sinpi,d=l*.4,a=0:9/5,e=d*(s(.2)/s(.4))^2)g(x+c(d,e)*s(a),y+c(d,e)*cospi(a),w)){frame();plot.window(c(0,b),0:1);for(i in 0:6)g(c(d*(i>2),d*(i>2),b,b),c(0,l,l,0)+l*i*2,r);g(c(0,0,d,d),c(1-c,1,1,1-c),'#0A3161');mapply(p,x,y)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVFrToNAEI43aeIPZrbDYylQC1kT_dFTNCaUV7ehsIEaSo1X8AL-qRov5WlcwLqTzGu__XYe7x_N5XMvvp-PuXn3c_O2gU4Yt-vxGNRo_3HBV55rUCE2cKKeUlR12Rd1NUZEa52hRCxtvqBSJPaScq25Q1vBrRWlwloGtBOpzV06iyZTdBIJnIGHAfloWj4Nvk8eInPZjnrBzene1-zBP8LTka8xOXNJ_dXSilZWSupPSmZ5FAsnXNk-ZSJl0ILloq21Jn5ysYDTPIGUMmQtxEj9NUrqVskh0yG-5E18yAAjVdZHq5NVWneQgO4FyQk5RnndgJzJauaEgabUFAzkvYt0tdsBOrwotTg4L5nU9TYYFSOPQ-k4LtA9Eh_ETJCMW-dhwQNuYHSIlSp70EOiHl-ntXztASfvcpnsLw)
Takes optional inputs x, y which are the x- and y- components of a list of coordinates.
Multiline form:
```
j=\(w='#FFFFFF',r='#B31942',g=\(x,y,d)polygon(x,y,,,F,d),
c=7/13,l=c/7,f=c/10,b=1.9,d=.76,h=d/12,z=rep,x=c(z(1:6,5)-.5,z(1:5,4))*2*h,y=1-c(z(1:5,,,6)-.5,z(1:4,,,5))*f*2,
p=\(x,y,s=sinpi,d=l*.4,a=0:9/5,e=d*(s(.2)/s(.4))^2)g(x+c(d,e)*s(a),y+c(d,e)*cospi(a),w)){
frame()
plot.window(c(0,b),0:1)
for(i in 0:6)g(c(d*(i>2),d*(i>2),b,b),c(0,l,l,0)+l*i*2,r)
g(c(0,0,d,d),c(1-c,1,1,1-c),'#0A3161')
mapply(p,x,y)
}
```
The ratio of inner to outer diameters of the pentagonal star was calculated using a pair of similar isoceles triangles with tip angle pi/5 (36 degrees).
`j()` plots the following:
[](https://i.stack.imgur.com/obTol.png)
`j(x=c(0.2,0.3),y=c(0.7,0.8))` plots the following:
[](https://i.stack.imgur.com/M2YxG.png)
A few bytes could be saved by not pre-defining w/r since they are only used once.
[Answer]
# SVG(HTML5), ~~576~~ ~~560~~ 522 bytes
```
<svg viewBox=0,0,741,390><path d=M0,15H741m0,60H0m0,60H741m0,60H0m0,60H741m0,60H0m0,60H741m0,60H0 stroke=#B31942 stroke-width=30 /><rect width=296.4 height=210 fill=#0A3161 /><g fill=#fff><g id=8><g id=9><g id=5><g id=4><g id=2><path id=1 d=M24.7,9,31.7534230,30.7082039,13.2873218,17.2917961H36.1126782L17.6465770,30.7082039z /><use href=#1 y=42 /></g><use href=#2 y=84 /></g><use href=#1 y=168 /></g><use href=#4 x=24.7 y=21 /></g><use href=#9 x=49.4 /></g><use href=#8 x=98.8 /><use href=#9 x=197.6 /><use href=#5 x=247
```
I started trying to code this manually but half-way though I discovered that Jay Bala's Wikipedia specification image linked in the question had already golfed the repetition of the stars, so I just removed the explanation, updated the colours to match the question, and golfed it down to the bare minimum acceptable in HTML5. Edit: Turns out that I'd been looking at the wrong image all along - as @Deadcode points out the flag itself is linked in the question, and it uses `#fff` instead of `#ffffff` in two places, thus saving 6 bytes, but I was able to save a further 10 bytes by golfing the star repetition even further. Edit: Saved 38 bytes thanks to @bartyslartfast by dividing all the lengths by 10 and by assuming a white background and only drawing the red stripes.
[Answer]
## SVG(HTML5), 369 bytes
At first glance, repeating the stars with a `<use>` element looks like a good idea, but it isn't. A `<pattern>` element, even with the pesky `patternUnits=userSpaceOnUse` gets much better results.
Node positions of the stars have been rounded to integers, but that leaves the error <1.25% (0.5 for diameter=40).
```
<svg viewBox=0,0,1235,650><pattern id=p x=22 y=16 width=82 height=70 patternUnits=userSpaceOnUse><path d=M7,35,19,0,31,35,0,13H38ZM48,70,60,35,72,70,41,48H79Z fill=#fff /></pattern><path d=M0,25H1235m0,100H0m0,100H1235m0,100H0m0,100H1235m0,100H0m0,100H1235 stroke=#B31942 stroke-width=50 /><path d=M0,0H494V350H0Z fill=#0A3161 /><path d=M22,16h451v315H22Z fill=url(#p)
```
[Answer]
# Mathematica, 40 bytes
```
Entity["Country", "UnitedStates"]["Flag"]
```
This is not competing, since it does not follow the rules.
But it shows off the power of Mathematica, IMHO.
[Answer]
# Python3 (pillow), 403
```
from PIL import Image,ImageDraw as X
W,R,I,O,N=0xffffff,range,Image.new('RGB',(1001,520),4331955),56,66
d=X.Draw(I);Q=d.rectangle
[Q((0,j,1001,40+j),fill=W)for j in R(40,520,80)];Q((0,0,400,279),fill=6359601)
d.polygon([x-20for x in map(ord,'2 0*$*-0+:239:70@*4*2 ')],fill=W)
s,P=I.crop((16,12,44,38)),I.paste;[(P(s,(16+i*N,12+j*O)),P(s,(50+j*N,40+k*O)))for i in R(6)for j in R(5)for k in R(4)]
I.show()
```
] |
[Question]
[
# Challenge
Write code that outputs TeX (LaTeX) math-equation code (given below) that will typeset Sierpinski Triangle Fractal of 5 levels. **Shortest code wins**.
# Details
TeX (and friends like LaTeX, etc.) is a sophisticated typesetting system. It can render arbitrary nested complex expressions for mathematical formulas. Coincidentally this "nested complex" is also descriptive of fractals. The following is rendered with MathJaX
$${{{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}^{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}\_{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}}^{{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}^{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}\_{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}}\_{{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}^{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}\_{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}}}$$
by the following plain-text math-equation code consisting of nested super- and sub-scripts:
```
{{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}^{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}_{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}}
```
Note this is just a 5-level nesting. You do not need to generate `$...$` or `$$...$$` or other markup required to start/end a math equation in TeX & Co. You can preview generated TeX in many online editors, for instance: <http://www.hostmath.com> but you can find many others too. This question was inspired by a [discussion with friends](http://community.wolfram.com/groups/-/m/t/1188472).
# Update
There is a [similar question](https://codegolf.stackexchange.com/q/138245/4997) but it much more general and will produce different solutions. I wanted to see really kolmogorov-complexity for a very fixed simple code that in one system (TeX) is completely explicit while in another compressed. This also address the `n` instead of 5 levels comment.
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
```
exec"print'x'"+".join('{^_}')"*5
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P7UiNVmpoCgzr0S9Ql1JW0kvKz8zT0O9Oi6@Vl1TScv0/38A "Python 2 – Try It Online")
[Answer]
# plain TeX, 29 bytes
```
\def~#1x{{#1x_#1x^#1x}}~~~~~x
```
That outputs what others have output. But if we need the code to be compilable it would be 6 bytes more
```
\def~#1x{{#1x_#1x^#1x}}$~~~~~x$\bye
```
**Explanation**
`~` is an [active character](http://www.tex.ac.uk/FAQ-activechars.html) in TeX, so we can give it a (new) definition.
`\def~#1x{{#1x_#1x^#1x}}` defines `~` as a macro, so that when TeX sees `~`, it does the following:
* Read everything up to the next `x`, and call that `#1` (pattern-matching).
* Replace the whole thing with `{#1x_#1x^#1x}`
For example, `~ABCx` would get replaced with `{ABCx_ABCx^ABCx}`.
When `~~~~~x` is used, `#1` is `~~~~`, so the whole thing gets replaced with `{~~~~x_~~~~x^~~~~x}`. And so on.
Once we have the long string, we can print it out to terminal with `\message` (and ending with a `\bye` so TeX stops), so `\message{~~~~~x}\bye`. Or typeset the resulting expression (as a mathematical formula), by surrounding it in `$`s : so `$~~~~~x$\bye`.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~16~~ 12 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
x5{"{^_}”;∑
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIweDUlN0IlMjIlN0IlNUVfJTdEJXUyMDFEJTNCJXUyMjEx)
Port of Erik The Outgolfer's [Python 2 answer](https://codegolf.stackexchange.com/a/143276/59183)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
'x5F'x¡"{x^x_x}"ý
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fvcLUTb3i0EKl6oq4iviKWqXDe///BwA "05AB1E – Try It Online")
**Explanation**
```
'x # push "x"
5F # 5 times do
'x¡ # split on "x"
"{x^x_x}"ý # join on "{x^x_x}"
```
**Other programs at the same byte-count include**
```
"{x^x_x}"©4F'x¡®ý
'x5F'x"{x^x_x}".:
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~44~~ 35 bytes
```
"'x'"+"-replace'x','{x^x_x}'"*5|iex
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0m9Ql1JW0m3KLUgJzE5FcjTUa@uiKuIr6hVV9IyrclMrfj//79GdHJGYlF0bKx6UUZlSUZusbomAA "PowerShell – Try It Online")
Uses string multiplication to repeatedly `-replace` `x`es with the sub- and super-scripts, then output.
*Saved 9 bytes thanks to Joey.*
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~21~~ 20 bytes
```
'x'XJ5:"J'{x^x_x}'Zt
```
-1 byte thanks to *Giuseppe*
[Try it online!](https://tio.run/##y00syfn/X71CPcLL1ErJS726Iq4ivqJWPark/38A "MATL – Try It Online")
[Answer]
## JavaScript (ES6), ~~45~~ ~~42~~ 37 bytes
```
f=n=>n>4?'x':[...'{^_}'].join(f(-~n))
```
Edit: Saved ~~3~~ 2 bytes thanks to @Arnauld. Specifying 5 still costs me 2 bytes; this ~~41~~ ~~40~~ 35-byte version takes a parameter instead:
```
f=n=>n?[...'{^_}'].join(f(n-1)):'x'
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
'x5F"{^_}"Ssý
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fvcLUTak6Lr5WKbj48N7//wE "05AB1E – Try It Online")
Port of my Python 2 answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
”x“{^_}”j$5¡
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw9yKRw1zquPia4HMLBXTQwv//wcA "Jelly – Try It Online")
Port of my Python 2 answer.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~21~~ ~~20~~ 18 bytes
```
5Æ="\{^_}"¬qUª'xÃÌ
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=NcY9Ilx7Xl99IqxxVaoneMPM&input=)
---
## Explanation
```
5Æ Ã
```
Generate an array of length 5 and map over it.
```
"\{^_}"¬
```
Split a string to an array of characters
```
qUª'x
```
Rejoin (`q`) to a string using the current value of `U` or (`ª`) `"x"`.
```
=
```
Assign the result of that to `U`.
```
Ì
```
Get the last element in the array.
---
## Alternatives, 18 bytes
Same as above but reducing the array after it's been created.
```
5o r@"\{^_}"¬qX}'x
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=NW8gckAiXHteX30irHFYfSd4&input=)
The recursive option.
```
>4©'xª"\{^_}"¬qßUÄ
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=PjSpJ3iqIlx7Xl99Iqxx31XE&input=)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~179~~ 167 bytes
@Neil port
```
interface Y{static void main(String[]a){System.out.println(t.apply(1));}java.util.function.Function<Integer,String>t=N->N>0?Y.t.apply(N-1).replace("x","{x^x_x}"):"x";}
```
[Try it online!](https://tio.run/##NY6xCoMwFEV/RTIloI@61tZuhS4uTlLaEjRKrCYhPiUifnsaaLvdc4dzb88XnmgjVN@8vZcKhW15LaJqm5CjrKNFyyYauVS0RCtVd39wtpXrhGIEPSOYUOKgKAI3Zlhpyli298EKM8oB2lnVKLWC6y@cbmGjEzb@6nI8F0le5IdLBX9FkaQMrDBDOEKJIzHZ3NO93E7YMWC2e/8B "Java (OpenJDK 8) – Try It Online")
[Answer]
# Wolfram Language (*Mathematica*) - 40 characters
Summarizing 3 best answers [here](http://community.wolfram.com/groups/-/m/t/1188472):
### 40 bytes:
```
Nest["{"<>#<>"_"<>#<>"^"<>#<>"}"&,"x",5]
```
### 41 bytes:
```
Nest[StringReplace["x"->"{x^x_x}"],"x",5]
```
### 44 bytes:
```
Last@SubstitutionSystem["x"->"{x^x_x}","x",5]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 82 bytes
```
O(o){o--?_(125,O(o,_(95,O(o,_(94,O(o,_(123))))))):_(120);}main(){O(5);}
```
[Try it online!](https://tio.run/##S9ZNT07@/99fI1@zOl9X1z5ew9DIVAfI1YnXsIQzTKAMQyNjTQiwAnEMNK1rcxMz8zQ0q/01TIGc////JaflJKYX/9d1ibctKC1JzkgsAgA "C (gcc) – Try It Online")
[Answer]
# Pyth, ~~17~~ ~~16~~ 13 bytes
```
jF+\x*5]"{^_}
```
[Try it online!](https://tio.run/##K6gsyfj/P8tNO6ZCyzRWqTouvvb/fwA)
Python 3 translation:
```
from functools import*;print(reduce(lambda x,y:x.join(y),["x"]+5*["{^_}"]))
```
] |
[Question]
[
Imagine a continuous 2-dimensional path that can only turn left, right, or go straight, cannot intersect itself, and must fill a rectangular grid such as the grid of pixels in an image. We'll call this kind of path a *snake*.

This enlarged example shows a snake path in a 10×4 grid that starts out red and increases in hue by about 2% at every step until it is purple. (The black lines are only to emphasize the direction it takes.)
# Goal
The goal in this popularity contest is to write an algorithm that attempts to recreate a given image using a single snake whose color continuously changes by small amounts.
Your program must take in a true-color image of any size as well as a floating point value between 0 and 1 inclusive, the *tolerance*.
*Tolerance* defines the maximum amount the color of the snake is allowed to change in each pixel sized step. We'll define the distance between two RGB colors as the Euclidean distance between the two RGB points when arranged on an [RGB color cube](http://en.wikipedia.org/wiki/RGB_color_space). The distance will then be normalized so the maximum distance is 1 and the minimum distance is 0.
**Color distance pseudocode:** (Assumes all input values are integers in the range `[0, 255]`; output is normalized.)
```
function ColorDistance(r1, g1, b1, r2, g2, b2)
d = sqrt((r2 - r1)^2 + (g2 - g1)^2 + (b2 - b1)^2)
return d / (255 * sqrt(3))
```
If the result of calling this function on the snake's current color and another color is greater than the given tolerance then the snake may not change into that other color.
**If you prefer, you may use a different color distance function.** It must be something accurate and well documented such as those listed at <http://en.wikipedia.org/wiki/Color_difference>. You also must normalize it to be in within `[0, 1]`, i.e. the maximum possible distance must be 1 and the minimum must be 0. Tell us in your answer if you use a different distance metric.
# Test Images
You should of course post your output images (and even animations of the snake growing if you want). I suggest posting a variety of these images using different low tolerances (maybe around 0.005 to 0.03).


# Win Criteria
As stated, this is a popularity contest. The highest voted answer will win. Answers that provide the most accurate and aesthetically pleasing "snake path" depiction of the input images should be voted up.
**Any user who is found to be maliciously submitting images that are not actual snakes will be disqualified forever.**
# Notes
* Only one snake path may be used and it must completely fill the image without touching the same pixel twice.
* The snake may start and end anywhere in the image.
* The snake may start as any color.
* The snake must stay in the bounds of the image. The bounds are not cyclic.
* The snake cannot move diagonally or more than one pixel at a time.
[Answer]
## Python
I generate a dynamic path to minimize the color changes as the snake travels. Here are some images:
**tolerance = 0.01**


Cyclic color paths for the above images (blue to red, getting greener as it repeats):


The path is generated by starting with some initial path, then adding 2x2 loops onto it until the image is filled. The advantage of this method is that the loops can be added anywhere on the path, so you can't paint yourself into a corner and have more freedom to build the path you want. I keep track of the possible loops adjacent to the current path and store them in a heap, weighted by the color change along the loop. I then pop off the loop with the least color change and add it to the path, and repeat until the image is filled.
I actually track the loops alone ('DetourBlock' in the code), then reconstruct the path; this was a mistake as there are some special cases for odd width/height and I spent several hours debugging the reconstruction method. Oh well.
The path generation metric needs tuning and I also have an idea for better colorization, but I thought I'd get this out first since it works quite well. Except for this one, which seems better in some of the fixed paths:

Here's the Python code, with apologies for my atrocious coding habits:
```
# snakedraw.py
# Image library: Pillow
# Would like to animate with matplotlib... (dependencies dateutil, six)
import heapq
from math import pow, sqrt, log
from PIL import Image
tolerance = 0.001
imageList = [ "lena.png", "MonaLisa.png", "Mandrill.png", "smallGreatWave.png", "largeGreatWave.png", "random.png"]
# A useful container to sort objects associated with a floating point value
class SortContainer:
def __init__(self, value, obj):
self.fvalue = float(value)
self.obj = obj
def __float__(self):
return float(self.fvalue)
def __lt__(self, other):
return self.fvalue < float(other)
def __eq__(self, other):
return self.fvalue == float(other)
def __gt__(self, other):
return self.fvalue > float(other)
# Directional constants and rotation functions
offsets = [ (1,0), (0,1), (-1,0), (0,-1) ] # RULD, in CCW order
R, U, L, D = 0, 1, 2, 3
def d90ccw(i):
return (i+1) % 4
def d180(i):
return (i+2) % 4
def d90cw(i):
return (i+3) % 4
def direction(dx, dy):
return offsets.index((dx,dy))
# Standard color metric: Euclidean distance in the RGB cube. Distance between opposite corners normalized to 1.
pixelMax = 255
cChannels = 3
def colorMetric(p):
return sqrt(sum([ pow(p[i],2) for i in range(cChannels)])/cChannels)/pixelMax
def colorDistance(p1,p2):
return colorMetric( [ p1[i]-p2[i] for i in range(cChannels) ] )
# Contains the structure of the path
class DetourBlock:
def __init__(self, parent, x, y):
assert(x%2==0 and y%2==0)
self.x = x
self.y = y
self.parent = None
self.neighbors = [None, None, None, None]
def getdir(A, B):
dx = (B.x - A.x)//2
dy = (B.y - A.y)//2
return direction(dx, dy)
class ImageTracer:
def __init__(self, imgName):
self.imgName = imgName
img = Image.open(imgName)
img = img.convert(mode="RGB") # needed for BW images
self.srcImg = [ [ [ float(c) for c in img.getpixel( (x,y) ) ] for y in range(img.size[1]) ] for x in range(img.size[0])]
self.srcX = img.size[0]
self.srcY = img.size[1]
# Set up infrastructure
self.DetourGrid = [ [ DetourBlock(None, 2*x, 2*y) \
for y in range((self.srcY+1)//2)] \
for x in range((self.srcX+1)//2)]
self.dgX = len(self.DetourGrid)
self.dgY = len(self.DetourGrid[0])
self.DetourOptions = list() # heap!
self.DetourStart = None
self.initPath()
def initPath(self):
print("Initializing")
if not self.srcX%2 and not self.srcY%2:
self.AssignToPath(None, self.DetourGrid[0][0])
self.DetourStart = self.DetourGrid[0][0]
lastDB = None
if self.srcX%2: # right edge initial path
self.DetourStart = self.DetourGrid[-1][0]
for i in range(self.dgY):
nextDB = self.DetourGrid[-1][i]
self.AssignToPath(lastDB, nextDB)
lastDB = nextDB
if self.srcY%2: # bottom edge initial path
if not self.srcX%2:
self.DetourStart = self.DetourGrid[-1][-1]
for i in reversed(range(self.dgX-(self.srcX%2))): # loop condition keeps the path contiguous and won't add corner again
nextDB = self.DetourGrid[i][-1]
self.AssignToPath(lastDB, nextDB)
lastDB = nextDB
# When DetourBlock A has an exposed side that can potentially detour into DetourBlock B,
# this is used to calculate a heuristic weight. Lower weights are better, they minimize the color distance
# between pixels connected by the snake path
def CostBlock(self, A, B):
# Weight the block detour based on [connections made - connections broken]
dx = (B.x - A.x)//2
dy = (B.y - A.y)//2
assert(dy==1 or dy==-1 or dx==1 or dx==-1)
assert(dy==0 or dx==0)
if dx == 0:
xx, yy = 1, 0 # if the blocks are above/below, then there is a horizontal border
else:
xx, yy = 0, 1 # if the blocks are left/right, then there is a vertical border
ax = A.x + (dx+1)//2
ay = A.y + (dy+1)//2
bx = B.x + (1-dx)//2
by = B.y + (1-dy)//2
fmtImg = self.srcImg
''' Does not work well compared to the method below
return ( colorDistance(fmtImg[ax][ay], fmtImg[bx][by]) + # Path connects A and B pixels
colorDistance(fmtImg[ax+xx][ay+yy], fmtImg[bx+xx][by+yy]) # Path loops back from B to A eventually through another pixel
- colorDistance(fmtImg[ax][ay], fmtImg[ax+xx][ay+yy]) # Two pixels of A are no longer connected if we detour
- colorDistance(fmtImg[bx][by], fmtImg[bx+xx][by+yy]) ) # Two pixels of B can't be connected if we make this detour
'''
return ( colorDistance(fmtImg[ax][ay], fmtImg[bx][by]) + # Path connects A and B pixels
colorDistance(fmtImg[ax+xx][ay+yy], fmtImg[bx+xx][by+yy])) # Path loops back from B to A eventually through another pixel
# Adds a detour to the path (really via child link), and adds the newly adjacent blocks to the potential detour list
def AssignToPath(self, parent, child):
child.parent = parent
if parent is not None:
d = parent.getdir(child)
parent.neighbors[d] = child
child.neighbors[d180(d)] = parent
for (i,j) in offsets:
x = int(child.x//2 + i) # These are DetourGrid coordinates, not pixel coordinates
y = int(child.y//2 + j)
if x < 0 or x >= self.dgX-(self.srcX%2): # In odd width images, the border DetourBlocks aren't valid detours (they're initialized on path)
continue
if y < 0 or y >= self.dgY-(self.srcY%2):
continue
neighbor = self.DetourGrid[x][y]
if neighbor.parent is None:
heapq.heappush(self.DetourOptions, SortContainer(self.CostBlock(child, neighbor), (child, neighbor)) )
def BuildDetours(self):
# Create the initial path - depends on odd/even dimensions
print("Building detours")
dbImage = Image.new("RGB", (self.dgX, self.dgY), 0)
# We already have our initial queue of detour choices. Make the best choice and repeat until the whole path is built.
while len(self.DetourOptions) > 0:
sc = heapq.heappop(self.DetourOptions) # Pop the path choice with lowest cost
parent, child = sc.obj
if child.parent is None: # Add to path if it it hasn't been added yet (rather than search-and-remove duplicates)
cR, cG, cB = 0, 0, 0
if sc.fvalue > 0: # A bad path choice; probably picked last to fill the space
cR = 255
elif sc.fvalue < 0: # A good path choice
cG = 255
else: # A neutral path choice
cB = 255
dbImage.putpixel( (child.x//2,child.y//2), (cR, cG, cB) )
self.AssignToPath(parent, child)
dbImage.save("choices_" + self.imgName)
# Reconstructing the path was a bad idea. Countless hard-to-find bugs!
def ReconstructSnake(self):
# Build snake from the DetourBlocks.
print("Reconstructing path")
self.path = []
xi,yi,d = self.DetourStart.x, self.DetourStart.y, U # good start? Okay as long as CCW
x,y = xi,yi
while True:
self.path.append((x,y))
db = self.DetourGrid[x//2][y//2] # What block do we occupy?
if db.neighbors[d90ccw(d)] is None: # Is there a detour on my right? (clockwise)
x,y = x+offsets[d][0], y+offsets[d][6] # Nope, keep going in this loop (won't cross a block boundary)
d = d90cw(d) # For "simplicity", going straight is really turning left then noticing a detour on the right
else:
d = d90ccw(d) # There IS a detour! Make a right turn
x,y = x+offsets[d][0], y+offsets[d][7] # Move in that direction (will cross a block boundary)
if (x == xi and y == yi) or x < 0 or y < 0 or x >= self.srcX or y >= self.srcY: # Back to the starting point! We're done!
break
print("Retracing path length =", len(self.path)) # should = Width * Height
# Trace the actual snake path
pathImage = Image.new("RGB", (self.srcX, self.srcY), 0)
cR, cG, cB = 0,0,128
for (x,y) in self.path:
if x >= self.srcX or y >= self.srcY:
break
if pathImage.getpixel((x,y)) != (0,0,0):
print("LOOPBACK!", x, y)
pathImage.putpixel( (x,y), (cR, cG, cB) )
cR = (cR + 2) % pixelMax
if cR == 0:
cG = (cG + 4) % pixelMax
pathImage.save("path_" + self.imgName)
def ColorizeSnake(self):
#Simple colorization of path
traceImage = Image.new("RGB", (self.srcX, self.srcY), 0)
print("Colorizing path")
color = ()
lastcolor = self.srcImg[self.path[0][0]][self.path[0][8]]
for i in range(len(self.path)):
v = [ self.srcImg[self.path[i][0]][self.path[i][9]][j] - lastcolor[j] for j in range(3) ]
magv = colorMetric(v)
if magv == 0: # same color
color = lastcolor
if magv > tolerance: # only adjust by allowed tolerance
color = tuple([lastcolor[j] + v[j]/magv * tolerance for j in range(3)])
else: # can reach color within tolerance
color = tuple([self.srcImg[self.path[i][0]][self.path[i][10]][j] for j in range(3)])
lastcolor = color
traceImage.putpixel( (self.path[i][0], self.path[i][11]), tuple([int(color[j]) for j in range(3)]) )
traceImage.save("snaked_" + self.imgName)
for imgName in imageList:
it = ImageTracer(imgName)
it.BuildDetours()
it.ReconstructSnake()
it.ColorizeSnake()
```
And some more images at a **very low tolerance of 0.001**:



And also the great wave path because it's neat:

## EDIT
The path generation seems better when minimizing the color distance between the average colors of adjacent blocks, rather than minimizing the sum of the color distances between their adjacent pixels. Also, it turns out you can average the colors of any two tolerance-compliant snake paths and end up with another tolerance-compliant snake path. So I traverse the path both ways and average them, which smooths out a lot of the artifacts. Zombie Lena and Scary Hands Mona look much better. Final versions:
**Tolerance 0.01**:



**Tolerance 0.001**:



[Answer]
## Java
My program generate a snake path for a given width & height, using an algorithm similar to the one that generates the Hilbert curve.

*(little game: in the above picture, the snake starts at the top left corner. Can you find where he ends? Good luck :)*
Here are the results for various tolerance values :
**Tolerance = 0.01**

**Tolerance = 0.05**

**Tolerance = 0.1**

**Tolerance = 0.01**

**With 4x4 pixel blocks & the path visible**

**Computing the snake path**
A snake path is stored in a double dimension integer array. The snake always enters the grid by the upper left corner. There are 4 basic operation my program can do on a given snake path:
* create a new snake path for a grid of width 1 or height 1. The path is just a simple line that goes left to right or up to down, depending on the case.
* increase the grid height, by adding at the top a snake path from left to right, then by mirroring the grid (the snake must always enter the grid by the upper left corner)
* increate the grid width, by adding at the left a snake path from top to bottom, then by flipping the grid (the snake must always enter the grid by the upper left corner)
* double the dimension of the grid using an "Hilbert style" algorithm (see description below)
Using a series of these atomic operations, the program is able to generate a snake path of any given size.
The code below computes (in reverse order) which operations will be needed to obtain a given width & height. Once computed, the actions are executed one by one until we got a snake path of the expected size.
```
enum Action { ADD_LINE_TOP, ADD_LINE_LEFT, DOUBLE_SIZE, CREATE};
public static int [][] build(int width, int height) {
List<Action> actions = new ArrayList<Action>();
while (height>1 && width>1) {
if (height % 2 == 1) {
height--;
actions.add(Action.ADD_LINE_TOP);
}
if (width % 2 == 1) {
width--;
actions.add(Action.ADD_LINE_LEFT);
}
if (height%2 == 0 && width%2 == 0) {
actions.add(Action.DOUBLE_SIZE);
height /= 2;
width /= 2;
}
}
actions.add(Action.CREATE);
Collections.reverse(actions);
int [][] tab = null;
for (Action action : actions) {
// do the stuff
}
```
**Doubling the snake path size:**
The algorithm that double the size works as follow:
Consider this node which is linked to RIGHT and BOTTOM. I want to double its size.
```
+-
|
```
There are 2 ways to double its size and keep the same exits (right and bottom):
```
+-+-
|
+-+
|
```
or
```
+-+
| |
+ +-
|
```
To determine which one to choose, I need to handle for each node direction a "shift" value, indicating if the exit door is shifted left/right or up/down. I follow the path as the snake would do, and update the shift value along the path. The shift value determines uniquely which expanded block I need to use for the next step.
[Answer]
# Python
Here's a very simple algorithm to get things started. It starts at the top left of the image and spirals clockwise inwards, making the color as close as possible to the next pixel's color while staying within the tolerance.
```
import Image
def colorDist(c1, c2): #not normalized
return (sum((c2[i] - c1[i])**2 for i in range(3)))**0.5
def closestColor(current, goal, tolerance):
tolerance *= 255 * 3**0.5
d = colorDist(current, goal)
if d > tolerance: #return closest color in range
#due to float rounding this may be slightly outside of tolerance range
return tuple(int(current[i] + tolerance * (goal[i] - current[i]) / d) for i in range(3))
else:
return goal
imgName = 'lena.png'
tolerance = 0.03
print 'Starting %s at %.03f tolerance.' % (imgName, tolerance)
img = Image.open(imgName).convert('RGB')
imgData = img.load()
out = Image.new('RGB', img.size)
outData = out.load()
x = y = 0
c = imgData[x, y]
traversed = []
state = 'right'
updateStep = 1000
while len(traversed) < img.size[0] * img.size[1]:
if len(traversed) > updateStep and len(traversed) % updateStep == 0:
print '%.02f%% complete' % (100 * len(traversed) / float(img.size[0] * img.size[1]))
outData[x, y] = c
traversed.append((x, y))
oldX, oldY = x, y
oldState = state
if state == 'right':
if x + 1 >= img.size[0] or (x + 1, y) in traversed:
state = 'down'
y += 1
else:
x += 1
elif state == 'down':
if y + 1 >= img.size[1] or (x, y + 1) in traversed:
state = 'left'
x -= 1
else:
y += 1
elif state == 'left':
if x - 1 < 0 or (x - 1, y) in traversed:
state = 'up'
y -= 1
else:
x -= 1
elif state == 'up':
if y - 1 < 0 or (x, y - 1) in traversed:
state = 'right'
x += 1
else:
y -= 1
c = closestColor(c, imgData[x, y], tolerance)
out.save('%.03f%s' % (tolerance, imgName))
print '100% complete'
```
It takes a minute or two to run the larger images, though I'm sure the spiraling logic could be vastly optimized.
# Results
They're interesting but not gorgeous. Amazingly a tolerance above 0.1 produces quite accurate looking results.
The Great Wave at 0.03 tolerance:

Mona Lisa at 0.02 tolerance:

Lena at 0.03 tolerance, then 0.01, then 0.005, then 0.003:




Misc stuff at 0.1 tolerance, then 0.07, then 0.04, then 0.01:




[Answer]
# Cobra
```
@number float
use System.Drawing
class Program
var source as Bitmap?
var data as List<of uint8[]> = List<of uint8[]>()
var canvas as List<of uint8[]> = List<of uint8[]>()
var moves as int[] = @[0,1]
var direction as bool = true
var position as int[] = int[](0)
var tolerance as float = 0f
var color as uint8[] = uint8[](4)
var rotated as bool = false
var progress as int = 0
def main
args = CobraCore.commandLineArgs
if args.count <> 3, throw Exception()
.tolerance = float.parse(args[1])
if .tolerance < 0 or .tolerance > 1, throw Exception()
.source = Bitmap(args[2])
.data = .toData(.source to !)
.canvas = List<of uint8[]>()
average = float[](4)
for i in .data
.canvas.add(uint8[](4))
for n in 4, average[n] += i[n]/.source.height
for n in 4, .color[n] = (average[n]/.source.width).round to uint8
if .source.width % 2
if .source.height % 2
.position = @[0, .source.height-1]
.update
while .position[1] > 0, .up
.right
else
.position = @[.source.width-1, .source.height-1]
.update
while .position[1] > 0, .up
while .position[0] > 0, .left
.down
else
if .source.height % 2
.position = @[0,0]
.update
else
.position = @[.source.width-1,0]
.update
while .position[0] > 0, .left
.down
.right
.down
while true
if (1-.source.height%2)<.position[1]<.source.height-1
if .moves[1]%2==0
if .direction, .down
else, .up
else
if .moves[0]==2, .right
else, .left
else
.right
if .progress == .data.count, break
.right
.right
if .direction
.direction = false
.up
else
.direction = true
.down
image = .toBitmap(.canvas, .source.width, .source.height)
if .rotated, image.rotateFlip(RotateFlipType.Rotate270FlipNone)
image.save(args[2].split('.')[0]+'_snake.png')
def right
.position[0] += 1
.moves = @[.moves[1], 0]
.update
def left
.position[0] -= 1
.moves = @[.moves[1], 2]
.update
def down
.position[1] += 1
.moves = @[.moves[1], 1]
.update
def up
.position[1] -= 1
.moves = @[.moves[1], 3]
.update
def update
.progress += 1
index = .position[0]+.position[1]*(.source.width)
.canvas[index] = .closest(.color,.data[index])
.color = .canvas[index]
def closest(color1 as uint8[], color2 as uint8[]) as uint8[]
d = .difference(color1, color2)
if d > .tolerance
output = uint8[](4)
for i in 4, output[i] = (color1[i] + .tolerance * (color2[i] - _
color1[i]) / d)to uint8
return output
else, return color2
def difference(color1 as uint8[], color2 as uint8[]) as float
d = ((color2[0]-color1[0])*(color2[0]-color1[0])+(color2[1]- _
color1[1])*(color2[1]-color1[1])+(color2[2]-color1[2])*(color2[2]- _
color1[2])+0f).sqrt
return d / (255 * 3f.sqrt)
def toData(image as Bitmap) as List<of uint8[]>
rectangle = Rectangle(0, 0, image.width, image.height)
data = image.lockBits(rectangle, System.Drawing.Imaging.ImageLockMode.ReadOnly, _
image.pixelFormat) to !
ptr = data.scan0
bytes = uint8[](data.stride*image.height)
System.Runtime.InteropServices.Marshal.copy(ptr, bytes, 0, _
data.stride*image.height)
pfs = Image.getPixelFormatSize(data.pixelFormat)//8
pixels = List<of uint8[]>()
for y in image.height, for x in image.width
position = (y * data.stride) + (x * pfs)
red, green, blue, alpha = bytes[position+2], bytes[position+1], _
bytes[position], if(pfs==4, bytes[position+3], 255u8)
pixels.add(@[red, green, blue, alpha])
image.unlockBits(data)
return pixels
def toBitmap(pixels as List<of uint8[]>, width as int, height as int) as Bitmap
image = Bitmap(width, height, Imaging.PixelFormat.Format32bppArgb)
rectangle = Rectangle(0, 0, image.width, image.height)
data = image.lockBits(rectangle, System.Drawing.Imaging.ImageLockMode.ReadWrite, _
image.pixelFormat) to !
ptr = data.scan0
bytes = uint8[](data.stride*image.height)
pfs = System.Drawing.Image.getPixelFormatSize(image.pixelFormat)//8
System.Runtime.InteropServices.Marshal.copy(ptr, bytes, 0, _
data.stride*image.height)
count = -1
for y in image.height, for x in image.width
pos = (y*data.stride)+(x*pfs)
bytes[pos+2], bytes[pos+1], bytes[pos], bytes[pos+3] = pixels[count+=1]
System.Runtime.InteropServices.Marshal.copy(bytes, 0, ptr, _
data.stride*image.height)
image.unlockBits(data)
return image
```
Fills the image with a snake like:
```
#--#
|
#--#
|
#--#
|
```
This allows for much faster color adjustment than just lines in alternating directions, but doesn't become as blocky as a 3-wide version does.
Even at very low tolerances, the edges of an image are still visible (although at the loss of detail in smaller resolutions).
0.01

0.1

0.01

0.01

0.1

0.03

0.005

[Answer]
## C#
Snake starts at top left pixel with colour white and alternates left to right and then right to left down the image.
```
using System;
using System.Drawing;
namespace snake
{
class Snake
{
static void MakeSnake(Image original, double tolerance)
{
Color snakeColor = Color.FromArgb(255, 255, 255);//start white
Bitmap bmp = (Bitmap)original;
int w = bmp.Width;
int h = bmp.Height;
Bitmap snake = new Bitmap(w, h);
//even rows snake run left to right else run right to left
for (int y = 0; y < h; y++)
{
if (y % 2 == 0)
{
for (int x = 0; x < w; x++)//L to R
{
Color pix = bmp.GetPixel(x, y);
double diff = Snake.RGB_Distance(snakeColor, pix);
if (diff < tolerance)
{
snakeColor = pix;
}
//else keep current color
snake.SetPixel(x, y, snakeColor);
}
}
else
{
for (int x = w - 1; x >= 0; x--)//R to L
{
Color pix = bmp.GetPixel(x, y);
double diff = Snake.RGB_Distance(snakeColor, pix);
if (diff < tolerance)
{
snakeColor = pix;
}
//else keep current color
snake.SetPixel(x, y, snakeColor);
}
}
}
snake.Save("snake.png");
}
static double RGB_Distance(Color current, Color next)
{
int dr = current.R - next.R;
int db = current.B - next.B;
int dg = current.G - next.G;
double d = Math.Pow(dr, 2) + Math.Pow(db, 2) + Math.Pow(dg, 2);
d = Math.Sqrt(d) / (255 * Math.Sqrt(3));
return d;
}
static void Main(string[] args)
{
try
{
string file = "input.png";
Image img = Image.FromFile(file);
double tolerance = 0.03F;
Snake.MakeSnake(img, tolerance);
Console.WriteLine("Complete");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
```
Result image tolerance = 0.1

] |
[Question]
[
Gah! It's a shame that Pokémon Sword and Shield won't introduce a new eeveelution. Let's mourn them with a code golf.
The objective is to, when given a type name as the input, output the name of the corresponding eeveelution.
* When given `Water`, output `Vaporeon`.
* When given `Electric`, output `Jolteon`.
* When given `Fire`, output `Flareon`.
* When given `Psychic`, output `Espeon`.
* When given `Dark`, output `Umbreon`.
* When given `Grass`, output `Leafeon`.
* When given `Ice`, output `Glaceon`.
* When given `Fairy`, output `Sylveon`.
* All other input falls in *don't care* situation.
No other rules. Enjoy!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~77~~ 76 bytes
```
lambda s:'VFULJSGEalmeoylspaballaporrftvc'[hash(s)%3695%8::8]+'reon'[s<'V':]
```
[Try it online!](https://tio.run/##JYpBC4IwGEDP@St2kc/IU1HUyFspRYcgtIN5@FwbjpaTbzPw1xvW6T0erxt8Y9vlqJLHaPBdP5E5DkWaX8637IjmLe1gXIc1GoOdJVL@I6Bs0DWRm4erzW4dbjnfVgsgaVso3R4K4NWYJyXc0UuCmMHRSOFJi8lTTXLi1Q2i@acD0mtiRujcJCfxW1LUNEAVKEusZ7plOQ9mHenWsz5mKurn4xc "Python 2 – Try It Online")
In Python 2, the `hash` function consistently (across runs and also on different platforms) converts any immutable value into a 64-bit integer. By taking that integer first mod `3695`, then mod `8`, we get an integer `0<=i<8` (`3695` was found by brute force checking all possible values upto `10000`).
A common trick is used to encode a list of same-size strings into a single string and then using slicing via `[i::8]`to extract the strings without using `.split` or similar strategy. Only two options are not of length 4: `Esp` and `Vapor`. The former is handled by making it the last of the 8 strings encoded; and `Vapor` is handled using the final slicing `'reon'[s<'V':]`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~72 67 65~~ 64 bytes
```
{<Sylv Esp Glac Jolt Leaf Umbr Flar Vapor>[:36($_)%537%8]~'eon'}
```
[Try it online!](https://tio.run/##TZBPS8NAEMXP7qcYsH@SoiESbIu1OdkWiwehVA8llG26weC2G2ZWZQnpV4@7aw4efzOPmfdeJVCO25OBQQFzaOvHjZHfsKAKVpLnsFZSw4vgBWxPB4Sl5AhvvFKY7h6ScdDbh/37ZNKfZpehUOdh014TNyDLs6CIFOqgdrLoR@GRdnHWqZswTbvZaHaXWaCvA2kM4pvRbRLOGCsUQuDP/JfGGdTsyn3o7WGeQjQoWNO@cy06V9YDW0iRayz/vLvBskThnTt4JZN/2KVN6PCJ46eP5mCFnMindfScC9@BP8FLNOCqsfQL "Perl 6 – Try It Online")
A golf to all unique indexes by parsing the string as base 36 and moduloing it. I've left a version that just uses the sum below so other answer that may not have the same short base converting code that Perl 6/Raku does. There is also base 35 with modulo 51 and 10, but that comes out to the same byte count.
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 67 bytes
```
{<Leaf Esp Umbr Vapor 0 Sylv Flar Jolt Glac>[.ords.sum%64%9]~'eon'}
```
[Try it online!](https://tio.run/##LY@7CsJAEEVr8xVTGF9FsJCAaFKZiGIhiFqEIOO6weDmwWxUlqC/HncXyzOve6bmJPyuUDDIIICuXe44ZhDJGo7FleCEdUUwhYMSL4gFEmwr0cBaIAsTr6Kb9OSzcP2ZO0@/Q16Vw0@X6Y2RyEsux2Hovc1QMllMU2idnkQF/QsEIXiDzPl0Z2z4P0UvO5HgrKGc2RRTiHPiNtfAXip2101tZ3CF9LCWBtaEUoKRN7Rh3DraE5iTsg9o@gE "Perl 6 – Try It Online")
Differentiates between inputs by the sum of the ordinal values, modulo 64 modulo 9, leaving one extra spot to be filled in. Unfortunately, my [brute force script](https://tio.run/##PZBPa4NAFMTP7qd4B3VbSBeTQ0iJSg5NQksPhdA/EFJ4a1cqXaPs2hYR@9XNPoXuZZnHbwZmamX0cihbCHNIYOji@KHSDTwqzGGvMYOtreEF68pw/lxKA4dW/3D3dhpNmh5FZT6ssN9lsIiC@fz0x1V15j0lbtAl6uKsbJqKsBO/hB6j07@lXzOWVwYWkRDLKIKbFHyEjnlkls68uXIZb4G7Xq@ZR@hKiHfHECmJJNTPJ1SOqCTUs@juOOPAZ76cvhyK3LHioBpIElhBGJJErSGGW2fqWc@GV2yUmQq7ImyrVdaYIgNahQ67wiig7iSebJt9FuNGJO/QfAGNRGJv0NpxR1L3mRrnHCOwMO24o1MX) couldn't find any pairs of moduli that led to no empty spaces, and adding a third would cost more than it gained.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, ~~89~~ 67 bytes
Direct port of [Jo King's Perl answer](https://codegolf.stackexchange.com/a/195464/52194). ~~By sheer coincidence, the byte count is even the same.~~ The byte counts are no longer the same as Jo King has switched to using a technique that cannot be tersely replicated in Ruby.
```
$_=%w"Leaf Esp Umbr Vapor 0 Sylv Flar Jolt Glac"[$_.sum%64%9]+'eon'
```
[Try it online!](https://tio.run/##Dcy7CsIwFADQPV9xKQ0dio9BBIdutkVxEEQdRMptiDSYNOEmVfLzxo5nOTT1MYnBGpfyruLf7CTxBbV3cDU9wQ2dJVjDJeoPNBoJjlYHaDWK7JF3Sz8Zvt3w3bMspB2L@YCygnyV7hgksVpLEUgJ1iiS7OyjGGbskd6sJfSeHYRkDSqKP@uCsqNPC/cH "Ruby – Try It Online")
### Original Version, Ruby `-p`, 89 bytes
Basic lookup checking the first letter of the input (or first 2 if the second letter is `i`, which is only present in `Fire`).
```
$_=%w"WVapor EJolt PEsp DUmbr GLeaf IGlac FSylv FiFlar".find{|e|e.sub!$_[/.i?/],''}+'eon'
```
[Try it online!](https://tio.run/##DczBCoIwGADg@57iT4wdLH0C6aITo4MQ5SFC5po0Wk7@zWJkr555/C4fjq2f57BJ1@@gPvPBIOR7ox1UuR0gOz1bhOIgeQdlobkAdvT6BUwxzTGIO9XfPpOcZGzHdhU2lyRWu@S6ofQbUWl6uswQpRAmc82dRJJrKRwqQZhCSSrrxX1BxvFBCuTWklJIwrhC/zODU6a383b4Aw "Ruby – Try It Online")
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 29 bytes
```
EF 73 77 59 25 54 25 75 09 60 84 58 22 23 61 82 73 82 72 00 24 52 40 7E 5F 39 39 73 EF
```
[Try it here!](https://pyke.catbus.co.uk/?code=EF+73+77+59+25+54+25+75+09+60+84+58+22+23+61+82+73+82+72+00+24+52+40+7E+5F+39+39+73+EF&input=Fairy&warnings=0&hex=1), [Ungolfed with full tests](https://pyke.catbus.co.uk/?code=F.os+57%25T%25+96+600+34+35+97+371+370+0+36%5D9R%40%7E_99s.o&input=%5B%22Water%22%2C+%22Electric%22%2C+%22Fire%22%2C+%22Psychic%22%2C+%22Dark%22%2C+%22Grass%22%2C+%22Ice%22%2C+%22Fairy%22%5D&warnings=0&hex=0)
```
.o - map(ord, input)
s - sum(^)
wY%T% - (^ % 57) % 10 // wY is 57
R@ - v[^]
u\t`\x84X"#a\x82s\x82r\x00$ - [96, 600, 34, 35, 97, 371, 370, 0, 36]
~_99s - ^ + 333333 + 99
.o - dictionary_lookup(^)
```
We start off by converting the input to a list of integers corresponding to the ascii characters and then summing them. This produces the following set of numbers for `["Water", "Electric", "Fire", "Psychic", "Dark", "Grass", "Ice", "Fairy"]`: `[515, 811, 390, 723, 386, 512, 273, 507]`. We then perform a magic operation (`(x % 57) % 10`) to get the following list of offsets: `[2, 3, 8, 9, 4, 6, 5, 1]`.
The bytes below correspond to the following compressed list: `[96, 600, 34, 35, 97, 371, 370, 0, 36]`, and we index into it based on the offsets we had previously. There's a 0 in there due to my inability to get it not to wrap.
```
75 09 60 84 58 22 23 61 82 73 82 72 00 24
```
[Try it here!](https://pyke.catbus.co.uk/?code=75+09+60+84+58+22+23+61+82+73+82+72+00+24&input=&warnings=0&hex=1)
This list of numbers corresponds to the location in the Pokedex, minus 100. Pyke's dictionary handily contains the Pokedex starting from index 333333 (0 indexed). It also comes with a convenient default variable, `~_`, for getting that particular number. We then add 99 to it to take an offset to Pyke's dictionary, and then use `.o` to look up that particular word.
[Answer]
# [ink](https://github.com/inkle/ink), ~~111~~ 110 bytes
```
=e(t)
{
-t?"W":Vapor
-t?"E":Jolt
-t?"P":Esp
-t?"y":Sylv
-t?"D":Umbr
-t?"G":Leaf
-t?"I":Glac
-1:Flar
}<>eon->->
```
[Try it online!](https://tio.run/##VY4xD4IwFIT3/gryJhg6uDZYF5BgHEiMsrDUpsaGCqRtTIjxtyNUa8p2d9@9vJNdO9XMCh01mKY0wlTE4AJIMEVNhHIluNWShwWf@c5eahHyxXtWmZHf1@e/yDcyptsQL96zQjNjQugCT0u@ejvb/yIm9biatAQLnbYitgl6IWx3UAO5sKHXzuRADr2yTldAcjM4OQI5jerpdAbk/Lh@6wWQo2A3p0sghWIc4Q3ZK6bRO6Wi7zCd300f "ink – Try It Online")
## Explanation
```
=e(t) // Define a stitch e which takes a parameter t
{ // An if block - finds the first condition that is true and doeses the associated thing
-t?"W":Vapor // If "W" is a substring of our parameter, we print "Vapor"
-t?"E":Jolt // otherwise, if "E" is a substring of our parameter, we print "Jolt"
-t?"P":Esp // "P" is for "Psychic"
-t?"y":Sylv // We can't check "F" for "Fairy" because that'd also match "Fire", but since we got past "Psychic", "Fairy" is the only option that contains "y"
/* et cetera */
-1:Flar // If we get here, we check if 1 is truthy (it is) and if so, we print "Flar"
}<>eon->-> // Append "eon" to the last line printed, and return.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~47~~ ~~40~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•‡ιÏSnÛ@¥I´4óȬ–[и)h‘j"õújв•#ć«™sÇ<Oè
```
-7 bytes by porting [*@JoKing*'s `ord-sum % 64` trick](https://codegolf.stackexchange.com/a/195464/52210).
-2 bytes thanks to [*@JonathanAllan* by using the `ord-sum - length`](https://codegolf.stackexchange.com/a/195533/52210) on the input-type instead.
[Try it online](https://tio.run/##AVMArP9vc2FiaWX//y7igKLigKHOucOPU27Dm0DCpUnCtDTDs8OIwqzigJNb0LgpaOKAmGoiw7XDumrQsuKAoiPEh8Kr4oSic8OHPE/DqP//UHN5Y2hpYw) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6WKvpPCobZKCkv1/vUcNix41LDy383B/cN7h2Q6Hlnoe2mJyePPhjkNrHjVMjr6wQzPjUcOMLKXDWw/vyrqwCahc@Uj7odWPWhYVH2638T@84r/O/2il8MSS1CIlHSXXnNTkkqLMZCDTLbMoFUgFFFcmZ4AFXBKLsoGUe1FicTGQ9kwGSbslZhZVKsUCAA).
**Explanation:**
```
.•‡ιÏSnÛ@¥I´4óȬ–[и)h‘j"õújв•
"# Push compressed string "eon glac jolt leaf umbr esp vapor sylv flar"
# # Split it on spaces:
# ["eon","glac","","jolt","leaf","umbr","esp","vapor","sylv","flar"]
ć # Extract head; pop and push remainder-list and the first item
« # Concat this first item "eon" to each string in the remainder-list
™ # Titlecase each Eeveelution
sÇ # Get the input, and convert it to a list of unicode values
< # Decrease each value by 1
O # Sum these integers
è # And use this to (0-based) index into the list (with automatic wrap-around)
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•‡ιÏSnÛ@¥I´4óȬ–[и)h‘j"õújв•` is `"eon glac jolt leaf umbr esp vapor sylv flar"`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
§⪪”↶2'⧴mB⁼“↷⁻o⊟HtωhJ№↘Tθ⁼σ4Þχ℅)Zh” ⌕rtFhDscy§S⁴eon
```
[Try it online!](https://tio.run/##NY2xCsIwFEV3v@LxpgTq5tZJ0EjEQQi6xzTawGsS0mexXx8D4hkvh3vcaItLlmq9lhBZ7FnHwX@EyRRY4N3mVOCciEGRLXCcM9ymR4GLt084kXVgVlqwAwSUHagQB4GF1XiY3drm/5@O@c2GW@MlmreTjX7za6JPEWVfq3a@bhf6Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
§⪪”↶2'⧴mB⁼“↷⁻o⊟HtωhJ№↘Tθ⁼σ4Þχ℅)Zh”
```
Split the compressed string `Vapor Jolt Flar Esp Umbr Leaf Glac Sylv` on spaces and index into it using...
```
⌕rtFhDscy§S⁴
```
... the index of the fourth character of the input (taken cyclically) in the string `rtFhDcsy`.
```
eon
```
Output the shared suffix.
[Answer]
# Java 8, 84 bytes
```
t->"Leaf Esp Umbr Vapor Sylv Flar Jolt Glac".split(" ")[t.chars().sum()%64%9]+"eon"
```
Port of [*@JoKing*'s Perl answer](https://codegolf.stackexchange.com/a/195464/52210).
[Try it online.](https://tio.run/##PZBBTsMwEEX3PcXIUqVYoV4hJKhgRVOBoEJCwKLqYuo61K1jR7YTFFXZcgCOyEXCJAQ2/uNva96fOWCNs8Pu2EmDIcAjanuaAGgblc9RKlj1V4Dn6LV9B5WMReRz8tsJHSFi1BJWYOG6i7Mb9qAwh0Uo4aXYenjF0nlq0JgaMoMe7p2JsDQomQil0TFhwPg6CrlHHxIuQlUkfHpxPr3cpEw5y7p5jymrrSHMSKud3kFBacdA6w0g/42aO/@fsikVXIFVH/D37cTekGZjZ2xhlCRTUplpr0ieQiP3g3GL/kiy9LQU0jvZP2eofcNaPlD6iUJUhXBVFCX1jsYmPS9l8P35BSy1Qg0GH1fVdj8)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes
```
“ȦF³ḢẎŻṣ>[ɲ$Ɱ'⁻⁹ḋm¿:ṪœeḂɲẆy$\»Ḳ;€“°9»ŻɓO’Sị
```
**[Try it online!](https://tio.run/##AWgAl/9qZWxsef//4oCcyKZGwrPhuKLhuo7Fu@G5oz5bybIk4rGuJ@KBu@KBueG4i23CvzrhuarFk2XhuILJsuG6hnkkXMK74biyO@KCrOKAnMKwOcK7xbvJk0/igJlT4buL////J1dhdGVyJw "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9Rw5wTy9wObX64Y9HDXX1Hdz/cudgu@uQmlUcb16k/atz9qHHnwx3duYf2Wz3cuero5NSHO5pObnq4q61SJebQ7oc7Nlk/aloDNOLQBstDu4/uPjnZ/1HDzOCHu7v/H91zuB0o5/7/f7R6eGJJapG6joK6a05qcklRZjKI7ZZZlAqiA4orkzMgQi6JRdkg2r0osbgYxPBMBitxS8wsqlSPBQA "Jelly – Try It Online").
### How?
First makes the list `['Jolt', 'Leaf', 'Umbr', 'Esp', 'Vapor', 'Sylv', 'Flar', 'Glac']`, adds `'eon'` to each, and prepends a zero to the list. Then gets the ASCII code-points of the characters in the input list, subtracts one from each, sums those up and indexes into the created list (using 1-based, modular indexing - i.e. gets the value at index `i%9`).
[Answer]
# [Julia 1.0](http://julialang.org/), ~~85~~ ~~83~~ 75 bytes
```
f(s)=strip("VUEJGSFLamsolylepbplalaaor tcvrfr"[6hash(s)%47%8+1:8:33])*"eon"
```
[Try it online!](https://tio.run/##Vc09C8IwFIXh3V9RAoVGp1LRUhAcbIviIIg6iMM1JCQaTbm3fvTXx06SjueBw3t7WQPp13uVEF9Qi6ZJ2PFQbup9tYUHOdtZ2VwbCxbAYdSKNypk55kG0v0lns7jfJIWeZFlFz5m0j2ZX5J2n0glrDIoGR/99wlaiSGUVoq@KULbUSf0kFaA93DXCEQhrMWgU4HBjnH/Aw "Julia 1.0 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p -MList::Util=pairfirst`, 84 bytes
```
$_=(pairfirst{/$a/}D,Umbr,E,Jolt,Fa,Sylv,Fi,Flar,G,Leaf,I,Glac,P,Esp,W,Vapor)[1].eon
```
[Try it online!](https://tio.run/##Pc6xCsIwEADQPd/RQeFqcXApdGsTKhUKUh1E5AwpHsYmXIJQxF83OvkF73nDdpNSdqkWHolH4hBfRYbFu4bhcWVoYOtsBImwn@0TJIG0yKCgMzhCC8qihh6a4OEIB/SOl6f1eWXclFIfZn0jLSSxETXyXSjGEESrjZA/bf44H8lNIeW7jkIsyyGSrf6RlHv7BQ "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 103 bytes
I hash the first four bytes of the string to determine the index into the array (the hash function is not optimal, but works well enough: there's probably a more efficient one, but it would likely be bigger!) After the index is computed, I then print the four (or five) characters of the prefix and end with "eon". It's more compact than a string array, and by keeping the five-character string at the end I simplify the indexing.
I used some quirks in the language and implementation to save some length:
* Due to operator precedence, I use `4|j>7` to give me 4 or 5, as bitwise operators have a lower precedence than relational ones.
* Strings have to have `int`-appropriate alignment and `int` has to be a 32-bit, little-endian value so I can use type punning on the input string; fortunately this is the case for the test environment.
```
j;f(int*i){(j=(*i-2)%12%10)&&j--;printf("%.*seon",4|j>7,"SylvEsp\0JoltFlarLeafUmbrGlac Vapor"+4*j);}
```
[Try it online!](https://tio.run/##PY9Bb8IwDIXv/RVWJlASWgQIaYesnEbRJjRNQmyHbYcspDRdaKs4MFWsf31d4DAf3mf5SX62SvZK9X0pcmoqzw070zKl3CQzNpjOBtMJGw7LJBGNC3ZOyWDMUdcViec/5eI2JpvWnpbYvE8ea@szK91ay3x7@HQrKxWEepFN7chozksmuv7GVMoedxru0O9MPS4WURQWw0Gaip5qs2NwjgBUIR1w3zYa3z7SM3mVXjsSk6XVyjujQpsZpwOesVXFdXAv3VfAyknEwAd1sTNpXEvip@163cXAuQ@CIgoRee2oT68RAjDlfjQS0Bw9UkJYuAL@P0ZIF0BiQCYgpxftoq7/VbmVe@yT7z8 "C (gcc) – Try It Online")
] |
[Question]
[
**Warning : this is NOT a "hey, let's draw a cake in ASCII-art" challenge! Please keep reading ;)**
Some time ago it was my birthday, I'm 33 now.
So there is this awkward social tradition consisting in inviting family and friends, putting number-like candles on a cake, sing songs and open gifts.
```
33
--------
```
Instead of numbers, I can use the binary system to put standard candles: I place 6 of them on the cake and light two of them.
```
100001
--------
```
I can see that **both decimal and binary numbers of my age are palindromic!**
# Challenge
I want to know if any other number can be put on a cake with candles and be palindromic, decimal and binary.
Write a program/function to test if a number is palindromic in **both** decimal and binary. But wait, there's more : **in binary, leading zeros count for the test!**
## Input
A **decimal** number x that I want to test if it is birthday palindromic with 0 < x < 232-1 (yes, the people in my dimension live very long)
## Output
[Truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) if it meets exactly these two conditions, Falsey else:
* The decimal representation of the number is a standard palindrome
* The binary representation of the number is a standard palindrome, **and adding leading zeros may help with this**
## Test cases
```
1 > 1 => Truthy
6 > 110 (0110) => Truthy
9 > 1001 => Truthy
10 > 1010 (01010) => Falsey, 10 is not palindromic
12 => 1100 (001100) => Falsey, 12 is not palindromic
13 => 1101 (...01101) => Falsey, neither 13 nor 1101 are palindromic
14 => 1110 (01110) => Falsey, 14 is not palindromic
33 > 100001 => Truthy
44 > 101100 (..0101100) => Falsey, 101100 is not palindromic
1342177280 > 1010000000000000000000000000000 (00000000000000000000000000001010000000000000000000000000000) => Falsey, 1342177280 is not palindromic (but the binary representation is)
297515792 > 10001101110111011101100010000 (000010001101110111011101100010000) => Truthy
```
## Rules
* [Standard loopholes are disallowed](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* Built-in library conversions and tests are allowed
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code win!
Good luck, and eventually happy birthday!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
b0Ü‚DíQ
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/yeDwnEcNs1wOrw38/9/YGAA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##MzBNTDJM/V9TVln5P8ng8JxHDbNcDq8N/F@pdHi/lcLh/Uo6/w25zLgsuQwNuAyNuAyNuQxNuIyNuUxMAA)
**Explanation**
```
b # convert input to binary
0Ü # remove trailing zeroes
‚ # pair with input
D # duplicate
í # reverse each (in the copy)
Q # check for equality
```
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
```
lambda a:all(c==c[::-1]for c in[str(a),bin(a).strip('0b')])
```
[Try it online!](https://tio.run/##DcdBCoAgEADAr3hzFyoKb4IvMQ@rIQmmYl56/eZpmPaNuxbF0Zyc6fEXCdKUMwRjgtV6PVysXQSRin1HB8LFpzLZ5lIDuXuJDrn1VAZEUAqRfw "Python 3 – Try It Online")
-3 bytes thanks to Rod
-3 bytes thanks to Connor Johnston
[Answer]
# JavaScript (ES6), 65 bytes
Returns `0` or `1`.
```
n=>(g=b=>[...s=n.toString(b)].reverse().join``==s)()&g(2,n/=n&-n)
```
### How?
The helper function ***g()*** takes an integer ***b*** as input and tests whether ***n*** is a palindrome in base ***b***. If ***b*** is not specified, it just converts ***n*** to a string before testing it.
We get rid of the trailing zeros in the binary representation of ***n*** by isolating the least significant *1* with `n&-n` and dividing ***n*** by the resulting quantity.
Fun fact: it's truthy for `0` because `(0/0).toString(2)` equals `"NaN"`, which is a palindrome. (But `0` is not a valid input anyway.)
### Test cases
```
let f =
n=>(g=b=>[...s=n.toString(b)].reverse().join``==s)()&g(2,n/=n&-n)
console.log(f(1 )) // Truthy
console.log(f(6 )) // Truthy
console.log(f(9 )) // Truthy
console.log(f(10)) // Falsey
console.log(f(12)) // Falsey
console.log(f(13)) // Falsey
console.log(f(14)) // Falsey
console.log(f(33)) // Truthy
console.log(f(44)) // Falsey
```
[Answer]
# Mathematica, ~~52~~ 49 bytes
```
i=IntegerReverse;i@#==#&&!i[#,2,Range@#]~FreeQ~#&
```
[Try it on Wolfram Sandbox](http://sandbox.open.wolframcloud.com)
### Usage
```
f = (i=IntegerReverse;i@#==#&&!i[#,2,Range@#]~FreeQ~#&);
```
---
```
f[6]
```
>
> `True`
>
>
>
```
f /@ {9, 14, 33, 44}
```
>
> `{True, False, True, False}`
>
>
>
### Explanation
```
i=IntegerReverse;i@#==#&&!i[#,2,Range@#]~FreeQ~#&
i=IntegerReverse (* Set i to the integer reversing function. *)
i@#==# (* Check whether the input reversed is equal to input. *)
&& (* Logical AND *)
i[#,2,Range@#] (* Generate the binary-reversed versions of input, whose lengths *)
(* (in binary) are `{1..<input>}` *)
(* trim or pad 0s to match length *)
~FreeQ~# (* Check whether the result is free of the original input *)
! (* Logical NOT *)
```
### Version with builtin `PalindromeQ`
```
PalindromeQ@#&&!IntegerReverse[#,2,Range@#]~FreeQ~#&
```
[Answer]
# Pyth - 13 bytes
```
&_I.s.BQ`Z_I`
```
[Test Suite](http://pyth.herokuapp.com/?code=%26_I.s.BQ%60Z_I%60&test_suite=1&test_suite_input=1%0A6%0A9%0A10%0A12%0A13%0A14%0A33%0A44&debug=0).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
s ꬩ¢w n2 ¤ê¬
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=cyDqrKmidyBuMiCk6qw=&input=Ng==)
### Explanation
```
s ê¬ © ¢ w n2 ¤ ê¬
Us êq &&Us2 w n2 s2 êq Ungolfed
Implicit: U = input integer
Us êq Convert U to a string and check if it's a palindrome.
Us2 w Convert U to binary and reverse.
n2 s2 Convert to a number, then back to binary, to remove extra 0s.
êq Check if this is a palindrome.
&& Return whether both of these conditions were met.
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 57 bytes
```
a=>(b=c=>c==c[to by-1])(str(a))*b(bin(a)[2to].strip('0'))
```
[Try it online!](https://tio.run/##NYk7DoAgDEB3T@FGa6JRYS0XIQxAQsJCCXbx9Mji9j6ts3AdmUYgC5ES2USUnPAa3/3yCI90CIhbhFjqJHcL@2PW0kCdCnG0XqpABmMQl1@0nucD "Proton – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Bt0ŒḂaŒḂ
```
[Try it online!](https://tio.run/##y0rNyan8/9@pxODopIc7mhLB5P///01MAA "Jelly – Try It Online")
[Answer]
# APL, 27 31 Bytes
```
∧/(⌽≡⊢)∘⍕¨{⍵,⊂{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢⍵}
```
How's it work? Using 6 as the argument...
```
2⊥⍣¯1⊢6 ⍝ get the bit representation
1 1 0
⌽2⊥⍣¯1⊢6 ⍝ reverse it (if it's a palindrome, it doesn't matter)
0 1 1
{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢6 ⍝ drop off the trailing (now leading 0's)
1 1
6,⊂{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢6 ⍝ enclose and concatenate the bits to the original number
┌─┬───┐
│6│1 1│
└─┴───┘
(⌽≡⊢)∘⍕ ⍝ is a composition of
⍕ ⍝ convert to string and
(⌽≡⊢) ⍝ palindrome test
(⌽≡⊢)∘⍕¨6,⊂{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢6 ⍝ apply it to each of the original argument and the bit representation
1 1
∧/(⌽≡⊢)∘⍕¨6,⊂{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢6 ⍝ ∧/ tests for all 1's (truth)
1
```
[Try it on TryAPL.org](http://tryapl.org/?a=%u2227/%28%u233D%u2261%u22A2%29%u2218%u2355%A8%7B%u2375%2C%u2282%7B%u2375/%u2368%u2228%5C%u2375%7D%u233D2%u22A5%u2363%AF1%u22A2%u2375%7D6&run)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
↔?ḃc↔.↔
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbFPuHO5qTgbQeEP//b2Rpbmpoam5p9B8A "Brachylog – Try It Online")
That's a lot of `↔`'s…
### Explanation
With the implicit input and output, the code is: `?↔?ḃc↔.↔.`
```
?↔? The Input is a palindrome
ḃ Convert it to the list of its digits in binary
c Concatenate it into an integer
↔ Reverse it: this causes to remove the trailing 0's
.↔. The resulting number is also a palindrome
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 26 bytes
```
{≡∘⌽⍨⍕⍵,⍵,⍨(<\⊂⊢)⌽2⊥⍣¯1⊢⍵}
```
## Explanation
```
2⊥⍣¯1⊢⍵ encode ⍵ as binary
⌽ reverse
(<\⊂⊢) partition from first 1
⍵,⍵,⍨ prepend and append ⍵
⍕ turn into text string
≡∘⌽⍨ match text with its reverse (f⍨X is XfX, where f is a composed function that reverses its right argument and matches with left)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHnwkcdMx717H3Uu@JR79RHvVt1IHiFhk3Mo66mR12LNIGyRo@6lj7qXXxovSFQAKiglgKth1YYKpgpWCoYGigYGikYGisYmigYGyuYmADZJkaG5uZGFgYKRpbmpoam5pZGAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# Perl, 53 +3 (-pal) bytes
```
$_=sprintf"%b",$_;s/0+$//;$_="$_/@F"eq reverse"@F/$_"
```
[try it online](https://tio.run/##K0gtyjH9/18l3ra4oCgzryRNSTVJSUcl3rpY30BbRV/fGiijpBKv7@CmlFqoUJRallpUnKrk4KavEq/0/78hl7Exl6GBIZf5v/yCksz8vOL/ugWJOQA)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~68~~ 66 bytes
```
@(x)all([d=num2str(x) b=deblank(['' dec2bin(x)-48])]==flip([b d]))
```
[Try it online!](https://tio.run/##JcpBDsIgFATQvadgV/5CIr9UyoLEexAWUCBpRDRajbfHgpuXyczcl819Yk2aMVYv9AsuZ2qCLu8bvrbnXhCvQ/TZlSs1w0BCXNCvZR@OYrZgtU55fVDjSbAANVEOh0TPDdXgpy52x65ojj0L8e8Fcilx7l9UcuKTVAj1Bw "Octave – Try It Online")
Initial offering from Octave.
We basically create an array containing the number as a decimal string and the number as a binary string with trailing 0's removed. Then we create an array with the same to strings but with the binary and decimal numbers flipped. Finally both arrays are compared and the result is either true if they match (both palindromes) or false if they don't (one or both not palindromes).
---
* Save 2 bytes using `flip` instead of `fliplr`.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 10 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
Returns [1] if true, [0] if false
```
ĐɓƖ₫áĐ₫=ʁ∧
```
[Try it online!](https://tio.run/##K6gs@f//yISTk49Ne9S0@vDCIxOAlO2pxkcdy///N7I0NzU0Nbc0AgA)
Explanation:
```
Implicit input
Đ Duplicate input
ɓ Get input in binary (as string)
Ɩ Cast to integer
₫ Reverse the digits (this removes any trailing zeroes)
á Push the stack into a list
Đ Duplicate the list
₫ Reverse the digits of each element of the list
= Are the two lists equal element-wise
ʁ∧ Reduce the list by bitwise AND
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 72 bytes
```
.+
$*_;$&
+`(_+)\1
$+0
0_
_
0+;
;
+`\b(\w)((\w*)\1)?\b
$3
(\B;\B)|.*
$.1
```
[Try it online!](https://tio.run/##DckxCgIxEEDR/p9jkCQDIWOCICmEPcdAdMHCxkIEG@@eTfOL9z/P7@v9mDMrkkaXE3oPQ6MbooUyGBTt9OW@B//FsJLWjzffkUrwrfsW/zkh2eY0Llyxgp2xijVqpbUD "Retina – Try It Online") Link includes test cases. Works by creating a unary duplicate of the original number, but using `_`s so that it's not confused by e.g. an input of `11`. The unary number is then converted to "binary" and trailing zeros stripped. Palindromes then get successively truncated and the last stage tests whether there is anything left.
[Answer]
# Mathematica, 70 bytes
```
(P=PalindromeQ)[PadRight[#~IntegerDigits~2,#~IntegerExponent~2]]&&P@#&
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
¤&S=↔ȯ↓=0↔ḋ⁰d⁰
```
[Try it online!](https://tio.run/##yygtzv7//9AStWDbR21TTqx/1DbZ1gDIerij@1HjhhQg/v//v7ExAA "Husk – Try It Online")
### Ungolfed/Explanation
```
d⁰ -- digits of input in decimal
ḋ⁰) -- digits of input in binary
↔ -- reverse
(↓=0 -- and drop all leading zeros
¤& -- test the two lists if
S=↔ -- they're equal to their own reverse
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 10 bytes
```
ṙṭ@ḍ2⁻Πbṭ∧
```
[Try it online!](https://tio.run/##S0/MTPz//@HOmQ93rnV4uKPX6FHj7nMLkoC8Rx3L//83NgYA "Gaia – Try It Online")
### Explanation
Instead of checking with leading zeroes in binary, I check without without the trailing zeros.
```
ṙ String representation of number
ṭ Is palindromic?
@ Push input again
ḍ Prime factors
2⁻ Remove all 2s
Π Product
b Convert to binary
ṭ Is palindromic?
∧ Logical and
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 105 bytes
```
r(n,b){int s=0,c=n;for(;n;n/=b)s=s*b+n%b;return s==c;}
c;f(n){for(c=n;c%2<1;c/=2);return r(n,10)&r(c,2);}
```
[Try it online!](https://tio.run/##dY5BDoIwEEXXcgqDwbSKQguIpNSTuIEBlEQHU2BFODu2Jq6su5@XN/8PHG4Ay6ZFeIxVvc77oWq74/2yKIJ@SacWh3UvQx8kiqZTRKDAQJa0l/2u3KNXClUPo0ItSRCzA6IhSCejmhPweM4EBJLTr2iKWUi3WvA1nRcz8SxaJCYUdHJWL6VjQ1yvuqLrN4RRKn7pyUozK9WDVsztOLLj2Iojux3Hf7pjztKUn@0f8SxNWJJmn8fm5Q0 "C (gcc) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~130 129 179~~ 173 + 23 bytes
a few things, thank you to Ed Marty for pointing out that i need to check for as many 0's padded in front for a palindrome. And i need to make sure that i can check up to x^32-1.
```
x=>{var a=Convert.ToString(x,2);var b=x+"";Func<string,bool>p=z=>z.SequenceEqual(z.Reverse());return new int[a.Length].Select((_,z)=>p(new string('0',z)+a)).Any(z=>z)&p(b);}
```
[Try it online!](https://tio.run/##dVBRa8IwEH7vrzjKmMnqijqZg9qOMbYn9zIHexAZMZ5doCY1SZ229Ld3rZVBkX33kOO@@767HDe3XGmsJNuiSRlHmB@Nxa0/E3JXODxhxkBaOMYyKzi8ZpJPEyXj/kqpJNqE1SGMij3TwMJnJfeorf@h5lYLGZNDf0SDhluFB891g5PYnLhWnoZ5GOX@HHcZSo4vu4wlJPffsfYxSCgNNNpMS5D4A0LaBfNnKGP7vaw1CXJLyFc/p2GUkqajtSa9Qa8ueoxS/0keSTOCXqdkRYOyChw4/2SvxBremJCklS2WwHRsqANnFH9Zg43SpN4ABIQwDOpnCsNBk3ge7TR2ZQ3quxiVoP@phcX6rEiuXGGgECUwSFki5Fqr7SMUGyJo6dLgwqFTKJ3/DEfD8WT8cHc/nsxuRpfmHbodVDZR/QI "C# (.NET Core) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
lambda n:all(s==s[::-1]for s in(`n`,bin(n).strip("0b")))
```
[Try it online!](https://tio.run/##Pc1BCoMwEAXQvacYXCWQiona1EC2nqA7KxhpRSGNkkwXnt7GCh0YZhaP/9cNp8WJvdGP3Zr38DTglLGWBK1Dq9SFd@PiIcDsSO96NsTraBbQzytJ8yGllO53/8FpAw0tZ3BlUDMoCgailhWvZC26pDE2vE6RM@AibgS8ZFCWx18KLqW45V1ytGFsgzNUgQnh5RGOaQjSHxgPcGb@gVswgpEmq58dQrotWbp/AQ "Python 2 – Try It Online")
Uses Python's `strip` method to both remove the `bin(..)`'s output's leading `0b` *and* the binary number's trailing zeros (as they will always have a matching bit).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~25~~ ~~22~~ ~~19~~ ~~18~~ 17 bytes
-~~3~~ ~~6~~ ~~7~~ 8 bytes by learning the language further
```
Ks_.Bsz&_IzqKs_`K
```
Explanation:
```
Ks Set K to the integer version of...
_.BsJ Reverse string of the binary input
& And
_Iz Is the input equal to the reverse of itself?
qKs_`K Is K equal to int(the reverse of basically string(K))
```
I am sure that this can be golfed down, I'll be working on that.
[Test Suite](http://pyth.herokuapp.com/?code=Ks_.Bsz%26_IzqKs_%60K&test_suite=1&test_suite_input=1%0A6%0A9%0A10%0A12%0A13%0A14%0A33%0A44&debug=0 "Pyth – Try It Online")
[Answer]
# PHP, 69+1 bytes
```
$q=trim(decbin($p=$argn),0);if(strrev($p)==$p&&strrev($q)==$q)echo$p;
```
Run as pipe with `-nR`
Echoes the original input for truthy / nothing for falsey
[Try it online!](https://tio.run/##NYzLCsIwEEX3fsUsQklAqS2U0kf0H9yKi5qMNtAkk1i78t9jK7g5cA6XSyOl/kwj7dgQn05uXK7FrYM8B7TvaZgRlLd2cBom47CFD6xzOLgL9MprPCUW5ByN5RrV3TjO6PfixP4oOvPgrzlGXNYspGSUZX8PmweBavSMupRS2dRVUdVN@QU)
[Answer]
# APL2 (not Dyalog), 36 bytes
```
(N≡⌽N←⍕N)^∨/(((⌽B)⍳1)↓B)⍷B←(32⍴2)⊤N←
```
First let B be the 32-bit representation of N:
```
B←(32⍴2)⊤N
```
Then mirror B and find the position of the 1st 1:
```
(⌽B)⍳1
```
Then drop that many positions from B. This will preserve the correct number of leading 0s.
Then perform FIND and an OR-REDUCTION to see if the cropped B contains its own mirror.
Now let's look at N, the decimal. The left-most bracketed expression converts N to a character vector and checks if it MATCHes its own mirror.
Finally, an AND joins the two checks.
---
In APL2 I can't make a neat lambda so I wrote a one-liner and included the assignment arrow. Hope this isn't cheating.
[Answer]
# Java 8, ~~105~~ 104 bytes
```
n->{String t=n+n.toString(n,2).replaceAll("0*$","")+n;return t.contains(new StringBuffer(t).reverse());}
```
**Explanation:**
[Try it here.](https://tio.run/##hU@xbsIwFNz5iqeog10gkBCa0ohK7VCpQ1noVnUwwdBQ8xzZL6kQyrenhmRtLdnD6e7e3R1ELca6lHjYfre5EtbCmyjwPAAokKTZiVzC6gIBNlorKRBy9uqovTSAPHNM4757lgQVOawAYQktjh/PazIF7oGWOMSQdAcZjmIeGlkqd/pJKRZMb2@CURDwIWZGUmUQKMw1kuthGcof6IzP1W4nDaOLuZbGSsZ51rRZl15WG@XS@xK1LrZwdAdY5/34BMG7FZMJvJuKvk4PV7g@WZLHUFcUlk5JChmGOYv4ddqf/J2HX3j42cwjiBfpPJqni/gfXc@4RS9CWelZNPUkRrFP4OscJR5BkngjkjhK0/i@L9sMmvYX)
```
n->{ // Method with Integer parameter and boolean return-type
String t=n // Create a String `t` starting with the input Integer
+n.toString(n,2) // Append the binary representation of the input Integer,
.replaceAll("0*$","") // with all trailing zeroes removed
+n; // Append the input Integer again
return t.contains(new StringBuffer(t).reverse());
// Return true if `t` is a palindrome
} // End of method
```
] |
[Question]
[
# The task
Write a program or function whose input is a list/array *X* of integers, and whose output is a list of sets of integers *Y*, such that for each element *e* in each set *Y*[*i*], *X*[*e*] = *i*, and such that the total number of elements in the sets in *Y* equals the number of elements in *X*.
(This is basically the same operation as reversing a hashtable/dictionary, except applied to arrays instead.)
# Examples
These examples assume 1-based indexing, but you can use 0-based indexing instead if you prefer.
```
X Y
[4] [{},{},{},{1}]
[1,2,3] [{1},{2},{3}]
[2,2,2] [{},{1,2,3}]
[5,5,6,6] [{},{},{},{},{1,2},{3,4}]
[6,6,5,5] [{},{},{},{},{3,4},{1,2}]
```
# Clarifications
* You may represent a set as a list, if you wish. If you do so, the order of its elements does not matter, but you may not repeat elements.
* You can use any reasonable unambiguous I/O format; for example, you could separate elements of a set with spaces, and the sets themselves with newlines.
* *Y* should be finitely long, and at least long enough to have all elements of *X* as array indexes. It may, however, be longer than the maximal element of *X* (the extra elements would be empty sets).
* The elements of *X* will all be valid array indices, i.e. non-negative integers if you use 0-based indexing, or positive integers if you use 1-based indexing.
# Victory condition
As a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, shorter is better.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
tn:IXQ&D
```
Input is a column vector, with `;` as separator (for example `[2;2;2]`). Output is the string representation of a cell array of row vectors (for example `{[]; [1 2 3]}`). A row vector of a single element is the same as a number (so `{1; 2; 3}` would be output instead of `{[1]; [2]; [3]}`).
[Try it online!](https://tio.run/nexus/matl#@1@SZ@UZEajm8v9/tJm1mbWptWksAA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/hfkmflGRGo5vLfJeR/tEksV7ShtZG1MZA2AtJGQNrU2tTazNoMyAKSQLZpLAA).
### Explanation
```
t % Implicit input, say x. Duplicate
n % Number of elements, say N
: % Range: [1 2 ... N]
IXQ % accumarray(x, [1 2 ... N], [], @(x){sort(x).'})
&D % String representation
```
Most of the work is done by Matlab's higher-order function `accumarray`, which groups elements in the second input according to matching values in the first, and applies a specified function to each group. The function in this case is `@(x){sort(x).'}`, which outputs the sorted elements in each group and causes the results for all groups to be packed in a cell array.
[Answer]
# Python, 69 bytes
```
lambda s:[[j for j,x in enumerate(s)if x==i]for i in range(max(s)+1)]
```
Uses 0-based indexing.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 5 bytes
```
=þṀT€
```
[Try it online!](https://tio.run/nexus/jelly#@297eN/DnQ0hj5rW/D/cDiQVjk56uHMGiBGp8HDH9kcNcxR8EwsUSjJSFXIy87J1FJLz88pSi0oUSvIVAipLMvLz1IsVikuKMvPSFYpSC4pSi1PzShJLMvPzdBSKUwsSixJLUhWSKhXyUsuB@lOL9f7/jzaJ1VGINtQx0jEGMYyADCMQw1THVMdMxwzEBFJAjmksAA "Jelly – TIO Nexus")
### How it works
```
=þṀT€ Main link. Argument: A (array)
Ṁ Yield m, the maximum of A.
=þ Equals table; for each t in [1, ..., m], compare all elemnts of A with t,
yielding a 2D Boolean array.
T€ Truth each; for each Boolean array, yield all indices of 1.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Jẋ"Ṭ€;"/
```
[Try it online!](https://tio.run/nexus/jelly#@@/1cFe30sOdax41rbFW0v///3@0mY6ZjomOSSwA "Jelly – TIO Nexus")
## How it works
```
Jẋ"Ṭ€;"/ argument: z eg. [6,6,4,4]
J [1 .. len(z)] [1,2,3,4]
Ṭ€ untruth each of z [[0,0,0,0,0,1],
[0,0,0,0,0,1],
[0,0,0,1],
[0,0,0,1]]
ẋ" repeat each of ^^ [[[],[],[],[],[],[1]],
as many times as [[],[],[],[],[],[2]],
each of ^ [[],[],[],[3]],
[[],[],[],[4]]]
/ reduce by...
;" vectorized concatenation [[],[],[],[3,4],[],[1,2]]
```
[Answer]
## Mathematica, 36 bytes
```
Join@@@#~Position~n~Table~{n,Max@#}&
```
## Explanation
[](https://i.stack.imgur.com/LRfYZ.png)
For each `n` in `{1, 2, ..., Max@#}`, where `Max@#` is the largest integer in the input list, computes the `Position`s where `n` appears in the input list `#`. Since `Position[{6,6,5,5},5]` (for example) returns `{{3},{4}}`, we then `Apply` `Join` to all elements at level `{1}` of the result.
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
`s` takes a list of integers and returns a list of lists. 1-indexed to keep the test case inputs unmodified (although the output gets some extra empty lists).
```
s l=[[i|(i,y)<-zip[1..]l,y==x]|x<-[1..sum l]]
```
[Try it online!](https://tio.run/nexus/haskell#HYhBCoMwEEX3nsJFFwrjgGnjypwkzCLYQAeSVIxSLd49Trv5770fHSfDafWLm9bblgInnzG6ucmv9wczLt49W/zfJdfBWMtnw3C0Y/fl2faIFOAwZqdzH7tf5y3WgagU@6DK9qDgLlRCJdSgYYBBTFZcU3UB "Haskell – TIO Nexus")
These are pretty straightforward nested list comprehensions. The only slight tweak is taking advantage of the option to make a longer list by using `sum` instead of `maximum`.
[Answer]
# PHP, 55 bytes
```
<?while($i<=max($_GET))print_r(array_keys($_GET,$i++));
```
0-indexed.
[Answer]
# R, ~~68~~ ~~49~~ 47 bytes
```
lapply(1:max(x<-scan()),function(y)which(y==x))
```
Surprisingly, a lot more straightforward than the longer solutions. Takes a vector `x` from STDIN, creates a vector from `1` to `max(x)`, implicitly generates a list of length `max(x)`, and checks which indices in `x` correspond with those in the new list. Implicitly prints output.
## Older version:
```
o=vector('list',max(x<-scan()));for(i in x)o[[i]]=c(o[[i]],F<-F+1);o
```
Slightly different approach to the other R answer. Takes a vector to STDIN, creates a list with length equal to the maximum value in the input. Loops over the input and adds the index into the right place.
Uses 1-based indexing.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~91~~ ~~86~~ 85 bytes
I am programming on my phone but I really liked this challenge. I can most definitely golf this further.
```
def f(a):
r=[[]for i in range(max(a)+1)]
for i,j in enumerate(a):r[j]+=[i]
print r
```
[Try it online!](https://tio.run/nexus/python2#JYtBCsMwDATvfoWONvElbppDIS8ROhgqBwfiFpFCf@/INiyI0ezWNydINrqXAdkQKX0EMuQCEsvO9ox/ldPsyEBX/miSy@9kiRe3peBB04ZZK1/J5QKpyeJCzuiZPQQPjwGhQxjw9KBZNYPXDu1Lrt4 "Python 2 – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṭ+\ịĠȧ@"Ṭ
```
1-indexed, empty sets represented as `0`, sets of one item represented as `N` sets of multiple items represented as `[M,N,...]`
**[Try it online!](https://tio.run/nexus/jelly#@/9w5xrtmIe7u48sOLHcQQnI@///f7SZjpmOiY5JLAA "Jelly – TIO Nexus")**
### How?
```
Ṭ+\ịĠȧ@"Ṭ - Main link: list a e.g. [6,6,4,4]
·π¨ - untruth a [0,0,0,1,0,1]
\ - cumulative reduce with:
+ - addition [0,0,0,1,1,2]
Ġ - group indices of a by value [[3,4],[1,2]]
ị - index into [[1,2],[1,2],[1,2],[3,4],[3,4],[1,2]]
·π¨ - untruth a [0,0,0,1,0,1]
" - zip with:
ȧ@ - and with reversed @rguments [0,0,0,[3,4],0,[1,2]]
```
[Answer]
## JavaScript (ES6), ~~64~~ 62 bytes
*Saved 2 bytes thanks to @SteveBennett*
---
Takes 0-indexed input. Returns a comma-separated list of sets.
```
a=>a.map((n,i)=>o[n]=[i,...o[n]||[]],o=[])&&`{${o.join`},{`}}`
```
### Test cases
```
let f =
a=>a.map((n,i)=>o[n]=[i,...o[n]||[]],o=[])&&`{${o.join`},{`}}`
console.log(f([3]))
console.log(f([0,1,2]))
console.log(f([1,1,1]))
console.log(f([4,4,5,5]))
console.log(f([5,5,4,4]))
```
---
### Alternate version, 53 bytes
If a simplified output such as `'||||3,2|1,0'` is acceptable, we can just do:
```
a=>a.map((n,i)=>o[n]=[i,...o[n]||[]],o=[])&&o.join`|`
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 109 bytes
Too bad there is no built-in for array max value.
```
a=($@)
for((x=m=1;x<=m;x++)){ for((y=0;y<$#;)){((m<a[y]))&&((m=a[y]));((a[y++]==x))&&printf "%d " $y;};echo;}
```
[Try it online!](https://tio.run/nexus/bash#@59oq6HioMmVll@koVFhm2traF1hY5trXaGtralZrQAWrrQ1sK60UVG2BopoaOTaJEZXxmpqqqkB2bYQtrWGBpChrR1ra1sBkikoyswrSVNQUk1RUFJQqbSutU5Nzsi3rv3//78ZEJr@NwUA "Bash – TIO Nexus")
[Answer]
## Mathematica 62 bytes
```
(Y={}~Table~Max@#;Y[[#[[j]]]]~AppendTo~j~Table~{j,Tr[1^#]};Y)&
```
I'll run it for you
```
(Y={}~Table~Max@#;Y[[#[[j]]]]~AppendTo~j~Table~{j,Tr[1^#]};Y)&[{4,5,2,3,3,8,6,3}]
```
>
> {{}, {3}, {4, 5, 8}, {1}, {2}, {7}, {}, {6}}
>
>
>
[**Try it online**](https://sandbox.open.wolframcloud.com/app/objects/) (just paste the code with ctrl-v and press shift+enter)
don't forget to paste the input list at the end like in the example above
[Answer]
# [Perl 6](https://perl6.org), ~~ 36 32 ~~ 29 bytes
```
->\a{map {a.grep(*==$_):k},1..a.max}
```
[Try it](https://tio.run/nexus/perl6#bZDRboIwFIbv@xTnYq6AtQZULmQYH2CXu4NmabQaMlBiwWgIe3V32qpziwRKTv/v/Kf9W63gGPNVQqozvK72awXpZbTIZVfJGjrJtwdVe0Gavnz686@ehZxLXslTf0F@2SjdQAplsVPa83G/nncEoJrrMf4AaEbhG6igsHwrdnXbLJD28vXQD2AAlNG/lK0AWXWq1apRa4tfd5HrLNcbt6MsW6Wf2gE8lOOEwH24OaA3DHz@XuiGPYyxQnAzddUodJxbSU9ajOoDL5yQupQ7GNrbJ2SzP1yDGC3wMHYSy2/WPthAzpAflG5Lk5YJ2bOYszYnLDQ4ncGtk0FmIcG3CPFN1Xh0EMbaBOFjDplrcHJC@ks2FfD7ZF3Prm/YC5KFLGITcRdD3I/wmxgtQi0Sj42WNtKMzVjMYvHf0zHGgE0NhwySs2ecIRwtfgA "Perl 6 – TIO Nexus")
```
{map {.grep(*==$^a):k},1.. .max}
```
[Try it](https://tio.run/nexus/perl6#bZDRboIwFIbv@xTnYq6AtQZULmQYH2CXu8MuIVoNGSixYDSke3V32qpjiwRKTv/v/Kf9WyXhFPN1QqoLvK4PGwnptavyGjq@O8raC9L05TP351@ahZwDr/KzviK7bKRqIIWy2Evl@bhfzzsCUM3VGH8ANKPwDVRQWL4V@7ptFkh7q83QD2AAlNG/lK0AWXmu5bqRG4vfdpHrLKeN2ykvW6me2gH0ynFC4DHcHNAbBj5/L1TDemOsENxNXTUKHedWokmLMX3ghRNSl/kehvb2CdkejrcgRgs8jJ3EVndrH2wgF1gdpWpLk5YJ2LOYszYnLBQ4ncG9k0FmIcF3CPFt1Xh0EMbKBOFjDplrcHJC9DWbCvh9sk6z2xtqQbKQRWwiHmKI@xF@E6NFqEWi32hpI83YjMUsFv89HWMM2NRwyCA5e8YZwtHiBw "Perl 6 – TIO Nexus")
```
{map {.grep($^a):k},1.. .max}
```
[Try it](https://tio.run/nexus/perl6#bZDfboIwFMbv@xTnYq78qTWgciHT@AC73B12CdFqyECJBaMh3au701YdWyRQcvr9znfar1USTglfp6S6wOv6sJEwv3ZVXkPHd0dZey@fuT/70iziHHiVn/UVwWUjVQNzKIu9VJ6P@/WsIwDVTI3wB0AzCt9ABYXlW7Gv22aBtLfahH4AA6CM/qVsBcjKcy3XjdxY/LaLXGc5bdxOedlK9dQOoFeOUgKP4eaAXhj4/L1QDeuNsUJwN3XVMHKcW4kmLWb0gRdOSV3mewjt7VOyPRxvQQwXeBg7ia3u1j7YQC6wOkrVliYtk65nMWdtTlgocDqDeyeDzEKC7xDi26rx6CBKlAnCxxwy1@DklOhrNhHw@2SdZrc30oJkEYvZWDzECPdj/MZGi1GLRb/R0kaasilLWCL@ezrGGLCJ4ZBBcvqMM4SjxQ8 "Perl 6 – TIO Nexus")
---
## Expanded:
```
{ # bare block lambda with implicit parameter ÔΩ¢$_ÔΩ£
map
{ # bare block lambda with placeholder parameter ÔΩ¢$aÔΩ£
.grep( # grep for the values in ÔΩ¢$_ÔΩ£
$^a # that are equal to the currently tested value (and declare param)
) :k # return the key (index) rather than the value
},
1 .. .max # Range from 1 to the maximum value in ÔΩ¢$_ÔΩ£
}
```
---
Returns zero based indexes, to get 1 based [use cross operator (`X`) combined with `+` op](https://tio.run/nexus/perl6#bZBRb4IwFIXf@yvOwxwgXRdQeZBp/AF73MMS7BKi1ZCBEgtGQ9hfd7dFnS4SKGnPd8@9PbVW2EdiEbPiiOfFdqkwOTVFWqIJ8OmL9U6V7tNX6o2/Wx4IAVGkh/ZE8KxSusIEebZR2vXovBw3DCjG@pV@gJM4@IEjHczesk1ZV1Oi3fnS9/roweHOPWV3IFYdSrWo1NLi51PiGsu1xm2f5rXSD@2Am@1rzHBtbgZ0/b4n3jNd8Zs2VuhfTO@wbmUtqymmD7pvzMo83cC3l4/Zars75/AypVlsIz6/OHuweRwx3yld5yYsE7Brsc7aDJhpdDrHpZIjsZAUa4LEqqhcpxdE2uTgUQxJV9DJMWtPyVDi70malp/foJUsCXjIB/IqBnQe0jcwWkhaKG8LLW2kER/xiEfyv2fHGAM@NBwxRI4ecYboaPkL "Perl 6 – TIO Nexus"). (33 bytes)
```
{1 X+.grep($^a):k}
```
To get it to return [Set](https://docs.perl6.org/type/Set)s just [add `set`](https://tio.run/nexus/perl6#bZDRboIwFIbv@xTnYq4gXRdQuZBpfIDdbRdLsEuIVkMGSmwxGtK9ujtt1blFAiE9/3f@c/q3SsI@5YuM1Ed4XGyXEianri4a6JTUEMNHxNc72QQPn0U4/jIs5hx4XRzMCRtmWioNE6jKjVRBiPVm3BGAeqye8QdAcwrfQAWF2Uu5aVo9RTqYL6OwDz2gjP6l3AmQlYdGLrRcOvxcRa5znLFu@6JqpbprB3BzfM4IXIfbBYOoH/LXUml2M8YJ/YvpFXuT2rPEkBaTesfrZqSpig1E7u4ZWW135xiepriKm8PmF@MQXBxHmO@kaiublc04cJi3tvuVCrzO4NLJIHeQ4GuE@KrWAe3FqbIxhJhC7hu8nBFzyocCfp@8M@z8xkaQPGYJG4irGGM9wW9gtQS1RNw2OtpKIzZiKUvFf0/PWAM2tBwySI7ucZbwtPgB "Perl 6 – TIO Nexus") in there (total 37 bytes)
```
{set 1 X+.grep($^a):k}
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 51 bytes
```
f s{seq(1,max(s))|[[s()|enum|[_2+1]if[_1=i]]]for i}
```
It's a port of the [Python answer by Uriel](https://codegolf.stackexchange.com/a/119868/66323).
Another version (88 bytes):
```
f a{I=indexOf;seq(1,max(a))|{|i|b=a[:]c=[]x=1{c+=x+I(i,b)b-=i;x++}until[I(i,b)<0];[c]}_}
```
[Try it online!](https://tio.run/nexus/roda#PZDNboMwEITP8BSjnCC4zU9LDqHunVMuuVlWZYxpLIFpwahUhGdPFyH14vl25Z0de7cNscX1ZtCoEdXgtLetw4/qYZ3v2nLQpkRhqrYz8HRN31RdG/dpGIrBw/ZwrQeNXPMLfo1/Jr9d@G9ErpGKMYVBgzPHflEOC/Kj0zoo2AqC@B0NZBh0xg8dzYXzo4Kacm5dacZLlfXmOzqw1S@@T3d7L7gSZ6m5kCM/TDrhY5JHlhVx8cRtNibJPDhva7E23/YyE1rOH/OjUbSYIi0hvF5SiDAIxKtkixzYkb2seCQ8rpiylJ3YaS0IqEwprkTZUqeKvI5Jvzr6tWizIS5bZ@gRfw "Röda – TIO Nexus")
Both a 1-indexed.
[Answer]
# R, ~~80~~ 72 bytes
1-indexed, takes `X` from stdin. Returns a list of vectors of the indices, with `NULL` as the empty set.
```
X=scan();Y=vector('list',max(X));Y[X]=lapply(X,function(x)which(X==x));Y
```
[Try it online!](https://tio.run/nexus/r#@x9hW5ycmKehaR1pW5aaXJJfpKGek1lcoq6Tm1ihEaEJFI@OiLXNSSwoyKnUiNBJK81LLsnMz9Oo0CzPyEzO0Iiwta0AqfpvqmCqYKZg9h8A)
old version:
```
X=scan();Y=vector('list',max(X));for(i in 1:length(X))Y[[X[i]]]=c(Y[[X[i]]],i);Y
```
[Try it online!](https://tio.run/nexus/r#@x9hW5ycmKehaR1pW5aaXJJfpKGek1lcoq6Tm1ihEaGpaZ0GFMpUyMxTMLTKSc1LL8kAiUZGR0dEZ8bGxtoma8DZOplAU/6bKpgqmCmY/QcA)
[Answer]
## PowerShell, 81 bytes
```
$args[0]|%{if($_-gt($c=$r.count)){$r+=@($t)*($_-$c)}$r[--$_]+=,++$i};$r|%{"{$_}"}
```
[Try it online!](https://tio.run/nexus/powershell#FctLCoAgFAXQvcQNNJ/Rh5qE0D4iJISiScHLRubarcaHk7Dwdk3V/ORhXwWs3ryAM@DSnffhpQxgZUYBL4uf4WQET1rDzsqQUtjjAP56FmBjFlNKdUU9ddRS8wI)
1-indexed.
[Answer]
# [GNU Make](https://www.gnu.org/software/make/), ~~214~~ ~~213~~ ~~208~~ 204 bytes
```
X=$(MAKECMDGOALS)
M=0
P=$(eval N=$(word $1,$X))$(if $N,$(if $(shell dc -e$Nd$Mds.\>.p),$(eval M=$N),)$(eval A$N+=$1$(call $0,$(shell expr $1 + 1))),)
$(call P,1)$(foreach K,$(shell seq $M),$(info $(A$K)))
```
I/O: input array via arguments, output to stdout, one per line, separated by spaces.
```
$ make -f swap.mk 2 2 2
3 2 1
make: *** No rule to make target `2'. Stop.
```
## Explanation
```
X=$(MAKECMDGOALS) # Input array
M=0 # Max value encountered in X
P=$(eval
N=$(word $1,$X)) # Get next word from X
$(if $N,$(if $(shell dc -e$Nd$Mds.\>.p),
$(eval M=$N),) # Update M
$(eval A$N+=$1 # Append index to a variable named after value
$(call $0, # Recurse (call returns empty string)
$(shell expr $1 + 1))),)
$(call P,1) # Initial call to P. 1 is the first index
$(foreach K, # Print all values of A* variables
$(shell seq $M),
$(info $(A$K))) # Uninitialized ones default to empty strings
```
The order of indices in sets is reversed because `P` calls itself recursively before updating `A$2` (call executed in the evaluation of the right-hand side).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ZFā¹N-ψ}¯
```
[Try it online!](https://tio.run/nexus/05ab1e#@x/ldqTx0E4/3cP9p9tqD63//z/aTMdMx1THNBYA "05AB1E – TIO Nexus")
[Answer]
# Common Lisp, 91 bytes
```
(lambda(x &aux(l(make-list(eval`(max,@x))))(i 0))(dolist(y x l)(push(incf i)(nth(1- y)l))))
```
1-based indexing, returns the sets as lists.
[Try it online!](https://tio.run/##HYpBDoJAEAS/0iftTSTRA5x9iiNgmDisG1nI8Pp1sQ@dVKp60yUVpq/GDBaazM9B6DjJ6jTO8h6b2mSOm9ijsl/uHuqouNYfPn@7w2GBaV0mauxf0MCYJ94a7MGOvpzZokWH7oAf)
[Answer]
# [k](https://en.wikipedia.org/wiki/K_(programming_language)), 13 bytes
```
{(=x)@!1+|/x}
```
This is 0-indexed.
[Try it online!](https://tio.run/##y9bNz/7/P82qWsO2QtNB0VC7Rr@i9n@aup6VuoGVkn5Kapl@cUlKZp7Sfx1jLgMFQwUjLkMgachlomCiYKpgygXEQJYJAA "K (oK) – Try It Online")
```
{ } /function(x)
(=x) /make a map/dictionary of values to their indices
|/x /get maximum value in x
!1+ /make a range from 0 to the value, inclusive
@ /get map value at each of the values in the range
/ 0N is given where there is no result
```
[Answer]
# [Uiua](https://uiua.org), 6 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⊕□∶⇡⧻.
```
[Try it!](https://uiua.org/pad?src=ZiDihpAg4oqV4pah4oi24oeh4qe7LgoKZiBbM10KZiBbMCAxIDJdCmYgWzEgMSAxXQpmIFs0IDQgNSA1XQpmIFs1IDUgNCA0XQo=)
0-indexed.
```
⊕□∶⇡⧻.
. # duplicate
⧻ # length
‚á° # range
‚à∂ # swap
‚äï‚ñ° # group by box
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Output is 0-based.
```
rÔõ@ð¶X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ctT1QPC2WA&input=WzYsNiw1LDVdCi1R)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 38 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.75 bytes
```
G«í=vT
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiR8eSPXZUIiwiIiwiWzIsMiwyXSJd)
Bitstring:
```
01011011100001100011111110111100010001
```
Exact same algorithm as Jelly, independently discovered.
## Explained
```
Gǒ=vT­⁡​‎⁠‎⁡⁠⁢‏⁠‏​⁡⁠⁡‌⁢​‎‏​⁢⁠⁡‌⁣​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢⁡​‎⁠‏​⁢⁠⁡‌⁢⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌­
«í # ‚Äé‚Å°Reduce pairs in the cartesian product of
# ‚Äé‚Å¢the input
G # ‚Äé‚Å£and the maximum of the input
= # ‎⁤by equality
# ‎⁢⁡This creates a list of [1s in places where input == x for x in range(max(input))]
vT # ‎⁢⁢Get the indices of those 1s for each list
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 73 bytes
```
x=>x.map((n,i)=>A[(g=n=>n&&g(n-1,A[n]=A[n]||[]))(n),n].push(i),A=[[]])&&A
```
[Try it online!](https://tio.run/##bcpBDsIgEIXhvQchQzIlou1ySDgHYUFqW2vqQIqaLnp3xK3p5i2@/z3CJ@R@ndOr4XgbykhlI7OpZ0gAjLMkYx1MxGRYiAm40Wgde/rNvjsvJbBE9iq98x1miZac814KYUsfOcdlUEucYAR3refTn51R4@XAdXV94C222GF3UKrW1tZSvg "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
# Introduction
I think everyone agrees that nice pictures have to have a nice frame. But most challenges on this site about ASCII-Art just want the raw picture and don't care about it's preservation.
Wouldn't it be nice if we had a program that takes some ASCII-Art and surrounds it with a nice frame?
# The Challenge
Write a program that takes some ASCII-Art as input and outputs it surrounded by a nice frame.
**Example:**
```
*****
***
*
***
*****
```
becomes
```
╔═══════╗
║ ***** ║
║ *** ║
║ * ║
║ *** ║
║ ***** ║
╚═══════╝
```
* You have to use the exact same characters for the frame as in the example: `═ ║ ╔ ╗ ╚ ╝`
* The top and the bottom of the frame get inserted before the first and after the last line of the input.
* The left and rights parts of the frame have to have exact one space padding to the widest line of the input.
* There may be no leading or trailing whitespaces in the output. Only a trailing newline is allowed.
* You may assume that the input has no unnecessary leading whitespaces.
* You may assume that the input has no trailing whitespaces on any line.
* You don't have to handle empty input.
* The input will only contain printable ASCII-characters and newlines.
# Rules
* Function or full program allowed.
* [Default rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
**Happy Coding!**
*Using some great ASCII-Art, that was produced in any challenge on this site, as input to your program and showing it with a nice frame is highly encouraged!*
[Answer]
## Haskell, 139 bytes
```
q=length
g x|l<-lines x,m<-maximum$q<$>l,s<-[-1..m]>>"═"='╔':s++"╗\n"++(l>>= \z->"║ "++z++([q z..m]>>" ")++"║\n")++'╚':s++"╝"
```
As an example I'm framing [snowman "12333321"](https://codegolf.stackexchange.com/a/49709/34531).
```
*Main> putStrLn $ g " _===_\n (O.O)\n/(] [)\\\n ( : )"
╔═════════╗
║ _===_ ║
║ (O.O) ║
║ /(] [)\ ║
║ ( : ) ║
╚═════════╝
```
How it works:
```
bind
l: input split into lines
m: maximum line length
s: m+2 times ═
build top line
prepend left frame to each line, pad with spaces, append right frame
build bottom line.
```
[Answer]
## JavaScript (ES6), 138 bytes
This is 138 bytes in the IBM866 encoding, which at time of writing is still supported in Firefox, but 152 in UTF-8.
```
s=>`╔${t='═'.repeat(w=2+Math.max(...(a=s.split`
`).map(s=>s.length)))}╗
${a.map(s=>('║ '+s+' '.repeat(w)).slice(0,w+1)).join`║
`}║
╚${t}╝`
```
[Answer]
## CJam, 45 chars / 52 bytes
```
qN/_z,)[_)'═*N]2*C,3%'╔f+.\4/@@f{Se]'║S@2$N}*
```
Trying to avoid those expensive 3-byte chars was... interesting.
[Try it online](http://cjam.aditsu.net/#code=qN%2F_z%2C%29%5B_%29'%E2%95%90*N%5D2*C%2C3%25'%E2%95%94f%2B.%5C4%2F%40%40f%7BSe%5D'%E2%95%91S%402%24N%7D*&input=%20%20__%0A%20%2F%20%20%5C%0A%20%5C__%2F%0A%7C%20%7C%0A%7C%20%7C_____%20%20%20%20%2F%0A%7C%20%7C%20%20%20%20____%2F%0A%7C%20%7C___%20%3D%3D%3D%3D%3D%3D%3D%3D%3D%0A-----%7C%20%20%7C%0A%7C%20%20%20%7C%7C%20%20%7C%0A%7C%20%20%20%7C%7C%20%20%7C)
### Explanation
```
qN/ Split input by newline
_z, Zip and get length L, i.e. length of longest line
) Increment -> L+1
[_)'═*N] Make two-element array of "═"*(L+2) and newline
2* Double the array, giving ["═"*(L+2) "\n" "═"*(L+2) "\n"]
C, range(12), i.e. [0 1 2 ... 11]
3% Every third element, i.e. [0 3 6 9]
'╔f+ Add "╔" to each, giving "╔╗╚╝"
.\ Vectorised swap with the previous array, giving
["╔" "═"*(L+2) "╗" "\n" "╚" "═"*(L+2) "╝" "\n"]
4/ Split into chunks of length 4
@@ Move split input and L+1 to top
f{...} Map with L+1 as extra parameter...
Se] Pad line to length L+1, with spaces
'║S Put "║" and space before it
2$N Put "║" and newline after it
* Join, putting the formatted lines between the top and bottom rows
```
[Answer]
# Bash, 173 171 150 148 147 bytes, 157 136 134 133 characters
```
q(){((n=${#2}>n?${#2}:n));};mapfile -tc1 -C q v;for((p=++n+1;p;--p));do z+=═;done;echo ╔$z╗;printf "║ %-${n}s║\n" "${v[@]}";echo ╚$z╝
```
### *Multiline:*
```
q() {
(( n = ${#2} > n ? ${#2} : n))
}
mapfile -tc1 -C q v
for((p=++n+1;p;--p))
do
z+=═
done
echo ╔$z╗
printf "║ %-${n}s║\n" "${v[@]}"
echo ╚$z╝
```
### Example execution:
```
bash -c 'q(){((n=${#2}>n?${#2}:n));};mapfile -tc1 -C q v;for((p=++n+1;p;--p));do z+=═;done;echo ╔$z╗;printf "║ %-${n}s║\n" "${v[@]}";echo ╚$z╝'< bear.txt
```
Sample run from script:
```
$ cat bear2.txt
(()__(()
/ \
( / \ \
\ o o /
(_()_)__/ \
/ _,==.____ \
( |--| )
/\_.|__|'-.__/\_
/ ( / \
\ \ ( /
) '._____) /
(((____.--(((____/mrf
$ ./frame< bear2.txt
╔═══════════════════════╗
║ (()__(() ║
║ / \ ║
║ ( / \ \ ║
║ \ o o / ║
║ (_()_)__/ \ ║
║ / _,==.____ \ ║
║ ( |--| ) ║
║ /\_.|__|'-.__/\_ ║
║ / ( / \ ║
║ \ \ ( / ║
║ ) '._____) / ║
║ (((____.--(((____/mrf ║
╚═══════════════════════╝
```
[Answer]
# Perl, 111 characters
(score includes +5 for the interpreter flags)
```
#!/usr/bin/perl -n0 -aF\n
$n=(sort{$b<=>$a}map length,@F)[0];$l="═"x$n;
print"╔═$l═╗\n",(map{sprintf"║ %-${n}s ║\n",$_}@F),"╚═$l═╝";
```
First, we find the longest line length `$n`, by numerically sorting the lengths of all lines.
We set `$l` to be the header/footer bar to be `$n` repetitions of the horizontal frame character.
Then we print each line formatted to left-align in a field of width `$n`, sandwiched in between the frame characters.
### Result:
```
╔═══════════╗
║ |\_/| ║
║ / @ @ \ ║
║ ( > * < ) ║
║ `>>x<<' ║
║ / O \ ║
╚═══════════╝
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~159~~ 141 bytes
```
{a[NR,1]=x=length(a[NR]=$0)
m=m<x?x:m}END{for(;i++<m+2;)t=t"═"
for(print"╔"t"╗";j++<NR;)printf"║ %-"m"s ║\n",a[j]
print"╚"t"╝"}
```
[Try it online!](https://tio.run/##SyzP/v@/OjHaL0jHMNa2wjYnNS@9JEMDJBBrq2KgyZVrm2tTYV9hlVvr6udSnZZfpGGdqa1tk6ttZK1ZYlui9GjqBCUukHBBUWYeiDtFCUROV7LOAirzC7LWBEukAcUmKqjqKuUqFSsAmTF5SjqJ0VmxXDBts8Da5irV/v@vBQJcCmBCAcoAi/0HAA "AWK – Try It Online")
Apparently `awk` can print Unicode if you can figure out how to get it in the code.
Thanks, @ceilingcat, for pointing out that my code could be rearranged to save 18 bytes.
[Answer]
## Pyth, 44 chars (58 bytes)
```
++\╔K*JhheSlR.z\═\╗jbm+\║+.[+;d;J\║.z++\╚K\╝
```
Explanation
```
++\╔K*JhheSlR.z\═\╗ - print out the first line
lR.z - map(len, all_input())
S - sorted(^)
e - ^[-1]
hh - ^+2
J - autoassign J = ^
* \═ - ^*"═"
K - autoassign K = ^
++\╔ \╗ - imp_print("╔"+^+"╗")
jbm+\║+.[+;d;J\║.z - print out the middle
jb - "\n".join(V)
m .z - [V for d in all_input()]
+\║+ \║ - "║"+V+"║"
.[ ;J - pad(V, " ", J)
+;d - " "+d
++\╚K\╝ - print out the end
++\╚K\╝ - imp_print("╚"+K+"╝")
```
[Try it here.](http://pyth.herokuapp.com/?code=%2B%2B%5C%E2%95%94K*JhheSlR.z%5C%E2%95%90%5C%E2%95%97jbm%2B%5C%E2%95%91%2B.[%2B%3Bd%3BJ%5C%E2%95%91.z%2B%2B%5C%E2%95%9AK%5C%E2%95%9D&input=*****%0A+***%0A++*%0A+***%0A*****&debug=0)
[Answer]
# PHP 5.3, 209 bytes
This only works using the encoding [OEM 860](https://en.wikipedia.org/wiki/Code_page_860). It is an Extended ASCII superset, used in Portuguese DOS versions. Since I'm Portuguese (and I used to love doing these "frames" in Pascal) and this is a standard encoding, I went ahead with this:
```
<?foreach($W=explode('
',$argv[1])as$v)$M=max($M,strlen($v)+2);printf("É%'Í{$M}s»
º%1\${$M}sº
%2\$s
º%1\${$M}sº
È%1\$'Í{$M}s¼",'',join('
',array_map(function($v)use($M){return str_pad(" $v ",$M);},$W)));
```
Here's the base64:
```
PD9mb3JlYWNoKCRXPWV4cGxvZGUoJwonLCRhcmd2WzFdKWFzJHYpJE09bWF4KCRNLHN0cmxlbigkdikrMik7cHJpbnRmKCLilZQlJ+KVkHskTX1z4pWXCuKVkSUxXCR7JE19c+KVkQolMlwkcwrilZElMVwkeyRNfXPilZEK4pWaJTFcJCfilZB7JE19c+KVnSIsJycsam9pbignCicsYXJyYXlfbWFwKGZ1bmN0aW9uKCR2KXVzZSgkTSl7cmV0dXJuIHN0cl9wYWQoIiAkdiAiLCRNKTt9LCRXKSkpOw==
```
This answer was based on my answer on: <https://codegolf.stackexchange.com/a/57883/14732> (the heavy lifting was all made there, just had to twitch a bit).
[Answer]
# Python 3, 119 Bytes
```
def f(x):
n='\n';s="║ ";e=" ║";h=(x.find(n)+2)*"═";return"╔"+h+"╗"+n+s+x.replace(n,e+n+s)+e+n+"╚"+h+"╝"
```
~~126 bytes~~
```
import sys
o=["║ %s ║\n"%j[:-1] for j in sys.stdin]
h="═"*(len(o[0])-3)
print("╔"+h+"╗\n"+"".join(o)+"╚"+h+"╝")
```
Input:
```
hello
there
!
```
Output:
```
╔═══════╗
║ hello ║
║ there ║
║ ! ║
╚═══════╝
```
[Answer]
# Python 2, 115 Bytes
```
def f(i):w='═'*(i.find('\n')+2);return'╔%s╗\n║ %s ║\n╚%s╝'%(w,' ║\n║ '.join(i.split('\n')),w)
```
Looks shorter than 115 here, but working file includes 3-byte UTF-8 BOM mark signature, bumping it up to 115 bytes. If you were to run it in Python 3 you wouldn't need the BOM and it'd get down to 112 bytes.
[Answer]
# C, 290 bytes
Golfed function `B`, with dependencies; takes input as null-terminated char\*
```
#define l(s) strlen(s)
p(char*s,int n){while(n--)printf(s);}
B(char*s){char*t=strtok(s,"\n");int x=l(t),z=1;while(t=strtok(0,"\n"))z++,x=l(t)>x?l(t):x;p("╔",1);p("=",x+2);p("╗\n",1);while(z--)printf("║ %s", s),p(" ",x-l(s)),p(" ║\n",1),s+=l(s)+1;p("╚",1);p("=",x+2);p("╝\n",1);}
```
Somewhat-ungolfed function in full program
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1024
// GOLF-BEGIN =>
#define l(s) strlen(s)
// since multibyte chars don't fit in char: use char* instead
void p (char*s,int n){ while(n--)printf(s); }
void B (char *s){
char *t = strtok(s,"\n");
int x=l(t), z=1;
while(t=strtok(0,"\n"))z++,x=l(t)>x?l(t):x;
// x is l(longest line), z is #lines
p("╔",1);p("=",x+2);p("╗\n",1);
while(z--)printf("║ %s", s),p(" ",x-l(s)),p(" ║\n",1),s+=l(s)+1;
p("╚",1);p("=",x+2);p("╝\n",1);
}
// <= GOLF-END
int main(int argc, char **argv) {
char buffer[MAX];
memset(buffer, 0, MAX);
FILE *f = fopen(argv[1], "rb");
fread(buffer, 1, MAX, f);
B(buffer);
return 0;
}
```
[input](http://www.chris.com/ascii/index.php?art=objects/light%20bulbs)
```
_.,----,._
.:' `:.
.' `.
.' `.
: :
` .'`':'`'`/ '
`. \ | / ,'
\ \ | / /
`\_..,,.._/'
{`'-,_`'-}
{`'-,_`'-}
{`'-,_`'-}
`YXXXXY'
~^^~
```
output
```
╔======================╗
║ _.,----,._ ║
║ .:' `:. ║
║ .' `. ║
║ .' `. ║
║ : : ║
║ ` .'`':'`'`/ ' ║
║ `. \ | / ,' ║
║ \ \ | / / ║
║ `\_..,,.._/' ║
║ {`'-,_`'-} ║
║ {`'-,_`'-} ║
║ {`'-,_`'-} ║
║ `YXXXXY' ║
║ ~^^~ ║
╚======================╝
```
C golfing tips appreciated!
] |
[Question]
[
# Challenge description
A "derangement" of a sequence is a permutation where no element appears in its original position. For example `ECABD` is a derangement of `ABCDE`, but `CBEDA` is not:
```
ABCDE
| | <- B and D are in their orignal positions
CBEDA
```
Given a sequence, generate a random derangement of it.
# Notes
* You may take either a string as an input or an array/list of elements (integers, chars, objects...)
* Instead of returning a new object, you can modify an existing one by swapping its elements
* Each derangement should have an equal probability of being generated
* You may assume that there is more than one element in the sequence and none appear more than once
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 14 bytes
```
q:X{mr_X.=:|}g
```
[Try it online!](https://tio.run/nexus/cjam#@19oFVGdWxQfoWdrVVOb/v@/o5OziysA "CJam – TIO Nexus")
Keeps shuffling the input until it's a derangement.
### Explanation
```
q:X e# Read input and store it in X.
{ e# While the condition at the end of the loop is truthy...
mr e# Shuffle the string.
_X e# Duplicate it and push the input.
.= e# Element-wise equality check.
:| e# Reduce OR over the list, gives something truthy if any character
e# remained in its original position.
}g
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes
```
Ẋ=³S$¿
```
[Try it online!](http://jelly.tryitonline.net/#code=4bqKPcKzUyTCvw&input=&args=MSwyLDM)
## Explanation
```
Ẋ ¿ Shuffle the given list while this is nonzero for it:
$ A two-step process:
=³ Element-wise equality of it and L (the original list)...
S Sum the ones in this binary array.
```
Jonathan Allan saved a byte.
[Answer]
# Python, 85 bytes
Modifies the list passed to it (allowed by meta and in the question).
```
from random import*
def D(l):
o=l[:]
while any(x==y for x,y in zip(o,l)):shuffle(l)
```
[**Try it online here!**](https://repl.it/Esrn/0)
[Answer]
# ES6 (Javascript), ~~71~~, 69 bytes
Input and output are arrays, should work with any element types (strings, numbers e.t.c.), as long as they can be compared with "==".
**Golfed**
```
F=s=>(r=[...s]).sort(_=>Math.random()-.5).some((e,i)=>s[i]==e)?F(s):r
```
**Test**
```
F=s=>(r=[...s]).sort(_=>Math.random()-.5).some((e,i)=>s[i]==e)?F(s):r
F(['A','B','C','D'])
Array [ "D", "C", "A", "B" ]
F(['A','B','C','D'])
Array [ "D", "A", "B", "C" ]
F(['A','B','C','D'])
Array [ "C", "D", "B", "A" ]
F(['A','B','C','D'])
Array [ "D", "C", "B", "A" ]
F(['A','B','C','D'])
Array [ "C", "D", "B", "A" ]
```
**Interactive Snippet**
```
F=s=>(r=[...s]).sort(_=>Math.random()-.5).some((e,i)=>s[i]==e)?F(s):r
function G() {
console.log(F(T.value.split``).join``);
}
```
```
<input id=T value="ABCDEF"><button id=G onclick="G()">GENERATE</button>
```
[Answer]
## [Perl 6](http://perl6.org/), 33 bytes
```
{first (*Zne$_).all,.pick(*)xx *}
```
A lambda that takes a list of integers or characters as input, and returns a new list.
If it must support lists of *arbitrary* values, `ne` would have to be replaced with `!eqv` (+2 bytes).
([Try it online.](https://tio.run/#aWM7Z))
### Explanation:
* `{ }`: Defines a lambda.
* `.pick(*)`: Generates a random shuffle of the input list.
* `.pick(*) xx *`: Creates a lazy infinite sequence of such shuffles.
* `(* Zne $_).all`: A lambda that zips two lists (its argument `*`, and the outer lambda's argument `$_`) with the `ne` (negative string equality) operator, yielding a list of booleans, and then creates an [`all` junction](https://docs.perl6.org/type/Junction) to collapse them to a single boolean state.
* `first PREDICATE, SEQUENCE`: Takes the first element from our infinite sequence of permutations that fulfills the "derangement" test.
[Answer]
# MATL, 7 bytes
This is a translation of my Octave post (and similar to some of the other submissions here). I posted my first MATL post yesterday (CNR crack), so I guess this is not optimal, but it's the best I've got so far.
To be honest, I'm not entirely sure `t` is needed in there, but it's the only way I can get this to work. It's used so that I can compare the user input (retrieved with `G`), with the random permutation. I would think I could compare the two without it, but...?
Anyway, here goes:
```
`Z@tG=a
` % Loop
Z@ % Random permutation of input
t % Duplicating the stack
G % Paste from clipboard G (user input)
= % Comparing the random permutation with the input (retrieved from clipboard)
a % any(input == random permutation)
% Implicit end and display
```
[Try it online!](http://matl.tryitonline.net/#code=YFpAdEc9YQ&input=J0FCQ0RFRic)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~19~~ ~~18~~ ~~15~~ 13 bytes
```
@~.:?z:#da;?&
```
[Try it online!](https://tio.run/nexus/brachylog#@@9Qp2dlX2WlnJJoba/2/3@0oZWRlbGViZWplVns/ygA "Brachylog – TIO Nexus")
### Explanation
```
@~. Output is a shuffle of the input
.:?z Zip the output with the input
:#da All couples of integers of the zip must be different
; Or
?& Call recursively this predicate with the same input
```
[Answer]
# [Perl 6](https://perl6.org), 45 bytes
```
{(@^a,{[.pick(*)]}...{none @a Zeqv@$_})[*-1]}
```
```
{(@^a,{[.pick(*)]}...{!sum @a Zeqv@$_})[*-1]}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS85PSVWw/V@t4RCXqFMdrVeQmZytoaUZW6unp1edl5@XquCQqBCVWljmoBJfqxmtpWsYW/u/OLFSAazRxlHBScFZwUXB1U4hLb9IIc7QwJoLJKuuDqHBqqINdYx0jHUO7dV51DpVpwaiyS4WoeM/AA "Perl 6 – TIO Nexus")
Input is an Array of anything.
## Expanded:
```
{
(
@^a, # declare parameter, and seed sequence generator
{ # lambda with implicit parameter 「$_」
[ # store into an array
.pick(*) # shuffle 「$_」
]
}
... # keep generating the sequence until
{
none # none
@a # of the outer blocks input
Z[eqv] # is zip equivalent
@$_ # with the current value being tested
}
)[ * - 1 ] # return the last value
}
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 13 bytes
```
;;WX╚│♀=ΣWX)X
```
[Try it online!](https://tio.run/nexus/actually#@29tHR7xaOqsR1OaHs1ssD23ODxCM@L/fyVHJ2cXVyUA "Actually – TIO Nexus")
Explanation:
```
;;WX╚│♀=ΣWX)X
;; make two copies of input
WX╚│♀=ΣW while top of stack is truthy:
X discard top of stack
╚ shuffle array
│ duplicate entire stack
♀= compare corresponding elements in shuffled and original for equality
Σ sum (truthy if any elements are in the same position, else falsey)
X)X discard everything but the derangement
```
[Answer]
# Octave, ~~56~~ 55 bytes
```
x=input('');while any(x==(y=x(randperm(nnz(x)))));end,y
```
We have to use `input('')` since this is not a function. Also, since I can choose to have the input as a string we can use the trick that `nnz(x)==numel(x)`.
**Explanation:**
```
x=input('') % Self-explanatory
while any(x==y) % Loop until x==y has only 0s (i.e. no elements are equal)
y=x(randperm(nnz(x))) % Continue to shuffle the indices and assign x(indices) to y
end % End loop
y % Display y
```
Thanks to Luis for noticing that the input can be a string, thus I could use `nnz` instead of `numel` saving two bytes.
[Answer]
# MATL, 13 bytes
This is a joint effort of @LuisMendo and me. In contrast to many other answers here this one is deterministic in the sense that it does not sample random permutations until it gets a derangement, but it generates all derangements and chooses one randomly.
```
Y@tG-!Af1ZrY)
```
[Try It Online!](https://tio.run/nexus/matl#@x/pUOKuq@iYZhhVFKn5/796YlJyijoA)
### Explanation
```
Y@tG-!Af1ZrY)
Y@ generate all permutatoins
t create a duplicate
G-!A find the (logical) indices of all valid derangements (where no character of the string is in the same position as the original string)
f convert logical to linear indices
1Zr choose one of those indices randomly
Y) get the derangement (from the ones we generated earlier) at this index
```
[Answer]
# Pyth - ~~10~~ 9 bytes
This keeps on shuffling the input while any of the characters equal the characters at their index in the input.
```
.WsqVHQ.S
```
[Try it online here](http://pyth.herokuapp.com/?code=.WsqVHQ.S&input=%22ABCDE%22&debug=0).
```
.W Iterate while
s Sum, this is works as any() on a boolean list
qV Vectorized equality
H The lambda variable for the check step
Q The input
.S Shuffle
(Z) Lambda variable, implicit
(Q) Start .W with input, implicit
```
[Answer]
# Mathematica, 57 bytes
```
#/.x_:>RandomChoice@Select[Permutations@x,FreeQ[#-x,0]&]&
```
Unnamed function taking a list of whatevers as input and outputting a list. After generating all permutations `#` of the input `x`, we keep only the ones for which the set `#-x` of element-wise differences doesn't contain a `0`; then we make a (uniformly) random choice from that set.
[Answer]
# PHP, 85 bytes
```
for($a=$b=str_split($argv[1]);array_diff_assoc($a,$b)!=$a;)shuffle($b);echo join($b);
```
Copies the string argument to two arrays, shuffles one of them until the difference between them (also comparing indexes of the elements) equals the other one. Run with `-r`.
[Answer]
# R, 59 bytes
```
z=x=1:length(y<-scan(,""));while(any(x==z))z=sample(x);y[z]
```
Reads a list of elements to STDIN, takes the length of the list and starts sampling ranges from 1 to the length, until it finds one that shares no places with the ordered list. Then prints that list.
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 32 bytes
```
f\@[/>#I zip#=[#0a\shuf#0]?f a?a
```
Usage:
```
f\@[/>#I zip#=[#0a\shuf#0]?f a?a];f[1 2 3 4 5]
```
# Explanation
More readable:
```
f\@[
some #I zip #= [#0; a\ shuf #0]
? f a
? a
]
```
Recursive function `f`. Does an element-wise comparison between `f`'s input list and and a shuffled version of the input list. If the comparison yields any equal values, then `f` is called on the shuffled list. Otherwise, we simply return the shuffled list.
[Answer]
# Ruby, 67 bytes
```
def f a
while (a.zip(o=a.shuffle).map{|x,y|x-y}.index 0);end
o
end
```
[Answer]
# Octave, ~~54~~ 53 bytes
```
@(a)((p=perms(a))(L=!any(p==a,2),:))(randi(sum(L)),:)
```
Generate all permutations of `a` and select randomly a row that doesn't have a common element with `a` .
note: It is accidentally the same as @flawr MATL answer!
[Answer]
## Clojure, ~~94~~ ~~90~~ 79 bytes
```
#(let[s(shuffle %)](if(not(some(fn[[x y]](= x y))(map vector % s)))s(recur %)))
```
-4 bytes by changing the conditional inside the reduction to an `and`, and inlining `done?`.
-11 bytes by converting the reduction to `some`.
WOOT! Beat PHP.
Brute-force method. Shuffles the list while it's invalid. This finishes stupid fast considering it's a brute force method that does nothing to prevent duplicate tries. It found 1000 dearangments of a 1000 element long list in less than a second.
Ungolfed:
```
(defn dearang [ls]
(let [s (shuffle ls)
bad? (some (fn [[x y]] (= x y))
(map vector ls s))]
(if (not bad?) s (recur ls))))
```
[Answer]
## Clojure, 56 bytes
```
#(let[s(shuffle %)](if((set(map = % s))true)(recur %)s))
```
Note that a string cannot be shuffled, must be passed through `seq` or `vec`.
Originally I tried `#(first(remove(fn[s]((set(map = % s))true))(iterate shuffle %)))` but `recur` approach is indeed shorter than `iterate`.
The magic is that `(set(map = % s))` returns either a set of false, set of true or set of true and false. This can be used as a function, if it contains `true` then the answer is `true`, otherwise falsy `nil`. `=` is happy to take two input arguments, no need to wrap it with something.
```
((set [false]) true)
nil
```
Maybe there is even shorter way to check if any of the values is true?
[Answer]
# APL, 11 bytes.
With the string in the right argument:
`⍵[⍋(⍴⍵)?⍴⍵]`
# Explanation
`ρ⍵` gets the length (or shape) of the right argument.
`?` returns a random array of `(⍴⍵)` of these numbers.
`⍋` returns the order of them in order to ensure no duplicates.
`⍵[..]` represents the random assortment of the string using this index.
] |
[Question]
[
[In the United States](http://mutcd.fhwa.dot.gov/services/publications/fhwaop02090/twtmarkings_longdesc.htm), the two opposing directions of traffic on a road are separated by a dashed yellow line if passing is allowed and two solid yellow lines if passing is not allowed.

(Just one side can be dashed to allow passing on that side, and yellow lines can mean other things like center or reversible lanes, but we aren't concerned with any of those cases.)
Write a program that takes in a [run-length encoded](http://en.wikipedia.org/wiki/Run-length_encoding) string of `P` for *passing* and `N` for *no passing*, and prints an ASCII version of the corresponding road. Except for the center line, the road always has the same pattern, which can be easily inferred from the examples below.
There will be a positive decimal number before each `P` and `N` in the input string. This number defines the length of the *passing* or *no passing* region of the current part of the road.
### Examples
An input of `12N` would produce 12 columns of *no passing* road (center line all `=`):
```
____________
============
____________
```
An input of `12P` would produce 12 columns of *passing* road (center line `-` repeating):
```
____________
- - - - - -
____________
```
*Passing* and *no passing* can then be combined, e.g. `4N4P9N7P1N1P2N2P` would produce:
```
______________________________
====- - =========- - - -=-==-
______________________________
```
These are 4 *no passing* columns, then 4 *passing*, then 9 *no passing*, etc.
**Note that a *passing* zone always starts with a dash (`-`) on the leftmost side, not a space (). This is required.**
### Details
* The input will never have two `N` zones or two `P` zones in a row. e.g. `4P5P` will never occur.
* You don't need to support letters without a leading positive number. Plain `P` will always be `1P`, plain `N` will always be `1N`.
* There may be trailing spaces as long as they do not extend beyond the final column of the road. There may be one optional trailing newline.
* Instead of a program, you may write a function that takes in the run-length encoded string and prints or returns the ASCII road.
* Takes input in any standard way (stdin, command line, function arg).
**The shortest code in bytes wins. Tiebreaker is earlier post.**
[Answer]
# JavaScript (ES6), 114
Using [template strings](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/template_strings), the 5 linefeeds are significant and thus must be counted.
```
f=s=>(b=(s=s.replace(/(\d+)(.)/g,(x,n,b)=>(b<'P'?'=':'- ').repeat(n).slice(0,n))).replace(/./g,'_'))+`
${s}
`+b
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 46 bytes
Created on the APL Farm with lots of input from chrispsn.
```
{++(,/(.x@y)#'"-="x_y#="PNP";"_")@3\466}`c$!58
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rW1tbQ0dfQq3Co1FRWV9K1VaqIr1S2VQrwC1CyVopX0nQwjjExM6tNSFZRNLXg4kowsEpTUDI08lOCMwNgTBM/kwBLP/MAQz/DACM/oDgAQCoWRQ==)
---
# k9 2021.03.27, ~~53~~ 52 bytes
-1 byte thanks to chrispsn!
```
++"_ ",|"_ ",,,/{.[x]#*"-="y#="PNP"}/'-2^(~=':64>)^
```
[Try it online](https://kparc.io/k/#f%3A%2B%2B%22_%20%20%22%2C%7C%22_%20%22%2C%2C%2C%2F%7B.%5Bx%5D%23*%22-%3D%22y%23%3D%22PNP%22%7D%2F%27-2%5E(%7E%3D%27%3A64%3E)%5E%3B%20f%20%2212P4N4P9N7P1N1P2N2P%22) on kparc.io!
[Answer]
# CJam, 38 bytes
```
"_ - _":N3'=t:P;q~]2/e~z'
*"--"/"- "*
```
**How it works**
We first assign the correct road column to variables `N` and `P` and then simply evaluate the input string. This leaves a pair of the length and the column on stack. We group them up, run an RLD on it to get the full columns, transpose to join them and then finally, convert the continuous `--` to `-` .
```
:_ - _":N e# This is the no passing column. We assign it to N
3'=t:P e# Replace the '-' in N with '=" and assign it to P
q~]2/ e# Read the input, evaluate it and then group it in pairs
e~ e# Run a run-length-decoder on the pairs
z'
* e# Transpose and join with new lines.
"--"/ e# Split on two continuous occurrence of -
"- "* e# Join by an alternate "- "
```
[Try it online here](http://cjam.aditsu.net/#code=%22_%20%20-%20_%22%3AN3%27%3Dt%3AP%3Bq%7E%5D2%2Fe%7Ez%27%0A*%22--%22%2F%22-%20%22*&input=4N4P9N7P1N1P2N2P)
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 252 chars
Although this might not count because I [added the convergence operator as a ripoff of Martin Büttner's Retina](https://github.com/kirbyfan64/rs/commit/29f5993f443a40982ca89fe5be48a920718f0072) an hour ago...I'm not really here to compete anyway. It's just fun making a regex-based solution for this.
```
(\d+\D)/#\1
+(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)(?=\d*\D)/\1\1\1\1\1\1\1\1\1\1\2\3\4\5\6\7\8\9\10#
\d(?=\d*#N)/=
(^|(?<=\D))\d(?=\d*#P)/-
+(?<=-)\d\d(?=\d*#P)/ -
(?<=-)\d(?=\d*#P)/
#\D/
((?:(=|-| ))+)/A\1\n\n\n\1\n\nA\1\n
+(A_*)(.)/\1_
A/
```
I got line 2 from [Martin's Retina answer for Programming Languages Through the Years](https://codegolf.stackexchange.com/a/48479/21009).
## Explanation
```
(\d+\D)/#\1
+(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)(?=\d*\D)/\1\1\1\1\1\1\1\1\1\1\2\3\4\5\6\7\8\9\10#
```
This does lots of magic. See the answer I linked above for more info.
Basically, with the input `4N4P9N7P1N1P2N2P`, this will be the result:
```
4444#N4444#P999999999#N7777777#P1#N1#P22#N22#P
```
Next:
```
\d(?=\d*#N)/=
```
This replaces the numbers preceding the no-passing symbol (N) with the equal signs. The result with the previous input:
```
====#N4444#P=========#N7777777#P=#N1#P==#N22#P
```
This:
```
(^|(?<=\D))\d(?=\d*#P)/-
```
replaces the first number preceding a passing symbol (P) with the first dash. The result:
```
====#N-444#P=========#N-777777#P=#N-#P==#N-2#P
```
The next two lines continue the same pattern:
```
+(?<=-)\d\d(?=\d*#P)/ -
(?<=-)\d(?=\d*#P)/
```
The first line replaces the rest of the line with the dash-space pattern. The second one handles an odd number; it replaces the last dash followed by a single integer (such as `-5`) with a dash-space (`-`). Now, the output is:
```
====#N- - #P=========#N- - - -#P=#N-#P==#N- #P
```
Now things are starting to fall into place. The next line:
```
#\D/
```
just removes the `#N` and `#P`.
```
((?:(=|-| ))+)/A\1\n\n\n\1\n\nA\1\n
+(A_*)(.)/\1_
```
set up the underscores on the top and bottom to give:
```
A______________________________
====- - =========- - - -=-==-
A______________________________
```
Lastly, we remove the `A`:
```
A/
```
[Answer]
## Python 2, 136 bytes
Surprisingly, importing `re` seems to be actually worthwhile here.
```
import re
s=""
for x,y in re.findall("(\d+)(.)",input()):s+=(("- ","==")[y=="N"]*int(x))[:int(x)]
t="_"*len(s);print t+"\n"*3+s+"\n"*2+t
```
[Answer]
# k9 2021.03.27, 72 bytes
```
" -=_"{++(3;0;0;mod[x]+2*~x;0;3)}@{y*x+y}\&?`P=!/`i`n$+-2^{9<a|-a:-':x}^
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~71~~ ~~69~~ ~~68~~ ~~64~~ ~~69~~ ~~68~~ 65 bytes
```
{++"_ ",|"_ ",+" =-"@+/1(~<\2=)\-78+*'&.'!/|+0N 2#(&~=':58<x)_x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rW1laKV1BQ0qkBUko62koKtrpKDtr6hhp1NjFGtpoxuuYW2lrqanrqivo12gZ+CkbKGmp1tupWphY2FZrxFbVcXMVWSiZ+JgGGBn7mAYZ+hgFGfkYBSlxcCQZWaQ7FAEE4FqE=)
-2 superfluous parens
-1 shuffling
-4 borrowing a parsing idea from ovs
+5 I actually prefer using "-" for the embankment, but what evs.
-1 woo hoo!
-4 bye bye beloved Bubbler train...
[Answer]
# Python 3, ~~169~~ 168 bytes. (167 with Python 2)
```
p,s='',str.split
for _ in s('N '.join(s('P '.join(s(input(),'P')),'N'))):
v=int(_[:-1]);p+=['='*v,('- '*v)[:v]][_[-1]=='P']
l=len(p)
u='_'*l
print(u+'\n'*3+p+'\n\n'+u)
```
**Fairly ungolfed:**
```
p=''
for i in'N '.join('P '.join(input().split('P')).split('N')).split():
v=int(i[:-1]) # Get the number from the input section
if i[-1]=='N': # Check the letter (last char) from the input section
p+=('='*v) # Repeat `=` the number from input (v)
else:
p+=('- '*v)[:v] #Repeat `- ` v times, then take first v chars (half)
l=len(p) #Get the length of the final line markings
print('_'*l+'\n\n\n'+p+'\n\n'+'_'*l)
```
---
```
print('_'*l # Print _ repeated the length of p
+'\n\n\n' # 3 new lines
+p+ # print out p (the markings)
'\n\n' # 2 new lines
+'_'*l) # Print _ repeated the length of p
```
---
```
for i in
'N '.join(
'P '.join(
input().split('P'))
.split('N'))
.split():
# Split the input into items of list at P
# Join together with P and ' '
# Split at N...
# Join with N and ' '
# Split at space
# Loop through produced list
```
Try it online [here](http://repl.it/lOt).
[Answer]
# J (~~69~~ ~~59~~ ~~55~~ 52 bytes)
-14 bytes thanks to *Raul Miller* and *ovs* on *The APL Farm* Discord.
-3 bytes by removing noun assigments
```
6$'_',4$'','',:'\d+.'(".@}:$'-= '#~'PNP'={:)rxapply]
```
[Attempt This Online](https://ato.pxeger.com/run?1=LYxLCoJQAEXnreJWwlUySXv0eSQ0cvh4CyhCUonIlCgoHraRJjZoES2l3fQxOKPLued239b143TM-pOXGFlc0RUW6X6QXCQ9j3bHm1fSYj8Eu1dqpRka6RzOcVnuLsv_V2X7OE8RejAGti3acujAwsCBkfKK7yAczMALUVUgW0kBRgglXRgPzInskMYJfqGmWj_T9aZABAol9FSNta98HahAsxHe)
#### Explanation
`'\d+'(...)rxapply]`: For every match of pattern `\d+`, apply the function...
`".@}:$'-= '#~'PNP'={:`, a Fork/3-Train.
* `'-= '#~'PNP'={:`: The right tine of the Fork. `{:` takes the last element (`'N'` or `'P'`), and checks it's equality against `'PNP'`, then uses the resulting boolean mask to select from `'-= '`. `'P'` gets `1 0 1` so it selects `'- '`, and N gets `0 1 0` and selects `'='`.
* `".@}:"`: The left tine of the Fork. `}:` drops the last element, keeping the digit(s) as a sting. The string is converted to a integer with `".`, the Execute operator.
* `$`: The Reshape operator reshapes the right arg by the left arg
The expression so far has produced the mid line, eg. `====- - =========- - - -=-==-` , which I will refer to as `m` below.
`,:` Itemize `m` (ie. Puts it in an array, changing the shape from `30` to `1 30`)
`4$'',''` Prepend 2 blank rows (arrays are rectangular, so the 2 chars get padded to the width of `m`) and then reshape by 4. Since there are 3 rows, reshape cycles to reuse the first row, adding another blank line.
`6$'_',` Prepends a `_` char (which again gets padded to the width of `m`) then reshapes to 6. Again, since there's 5 rows, reshaping cycles back to the first item in the array (ie. the top line) which is appended to the array, producing the final result.
[Answer]
# Haskell, 165 bytes
```
k 'N'="="
k _="- "
d c=c>'/'&&c<':'
p[]=[]
p s=take(read$takeWhile d s)(cycle$k a)++p r where(a:r)=dropWhile d s
f s=unlines[q,"\n",p s,"",q]where q=map(\x->'_')$p s
```
Example run (`f` returns a string, so for better display print it):
```
*Main> putStr $ f "4N4P9N7P1N1P2N2P"
______________________________
====- - =========- - - -=-==-
______________________________
```
How it works: `p` returns the middle line by recursively parsing the input string and concatenating the given number of symbols found by the lookup function `k`. The main function `f` joins a five element list with newlines, consisting of the top line (every char of the middle line replaced by `_`), a newline, the middle line, an empty line and the bottom line (same as top).
[Answer]
# PHP, 187 bytes
```
preg_match_all('/(\d+)(\w)/',$argv[1],$m,2);
$o='';
foreach($m as $p)
$o.=str_replace('--','- ',str_repeat($p[2]<'P'?'=':'-',$p[1]));
$a=preg_replace('/./','_',$o);
echo("$a\n\n\n$o\n\n$a\n");
```
The code can stay on a single line; it is displayed here on multiple lines to be more readable (the whitespaces and newlines used for formatting were not counted).
Two bytes can be saved by not printing the trailing newline. Five more bytes can be saved by using real newline characters on the `echo()`:
```
echo("$a
$o
$a");
```
Six additional bytes can be saved by omitting the initialization of `$o` (`$o='';`) but this will trigger a notice. The notice can be suppressed by running the script using the command line:
```
$ php -d error_reporting=0 <script_name> 4N4P9N7P1N1P2N2P
```
These brings it to 174 bytes.
[Answer]
# Ruby, ~~137~~ 135 bytes
Not the shortest I could come up with, but close to the nicest. Partly borrowed from Optimizer's answer.
```
require'scanf'
N='_ = _'
P='_ - _'
a=[]
scanf('%d%c'){|l,t|a+=[eval(t).chars]*l}
puts (a.shift.zip(*a).map(&:join)*?\n).gsub'--','- '
```
Ungolfed:
```
require 'scanf'
N = '_ = _'
P = '_ - _'
columns = [] # array of columns
# scan stdin for a number followed by a single char
scanf('%d%c') do |length, type|
columns += [eval(type).chars] * length
done
# Convert to an array of rows, and join into a string
rows = columns.shift.zip(*columns).map(&:join)
str = rows * "\n" # join lines
# Replace '--' by '- ' and print
puts str.gsub(/--/, '- ')
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~35~~ 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.γa}2ôε`„PN…- =2ä‡s∍}J©¶ĆìĆ'_®∍DŠ»
```
[Try it online](https://tio.run/##AVUAqv9vc2FiaWX//y7Os2F9MsO0zrVg4oCeUE7igKYtID0yw6TigKFz4oiNfUrCqcK2xIbDrMSGJ1/CruKIjUTFoMK7//80TjRQOU43UDFOMVAyTjJQMTJO) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4elU/tc7tzmx1ujwlnNbEx41zAvwe9SwTFfB1ujwkkcNC4sfdfTWeh1aeWjbkbbDa460qccfWgcUcjm64NDu/zqHttn/NzTy4zI0CuAy8TMJsPQzDzD0Mwww8jMKAAA).
**Explanation:**
```
.γ # Consecutive group the (implicit) input by:
a # Check if the character is a letter
}2ô # After the group by: split it into parts of size 2
ε # Map each pair of integer + letter to:
` # Pop and push them separated to the stack
„PN # Push string "PN"
…- = # Push string "- ="
2ä # Split it into 2 parts: ["- ","="]
‡ # Transliterate the "P" to "- " and "N" to "="
s # Swap to take the integer value
∍ # Extend (or shorten) the string to that length
}J # After the map: join all parts together to a single string
© # And store it in variable `®` (without popping)
¶ # Push a newline character "\n"
Ć # Double it "\n\n"
ì # Prepend it in front of the string
Ć # Enclose the string, appending it's own first character
'_ '# Push string "_"
®∍ # Extend it to a size equal to the length of string `®`
D # Duplicate it
Š # Triple swap the three values on the stack from a,b,c to c,a,b
» # Join the values on the stack with newline delimiter
# (after which the result is output implicitly)
```
[Answer]
# Ruby, 94 bytes
Borrows the `gsub'--','- '` idea from [14mRh4X0r's answer](https://codegolf.stackexchange.com/a/49406/26465). I think that answer is more interesting, though, although this is shorter.
```
f=->x{n=?_*x.gsub!(/(\d+)(.)/){($2==?P??-:?=)*$1.to_i}.size
"#{n}
#{x.gsub'--','- '}
#{n}"}
```
Testing:
```
f=->x{n=?_*x.gsub!(/(\d+)(.)/){($2==?P??-:?=)*$1.to_i}.size
"#{n}
#{x.gsub'--','- '}
#{n}"}
puts f['4N4P9N7P1N1P2N2P']
```
Produces:
```
______________________________
====- - =========- - - -=-==-
______________________________
```
[Answer]
let me include my ***matlab*** version
## MATLAB (267 b)
```
function d=p(V,a),j=numel(V)-1;if (a==0),d=0;return; end,d=(V(a)-48+10*p(V,a-1))*(V(a)<64);fprintf('%c%.*s%c%.*s',(a>=j)*10,(a==j|a==1)*eval(strcat(regexprep(V,'[NP]','+'),48)),ones(99)*'_',(a<3)*10,(V(a+1)>64)*d,repmat((V(a+1)==78)*'=='+(V(a+1)==80)*'- ',[1 99]));end
```
---
## input
An ascii-formatted string tailed by a space (since there is no end of chain '\0' in matlab
**example** V='12N13P '
---
## output
pattern representation of the road
```
_________________________
============- - - - - - -
_________________________
```
## function
the function must be called from its tail-1 (the empty character is removed)
**example** : p(V,numel(V)-1)
## Simulation
try it online [here](http://www.tutorialspoint.com/codingground/index.htm?port=9197&sessionid=sup8e17e757ccean6qdbiahe91&home=http://codingground.tutorialspoint.com)
[Answer]
# R, 132 bytes
Not greatly happy with this, but it was a bit of fun to do:) Tried to get rid of the multiple `gsub`s, but my efforts were in vain. I suspect there's a much better way to do this.
```
cat(rbind(nchar(a<-scan(,'',t=gsub('PN','P N',gsub('NP','N P',chartr('- =','PPN',scan(,'',sep='|')[4]))))),substring(a,1,1)),sep='')
```
* `scan` gets the strings from STDIN and grabs the 4th one. **Note** that the empty lines require a space (or something) in them for scan to carry on getting the input.
>
> "====- - =========- - - -=-==- "
>
>
>
* It replaces the `=`s with `N`s, the `-` and with `P`s.
>
> "NNNNPPPPNNNNNNNNNPPPPPPPNPNNPP"
>
>
>
* Then it inserts a space between each `NP` and `PN`
>
> "NNNN PPPP NNNNNNNNN PPPPPPP N P NN PP"
>
>
>
* The scan splits the string on spaces
>
> "NNNN" "PPPP" "NNNNNNNNN" "PPPPPPP" "N" "P" "NN" "PP"
>
>
>
* The string length is then bound(`rbind`) with the first character of each string
>
> 4 4 9 7 1 1 2 2
>
> "N" "P" "N" "P" "N" "P" "N" "P"
>
>
>
* The array is then output using `cat`.
Test run
```
cat(rbind(nchar(a<-scan(,'',t=gsub('PN','P N',gsub('NP','N P',chartr('- =','PPN',scan(,'',sep='|')[4]))))),substring(a,1,1)),sep='')
1: ____________
2:
3:
4: ============
5:
6: ____________
7:
Read 6 items
Read 1 item
12N
>
> cat(rbind(nchar(a<-scan(,'',t=gsub('PN','P N',gsub('NP','N P',chartr('- =','PPN',scan(,'',sep='|')[4]))))),substring(a,1,1)),sep='')
1: ____________
2:
3:
4: - - - - - -
5:
6: ____________
7:
Read 6 items
Read 1 item
12P
> cat(rbind(nchar(a<-scan(,'',t=gsub('PN','P N',gsub('NP','N P',chartr('- =','PPN',scan(,'',sep='|')[4]))))),substring(a,1,1)),sep='')
1: ______________________________
2:
3:
4: ====- - =========- - - -=-==-
5:
6: ______________________________
7:
Read 6 items
Read 8 items
4N4P9N7P1N1P2N2P
```
[Answer]
# C, 155 153 bytes
−2 bytes thanks to **ceilingcat**
```
l=6;main(k,v,n,x,s,c)char*s,**v,c;{for(;l--;puts(s))for(s=v[1];*s;s+=k)for(x=sscanf(s,"%d%c%n",&n,&c,&k);n--;)putchar(" -=_"[l%5?l^2?0:c^78?++x&1:2:3]);}
```
More readable:
```
main(l,v,k,n,x,s,c)
char*s,**v,c;
{
for(l=6;l--;puts(s))
for(s=v[1];*s;s+=k)
for(x=sscanf(s,"%d%c%n",&n,&c,&k);n--;)
putchar(l%5?l^2?32:c^78?++x&1?45:32:61:95);
}
```
The outer loop counts lines from 5 to 0.
The middle loop iterates over parts of the encoded string:
```
4N4P9N7P1N1P2N2P
4P9N7P1N1P2N2P
9N7P1N1P2N2P
7P1N1P2N2P
1N1P2N2P
1P2N2P
2N2P
2P
string is empty - exit
```
The inner loop decodes a part, like, `7P`, and iterates the needed number of times (e.g. 7).
Each iteration prints one `char`. The value of the `char` is described by the code `" -=_"[l%5?l^2?0:c^78?++x&1:2:3]`:
* If line number is 5 or 0, print `_`
* Otherwise, if line number is not equal to 2, print a space
* Otherwise, if the symbol is 'N', print `=`
* Otherwise, increase `x` by 1 (it was initialized to 2 by `sscanf`)
* If odd, print `-`, else print a space
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~30~~ ~~29~~ ~~28~~ 29 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input in lowercase, prepend `v<space>` for +2 bytes if that's not allowed. Had to sacrifice a byte to fix a bug with inputs that contained a `0` :\
```
ò!Í®n îZèÍg"- ="òìyÈû4 Ôû6'_
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=8iHNrm4g7lrozWciLSA9IvLDrHnI%2bzQg1Ps2J18&input=IjRuNHA5bjdwMW4xcDJuMnAi)
```
ò!Í®n îZèÍg"- ="òìyÈû4 Ôû6'_ :Implicit input of string
ò!Í :Partition into the run length groups we need (See more detailed explanation below)
® :Map each Z
n : Convert to integer (the letter at the end is ignored)
î : Repeat and slice to that length
Zè : Count the occurrences in Z of
Í : "n" (see below for the why)
g : Index into
"- ="ò : Partitions of "- =" of length 2
à :End map
¬ :Join
y :Transpose
È :Pass each row through the following function and transpose back
û4 : Centre pad with spaces to length 4
Ô : Reverse ('cause centre padding is right-biased)
û6'_ : Centre pad with "_" to length 6
```
OK, I finally (think I) figured out how the partitioning is working! First the basics: The `ò` method partitions string between pairs of characters (X & Y) that return a truthy value when run through the method that's passed as an argument. We're using `Í` here, which is the shortcut for `n2<space>`. The space is used to close the `ò` method and the `n` and the `2` being split into two separate arguments, with the second being ignored as `ò` only expects one argument. That means that we're currently testing `XnY` but, by adding the `!`, the elements get flipped giving us `YnX`.
And now for the trickery: The possible combinations we can have (where `L=[np]` & D=`[0-9]`) are `DnL`, `LnD` & `DnD` and, in all cases, both elements are strings, which is important. The `n` attempts to convert Y to an integer, run X on it as a method and convert it back to a string, with the following possible outcomes:
* `Dnp` squares the integer resulting in a non-empty string, which is truthy, creating a partition.
* `Dnn` negates the integer resulting in a non-empty string, which is truthy, creating a partition.
* `DnD` & `LnD`, for some reason that I can't figure out, both result in `0`, which is falsey, so no partition is created.
Hopefully, that all made some sort of sense but, if it helps, [here's a handy table](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVI&code=5EBbWFlZblggISFZblhdw2kiWCBZIFluWCBCb29sZWFuIrggrvk0IG/5OCC4w2nJIPot&input=IjhuODhwODA4biI).
And, as a final note: the `Í` works exactly the same way as above when passed to the `è` method, which only expects a single string argument.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 158 bytes
```
$f='';($_|sls "\d*\w"-a|% m*).value|%{$n=($_|sls "\d+"-a|% m*).value;if($n-eq$null){$n=1};switch($_[-1]){N{$f+='='*$n}P{$f+=-join(1..$n|%{(' ','-')[$_%2]})}}}
```
**Ungolfed**
```
$args|%{
# empty string for adding road later
$finalString=''
# breaks every pair apart and selects the value (N4, P4, etc.)
($_|sls "\d*\w"-a|% m*).value|%{
# selects just the number
$num = ($_|sls "\d+"-a|% m*).value
# for those pairs that don't have a number associated
if($num -eq $null){$num = 1}
# switch depending on the char
switch($_[-1]){
# nothing to do with N so append to finalString var
N{
$finalString += '=' * $num
}
# for loop to determine the alternating of the road pattern
P{
$finalString += -join (1..$num | %{(' ','-')[$_%2]})
}
}
}
# formats string for desired output
"{0}`n`n`n{1}`n`n{0}" -f $("_"*$finalString.length),$finalString
}
```
[Try it online!](https://tio.run/##XY3RasMwDEXf9xXGKNhO6zCngTJCfsH4vS1Z2OImw3W3ul0eHH@75wQGYwjula6O0Od16m9u6I2J0N3Obs58BN0QUlNoZ2ccwsf3/Dhh3s0ZuuSs@O7Mo08Y2OYPsvkH1KOmYHn/BfZhDFtoEWo3jfe3IZ0duDgxLz3oTUMakoMNah34x3W0VBQF2PSDEkS2hBN2gDYrT4GFECL2z@HVLuXF2qQZI64RUNziHHRhenu@D2wL@inEiEUpMUqqklayUi9yr4QUqpRrtNhO7tSyWvw3rmRZKfwD "PowerShell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `L`, 180 bits[v1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 22.5 bytes
```
⁽aḊyC½`- =`½$İ$⌊Ẏ∑ƛ4↳Ǔ\_pǏ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJMPSIsIiIsIuKBvWHhuIp5Q8K9YC0gPWDCvSTEsCTijIrhuo7iiJHGmzTihrPHk1xcX3DHjyIsIiIsIjRONFA5TjdQMU4xUDJOMTJQIl0=)
```
Ḋ # Group by...
⁽a # Is it an uppercase letter?
y # Uninterleave - split into [numbers, chars]
C½ # Charcodes / 2 - N -> 39, P -> 40
$İ # Index into...
`- =`½ # ["- ", "="]
Ẏ # Extend to length
$⌊ # numbers
∑ # Concatenate into a single string
ƛ # For each character
4↳ # Prepend three spaces
Ǔ # Move a space to the end
\_p # Prepend a _
Ǐ # Append the _
# L flag transposes and joins the whole thing
```
[Answer]
# [Lua](https://www.lua.org/), 123 122 bytes
```
p=print s=(...):gsub('(%d+)(.)',load'a,b=...return({N="=",P="- "})[b]:rep(a):sub(1,a)')r=('_'):rep(#s)p(r)p'\n'p(s)p()p(r)
```
[Try it online!](https://tio.run/##HcvRCsIgFIDhVxlGnHPIBMcgEs4riPcVoWxEMJzovIqe3doufz7@ufrWEqf8jmtXGJVSZF6lBgQ8jidCRSDnxY/gZeC/5mmtOeLHsmAhHYtzJ750Cw@Tp4SezPZq6QkoM8ITaIdDoYSZEtwjJNxi79baYAd3tRenrXa97d0P "Lua – Try It Online")
Ungolfed Version:
```
p=print
s=(...):gsub('(%d+)(.)', --For each number/letter pair
function(a,b) --Number in a, letter in b
return({N="=",P="- "})[b]:rep(a):sub(1,a) --Replace each number/letter pair
--with respective pattern
end)
r=('_'):rep(#s) --Create edges of road
p(r)p'\n'p(s)p()p(r) --Print road
```
[Answer]
# Scala, 163 bytes
```
(s:String)=>{val r=(("\\d+(P|N)"r) findAllIn(s) map(r=>{val l=r.init.toInt;if(r.last=='N')"="*l else ("- "*l).take(l)})).mkString;val k="_"*r.length;s"$k\n\n\n$r\n\n$k"}
```
First try, might be golfed some more.
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 64 bytes
```
y/PN/-=/;s/\d+(.)/$1x$&/ge;s/--/- /g;$_=($t=y//_/cr)."
$_
$t"
```
[Try it online!](https://tio.run/##K0gtyjH9/79SP8BPX9dW37pYPyZFW0NPU1/FsEJFTT89FSiiq6uvq6Cfbq0Sb6uhUmJbqa8fr59cpKmnxMXFpRIPxCVK//@b@JkEWPqZBxj6GQYY@RkF/MsvKMnMzyv@r@trqmdgaPBftyAHAA "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 89 bytes
```
{,⌿{⍪(⌽,2∘↓∘⊢)⍵,' _'}¨⍪⍎¯1↓('\d+'⎕R{'(',⍵.Match})('[P]' '[N]'⎕R'⍴''- ''),' '⍴''=''),')⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v1rnUc/@6ke9qzQe9ezVMXrUMeNR22QQ2bVI81HvVh11BYV49dpDK4AqHvX2HVpvCJTWUI9J0VZ/1Dc1qFpdQ10HqEzPN7EkOaNWU0M9OiBWXUE92i8WLK/@qHeLurqugrq6JtAkCM8WzAEZXvs/7VHbBKCxj7qaH/WuAcoeWm/8qG0iUGdwkDOQDPHwDP6fpqBu4mcSYOlnHmDoZxhg5GcUoA4A "APL (Dyalog Extended) – Try It Online")
A huge, clunky solution with a lot of regex and `⍎`.
## Explanation
`('[P]' '[N]'⎕R'⍴''- ''),' '⍴''=''),')⍵` Replace `N` with code for producing '=' and `P` for producing '- ' with a closing bracket
`('\d+'⎕R{'(',⍵.Match})` prepend an opening bracket to each digit
('\d+'⎕R{'(',⍵.Match})
`⍎¯1↓` drop the last character, and execute (gives the road markings)
`⍪` table it
`⍵,' _'}¨` add two spaces and underscore for each marking
`⍪(⌽,2∘↓∘⊢)` Palindromize that, table it
`,⌿` join all the columns into a single road
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/6309/edit).
Closed 5 years ago.
[Improve this question](/posts/6309/edit)
Rules are simple:
* **First n primes** (not primes below **n**), should be printed to standard output separated by newlines (primes should be generated within the code)
* primes **cannot be generated by an inbuilt function or through a library**, i.e. use of a inbuilt or library function such as, prime = get\_nth\_prime(n), is\_a\_prime(number), or factorlist = list\_all\_factors(number) won't be very creative.
* Scoring - Say, we define **Score** = *f*([number of chars in the code]), **O**(*f*(n)) being the complexity of your algorithm where n is the number of primes it finds. So for example, if you have a 300 char code with **O**(n^2) complexity, score is 300^2 = **90000**, for 300 chars with **O**(n\*ln(n)), score becomes 300\*5.7 = **1711.13** (let's assume all logs to be natural logs for simplicity)
* Use any existing programming language, lowest score wins
**Edit:** Problem has been changed from finding 'first 1000000 primes' to 'first n primes' because of a confusion about what 'n' in O(f(n)) is, **n** is the number of primes you find (finding primes is the problem here and so complexity of the problem depends on the number of primes found)
**Note:** to clarify some confusions on complexity, if 'n' is the number of primes you find and 'N' is the nth prime found, complexity in terms of n is and N are not equivalent i.e. **O(f(n)) != O(f(N))** as , f(N) != constant \* f(n) and N != constant \* n, because we know that nth prime function is not linear, I though since we were finding 'n' primes complexity should be easily expressible in terms of 'n'.
As pointed out by Kibbee, you can visit [this site](http://primes.utm.edu/lists/small/millions) to verify your solutions ([here](https://docs.google.com/open?id=0B2QNmfbXDokqTG9qcjBTQWppLWc), is the old google docs list)
Please Include these in your solution -
* what complexity your program has (include basic analysis if not trivial)
* character length of code
* the final calculated score
This is my first CodeGolf Question so, if there is a mistake or loophole in above rules please do point them out.
[Answer]
## Python (129 chars, O(n\*log log n), score of 203.948)
I'd say the Sieve of Eratosthenes is the way to go. Very simple and relatively fast.
```
N=15485864
a=[1]*N
x=xrange
for i in x(2,3936):
if a[i]:
for j in x(i*i,N,i):a[j]=0
print [i for i in x(len(a))if a[i]==1][2:]
```
Improved code from before.
## Python (~~191 156~~ 152 chars, O(n\*log log n)(?), score of 252.620(?))
I cannot at all calculate complexity, this is the best approximation I can give.
```
from math import log as l
n=input()
N=n*int(l(n)+l(l(n)))
a=range(2,N)
for i in range(int(n**.5)+1):
a=filter(lambda x:x%a[i] or x==a[i],a)
print a[:n]
```
`n*int(l(n)+l(l(n)))` is the [top boundary](http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number) of the `n`th prime number.
[Answer]
## Haskell, n^1.1 empirical growth rate, 89 chars, score 139 (?)
The following works at GHCi prompt when the general library that it uses have been previously loaded. Print *n*-th prime, 1-based:
`let s=3:minus[5,7..](unionAll[[p*p,p*p+2*p..]|p<-s])in getLine>>=(print.((0:2:s)!!).read)`
This is unbounded sieve of Eratosthenes, using a general-use library for ordered lists. Empirical complexity between 100,000 and 200,000 primes `O(n^1.1)`. Fits to `O(n*log(n)*log(log n))`.
## About complexity estimation
I measured run time for 100k and 200k primes, then calculated `logBase 2 (t2/t1)`, which produced `n^1.09`. Defining `g n = n*log n*log(log n)`, calculating `logBase 2 (g 200000 / g 100000)` gives `n^1.12`.
Then, `89**1.1 = 139`, although `g(89) = 600`. --- **(?)**
It seems that for scoring the estimated growth rate should be used instead of complexity function itself. For example, `g2 n = n*((log n)**2)*log(log n)` is much better than `n**1.5`, but for 100 chars the two produce score of `3239` and `1000`, respectively. This can't be right. Estimation on 200k/100k range gives `logBase 2 (g2 200000 / g2 100000) = 1.2` and thus score of `100**1.2 = 251`.
Also, I don't attempt to print out all primes, just the *n*-th prime instead.
## No imports, 240 chars. n^1.15 empirical growth rate, score 546.
```
main=getLine>>=(print.s.read)
s n=let s=3:g 5(a[[p*p,p*p+2*p..]|p<-s])in(0:2:s)!!n
a((x:s):t)=x:u s(a$p t)
p((x:s):r:t)=(x:u s r):p t
g k s@(x:t)|k<x=k:g(k+2)s|True=g(k+2)t
u a@(x:r)b@(y:t)=case(compare x y)of LT->x:u r b;EQ->x:u r t;GT->y:u a t
```
[Answer]
## Haskell, ~~72~~ 89 chars, O(n^2), Score 7921
Highest score per char count wins right? Modified for first N. Also I apparently can't use a calculator, so my score is not as abysmally bad as I thought. (using the complexity for basic trial division as found in the source below).
As per **Will Ness** the below is not a full Haskell program (it actually relies on the REPL). The following is a more complete program with a pseudo-sieve (the imports actually save a char, but I dislike imports in code golf).
```
main=getLine>>= \x->print.take(read x).(let s(x:y)=x:s(filter((>0).(`mod`x))y)in s)$[2..]
```
This version is undoubtedly (n^2). The algorithm is just a golf version of the naive ``sieve'', as seen [here](https://stackoverflow.com/questions/3596502/lazy-list-of-prime-numbers)
Old ghci 1 liner
```
getLine>>= \x->print.take(read x)$Data.List.nubBy(\x y->x`mod`y==0)[2..]
```
Leaving up the old, cheating answer because the library it links to is pretty nice.
```
print$take(10^6)Data.Numbers.Primes.primes
```
See [here](https://github.com/sebfisch/primes) for an implementation and the links for the time complexity. Unfortunately wheels have a log(n) lookup time, slowing us down by a factor.
[Answer]
This is so easy even my text editor can do this!
# Vim: 143 keystrokes (115 actions): O(n^2\*log(n)): Score: 101485.21
## Submission:
```
qpqqdqA^V^Ayyp<Esc>3h"aC@a<Esc>0C1<Esc>@"ddmpqdmd"bywo^Ra ^Rb 0 0 `pj@p ^Ra 0 ^R=@a%@b<Enter> `pdd@p 0 `dj@d<Esc>0*w*wyiWdd@0qqpmp"aywgg@dqgg@p
```
Input: N should be on the first line of a blank document. After this is finished, each prime from 2 to N will be a separate line.
## Running the Commands:
First, note that any commands with a caret in front of them mean you need to hold Ctrl and type the next letter (e.g. ^V is `Ctrl-v` and ^R is `Ctrl-r`).
This will overwrite anything in your @a, @b, @d, and @p registers.
Because this uses `q` commands, it can't just be placed in a macro. However, here are some tips for running it.
* `qpqqdq` just clears registers
* `A^V^Ayyp<Esc>3h"aC@a<Esc>0C1<Esc>@"dd` will create a list of numbers 2 to N+1. This is a break between the two main parts, so once this is done, you shouldn't need to do it again
* `mpqdmd"bywo^Ra ^Rb 0 0 `pj@p ^Ra 0 ^R=@a%@b<Enter> `pdd@p 0 `dj@d<Esc>0*w*wyiWdd@0qqpmp"aywgg@dqgg@p` does need to be typed in one go. Try to avoid backspace as it may screw something up.
+ If you make a mistake, type `qdqqpq` then try this line again.
For large N, this is *very* slow. It took around 27 minutes to run N=5000; consider yourself warned.
## Algorithm:
This uses a basic recursive algorithm for finding primes. Given a list of all primes between 1 and A, A+1 is prime if it not divisible by any of the numbers in the list of primes. Start at A = 2 and add primes to the list as they are found. After N recursions, the list will contain all the primes up to N.
## Complexity
This algorithm has a complexity of O(nN), where N is the input number and n is the number of primes up to N. Each recursion tests n numbers, and N recursions are performed, giving O(nN).
However, N ~ n\*log(n), giving the final complexity as O(n2\*log(n))(<https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number>)
## Explanation
It's not easy to discern the program flow from the vim commands, so I rewrote it in Python following the same flow. Like the Vim code, the python code will error out when it reaches the end. Python doesn't like too much recursion; if you try this code with N > 150 or so, it will reach the max recursion depth
```
N = 20
primes = range(2, N+1)
# Python needs these defined.
mark_p = b = a = -1
# Check new number for factors.
# This macro could be wrapped up in @d, but it saves space to leave it separate.
def p():
global mark_d, mark_p, primes, a
mark_d = 0
print(primes)
a = primes[mark_p]
d()
# Checks factor and determine what to do next
def d():
global mark_d, mark_p, a, b, primes
b = primes[mark_d]
if(a == b): # Number is prime, check the next number
mark_p += 1
p()
else:
if(a%b == 0): # Number is not prime, delete it and check next number
del(primes[mark_p])
p()
else: # Number might be prime, try next possible factor
mark_d += 1
d()
mark_p = 0 #Start at first number
p()
```
Now, to break down the actual keystrokes!
* `qpqqdq` Clears out the @d and @p registers. This will ensure nothing runs when setting up these recursive macros.
* `A^V^Ayyp<Esc>3h"aC@a<Esc>0C1<Esc>@"dd` Turns the input into a list of numbers from 2 to N+1. The N+1 entry is deleted as a side effect of setting up the @d macro.
+ Specifically, writes a macro that increments a number, then copies it on the next line, then it writes a 1 and executes this macro N times.
* `mpqdmd"bywo^Ra ^Rb 0 0 `pj@p ^Ra 0 ^R=@a%@b<Enter> `pdd@p 0 `dj@d<Esc>0*w*wyiWdd@0q` writes the @d macro, which implements the d() function above. "If" statements are interesting to implement in Vim. By using the search operator \*, it's possible to choose a certain path to follow. Breaking the command down further we get
+ `mpqd` Set the p mark here and start recording the @d macro. The p mark needs to be set so there is a known point to jump to as this runs
+ `o^Ra ^Rb 0 0 `pj@p ^Ra 0 ^R=@a%@b<Enter> `pdd@p 0 `dj@d<Esc>` Writes the if/else statement text
+ `0*w*wyiWdd@0` actually executes the if statement.
+ Before executing this command, the line will contain `@a @b 0 0 `pj@p @a 0 (@a%@b) `pdd@p 0 `dj@d`
+ `0` moves the cursor to the beginning of the line
+ `*w*w` Moves the cursor to the code to execute next
1. if @a == @b, that is ``pj@p`, which moves to the next number for @a and runs @p on it.
2. if @a != @b and @a%@b == 0, that is ``pdd@p`, which deletes the current number @a, then runs @p on the next one.
3. if @a != @b and @a%%b != 0, that is ``dj@d`, which checks the next number for @b to see if it is a factor of @a
+ `yiWdd@0` yanks the command into the 0 register, deletes the line and runs the command
+ `q` ends the recording of the @d macro
* When this is first run, the ``pdd@p` command is run, deleting the N+1 line.
* `qpmp"aywgg@dq` writes the @p macro, which saves the number under the cursor, then goes to the first entry and runs @d on that.
* `gg@p` actually executes @p so that it will iterate over the whole file.
[Answer]
## C#, 447 Characters, Bytes 452, Score ?
```
using System;namespace PrimeNumbers{class C{static void GN(ulong n){ulong primes=0;for (ulong i=0;i<(n*3);i++){if(IP(i)==true){primes++;if(primes==n){Console.WriteLine(i);}}}}static bool IP(ulong n){if(n<=3){return n>1;}else if (n%2==0||n%3==0){return false;}for(ulong i=5;i*i<=n;i+=6){if(n%i==0||n%(i+2)==0){return false;}}return true;}static void Main(string[] args){ulong n=Convert.ToUInt64(Console.ReadLine());for(ulong i=0;i<n;i++){GN(i);}}}}
```
## scriptcs Variant, 381 Characters, 385 Bytes, Score ?
```
using System;static void GetN(ulong n){ulong primes=0;for (ulong i=0;i<(n*500);i++){if(IsPrime(i)==true){primes++;if(primes==n){Console.WriteLine(i);}}}}public static bool IsPrime(ulong n){if(n<=3){return n>1;}else if (n%2==0||n%3==0){return false;}for(ulong i=5;i*i<=n;i+=6){if(n%i==0||n%(i+2)==0){return false;}}return true;}ulong n=Convert.ToUInt64(Console.ReadLine());for(ulong i=0;i<n;i++){GetN(i);}
```
If you install scriptcs then you can run it.
*P.S. I wrote this in Vim* `:D`
[Answer]
## GolfScript (45 chars, score claimed ~7708)
```
~[]2{..3${1$\%!}?={.@\+\}{;}if)1$,3$<}do;\;n*
```
This does simple trial division by primes. If near the cutting edge of Ruby (i.e. using 1.9.3.0) the arithmetic uses Toom-Cook 3 multiplication, so a trial division is O(n^1.465) and the overall cost of the divisions is `O((n ln n)^1.5 ln (n ln n)^0.465) = O(n^1.5 (ln n)^1.965)`†. However, in GolfScript adding an element to an array requires copying the array. I've optimised this to copy the list of primes only when it finds a new prime, so only `n` times in total. Each copy operation is `O(n)` items of size `O(ln(n ln n)) = O(ln n)`†, giving `O(n^2 ln n)`.
And this, boys and girls, is why GolfScript is used for golfing rather than for serious programming.
† `O(ln (n ln n)) = O(ln n + ln ln n) = O(ln n)`. I should have spotted this before commenting on various posts...
[Answer]
### Scala 263 characters
Updated to fit to the new requirements. 25% of the code deal with finding a reasonable upper bound to calculate primes below.
```
object P extends App{
def c(M:Int)={
val p=collection.mutable.BitSet(M+1)
p(2)=true
(3 to M+1 by 2).map(p(_)=true)
for(i<-p){
var j=2*i;
while(j<M){
if(p(j))p(j)=false
j+=i}
}
p
}
val i=args(0).toInt
println(c(((math.log(i)*i*1.3)toInt)).take(i).mkString("\n"))
}
```
I got a sieve too.
Here is an empirical test of the calculation costs, ungolfed for analysis:
```
object PrimesTo extends App{
var cnt=0
def c(M:Int)={
val p=(false::false::true::List.range(3,M+1).map(_%2!=0)).toArray
for (i <- List.range (3, M, 2)
if (p (i))) {
var j=2*i;
while (j < M) {
cnt+=1
if (p (j))
p(j)=false
j+=i}
}
(1 to M).filter (x => p (x))
}
val i = args(0).toInt
/*
To get the number x with i primes below, it is nearly ln(x)*x. For small numbers
we need a correction factor 1.13, and to avoid a bigger factor for very small
numbers we add 666 as an upper bound.
*/
val x = (math.log(i)*i*1.13).toInt+666
println (c(x).take (i).mkString("\n"))
System.err.println (x + "\tcount: " + cnt)
}
for n in {1..5} ; do i=$((10**$n)); scala -J-Xmx768M P $i ; done
```
leads to following counts:
```
List (960, 1766, 15127, 217099, 2988966)
```
I'm not sure how to calculate the score. Is it worth to write 5 more characters?
```
scala> List(4, 25, 168, 1229, 9592, 78498, 664579, 5761455, 50847534).map(x=>(math.log(x)*x*1.13).toInt+666)
res42: List[Int] = List(672, 756, 1638, 10545, 100045, 1000419, 10068909, 101346800, 1019549994)
scala> List(4, 25, 168, 1229, 9592, 78498, 664579, 5761455, 50847534).map(x=>(math.log(x)*x*1.3)toInt)
res43: List[Int] = List(7, 104, 1119, 11365, 114329, 1150158, 11582935, 116592898, 1172932855)
```
For bigger n it reduces the calculations by about 16% in that range, but afaik for the score formula, we don't consider constant factors?
### new Big-O considerations:
To find 1 000, 10 000, 100 000 primes and so on, I use a formula about the density of primes x=>(math.log(x)\*x\*1.3 which determines the outer loop I'm running.
So for values i in 1 to 6=> NPrimes (10^i) runs 9399, 133768 ... times the outer loop.
I found this O-function iteratively with help from the comment of Peter Taylor, who suggested a much higher value for exponentiation, instead of 1.01 he suggested 1.5:
```
def O(n:Int) = (math.pow((n * math.log (n)), 1.01)).toLong
```
O: (n: Int)Long
```
val ns = List(10, 100, 1000, 10000, 100000, 1000*1000).map(x=>(math.log(x)*x*1.3)toInt).map(O)
```
ns: List[Long] = List(102, 4152, 91532, 1612894, 25192460, 364664351)
```
That's the list of upper values, to find primes below (since my algorithm has to know this value before it has to estimate it), send through the O-function, to find similar quotients for moving from 100 to 1000 to 10000 primes and so on:
(ns.head /: ns.tail)((a, b) => {println (b*1.0/a); b})
40.705882352941174
22.045279383429673
17.62109426211598
15.619414543051187
14.47513863274964
13.73425213148954
```
This are the quotients, if I use 1.01 as exponent. Here is what the counter finds empirically:
```
ns: Array[Int] = Array(1628, 2929, 23583, 321898, 4291625, 54289190, 660847317)
(ns.head /: ns.tail)((a, b) => {println (b*1.0/a); b})
1.799140049140049
8.051553431205189
13.649578085909342
13.332251210010625
12.65003116535112
12.172723833234572
```
The first two values are outliers, because I have make a constant correction for my estimation formular for small values (up to 1000).
With Peter Taylors suggestion of 1.5 it would look like:
```
245.2396265560166
98.8566987153728
70.8831374743478
59.26104390040363
52.92941829568069
48.956394784317816
```
Now with my value I get to:
```
O(263)
res85: Long = 1576
```
But I'm unsure, how close I can come with my O-function to the observed values.
[Answer]
**QBASIC, 98 Chars, Complexity N Sqrt(N), Score 970**
```
I=1
A:I=I+2
FOR J=2 TO I^.5
IF I MOD J=0 THEN GOTO A
NEXT
?I
K=K+1
IF K=1e6 THEN GOTO B
GOTO A
B:
```
[Answer]
**Ruby 66 chars, O(n^2) Score - 4356**
`lazy` is available since Ruby 2.0, and `1.0/0` is a cool trick to get an infinite range:
```
(2..(1.0/0)).lazy.select{|i|!(2...i).any?{|j|i%j==0}}.take(n).to_a
```
[Answer]
# Ruby, 84 chars, 84 bytes, score?
This one is probably a little too novice for these parts, but I had a fun time doing it. It simply loops until `f` (primes found) is equal to `n`, the desired number of primes to be found.
The fun part is that for each loop it creates an array from 2 to one less than the number being inspected. Then it maps each element in the array to be the modulus of the original number and the element, and checks to see if any of the results are zero.
Also, I have no idea how to score it.
## Update
Code compacted and included a (totally arbitrary) value for `n`
```
n,f,i=5**5,0,2
until f==n;f+=1;p i if !(2...i).to_a.map{|j|i%j}.include?(0);i+=1;end
```
## Original
```
f, i = 0, 2
until f == n
(f += 1; p i) if !(2...i).to_a.map{|j| i % j}.include?(0)
i += 1
end
```
The `i += 1` bit and `until` loop are sort of jumping out at me as areas for improvement, but on this track I'm sort of stuck. Anyway, it was fun to think about.
[Answer]
## Scala, 124 characters
```
object Q extends App{Stream.from(2).filter(p=>(2 to p)takeWhile(i=>i*i<=p)forall{p%_!= 0})take(args(0)toInt)foreach println}
```
Simple trial division up to square root. Complexity therefore should be
O(n^(1.5+epsilon))
124^1.5 < 1381, so that would be my score i guess?
[Answer]
## Perl - 94 characters, O(n log(n)) - Score: 427
```
perl -wle '$n=1;$t=1;while($n<$ARGV[0]){$t++;if((1x$t)!~/^1?$|^(11+?)\1+$/){print $t;$n++;}}'
```
## Python - 113 characters
```
import re
z = int(input())
n=1
t=1
while n<z:
t+=1
if not re.match(r'^1?$|^(11+?)\1+$',"1"*t):
print t
n+=1
```
[Answer]
# AWK, ~~96~~ 86 bytes
*Subtitle: Look Mom! Only adding and some bookkeeping!*
File `fsoe3.awk`:
```
{for(n=2;l<$1;){if(n in L)p=L[n]
else{print p=n;l++}
for(N=p+n++;N in L;)N+=p
L[N]=p}}
```
Run:
```
$ awk -f fsoe3.awk <<< 5
2
3
5
7
11
$ awk -f fsoe3.awk <<< 1000 | wc -l
1000
```
---
# BASH, 133 bytes
File `x.bash`:
```
a=2
while((l<$1));do if((b[a]))
then((c=b[a]));else((c=a,l++));echo $a;fi;((d=a+c))
while((b[d]));do((d+=c));done
((b[d]=c,a++));done
```
Run:
```
$ bash x.bash 5
2
3
5
7
11
$ bash x.bash 1000 | wc -l
1000
```
---
Primes get calculated by letting the already found primes jump on the "tape of positive integers". Basically it is a serialised Sieve Of Eratosthenes.
```
from time import time as t
L = {}
n = 2
l = 0
t0=t()
while l<1000000:
if n in L:
P = L[n]
else:
P = n
l += 1
print t()-t0
m = n+P
while m in L:
m += P
L[m] = P
n += 1
```
...is the same algorithm in Python and prints out the time when the `l`-th prime was found instead of the prime itself.
The output plotted with `gnuplot` yields the following:
[](https://i.stack.imgur.com/PwdrR.png)
The jumps probably have something to do with file i/o delays due to writing buffered data to disk...
Using much larger numbers of primes to find, will bring additional system dependent delays into the game, e.g. the array representing the "tape of positive integers" grows continuously and sooner or later will make every computer cry for more RAM (or later swap).
...so getting an idea of the complexity by looking at the experimental data does not really help a lot... :-(
---
Now counting the additions needed to find `n` primes:
```
cells = {}
current = 2
found = 0
additons = 0
while found < 10000000:
if current in cells:
candidate = cells[current]
del cells[current] # the seen part is irrelevant
else:
candidate = current
found += 1 ; additons += 1
print additons
destination = current + candidate ; additons += 1
while destination in cells:
destination += candidate ; additons += 1
cells[destination] = candidate
current += 1 ; additons += 1
```
[](https://i.stack.imgur.com/dsEJW.png)
[Answer]
## Scala 121 (99 without the Main class boilerplate)
```
object Q extends App{Stream.from(2).filter{a=>Range(2,a).filter(a%_==0).isEmpty}.take(readLine().toInt).foreach(println)}
```
[Answer]
# Python 3, ~~117~~ 106 bytes
This solution is slightly trivial, as it outputs 0 where a number is not prime, but I'll post it anyway:
```
r=range
for i in[2]+[i*(not 0 in[i%j for j in r(3,int(i**0.5)+1,2)])for i in r(3,int(input()),2)]:print(i)
```
Also, I'm not sure how to work out the complexity of an algorithm. Please don't downvote because of this. Instead, be nice and comment how I could work it out. Also, tell me how I could shorten this.
[Answer]
# Haskell (52²=2704)
```
52`take`Data.List.nubBy(((1<).).gcd)[2..]`forM_`print
```
[Answer]
## Perl 6, 152 bytes, O(n log n log (n log n) log (log (n log n))) (?), 9594.79 points
According to [this page](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), the bit complexity of finding all primes up to n is O(n log n log log n); the complexity above uses the fact that the nth prime is proportional to n log n.
```
my \N=+slurp;my \P=N*(N.log+N.log.log);my @a=1 xx P;for 2..P.sqrt ->$i {if @a[$i] {@a[$_*$i]=0 for $i..P/$i}};say $_[1] for (@a Z ^P).grep(*[0])[2..N+1]
```
[Answer]
# Groovy (50 Bytes) - O(n\*sqrt(n)) - Score 353.553390593
```
{[1,2]+(1..it).findAll{x->(2..x**0.5).every{x%it}}}
```
Takes in n and outputs all numbers from 1 to n which are prime.
The algorithm I chose only outputs primes n > 2, so adding 1,2 at the beginning is required.
## Breakdown
`x%it` - Implicit truthy if it is not divisible, falsy if it is.
`(2..x**0.5).every{...}` - For all the values between 2 and sqrt(x) ensure that they are not divisible, for this to return true, must return true for *every*.
`(1..it).findAll{x->...}` - For all values between 1 and n, find all that fit the criteria of being non-divisible between 2 and sqrt(n).
`{[1,2]+...}` - Add 1 and 2, because they are always prime and never covered by algorithm.
[Answer]
## Racket 155 bytes
```
(let p((o'(2))(c 3))(cond[(>=(length o)n)(reverse o)][(ormap(λ(x)(= 0(modulo c x)))
(filter(λ(x)(<= x(sqrt c)))o))(p o(add1 c))][(p(cons c o)(add1 c))]))
```
It keeps a list of prime numbers found and checks divisibility of each next number by primes already found. Moreover, it checks only upto the square root of number being tested since that is enough.
Ungolfed:
```
(define(nprimes n)
(let loop ((outl '(2)) ; outlist having primes being created
(current 3)) ; current number being tested
(cond
[(>= (length outl) n) (reverse outl)] ; if n primes found, print outlist.
[(ormap (λ(x) (= 0 (modulo current x))) ; test if divisible by any previously found prime
(filter ; filter outlist till sqrt of current number
(λ(x) (<= x (sqrt current)))
outl))
(loop outl (add1 current)) ] ; goto next number without adding to prime list
[else (loop (cons current outl) (add1 current))] ; add to prime list and go to next number
)))
```
Testing:
```
(nprimes 35)
```
Output:
```
'(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149)
```
[Answer]
**awk 45 (complexity N^2)**
another `awk`, for primes up to 100 use like this
```
awk '{for(i=2;i<=sqrt(NR);i++) if(!(NR%i)) next} NR>1' <(seq 100)
```
code golf counted part is
```
{for(i=2;i<=sqrt(NR);i++)if(!(NR%i))next}NR>1
```
which can be put in a script file and run as `awk -f prime.awk <(seq 100)`
[Answer]
## **Javascript, 61 chars**
```
f=(n,p=2,i=2)=>p%i?f(n,p,++i):i==p&&n--&alert(p)||n&&f(n,++p)
```
A bit worse than O(n^2), will run out of stack space for large n.
] |
[Question]
[
A *Munchausen Number* in base \$b\$, also known as a [Perfect digit-to-digit invariant](https://en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant) or PDDI is a peculiar type of positive integer where the sum of its base-\$b\$ digits raised to themselves is equal to the number itself. They are named for the fictional [Baron Munchausen](https://en.wikipedia.org/wiki/Baron_Munchausen), who apparently hoisted himself up via his own ponytail to save himself from drowning. A related concept is [Narcissistic numbers](https://codegolf.stackexchange.com/questions/15244/test-a-number-for-narcissism).
For instance, \$1\$ is trivially a Munchausen number in every base because \$1^1=1\$. Additionally, every positive integer is a base-1 Munchausen number by definition.
More interestingly, \$3435\$ is a base-10 Munchausen number because \$3^3+4^4+3^3+5^5=3435\$, and in fact is [the only other base-10 Munchausen number](https://arxiv.org/pdf/0911.3038v2.pdf).
A partial list of Munchausen numbers in every base up to 35 can be found on the OEIS as sequence [A166623](https://oeis.org/A166623).
Given a positive integer \$n>0\$, determine if it is a Munchausen number in any base \$b\geq2\$.
## Rules
* Default I/O rules apply, so:
+ Full program or functions are acceptable.
+ Input can be from STDIN, as a function argument, and output can be to STDOUT, as a function return value, etc.
* Default loopholes apply.
* The output must be one of two distinct, consistent results. So `TRUE` is fine for truthy and `FALSE` is fine for falsy, but you can reverse that or return `None` for truthy and `1` for falsy or whatever. Please specify the selected results in your answer.
* Your answer has to work at least theoretically for any positive integer.
* Munchausen numbers use the convention \$0^0=1\$, so \$2\$ is a base-2 Munchausen number as \$1^1+0^0=2\$. Your code must follow this convention.
* Explanations are strongly encouraged, even though submissions will most likely use the brute-force search method.
* Using esoteric languages earns you brownie points since Munchausen was apparently a strange person.
## Test Cases
```
Truthy
1 (all bases)
2 (base 2)
5 (base 3)
28 (base 9 and base 25)
29 (base 4)
55 (base 4)
3435 (base 10)
923362 (base 9)
260 (base 128)
257 (base 64 and base 253)
Falsy
3
4
591912
3163
17
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language (in bytes) wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
LвDmOQZ
```
[Try it online!](https://tio.run/##yy9OTMpM/W9o7HZ4gou9koKunYKS/X@fC5tccv0Do/7rxPw35DLiMuUysuAysuQyBTJMzbmMzAy4jE2MTbmMuUy4jA3NjLkMzQE "05AB1E – Try It Online")
The larger test cases will time out on TIO.
**Explanation**
```
L # push range [1 ... input]
в # convert input to a digit list in each of these bases
Dm # raise each digit to the power of itself
O # sum each
Q # check each for equality with input
Z # max
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
bŻ*`§ċ⁸Ị
```
Yields `0` for Munchausen and `1` otherwise.
**[Try it online!](https://tio.run/##y0rNyan8/z/p6G6thEPLj3Q/atzxcHfX////jSwA "Jelly – Try It Online")**
Or [see the first five hundred positive integers split up](https://tio.run/##ASsA1P9qZWxsef//YsW7KmDCp8SL4oG44buK/8OH4oKsVCxA4bifQMKlUv//NTAw "Jelly – Try It Online") as `[[Munchausen], [non-Munchausen]]`.
### How?
```
bŻ*`§ċ⁸Ị - Link: integer, n
Ż - zero-range -> [0,1,2,3,4,...,n]
b - (n) to base (vectorises)
` - with left as both arguments:
* - exponentiation (vectorises)
§ - sums
ċ - count occurrences of:
⁸ - n
Ị - is insignificant (abs(x) <= 1)
```
---
Alternative for `1` for Munchausen and `0` otherwise:
```
bŻ*`§ċ>1
```
[Answer]
# [J](http://jsoftware.com/), ~~33~~ ~~28~~ 27 bytes
```
e.1#.i.@>:^~@(#.inv ::1)"0]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/U/UMlfUy9RzsrOLqHDSAzLwyBSsrQ00lg9j/mlypyRn5ChppSgaaCoYKRgqmCkYWCkaWCqamCsYmxqbI0sYKJgqG5grGhmbG/wE "J – Try It Online")
* `e.` is the input an element of...
* `1#.` the sum of each row of...
* `i.@>: ... ]` 0..input and the input itself, passed as left and right args to...
* `^~@(#.inv)"0` convert the right arg (input) to each base in the left arg and raise each result elementwise to itself `^~@`.
* `::1` finally this is needed because you can't convert uniquely to base 1, so it errors. in this case, we simply return 1, which won't match for any number *except* 1, which is what we want
[Answer]
# [R](https://www.r-project.org/), ~~72~~ 69 bytes
-1 byte thanks to digEmAll
```
function(x){for(b in 1+1:x)F=F|!sum((a=x%/%b^(0:log(x,b))%%b)^a)-x;F}
```
[Try it online!](https://tio.run/##JYzRCsIwDEXf/Yr6UEhw4rJs00722s8YrIPKYHYwHRTUb6@6vOTe3JybJfk2@TUMz3EOEPHl5wWcGoOiAzURbWvf@8d6B@jbqE/adZA303yDmDlErR12PR7j1X7SAB4IM@Wh2GYl/iJiJJOQSxZjCuZa8KLORasz4u7/jLe9lKIhQwIy1XKhH5i@ "R – Try It Online")
Outputs `TRUE` for Munchausen numbers and `FALSE` otherwise.
`x%/%b^(0:log(x,b))%%b)` converts `x` to base `b`, and the for loop does the rest of the work (reassigning `F`, which is `FALSE` by default).
We need to allow the base `b` to go all the way to `x+1` instead of `x` to handle the case `x=1`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
õ@ìXÄ x_pZ
øN
```
Saved one byte thanks to @Shaggy
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9UDsWMQgeF9wWgr4Tg&input=NQ)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 51 bytes
```
{?grep {$_==sum [Z**] .polymod($^a xx*)xx 2},^$_+2}
```
[Try it online!](https://tio.run/##BcHfCoIwFAfg@99TnIsR/onIc9zMC@k9ihQhlWCmTILJ8NnX962DsybOO51GamK4T25YKaiuabbfTM9Hlr3osi52n5d3otqevM9S74mPc6u6nI84Lo4S@/kOW0oBRFu/05jkqktxxAIMDb6Ba2gNKUWjZhHDYHMF6wqCElIYQVH9AQ "Perl 6 – Try It Online")
### Explanation:
```
{ } # Anonymous code block
?grep { } # Do any
,^$_+2 # Of the bases from 2 to n+1
sum # Have the sum of
.polymod($^a xx*) # The digits of n in that base
[Z**] xx 2 # Raised to the power of themselves
$_== # Equal to the original number?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 50 bytes
TIO timed out on 591912. Somehow edges out Perl by 1 byte... (at time of writing)
```
->n{(2..n+1).any?{|b|n.digits(b).sum{|d|d**d}==n}}
```
[Try it online!](https://tio.run/##BcFBDoIwEADA@76CAAfA0NhdCnIAH6KGSBpIDxZiy4G0/bp15nvMZ1yGZ6xH7QpkTF94yd76vDs/e82kWpU1xVwyc3ycl15WlQzDoEOI@2FNkmb5NCaZWx75xOw2qVdIIwcEAXgD7EEIoIYE9EjUImB7BRQdEDRAvCXgHfy23apNm1jrPw "Ruby – Try It Online")
[Answer]
# JavaScript (ES7), 60 bytes
Returns a Boolean value.
```
n=>(F=b=>(g=n=>n&&g(n/b|0)+(n%=b)**n)(n)==n||b<n&&F(b+1))(2)
```
[Try it online!](https://tio.run/##hdBLbsIwEAbgPafIpskMUcnDITQS7jIn6A5Y2DSkRdYEYahUKXdPnQaF1K5aLyzr96cZj4/iQ@j9@f10eaTmteoOvCP@DCWXZq@5OZPv10CRbGMMgR64xPmcEAg5p7aVa3NfggwTREix2zekG1UtVFNDsHk5Xy9vn7sAZ9P8AAZ73yuKPBBKeVLoStsqnapeeKlNlg5hTpWnmxlJ4ZDCJpnTaPkvYRkb0EiS2DZFyljez/XHY/J4aHUvY0aY/VDBljalUPqXr2VoJ5mTsCR3WbJC7L4A "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = input
( F = b => // F = recursive function taking a base b
( g = n => // g = recursive function taking an integer n
n && // if n is not equal to 0:
g(n / b | 0) + // do a recursive call with floor(n / b)
(n %= b) ** n // and add (n mod b) ** (n mod b)
)(n) // initial call to g with the original value of n
== n || // return true if the result is equal to n
b < n && // otherwise, if b is less than n:
F(b + 1) // try with b + 1
)(2) // initial call to F with b = 2
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~23~~ 13 bytes
```
⊢∊⊂+.*⍨⍤⊤⍨¨2…
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/R12LHnV0Pepq0tbTetS74lHvkkddS4CMQyuMHjUs@6/J9ahvKlBh2qEVhgpGCqYKRhYKRpYKpqYKxibGQJ6ZgYKRqTlCkbGCiYKxoZmxgqH5fwA "APL (dzaima/APL) – Try It Online")
Thanks to Adám, ngn and dzaima, we managed to shave 10 bytes off this answer by using dzaima/APL.
Prefix tacit function. Munchausen numbers return 1, else 0.
### How
```
⊢∊⊂+.*⍨⍤⊤⍨¨2… ⍝ Prefix tacit function, argument will be called ⍵
2… ⍝ Generate the integer sequence [2..⍵]
⊤⍨¨ ⍝ Convert ⍵ to each base in the vector
+.*⍨⍤ ⍝ Raise each digit of each element in the vector to itself, then sum
⊢∊⊂ ⍝ Check if ⍵ is in the resulting vector.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes
```
#<2||!Tr[Check[#^#,1]&/@#~IntegerDigits~i]~Table~{i,2,#}~FreeQ~#&
```
[Try it online!](https://tio.run/##FctBC4IwFMDxzxIPPL2obU4LKoQi6JbgTQyWPOaj9LDWSd1XX3b8w@/fG99Rbzy3JtpjhIOcplXl6nNH7auGB6Bokk0B4TZ4suQubNl/AjehMs83hZFRIszh6ojKAEm8Ox58UX6ZfA3rky3g/49iYRrlDuUetUaVqqWyLUqdo8IUlcgUinyO8Qc "Wolfram Language (Mathematica) – Try It Online")
*-4 bytes from @attinat*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
Nθ¬Φθ⁼θΣE↨θ⁺²ιXλλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDL79Ewy0zpwQkqKPgWliamFMMYgWX5mr4JhZoOCUWp4L4ATmlxRpGOgqZmppATn45UH2OjkKOJgRY//9vZGr@X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. My 16-byte attempt didn't work but that might be a bug in Charcoal, so watch this space. Outputs `-` unless the number is a Munchausen number. Explanation:
```
Nθ Input `n` as a number
Φθ Try bases `2` .. `n+1`
Σ Sum of
↨θ `n` converted to base
⁺²ι Next trial base
E Each digit
Xλλ Raised to its own power
⁼ Equals
θ `n`
¬ Logical Not
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 99 bytes
```
n=>Enumerable.Range(2,n).Any(x=>{int g=0,t=n;for(;t>0;t/=x)g+=(int)Math.Pow(t%x,t%x);return g==n;})
```
[Try it online!](https://tio.run/##hdDNS8MwFADw@/6KMBASrP1KVy0xBQ/upCAieJge0pJ2hfoKSYod4t9e45hzTREDubz83kdeqS9K3YzrHsrrBoxXdF2bV3wEnt9C/yaVKFrpPwqoJY49IP4N7PDA8w@LUc1Dz3BgVacwM3nITMAHUp9zbF/JvTBb/6F7x@Zs8OwlTEnTK7BpNueTjGzxrBoj7xqQeLl5Ur3Z7l6X5DRc4YgQhvYnCBAWbYsKoaUmExRP0DdA8VSs5oI6Na5@yFFkjshmInG6rP4TNKEHcxRROCVZTGm6/9Gfg6Thoc9vETv@4nSfL7BZi1bPF0qJE0jcAI3SGYoubWT8Ag "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
## Haskell, 61 bytes
```
_#0=0
b#n|m<-mod n b=m^m+b#div n b
f n=elem n$1:map(#n)[2..n]
```
Returns `True` for Munchausen and `False` otherwise.
[Try it online!](https://tio.run/##ZcvBCoJAEIDhu08xsB6KJnFn3DWjfRKxUFSSnFEqOvXuW507/vD91/ZxG@Y5xovJQ550Rt9y2svSg0IX5Cy7zvTT61fJCBqGeRDQ1B6lXTdGtzVlmTZR2kkhQL8kAOt90iek8BUwQm2R0CEdkCp0DrlghxUxe0LyOZIrm/@JsUC2ntGWTfwA "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/) `-lm`, ~~79~~ 75 bytes
```
f(n,b,i,g,c){for(g=b=1;b+++~n;g*=!!c)for(c=i=n;c-=pow(i%b,i%b),i/=b;);n=g;}
```
[Try it online!](https://tio.run/##LU7daoMwGL3PU9iCkNQjNUnjJlmeZOtFTZvwQRtLFQYT9@hzuvXunMP582X0fp4DT2hBiPBiDN2DR9c6aduiKL6TjTu32Xix6t6RS9aX7t59csqXTN4K0N61Vtjkop3m24kSFyOjNGTDpR/696MbmYSCgXqFamAM9EEbNErrWkHVFZR5AdM4wDSykQpa1hpy0SbL1t21jFxl6a2nr0sX@F@z2D9ZJSwVhWDZ/bE4A9/m9TnLzx9pi/8LdMQzs0AhLJsYm398uJ5iP5fX2y8 "C (gcc) – Try It Online")
Returns `0` for Munchausen numbers, and `1` otherwise.
---
### also 75 bytes
```
a,b;f(n){for(a=b=1;b+++~n;a*=g(n)!=n);n=a;}g(n){n=n?g(n/b)+pow(n%b,n%b):0;}
```
[Try it online!](https://tio.run/##LU5dS8MwFH3Pr6iDQq65Y02yVOs1@EN0D0m3lMCWjrUgWOpPt6a6hwvn6x5Ou@3adlkcego8wRT6G3fWW0leCPGdyD3aLhsPNgEl62he2ZRsestg50Fc@0@eSo/54KWiebm4mDhMLKaxGE/DOLwf7MQkKjSonlE1aAzqvTbYKK1rhaquUJknZBr3aBrZSIVa1hpl1mZi66a1LNqK4usQv0594H/NsLuzCigKAay43nIy8E1ZH4vy@JE2@D8hHvD@kyEAsZmx5acNZ9cNy/Z8@QU "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ 81 bytes
```
def f(n,b=2):
s=0;m=n
while m:k=m%b;s+=k**k;m/=b
return s==n or b<n>0<f(n,b+1)
```
[Try it online!](https://tio.run/##dYztCoMgFIb/exXCGGSNLbWP9eEups2RlBpqjK7eRSzszw4ceF7Oe55pcb1WxAs5aeOgXSxY92q5M/w5Gyu0GoUULsLpNsi/@Bu@I3XpGEE1gJaljWQKwE8vRg5lPTB57hqbsCGOh0beWAeg4W42au0yBbWBXaseabtJEoz8ZIRyqxMjsCO5H7hIQ6AZzUOqCKUF@VMlefkL4TtcMwROO@cVrvBBQ3FxaOIS@S8 "Python 2 – Try It Online")
Returns `1` for truthy and `0` for falsey. Because of the recursion, can't practically deal with `591912`, but it works in the abstract.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~66~~ 65 bytes
```
{$^a==1||[+] map {$a==[+] map {$_**$_},$a.polymod($_ xx*)},2..$a}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@79aJS7R1tawpiZaO1YhN7FAoVoFyEdw4rW0VOJrdVQS9Qrycypz81M0VOIVKiq0NGt1jPT0VBJr/1tzpeUXKRjq6RkbKOjaKagkKlRzcRYnViooAZlAgeo0oFitkjVX7X8A "Perl 6 – Try It Online")
[Answer]
# JavaScript (ES6), 88 bytes
```
f=n=>{for(b=2;n-b++;){for(c=0,r=n;r;r=(r-a)/b)c+=(a=(r%b))**a;if(n==c)return 1}return 0}
```
[Answer]
# [Icon](https://github.com/gtownsend/icon), 109 bytes
```
procedure m(n)
every k:=2to n&{i:=n;s:=0
while{a:=i%k;a<:=1;s+:=a^a;0<(i/:=k)}
n=s&return 1}
return n=1|0
end
```
[Try it online!](https://tio.run/##bY7RCsIwDEWf7VdEQWlx4Lrq1M58iSgUV7BMM@mmIuq3a1BBH0zI5ULIuQmbmh6PQ6w3vjxGD3tJSviTjxeoLGZtDTS4BotUNBZTcd6Gnb86i6FfFW5hURfN0KJbuyJdyDCyWKm7IGwG0bfHSKDv4uMI9S0VnsrfNBdIKgFc78xzDK1v5F52lzqBLIEJ64xnzpa9GRvWeWZMzsssT1km05VKoMf9Jr0YUnX@Y00CY@bonI3@XnZenz0B "Icon – Try It Online")
Times out for `591912`. [Icon](https://github.com/gtownsend/icon) treats `0^0` as an overflow and that's why I need an additional check for zero.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╡!←!║╝âñoêû►╦ä▓
```
[Run and debug it](https://staxlang.xyz/#p=b5211b21babc83a46f889610cb84b2&i=1%0A2%0A5%0A28%0A29%0A55%0A3435%0A260%0A257%0A%0A3%0A4%0A3163%0A17&a=1&m=2)
Takes very long for the larger test cases.
Explanation:
```
{^xs|E{c|*m|+x=m|a Full program, unpacked
Implicitly input x
{ m Map over bases [1 .. x]
^ Increment base (effectively mapping over [2 .. x+1])
xs Tuck x below base
|E Get digits of x in base
{ m Map over digits:
c|* copy and power
|+ Sum
x= sum = x?
|a Check if any element in array is true
Implicit output
```
] |
[Question]
[
The [Triforce](https://en.wikipedia.org/wiki/Triforce) is a fictional artifact in [The Legend of Zelda](https://en.wikipedia.org/wiki/The_Legend_of_Zelda), made of three identical-looking equilateral triangles representing power, wisdom and courage. Several games in the saga include an animation when the three parts finally join together.
The purpose of this challenge is to draw a single 2D frame of such a simplified animation, with a given width for the triangles and a given spacing between the parts.
## Input
The input consists of two integers: a width \$w\ge1\$ and a spacing value \$s\ge0\$.
## Output
The frame has to be drawn according to the following specifications:
```
/\
/ \____________ this part is horizontally centered
/ \
/______\
\___ s empty lines
/
/\ /\
/ \ / \______ w+1 backslashes
/ \ / \
/______\ /______\
\_______ 2w underscores
|__|
\_____________ 2s spaces
```
In the above example, we have \$w=3\$ and \$s=2\$.
## More examples
\$w=1\$, \$s=0\$:
```
/\
/__\
/\ /\
/__\/__\
```
\$w=2\$, \$s=0\$:
```
/\
/ \
/____\
/\ /\
/ \ / \
/____\/____\
```
\$w=3\$, \$s=3\$:
```
/\
/ \
/ \
/______\
/\ /\
/ \ / \
/ \ / \
/______\ /______\
```
\$w=4\$, \$s=1\$:
```
/\
/ \
/ \
/ \
/________\
/\ /\
/ \ / \
/ \ / \
/ \ / \
/________\ /________\
```
## Rules
* Trailing spaces on each line are optional.
* Extra leading spaces on each line are not allowed.
* You may output a single extra leading newline and/or a single extra trailing newline.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
[Answer]
# [Python 2](https://docs.python.org/2/), ~~197~~ ~~194~~ ~~169~~ ~~167~~ ~~155~~ 144 bytes
```
w,s=input()
l=['']*(2*-~w+s)
for i in range(-~w):W=w-i;b='/'+'_ '[i<w]*2*i+'\\';l[i::w-~s]=' '*(w+s-~W)+b,' '*W+b+' '*(W+s)+b
print'\n'.join(l)
```
[Try it online!](https://tio.run/##FcxNDoMgEEDhvadgN8BAm9CdlnOwUNOUpD/TmNGIDemGq1Ndvm/xlt/2ntnVmk3yxMt3k6qZfA8waum0LRmTap7zKkgQi/XOr4fcVbXBZ0td9HAGhJuAnq551E4TwjBAN/XUttmWNHoQoOX@sSUojObIgBFBHB72P8ZmWYk3GBhOn5lYTqrWi3F/ "Python 2 – Try It Online")
---
Saved:
* -3 bytes, thanks to Mr. Xcoder
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
←×_N↗⊕θ‖M≔⁺⊕θNηCη±η‖BO⊗⊕θ
```
[Try it online!](https://tio.run/##Xc49D4IwFIXhnV/RON0muOgmkx@LiSIhOhvAC21SSr3ckvDrKyQOyv6cN6dSBVVdYULISFuG3QVrjsVdt9jD6rmKxdk6z6lvSySQUibRFz5crhvFM6gIW7SML3jPIMfaYMVXTdRNmyTa971uLGTG9/Cvl/lYqMkfOzeCikWKTcEI6id68MxItRlvA5IpHJw6X5qptXghkxC20SasB/MB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
←×_N
```
Input `w` and draw `w` `_`s.
```
↗⊕θ
```
Draw `w+1` `/`s.
```
‖M
```
Reflect to complete the first triangle.
```
≔⁺⊕θNη
```
Input `s` and calculate the offset between the left and middle triangles.
```
Cη±η
```
Copy the left triangle to the middle.
```
‖BO⊗⊕θ
```
Reflect around the middle triangle to complete the triforce.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~127~~ 124 bytes
```
w,s=input()
n=2*-~w+s
while n:n-=1;I=w-n+(n>w)*(w-~s);print' '*n+(' '*(n+s)).join(['/'+I*2*' _'[I>=w]+'\\'][I>w:]*-~(n<=w))
```
[Try it online!](https://tio.run/##DY0xDsMgDAD3vILNNoRWZUxKdt6QoE6VQlU5qFBZXfJ1ynSnWy7/6n6wa03G4hPnb0Ua2DttTzFlkD29n4ontv42By@WDfIipFHsWWjOn8QVFOjeQXUim0J0eR2JcYUrmKCdBvWANSxeooFtg9hdptgXyHcvRK250f0B "Python 2 – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~20~~ ~~19~~ 16 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
+├:⁸╵\L_×;∔║ω╋║↕
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjBCJXUyNTFDJXVGRjFBJXUyMDc4JXUyNTc1JXVGRjNDJXVGRjJDXyVENyV1RkYxQiV1MjIxNCV1MjU1MSV1MDNDOSV1MjU0QiV1MjU1MSV1MjE5NQ__,i=NyUwQTA_,v=6)
Explanation:
```
+├ s + w + 2
: duplicated (for both X & Y)
⁸╵\ w+1 sized diagonal
L_× "_"*width of the diagonal
;∔ prepended before the diagonal
║ palindromize that
ω and push the argument of ║ (aka the unpalindromized version)
╋ overlap the upside down half-triangle over the upside down triangle at (s+w+2; s+w+2)
║ and palindromize the whole thing
↕ reverse everything vertically
```
note: in the making of this I fixed a mistake in the code, Without that fix, this would be [18 bytes](https://dzaima.github.io/Canvas/?u=JXVGRjBCJXUyNTFDJXVGRjFBJXUyMDc4JXUyNTc1JXVGRjNDJXVGRjJDXyVENyV1RkYxQiV1MjIxNCV1MjE5NSV1MjE5NSV1MjU1MSV1MDNDOSV1MjU0QiV1MjU1MSV1MjE5NQ__,i=NyUwQTA_,v=6).
[Answer]
# [R](https://www.r-project.org/), ~~225~~, ~~224~~, ~~214~~, ~~211~~, 208 bytes
```
function(w,s){M=matrix
C=cbind
h=w+1
k=C(apply(m<-diag(h)*60,1,rev)/4,m)
k[row(k)==h&!k]=63
z=rbind(C(a<-M(0,h,h+s),k,a),M(0,s,h*4+2*s),C(k,M(0,h,2*s),k))
z[]=intToUtf8(z+32,T)
apply(z,1,cat,sep='','
')
rm()}
```
[Try it online!](https://tio.run/##JU67TsNAEOz3L2jwrr1R/FJEka1cpwtVlOJwctzp8EPnIwYjvt3YuBrNaF5@1jLrz7YOtmtx5IF@TtKo4O0XVFK/2fYGRsYkAycVqr7/@MbmuLtZ9Y6G4kPKGfv7g/YlNwTu4rsRHYmY5yd3lUMBk/i1BJfwcXfClA2bZCB2rIhXPrCJyySPF61Cx5vlnzoimC5XsW04d69Bv@CUFDmfCbYf07Jdq8DDvZco4ggiAt8g/c4aM04JNOYbFFysUHJG8x8 "R – Try It Online")
* -1 byte thanks to Giuseppe
* -10 bytes after change of approach
* -3 bytes exploting ASCII code
* -3 bytes thanks to JayCe
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~296~~ 264 bytes
```
const A='/';B='\';var w,s,i:word;u:string;begin read(w,s);u:=StringOfChar('_',2*w);for i:=1to w do writeln(A:w+3+s+w-i,B:i*2-1);writeln(A:w+2+s,u,B);for i:=1to s do writeln;for i:=1to w do writeln(A:w+2-i,B:i*2-1,A:2*(s+w-i)+3,B:i*2-1);write(A,u,B,A:2*s+1,u,B)end.
```
[Try it online!](https://tio.run/##fY2xDoMgFEV/hQ0QbCNuEAftB3To2qShopbEoOFp@XxqWWo7dLnLuTln1tDqMe/nNsZ2crCgusJHrJoKX7F6ao8CB25lmLxRq4TFWzeoezdYh3ynDdkw3UB1SeTcnx7aE3zDXGSBqn7yyMqqWCYUkNnG26UbHallYCUDFnLLG2kzkRdU7aFgwFfefBlgZ/hrFh8rr6XISApRVv60SP1upAuwIvU6Zw4xlki8AA "Pascal (FPC) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~256~~ ~~248~~ ~~240~~ ~~228~~ ~~199~~ 195 bytes
A longer program, but slightly different approach:
```
f,b,o='/\ '
O=o*2
w,s=input()
l=f+'__'*w+b
a=l+O*s+l
m=n=[]
p=lambda g:(len(a)-len(g))/2*o+g
for i in range(w):m=m+[p(f+O*i+b)];t=f+O*i+b;n+=p(t+O*(w-i+s)+t),
print'\n'.join(m+[p(l)]+[o]*s+n+[a])
```
[Try it online!](https://tio.run/##LY5BDoIwEEX3PUV37TBVE9xh5gwcABtTImBNO22ghnh6ROPq/7f4Lz@/yyNxvW2j6U0idbpKJVpKVS1Ws5Dn/CoaRKAR1e2mqhV74ShgWy0YRCSmzopMwcX@7uTU6DCwdnD4xgRwqquEkxjTLL30LGfH06BXaCJF7LIed5HHHuyl0L9fGCnrsoNeDx4XwAJG5NlzUVdWx2fyrH/jABa7ZPcnjJ2zsG1nU38A "Python 2 – Try It Online")
---
saved a lot of bytes thanks to ignoring the trailing whitespace, and incorporating some tricks from @ovs
saved even more by defining a variable earlier
[Answer]
# [Ruby](https://www.ruby-lang.org/), 126 bytes
```
->w,s{(-v=w+1).upto(v){|i|j= ~-i%-~v;$><<[$/*s,$/+' '*(v+s)+t="/#{(j<w ?' ':?_)*j*2}\\".center(w*2+2)+' '*s*2,$/+t*2][0<=>i]}}
```
[Try it online!](https://tio.run/##HcvdCoMgGADQV4nmSD@zHy83rQcxGWwU1EUbacooe3X3c3vgLOv9HQcZWeNzs2HmpKc1KdaXfWJHtn3cJ5kcbDyzw11RI4RCJZgclTRLMsCOGkKtTMvThifhk/arl/ZGYAIeui4tHv1s@wV74JST/zHAf90C16oSshl1CHFQVV7r@AE "Ruby – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 141 bytes
```
\d+
$*
(?=( *),( *))
¶$1/$`$`\$1$2$2$1/$`$`\
T` `\_`/ *\\(?=.*,)
s`¶(.*),( *)
$1¶$.2$*¶$1
\G(( *)/( |__)*\\)\2( )*\1 *¶
$2 $#3$* $#4$* $1¶
```
[Try it online!](https://tio.run/##LY4xCsMwDEV3nUKQP9iusbHTtXTsBTIKrEA7dOnQduy5coBczJUhCD764r@P3o/v87X2LvcTITC568Vx8HGIp31DyVCooKDaHI4WZZWmmYOIISlETx/dN5cOllAMThVhdJDc3Lhmx/xrzRvlpZqxrbBFCJUxzfYBpvNQo3ufY/0D "Retina 0.8.2 – Try It Online") Note: Some trailing whitespace in output. Explanation:
```
\d+
$*
```
Convert the inputs into spaces. (The second line ends with a space.)
```
(?=( *),( *))
¶$1/$`$`\$1$2$2$1/$`$`\
```
Create the sides of the bottom two triangles with the appropriate spacing.
```
T` `\_`/ *\\(?=.*,)
```
Fill in the base of the triangles.
```
s`¶(.*),( *)
$1¶$.2$*¶$1
```
Duplicate the triangles with the appropriate vertical spacing.
```
\G(( *)/( |__)*\\)\2( )*\1 *¶
$2 $#3$* $#4$* $1¶
```
Convert the upper triangles into a single centred triangle.
[Answer]
# C (gcc), ~~404~~ 389 bytes
```
#define p(x)putchar(x);
#define F for
W;S;i;a=32;b=47;c=92;f(w,s){W=w,S=s;F(;w;--w){F(i=W+w+s+1;i--;)p(a)p(b)F(i=w*2;i++-2*W;)p(a)p(c)p(10)}F(i=W+s+1;i--;)p(a)p(b)F(i=0;i++-2*W;)p(95)p(c)F(;s--+1;)p(10)F(w=W;w;--w){F(i=w;i--;)p(a)p(b)F(i=w*2;i++-2*W;)p(a)p(c)F(i=w*2+S*2;i--;)p(a)p(b)F(i=w*2;i++-2*W;)p(a)p(c)p(10)}p(b)F(i=0;i++-2*W;)p(95)p(c)F(i=S*2;i--;)p(a)p(b)F(i=0;i++-2*W;)p(95)p(c)}
```
[Try it online!](https://tio.run/##lZGxCoMwEIbn@hSBLokxoLGlyJHVF3DIrFHbDFXRtimIz25jreAgpR0Ojvvvu/@HU@ys1Dju86LUVYEa/CTN/aYuaWs7cJZ5jMq6dSQkoCEVIYdMHE6gRMShxMbrSC@F8RLRQYzBAGOG9DHWQlJDOxqAZgxIg1NbGZkE43LQlDLuykVQtgKfDDO3SflrJjq@IWvYMWa3ZzzGRsh1BPOj@UegyST@Efd7Ni02720tD@Oj1jm6prrCU0dQ7@xKHHqI208M4ws "C (gcc) – Try It Online")
-14 bytes from [Rodolvertice](https://codegolf.stackexchange.com/questions/171516/ppcg-can-triforce/171547?noredirect=1#comment414156_171547)
-1 byte by fixing a loop variable decrementation
crossed out ~~404~~ is almost still 404
Ungolfed:
```
#define p(x)putchar(x); // save 7 bytes per putchar call (+24, -182)
#define F for // save 2 bytes per for loop (+14, -28)
int W, S, i; // W is w backup, S is s backup, i is an counter variable;
int a = ' '; // save 1 byte per space printed (+5, -8) (use a instead of 32)
int b = '/'; // save 1 byte per slash printed (+5, -6) (use b instead of 47)
int c = '\\'; // save 1 byte per backslash printed (+5, -6) (use c instead of 92)
// This isn't worth it for '\n' (-5, +3) (10), or '_' (-5, +3) (95)
int f(int w, int s) {
W = w; // Backup w and s, as we will modify them later,
S = s; // but will need their original values
for(; w != 0; --w) { // Top triangle (not the bottom line)
for(i = W+w+s+1; i != 0; --i) // leading spaces
putchar(' ');
putchar('/'); // left side of triangle
for(i = 2*w; i != 2*W; ++i) // inner spaces
putchar(' ');
putchar('\\'); // right side of triangle
putchar('\n'); // newline
}
for(i = W+s+1; i != 0; --i)
putchar(' '); // leading spaces for the bottom line
putchar('/'); // left side
for(i = 0; i != 2*W; ++i)
putchar('_'); // the bottom line
putchar('\\'); // right side
for(; s-- + 1 != 0;)
putchar('\n'); // newline after the bottom line and S empty lines
for(w = W; w != 0; --w) { // Bottom triangles
for(i = w; i != 0; --i)
putchar(' '); // leading spaces
putchar('/'); // left of left triangle
for(i = w*2; i != 2*W; ++i)
putchar(' '); // inside of left triangle
putchar('\\'); // right of left triangle
for(i = w*2+S*2; i != 0; --i)
putchar(' '); // spaces between left and right triangles
putchar('/');
for(i = w*2; i != 2*W; ++i)
putchar(' '); // inside of right triangle
putchar('\\'); // right of right triangle
putchar('\n'); // newline
}
putchar('//'); // left of left
for(i = 0; i != 2*W; ++i)
putchar('_'); // bottom of left triangle
putchar('\\'); // right of left
for(i = S*2; i != 0; --i)
putchar(' '); // space between triangles
putchar('/'); // left of right
for(i = 0; i != 2*W; ++i)
putchar('_'); // bottom of left triangle
putchar('\\'); // right of right
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 51 bytes
```
+‘⁶ẋ;Ɱ®Y
‘⁼þ`a”/o"”_o⁶Ṛ;ṚØ^yƊ$€©ż`j€Ḥ⁶ẋƊ}Y,@çj‘⁷ẋƊ}
```
[Try it online!](https://tio.run/##y0rNyan8/1/7UcOMR43bHu7qtn60cd2hdZFcYIE9h/clJD5qmKufrwQk4/NBSnbOsgbiwzPiKo91qTxqWnNo5dE9CVlAxsMdSyBGHOuqjdRxOLw8C2zGdojI////jf8bAwA "Jelly – Try It Online")
] |
[Question]
[
"Digital sum" refers to the sum of all the digits in a number.
For example, the digital sum of `1324` is `10`, because `1+3+2+4 = 10`.
The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.
## Example with walkthrough
As an example, take the number `9` as the input:
```
9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
```
The valid output would be the smallest number above, which is `18`.
## Specs
Note that `9` is not the valid output for this example, because the reversed number must be greater than the original number.
Note that the input will be positive.
## Test-Cases:
```
2 => 11 (2 = 1 + 1)
8 => 17 (8 = 1 + 7)
12 => 39 (12 = 3 + 9)
16 => 79 (16 = 7 + 9)
18 => 99 (18 = 9 + 9)
24 => 699 (24 = 6 + 9 + 9)
32 => 5999 (32 = 5 + 9 + 9 + 9)
```
## References:
This is [OEIS A161561](http://oeis.org/A161561).
**Edit:** Added an additional Testcase (18)
Thanks to [Martin Ender](https://codegolf.meta.stackexchange.com/users/8478/martin-ender) for the [Leaderboard Snippet](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet)
```
var QUESTION_ID=81047,OVERRIDE_USER=31373;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]
## Python 2, 33 bytes
```
lambda n:[n+9,`n%9`+n/9*'9'][n>9]
```
A direct expression. Makes a number string with 9's at the end and the remainder at the beginning. Except, for single-digit `n`, gives `n+9`.
Some outputs have leading zeroes (`099` for `18`).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
fqQsjT;h
```
[Test suite.](http://pyth.herokuapp.com/?code=fqQsjT%3Bh&test_suite=1&test_suite_input=2%0A8%0A12%0A16%0A24%0A32&debug=0)
```
fqQsjT;h
f h first number T from (input+1) onward where:
qQ the input is equal to
s the sum of
jT; the base-10 representation of T
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~39~~ 31 bytes
```
r`1{1,9}
$.&
T`d`_d`^.$
^.$
1$&
```
Takes input [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary).
[Try it online!](http://retina.tryitonline.net/#code=JShgLisKJCoKcmAxezEsOX0KJC4mClRgZGBfZGBeLiQKXi4kCjEkJg&input=MQoyCjMKNAo1CjYKNwo4CjkKMTAKMTEKMTIKMTMKMTQKMTUKMTYKMTcKMTgKMTkKMjQKMzI) (The first two lines allows running several test cases at once and converts from decimal to unary for convenience.)
This doesn't actually search for the result linearly, but computes it explicitly:
* If the input `n` is greater than 9, we replace it with `n % 9` followed by `n / 9` (floored) nines.
* Otherwise, we replace it with `n + 9`.
---
Using `!` (or anything else that isn't `1`) as the unary digit, I can save one more byte with the following approach:
```
^!(?!!{9})
1
r`!{0,9}
$.&
0\B
```
But this input format is a bit of a stretch, I think.
[Answer]
## Java 7, ~~68~~ 61 bytes
```
int f(int n){return n>9?-~(n%9)*(int)Math.pow(10,n/9)-1:n+9;}
```
Does roughly the same thing as many of the other answers here. Wanted to show the Java approach without using string manipulation and loops.
Thanks to FryAmTheEggman for reminding me that I'm dumb ;)
[Answer]
## 05AB1E, ~~19~~ ~~17~~ 8 bytes
**Code:**
```
[>DSO¹Q#
```
**Explained:**
```
[ # start infinite loop
> # increase loop variable, will initially be input
DSO # make a copy and sum the digits
¹Q# # if it equals the input, break
# else return to start of loop
# implicitly print
```
[Try it online](http://05ab1e.tryitonline.net/#code=Wz5EU0_CuVEj&input=MjQ)
**Edit:** Saved 9 bytes thanks to @Adnan
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 bytes
```
`QtV!UsG-
```
[**Try it online!**](http://matl.tryitonline.net/#code=YFF0ViFVc0ct&input=MTI)
### Explanation
```
` % Do...while
Q % Add 1. Takes input implicitly the first time
t % Duplicate
V!Us % To string, transpose, to number, sum. Gives sum of digits
G- % Subtract input. If 0, the loop ends and the stack is implicitly displayed
```
[Answer]
## JavaScript (ES7), 32 bytes
```
n=>(n%9+1)*10**(n/9|0)-(n>9||-8)
```
38 bytes as ES6:
```
n=>parseFloat(n%9+1+'e'+n/9)-(n>9||-8)
```
[Answer]
# Python 3, ~~128~~ ~~94~~ ~~84~~ 74 Bytes
Without output, direct approach, beginner codegolfer ;)
```
def r(n):
m=n
while 1:
m+=1
if sum(map(int,str(m)))==n:return(m)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
<.=:ef+?
```
`=` was modified after this challenge got posted, so that it now works on possibly infinite domains, which is the case here.
### Explanation
```
<. Output > Input
= Label the Output (i.e. unify it with an integer)
:ef Get the list of digits of the Output
+? Input is the sum of all those digits
```
This will backtrack on `=` until the value of Output makes this whole predicate true.
[Answer]
## Actually, 17 bytes
```
╗1`;$♂≈Σ╜;)=)>*`╓
```
[Try it online!](http://actually.tryitonline.net/#code=4pWXMWA7JOKZguKJiM6j4pWcOyk9KT4qYOKVkw&input=MTI)
Explanation:
```
╗1`;$♂≈Σ╜;)=)>*`╓
╗ save input to reg0
1`;$♂≈Σ╜;)=)>*`╓ first integer n (>= 0) where:
;$♂≈Σ╜;)= the base-10 digital sum equals the input and
)>* is greater than the input
```
[Answer]
# Python 2, 39 bytes
```
lambda n:[n+9,(1+n%9)*10**(n/9)-1][n>9]
```
Pure integer arithmetic.
### Full program with output
```
f=lambda n:[n+9,(1+n%9)*10**(n/9)-1][n>9]
print(f(2))
print(f(8))
print(f(12))
print(f(16))
print(f(17))
print(f(18))
print(f(24))
print(f(32))
```
Output:
```
11
17
39
79
89
99
699
5999
```
[Answer]
# C 73 65 bytes
A macro with a helper function.
```
e(y){return y?10*e(y-1):1;}
#define F(n) n<9?n+9:(1+n%9)*e(n/9)-1
```
The `e` function just calculates powers of ten, and the `F` macro uses the same solving method as [this ruby](https://codegolf.stackexchange.com/a/81077/31203), and [this python](https://codegolf.stackexchange.com/a/81050/31203) answer. sadly, it is longer than about the same length as both those answers put together. But it is the first C answer.
(8 bytes saved by Lynn's trick of removing `int`.)
[Answer]
## Lua, 52 bytes
```
n=...+0
print(n>9 and(n%9)..string.rep(9,n/9)or n+9)
```
Meant to be saved in a file and run with the Lua interpreter, e.g. `lua <file> <input number>`
You can also try it here: <https://repl.it/CXom/1>
(On repl.it the input number is hard-coded for ease of testing)
[Answer]
# Racket 70 characters, 71 bytes
Same algorithm as most of the others pretty much. Pretty sad about not having % for modulo, or \*\* for expt, or integer division by default, otherwise this could be a lot shorter and I could've outgolfed C and Java. Still love the language though
```
(λ(x)(if(> x 9)(-(*(+(modulo x 9)1)(expt 10(floor(/ x 9))))1)(+ x 9)))
```
[Answer]
# [Hexagony](https://esolangs.org/wiki/Hexagony), ~~40 31~~ 30 bytes
```
<_:->.(.+><.'!.\@"9!%>!/{.}|.?
```
Or, if you prefer your code to be a little less linear and a little more polygonal:
```
< _ : -
> . ( . +
> < . ' ! .
\ @ " 9 ! % >
! / { . } |
. ? . . .
. . . .
```
[Try it online!](http://hexagony.tryitonline.net/#code=PF86LT4uKC4rPjwuJyEuXEAiOSElPiEvey59fC4_&input=MjQ)
Thanks to @FryAmTheEggman for some ideas and inspiration :o)
Previous version: `<.:->+_.!(..'!.\><9!%>@.{.}|.?"`
Previouser version: `<><.-_|@"'!{|(.9+!8=@>{/".'/:!?$.%\1$..\`
[Answer]
# [Perl 6](http://perl6.org), ~~38~~ 29 bytes
```
~~{$\_>9??(1+$\_%9)\*10\*\*Int($\_/9)-1!!$\_+9}~~
{first *.comb.sum==$_,$_^..*}
```
( apparently the direct approach is shorter )
### Explanation:
```
{
first
*.comb.sum == $_, # lambda that does the check
$_ ^.. * # Range.new: $_, Inf, :excludes-min
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my @tests = (
2 => 11,
8 => 17,
9 => 18,
12 => 39,
16 => 79,
18 => 99,
24 => 699,
32 => 5999,
);
plan +@tests;
my &next-digital-sum = {first *.comb.sum==$_,$_^..*}
for @tests -> $_ ( :key($input), :value($expected) ) {
is next-digital-sum($input), $expected, .gist;
}
```
```
1..8
ok 1 - 2 => 11
ok 2 - 8 => 17
ok 3 - 9 => 18
ok 4 - 12 => 39
ok 5 - 16 => 79
ok 6 - 18 => 99
ok 7 - 24 => 699
ok 8 - 32 => 5999
```
[Answer]
## TSQL(sqlserver 2012), ~~107~~ 99 bytes
```
DECLARE @ INT = 32
,@2 char(99)WHILE @>0SELECT
@2=concat(x,@2),@-=x FROM(SELECT IIF(@>9,9,IIF(@2>0,@,@-1))x)y PRINT @2
```
[Try it online!](https://data.stackexchange.com/stackoverflow/query/494130/find-the-smallest-number-bigger-than-the-input-whose-digital-sum-is-the-input)
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 456 bytes
```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy.Ajax:You be I.[Exit Ajax][Enter Page]Scene V:.Page:You be the sum ofyou a cat.Remember you.Ford:You zero.Scene X:.Ford:You be the sum ofyou the remainder of the quotient betweenI twice the sum ofa cat a big big cat.Page:You be the quotient betweenyou twice the sum ofa cat a big big cat.Be you nicer zero?If solet usScene X.Recall.Am I as big as Ajax?If notlet usScene V.Open heart
```
[Try it online!](https://tio.run/##jVBdS8QwEPwr@wNK3s2LnKBQEBSFQ5E@pO32GmmSM9lyd/75urtWPM4XH/I1zMzOpOynZanM5t0dK3OXcl@ZR7dDRjqC2prnDiPK5e02EmYQIrjYg3Ab2ey9L4QRKNF4UiP7mmZoWcWioyfVNKtezJtv063VUT9sGhHKHCANJwYcdI7MEwYMLcsY0nRK/sSc1mAv9hf@4yGvjMH52LNFGhT4mBN5jMR0OiDGGujgu3OpjuYArd/pkiCXQS9ddNw/fG5QqkBkZtYe1/UAJU1IMJe1Erfu3DSZTYAaXFEtH/KLwo6Jzulb87Dn3x/RZVqWqy8 "Shakespeare Programming Language – Try It Online")
[Answer]
# Ruby, 33 bytes
This is a int arithmetic version that just happens to be the same as xnor's python answer. It is an anonymous function that takes and returns an int.
```
->n{n<10?n+9:(1+n%9)*10**(n/9)-1}
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~8~~ 7 bytes
```
Æ)_Σk=▼
```
[Try it online!](https://tio.run/##y00syUjPz0n7//9wm2b8ucXZto@m7fn/39gIAA "MathGolf – Try It Online")
Implicit input yay.
### Explanation:
```
Implicit input
Æ ▼ Do while false loop that pops the condition
) Increment top of stack
_ Duplicate
Σ Get the digit sum
k Get input
= Is equal?
Implicit output
```
[Answer]
# [Desmos](https://www.desmos.com/calculator), ~~57~~ 49 bytes
*-8 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow)!*
```
f(n)=\{n<9:n+9,(\mod(n,9)+1)10^{\floor(n/9)}-1\}
```
[Try it on Desmos!](https://www.desmos.com/calculator/ijpjyktlnf)
[Answer]
## PowerShell v2+, 62 bytes
```
param($n)for($a=$n+1;([char[]]"$a"-join'+'|iex)-ne$n;$a++){}$a
```
Takes input `$n` then executes a `for` loop. We initialize the loop by setting our target number, `$a`, to be one larger than `$n` (since it has to be bigger, plus this ensures `1..9` work correctly). Each loop we increment `$a++`. Nothing happens in the loop proper, but the conditional is where the program logic happens. We're literally taking the target number as a string, casting it as a char-array, `-join`ing the array with `+` and then piping it to `iex` (similar to `eval`). We test whether that's equal to our input number or not, and continue looping accordingly. Once we've exited the loop, we've reached where our target number is digit-sum equal to our input number, so `$a` is placed on the pipeline and output is implicit.
---
For reference, here's the "construct a string with the appropriate number of 9's" method that other folks have done, at **67 bytes**
```
param($n)(($n+9),(+(""+($n%9)+'9'*(($n/9)-replace'\..*'))))[$n-gt9]
```
or the "pure integer arithmetic" method that other folks have done, at **70 bytes**
```
param($n)(($n+9),("(1+$n%9)*1e$(($n/9)-replace'\..*')-1"|iex))[$n-gt9]
```
Neither of which are shorter, but both of which are more interesting.
[Answer]
# Ruby, 38 bytes
```
f=->n{n<11?n+9:"#{n<19?n-9:f.(n-9)}9"}
```
This answer returns a string or int depending on input size. It is a recursive solution that asks for a solution for 9 less then adds a "9" to the end.
---
# Ruby, 39 bytes
```
f=->n{n<11?n+9:(n<19?n-9:f.(n-9))*10+9}
```
For one more byte, this answer always returns an int. same algorithm as above but with numbers.
[Answer]
## JavaScript (ES2015), ~~45~~ ~~39~~ 33 bytes
Saved another 6 bytes thanks to @Conor O'Brien and @Shaun H.
I think I'll leave it as is, because this version differs from @Neil's answer by using `String.repeat()`.
```
v=>+(v>9?v%9+'9'.repeat(v/9):v+9)
```
Previous version (saved 6 bytes thanks to @Qwertiy):
```
f=v=>+(v/9>1?v%9+'9'.repeat(v/9|0):v+9)
```
First version:
```
f=v=>+(v/9>1?v%9+'9'.repeat(~~(v/9)):'1'+v-1)
```
[Answer]
# C, 80 bytes
```
i;s;g(j){s=0;for(;j;j/=10)s+=j%10;return s;}f(n){i=n;while(n-g(i))i++;return i;}
```
Ungolfed [try online](http://ideone.com/40ju8G)
```
int g(int j)
{
int s=0;
for(;j;j/=10) s += j%10;
return s;
}
int f(int n)
{
int i=n;
for(;n-g(i);i++);
return i;
}
```
[Answer]
# PHP, 77 characters
```
$n=$argv[1];$m=$n+1;while(1){if(array_sum(str_split($m))==$n)die("$m");$m++;}
```
[Answer]
# Oracle SQL 11.2, ~~165~~ bytes
```
SELECT l FROM(SELECT LEVEL l,TO_NUMBER(XMLQUERY(REGEXP_REPLACE(LEVEL,'(\d)','+\1')RETURNING CONTENT)) s FROM DUAL CONNECT BY 1=1)WHERE s=:1 AND l!=s AND rownum=1;
```
Un-golfed
```
SELECT l
FROM (
SELECT LEVEL l, -- Number to evaluate
XMLQUERY(
REGEXP_REPLACE(LEVEL,'(\d)','+\1') -- Add a + in front of each digit
RETURNING CONTENT
).GETNUMBERVAL()s -- Evaluate le expression generated by the added +
FROM DUAL
CONNECT BY 1=1 -- Run forever
)
WHERE s=:1 -- The sum must be equal to the input
AND l!=s -- The sum must not be the input
AND rownum=1 -- Keep only the first result
```
[Answer]
**Python 3 55 Bytes**
Takes two arguments that are the same
```
f=lambda a,b:a if sum(map(int,str(a)))==b else f(-~a,b)
```
i.e. to call it you would use f(x,x)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
@¶Xìx}aUÄ
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=QLZY7Hh9YVXE&input=OA==)
[Answer]
# Java 10, ~~114~~ 62 bytes
```
n->{var r="";for(int i=0;i++<n/9;r+=9);return(n>9?n%9:n+9)+r;}
```
[Try it online.](https://tio.run/##XZDBTsMwDIbvewqr0qRE2QorCNGFjidglx2BQ@iyKaN1p8QtQlOfvaTpJNZeEn2xZX9/TqpRy9P@u8sL5Ry8KYOXGYBB0vagcg3bHgF2ZA0eIWe@Asilf2xn/tgCQgYdLjeXRlmwWRTJQ2VDm8nupRHiBe9SaUWWcmk11RYZbtJXnKdrFCkXVrad7Eed66/C5OBIkb@ayuyh9DpsWP3@CYoPLr0klH4t6p8ALPgAkHbEykUyxucxribl1dOEJ/3J45gfkv/0t66hPKgtIMS/6u5@HekyrmqKzz4JFciMiNYfFIkyxth/Kb9ObLs/)
EDIT: **~~130~~ 73 bytes** without leading zeros (Thanks to *@levanth`*):
```
n->{var r="";for(int i=0;i++<n/9;r+=9);return new Long((n>9?n%9:n+9)+r);}
```
[Try it online.](https://tio.run/##XZDBbsIwDIbvPIVVCSlRoBvdNK1kZS@wceG4cchKQIHGRYnbaUJ99i4tSFt7SfTZ1q/PPqpazY@7U5sXynt4VwYvEwCDpN1e5RrWHQIUJR4gZ6EOyGUoNZPwrAEhgxbnq0utHLgsiuS@dP2Yye6lEeIF71LpRJZy6TRVDgH1N7yFOMZwlb7iNF2iSLlwXDat7FLP1VdhcvCkKHx1aXZggxfbkDN4@NiC4lepzhZsMOgiO2C9GgBpT8zOkiE@D3Exai@eRjyaTx6H/JD8HeK/a9@@qs2gv8RNd/PjSdu4rCg@h02oQGZEtPykSNgY43Bdfkts2l8)
**Explanation:**
```
n-> // Method with integer parameter and long return-type
var r=""; // Result-String, starting empty
for(int i=0;i++<n/9;r+=9); // Append `n` integer-divided by 9 amount of 9's to `r`
return new Long( // Cast String to number to remove any leading zeroes:
(n>9? // If the input `n` is 10 or larger
n%9 // Use `n` modulo-9
: // Else (`n` is smaller than 10):
n+9) // Use `n+9`
+r);} // And append `r`
```
] |
[Question]
[
Write a program for a specific language that in different orientations performs different tasks.
Your code should have at least two non-empty lines and at least two non-empty columns and should complete at least one challenge from each category of challenges below when oriented in different ways.
## Orientations
Your code can be arranged eight different ways, original and three ninety degree rotations and each reversed, eg:
```
$_= $@$ /$ =.
@F. /F_ .F@ _F/
$/ .= =_$ $@$
=_$ .= $/ $@$
.F@ /F_ @F. _F/
/$ $@$ $_= =.
```
[Here's a generator](https://tio.run/##fVLdboMgFL7nKc7SJmJnbZbdNWmyq72EMwYVVxZ6IEDnupd3gHa1TTduxO/nfJwD@uT2Cp@HYfGwOVqzqQVuOH6CHnEiDloZB/ZkCWl5B4Z3kjeu6oSxjjJj0i0Bvwx3R4PggWK7XT@V12rJ7okLo/pRDZ0y4P9AxBKT2xmGVivL71hX30LTVcAnMZOyUkZwdMwJhZY2quWV1VK4ydrDDg7si0qO1Gel89CZOGoXQDVrwSkf2DiG75JDL9werGYNt6PIp/uShRS@uVDnERJIVrSHNZwz0j9SylggULMzB0nBItqMe2OymymMo6oj3WTXA24mlkW2zm4uq07LcpxEWNoIdDR5wyT/UAJpMn2lQD4eOuxCpdkJ0ww4tjvv8r6UkEtDfhD@jeTWtQJzw1kb3JamZOEbEIfQhfDQOyDvI3XtLQJW/D6Fc/RFE7nSj7iYYQEi5L@bH4ZltSMvrzlZbn4A) (thanks to [@fireflame241](https://codegolf.stackexchange.com/users/68261/fireflame241)!)
## Tasks
### [string](/questions/tagged/string "show questions tagged 'string'")
* ["Hello, World!"](https://codegolf.stackexchange.com/q/55422/9365)
* [Covfefify a string](https://codegolf.stackexchange.com/q/123685/9365)
* [No A, just CAPS LOCK](https://codegolf.stackexchange.com/q/158132/9365)
* [Don't google "google"](https://codegolf.stackexchange.com/q/58891/9365)
* [1, 2, Fizz, 4, Buzz](https://codegolf.stackexchange.com/q/58615/9365)
### [number](/questions/tagged/number "show questions tagged 'number'")
* [Is this number a prime?](https://codegolf.stackexchange.com/q/57617/9365)
* [Fibonacci function or sequence](https://codegolf.stackexchange.com/q/85/9365)
* [You're on a 8 day streak!](https://codegolf.stackexchange.com/q/66841/9365)
* [Count up forever](https://codegolf.stackexchange.com/q/63834/9365)
* [Am I a Rude Number?](https://codegolf.stackexchange.com/q/180481/9365)
### [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'")
* [Sing Happy Birthday to your favourite programming language](https://codegolf.stackexchange.com/q/39752/9365)
* [Print a Tabula Recta!](https://codegolf.stackexchange.com/q/86986/9365)
* [Sing Baby Shark](https://codegolf.stackexchange.com/q/179998/9365)
* [Build me a brick wall!](https://codegolf.stackexchange.com/q/99026/9365)
* [Hare Krishna Hare Krishna Krishna Krishna Hare Hare](https://codegolf.stackexchange.com/q/117842/9365)
### [quine](/questions/tagged/quine "show questions tagged 'quine'")
* A program that is a [proper quine](https://codegolf.meta.stackexchange.com/a/4878/9365).
* [Program that creates larger versions of itself (quine-variant)](https://codegolf.stackexchange.com/q/21831/9365)
* [Print your code backwards - reverse quine](https://codegolf.stackexchange.com/q/16021/9365)
* [Print the last, middle and first character of your code](https://codegolf.stackexchange.com/q/188005/9365)
* [Mirror quine (or my head hurts)](https://codegolf.stackexchange.com/q/16043/9365) - This counts as two rotations!
### [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'")
* [Do you want to code a snowman?](https://codegolf.stackexchange.com/q/49671/9365)
* [It's my Birthday :D](https://codegolf.stackexchange.com/q/57277/9365)
* [In Honor of Adam West](https://codegolf.stackexchange.com/q/126223/9365)
* [5 Favorite Letters](https://codegolf.stackexchange.com/q/99913/9365)
* [It took me a lot of time to make this, pls like. (YouTube Comments #1)](https://codegolf.stackexchange.com/q/180509/9365)
## Scoring
Your score will be the number of different tasks solved by your code (higher is better) with code length as a tie-breaker (lower is better).
## Rules
* All programs must be in the same language
* The rules for each task are as specified in the linked questions.
* Multiple tasks can be completed in the same orientation to help maximise score. For example, if s challenge has no expectation to handle the empty input, you could instead perform another task that takes no input.
* Your code must perform tasks when oriented in at least three unique rotations.
* You can assume that spaces will be automatically added when rotating your code, however if your code does necessitate space padding on the end of lines of each rotation, these should be included.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ ~~14~~ ~~15~~ 18 rotations (~~5~~ ~~6~~ ~~7~~ 8 unique, ~~61~~ ~~213~~ ~~1488~~ 4367 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
.ï i…( )7ÝJ»•αγʒδÓ₂©8¥ŽQxΣxêÿ•sÅвJIvN”</[(0._-=:"ÆŸ,*”0¶:º•DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλݺ•20в趡Nè4äyè.;ëĀiηû»ëтÝ3Å€"Fizz"}5Å€á”ÒÖ”J}¦»]q]À=F₂Aë}š.?ćvD¡SaA„iĀë∍sna„>+?Å8IàQô2$4Žнв₄iï.
ï …
i _
Å |
f _
ë Ć
∞ Ƶ
€ м
, ×
] T
q ä
] »
. q
”
. !
… ï
ë ‚
p ,
i ™
ï Ÿ
.ïi_i“Ûà€‰€ž€¢‡Í! :D“ćuìëdiU„ $„ |}…-~-`)X·>δ∍»}ëĀi1ú.γžOså}R`¦??н©?н®ì.•gÍĆdQ¸G•Â‡D?,듫·Ħí¥Â“#€¦`«'kì)™•1¢₂P•3вè4ô»]q]»ì” ©¢ØŽ”)s”E1BA50 Ž¬”Дî€ot”ëFëgiʹŠ'iĀëå4B23iï. \””
```
[Try it online (integer input)](https://tio.run/##3VjdThNREL7fpyhIIoWy9GcJBIQGUjFwgeJPNCppIShZTURSJUgo2WwoIAnEtImiUtJWWsGtVNsChVpM5uty4cWmvsJ5ETzbF/D@7MXszM7ZmfOdOZnMzGx4ckp9cnkpI@9QmZZtdTi7kRilCtPS1k@r@CdmlRBnuk4HPZQxq@ML1pcFfMNvrg8jWi@MjsyPMS1xrfNRq1sOdvT3NmPVLLva@Dc3HffSGV8YwCk@Qm/vw7pV/KsjhRwVEb9PB9iCHgxdxNjbJA6ftVlxfMXGMnYRo7JVoOwsMlOdOFK6O@exZcW5Uaad2YvL2H5IR1YFiYYHr7tewD4dU2oM@wr23mBf7oNR01TrBBWqwOBuEz5EmZ5rHlYXF5sjXQ0BKW4TMbznr9EIZakyMTcBrX@YQx6EETFTsr@2Nh@g1J3JQabtqjUNBlvfDL@Y5NJAux/RnhEkx1HytihmtV6tF5i@oiIvS/xERXr45ZBUoRAFJUSFArQkPRUtQIZQgGqrElvfFQrSxZHE06hQkOq/JJdQgPBBmhAK0F1pTqwA7QkWIKpIslCA5iSh4PBqLiFYhJokXqGKlRXyotU/TPskvRQKkUuwnoitpEVrXM2yJCOvBlWm7eAzkrxcZdoPTs1zTijNtBQ2mxy9Aa6vrb1GDsa0eo93944WmyxFeF7pWO4IOR/QyYBV4s0/VSKN2YIHZ7JVNM9vhpGJ3A5R1u@vV@nAJofIyUxLz2Cztjo9TuUbXIDOXQX8LhjcExnYsj2vUBbfKWPrdq7Y@8mGyLj6HDknDwX/ycM3qOu3OOezRxwKSo0RBVXAUSQcdEBpbJtVzjvDnFz3DA12uR1mlWw13tnkkJudfWVzxjCMGRUbdGomrzZGGcgoQ16fPa/47zk@bkxfEpeXiuLxKIrP@w8): [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") Do you want to code a snowman?
[Try it online (string input)](https://tio.run/##3VjdThNREL7fpyhIIoWyFCiBgNBAKgYuUPyJRiUtBCSriUiKBAklmw0FJIGYNlFUStpKK3Ur1bZAYS0m83W58GJTX@G8SD3bF/D@7MXszM7ZmfOdOZnMzHxwalqZrdVk5BwKU9PNDmcPYmNkMDVp/bQKfyJWEVGmaZTppZRZnli2vizjG35zfRDhan5sdGmcqbEb7U@a3bK/baCvERtmydXCv7nptI8u@EIfzvERWms/tqzCXw0JZKmA6EPKYBeaP3AVYW/jOH7eYkXxFdtrOECESlae0vNITbfjxNPTvoRdK8qNMvXCXlzC3mM6sQzE6h463dU8juiUEuM48uDwDY7kfugVVbHOYJABnbuNdSHMtGzjiLKy0hjqrgtIcJuI4D1/jYUoTcbkwiTUgREOeQh6yEzI3srmko8S96aGmHqgVFTobGsn@HKKS4OtXoR7RxGfQLGzyWOWq@VqnmnrCnKyxE9UpIdfDkkRCpFfQlgoQKvSM9ECpAsFqLIhsa0DoSBdnUg8jQoFqfpLcgkFCB@kSaEA3ZcWxArQoWABIkOShQK0IAkFh1dzMcEi1CDxClWsrJATrf5h6ifplVCIXIL1RGw9KVrjapYkGTnFrzB1H58R5@UqU39wal5yQkmmJrDT4OjzcX1l8zWy0GeUB7y7dzTZZDXE80rbWlvA@YjOBq0ib/7JCNVnCx24kK2CeXk7iFToboDSXm@1TBmbHCMrMzU5h53KxswElW5xARp35fO6oHNPpGPX9rxOaXynlK3bv2bvJx0g/foLZJ08FPynDr5BTbvDuS57xOFBsT6iIAMcRcxBGUpizyxz3hnk5GbH8FC322GWyVbjnU2Oudn5RZvTR6DPKdimczN@vT7KQMoz3Nllzyv@e45P69OXWK22OBtc/Ac): [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") It took me a lot of time to make this, pls like. (YouTube Comments #1)
[Try it online (no input)](https://tio.run/##3VjdThNREL7fpyhIIj9lKVACAaGBVAxcoPgTjUpaCEpWE5FUCRJKNhv@JIGYNlFUSmillbqVKhQo1GIyX5cLLzb1Fc6L1Nm@gPdnL2Znds7OnO/MyWRmpkPjE9qTSkVF1qUJPVXvauhEbJgKQk/YP@2jPxE7h6gwDEp3UdIqjs7ZX@bwDb9ZH8Jy@XB4aHZE6LFrLY/qPWqgube7FitW3t3I3zx00k3nvNCPM3yE0dSDNfvor4E4MnSE6H1KYxNGIHgZEW93cfCs0Y7iK9YXsYMI5e1DSk0jOdGCY29nyyw27SgbFfq5sziPrYd0bBcQq3po85QPsU8nFB/Bvhd7b7Cv9sAs6Zp9igIVYLLbWDuWhZGpHdTm52vDHVUBcbaJCN7zazhMKSqMzYxB7x1kyP0ww1Zc9ZVWZ/0UvzPeL/QdraTDFGsboRfjLPU1@bDcNYTdUeTa6rxWsVwsHwpjSUNWVfhEZXr4ciiaVIgCCpalArSgPJUtQKZUgEoriljbkQrS5bHCaVQqSOVfilsqQPigjEkF6K4yI1eA9iQLEBUUVSpAM4pUcLiai0kWoRqFK1S5skJWtvpH6J@Ul1IhckvWE4mlhGyNq5VXVGS1gCb0bXzGLperQv/B1LpgQgmhx7FR4@r2s760@hoZmJPaPe7uXXUOWQhzXmlebA42PKDTPjvHzT8VwtXZQivOVfvIurgZQjJ8O0gpn69cpLRDDpBRhZ6YwkZpZXKU8jdYgMGu/D43TPZEJjYdz0uUwndKOrrtK85@UkEyrz5HpoFDwT@18gYN4xZz7c6Iw4tcdURBBTCKmIvSlMCWVWS@IcTkeutAf4fHZRXJUeOdQw7Y7PQrhzMHYU5pWKcza/dqdZSBpHegrd2ZV/z3HB9Xpy@xSuUf): [string](/questions/tagged/string "show questions tagged 'string'") 1, 2, Fizz, 4, Buzz
[Try it online with all rows reversed (integer input)](https://tio.run/##3VjdThNREL7fp1iQRAplKbQEAkIDqRi4QPEnGpW0EJSsJiKpEiSUbDYUKkmJaRNFpQ2ttFK3Um0LFNZiMl@XCy829RX2RerZvoD352QzO7Nzcma@zMnZM99icHZOftJoSCjIftlS9vAZ@5aat5QfTBoXTFDaUlKItoiDPuavbb1GHtq8fM9SkmKbLdZClpLtWu8KOB7Q6YhZtiJR0kPQaorcg3PJLBkXN4PIhG4HKOv11quUs8UR8pKlpBcQrW3OT1PlBjOgslA@rxMai0QaduzIG5TFd8rYvr0rdj7ZAGlXnyPvsDZYaukelqCq3mKau17EoQdl0meWZkgHQ5EQKUdp7BpVpjuCTFzvGRvtc4lGlWw33tniiC27@MrWtHFoCzK26czYvyrXFGjIeMZ63TIKkvi/8ZitwB4BBZGnYVQEmStAbN8IL7lC5BSg8VUi5ZPAThWuMKEgSFwBahFEzjZdgrMKLQkzXOEhXVji60w44KxCdwUnXwX6ILDLIVeQ6r8EK5LkCtLlMW8XoNqm8JQrQH4BYa4ArXHWFfl561tZ/yBIDJPMlHbR0Y/EJOmWkjZ/mqU/MbOMuKWqlBugjFGdXjG/rOAbfjN/EOF6cXJieYrdB691P2p3Sf6u4cFWbBoVZwf75qKTQTpnE304w0eonUOImKW/KlLIUwnx@5TDDlR/4DJmvd3H0bMOM46v2F5HEjGqmEXKLiIz141jT3/3MnbMeJM3OLcnV7D7kI5NHYlmhF6XTWnQCaWmbGbj4A0OpaEms2KeQicdGgubcCPM/lGt4/Lqamuor2kgZbMZMbxnr8kQZZuUCJThcQZ5FFrISEne2tayj1J3ZkctJdmkOqxINPhillkjnV6EByawP41yb5vHqNar9aKlbtgsSKPh/gc): [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") It's my Birthday :D
[Try it online with all rows reversed (string input)](https://tio.run/##3VjdThNBFL7fp1iQBAplKVACAaGBVAxcoPgTjUraIkhWEyoWCRJKNhsKlaTEtImiUtJWWqlbqbYFCmsxma/LhReb@grzInW2L@D9TDZnz9kzmXO@nMnsnM8f8M3K8/W6hLzskamyj89IUDVHlR9MGpdMkBRVkog0iYNu5q9uv0YO2px8nyoHYosl1oNUyXRudHptD8nZiFmi4QjRg9CqityNC8ksGpe3AkgH73hJxuWqVUjWEsfISVRJLSBS3ZqbJuWbzIDKQrlddmgsEtGwa0XeJBl8J2nLt3/NyifjJVrrC@RsdJOllupmCarqbab11go4cqJE9JmlGaKDoYiLJEtS2DMqTLcFmLjRPTba5xCNCrHceGeJY7asf9nStHFoCzJ2yLmRaJWrCjSknWM9vTLykvi/8YStwB4BeZGnYZQFmStAbN8IL7lCZBeg8VUi5ZPAThWuMCEvSFwBahJEzjZdnLMKLQkzXOEhurDE15lwyFmF7gl2vgr0QWCXQ64g1X4JNHzAFaSrE94uQNUt4RlXgDwCQlwBWuesK/Lw1rey/kGQGCaZKW2irR/xSaJTJWX@NIt/omYJMaqqJDtA0kZletX8sopv@M38AYRqhcmJlSl2H7ze9bjNIXk6hwebsWWU7e3sm4OcDpILNtGNc3yE2jGEsFn8qyKJHCki9oBksQvV472K0rcJHD9vN2P4ip0NHCBKymaBZPxIz3bhxNnftYJdM9bgDS6syWXsPSInpo54I0KPw6I0yClJTlnMxuEbHElDDWbFPINOdGgsbLwXIfaPah6X19aag30NA0mLzYjiPXtNBkmmQYlAGR5nkEehBY2k5Kpur7hJ8q5vlCoHDaqDhiOBRR@zRjpcCA1MIDGNUk@L06jUKrUCVTctFqRef/pq3rcs@xf/AQ): [string](/questions/tagged/string "show questions tagged 'string'") Covefify a string
[Try it online with all rows reversed (no input)](https://tio.run/##3VjdThNREL7fp1iQRAplKVACAaGBVAxcoPgTjUpaCEpWE5FUCRJKNhsKlaTEtImi0qattFK3Um0LFNZiMl@XCy829RX2RerZvoD352QzO7Nzcma@zMnZM99SYG5eftJoSCjIPtlS9vEZSUvNW8oPJo0LJihtKSlEWsQhL/PXtl8jD21BvmcpCbHNFutBS8l2bXT5HQ/odNQsW@EI6UFoNUXuwblkloyLmwFkgrf9lPV46lXK2eIIeclS0ouI1LYWZqhygxlQWSivxwmNRSINu3bkTcriO2Vs3/4VO5@sn7Srz5F3WJsstXQPS1BVbzGtr17EoRtl0meXZ0kHQxEXKUdp7BlVpjsCTFzvGR/rd4lGlWw33tniiC279MrWtAloizJ26MxIXpVrCjRk3OO9fTIKkvi/8ZitwB4BBZGnYVQEmStAbN8IL7lC5BSg8VUi5ZPAThWuMKEgSFwBahFEzjZdnLMKLQuzXOEhXVjm60w44KxCdwUnXwX6ILDLIVeQ6r8EK5zgCtLlMW8XoNqW8JQrQD4BIa4ArXPWFfl461tZ/yBIDJPMlHbRMYD4FOmWkjZ/mqU/UbOMmKWqlBukjFGdWTW/rOIbfjN/AKF6cWpyZZrdB691P2p3Sb6ukaFWbBkVZwf75qKTITpnE704w0eoncMIm6W/KlLIUwmx@5TDLlSf/zJqvU3i6FmHGcNX7GwggShVzCJll5CZ78axe6B7BbtmrMkbnNuTK9h7SMemjngzQq/LpjTohFLTNrNx8AaH0nCTWTFPoZMOjYWN9yHE/lGtE/LaWmuwv2kgZbMZUbxnr6kgZZuUCJSRCQZ5DFrQSEme2vaKl1J35sYsJdGkOqxwJPBijlmjnR6EBieRnEG5t81tVOvVetFSN20WpNH4Bw): [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") Hare Krishna Hare Krishna Krishna Krishna Hare Hare
[Try it online with each row reversed (integer input)](https://tio.run/##3VjdThNREL7fpyhIwl9ZWlqEgNBAKgYuUPyJRiUtBCWriUiqBAklmw0FJIGYNlH8adNWWqlbqbYFCrWYzNflwotNeYXzIvVsX8D7s9nMnpmdnTlf5mT2nG8hMDOrPKnXZeQUpq3X8rWKUXG39KA4hfh4P0KezmGmxmZeBNjWDvSqqnBtZOYOJbxL1U2PbCSC0EeYpo0NQZ1enKYypYMTTI3iPcLWI8G0LEK9weaVFWWsuaG4EL3UoFMZZfNEqarQB2UcvMG@GweTlKBjHNTyjh6mJukMUbNMRw@xhxJ7G2fqGY9pRrC71N3nxlH3LFILlDbzVEIYsTVs45sZ6XiGQ@58Efb7oGGXMvcRoQKySFxqZgFbg53c/BGn3kaGATp28KAddqOEjeaBoS6f7Gh71H2N2yaXxidqeYQC3BF/8H3Z/Lo8ZVQo1U8ZDhkRs/g3bBbMX1ag8gSife22NqamFRtyssQHNpEu5CSfUIAUaVWsAoUEK9BTqbohVoV06eJIKERsKybVfosFSctK@CAUJLt0Vyg80xL2hQK0KFFZsAotCoXH2s5FhUJkk5oEqxByYv2H1DRfdJ9E2wDZhQL0UmLrScFORUZJtHMr7938fvz/HoKc4uoZdSPVoDpajTidYluZhz4GnUd4tWARGIcWr/GOC8oaFZujd2TUeZ1rgXYujAr2KEkZm@WTpXKDEkHRbVEaLqYmbzFNo6STj/i6aUf2eSvpfkrzsFeY@gUapfCD0lhnagK7pFs23e7xWqrGP7pBpam56gZ25rki8wSHtYqHMlx4KO2/HUQqcNM4NwsyzpwNZiVIZba1YxaH6eRBu79rrYt3leAqn12sxRL3lDnoyL6ubvJM3gFbE3Z4Kkry@RjnXDD1p4U4js/8veJTkJPrdaezx@Xuvdr3Dw): [number](/questions/tagged/number "show questions tagged 'number'") You're on a 8 day streak!
[Try it online with each row reversed (string input)](https://tio.run/##3VhbTxNREH7fX7EgCbdSbiUQEJoSxMADipdoVMJFBFYTKhYQCSWbDYVKAjE0Uby0aSut1K1U2wKFWkzm6/Lgw6b8hfNH6tn@Ad/PZjN7ZnZ25nyZk9lzPrdnckp5Vi7bkVKYtlFKlwpGwVHThuwowkNd8Dkb@5gampz3MP8O9KKqcM01eZciA8vFLafdiHihu5imDfZCHVsYozzFvcNMDeI99qxHhGlJ@Dq81aurymB1RWlH8EqDTnnkzVOlqELvsePwDQ4cOByhCJ3gsJRuaWNqlM4RNPN0/Aj7yLG3Yaae85hmALvLzZ0OHDdPIeamuJmmHPYQWsc2vpmBhuc44s6XexPj0LBLiQcIUAZJRK40MwN/TyM3f8TZQCVDN5208KANNiOHzeru3qZxe0vd4@br3DayPDRcSsPn4Y74g@8r5teVUaNAsS5KcMgImNm/e2bG/GUFyg8j2Fkv1zE1rshI2SU@kEW6kJLGhQKkSGtiFcgnWIFmpOKmWBXSpctjoRAxf0gq/RYLkpaU8EEoSDbpnlB4xiQcCAVoQaK8YBVaEAqPtZ0LCoVIlqoEqxBSYv2H1DhfdJ9E2wDZhAL0UmIbUcFORUZOtHMr7938fvL/HoKU0t7W70CsQnXUGmE6w7YyC30QOo@w6LYIjCOL13jHBSWNgtzS4epvvcE1Tz0XRgH7FKWEbPkkKV@hRJB1WJRGO1Ojt5mmUbSVj/i6qUfyRS3pExTnYa8x9Qs0iuEHxbHB1Ah2Sbdsus05YKka/@gm5Uani5vYmeWKnSc4KhWclODCSfGJO17EPLeMCzNjx3lrhVnxUp75d8xsH50@rJ9oWm/iXcW7xmcXqrHEfWUaOpJLxS2eaaBbrsIOT0VRPh/jggum/rQQh/GZv1fGFaTs5bJL9iy@UuZn5dfK4pw8KU8tzT@dk90zsqvW8w8): [string](/questions/tagged/string "show questions tagged 'string'") No A, just CAPS LOCK
[Try it online with each row reversed (no input)](https://tio.run/##3VjdThNREL7fpyhIIoWyFCiBgNBAKgYuUPyJRiUtBCWriUiqBAklmw2FSlJi2kTxp01baaVupdoWKNRiMl@XCy825RXOi9SzfQHvz2Yze2Z2duZ8mZPZc74l/9y88qTRkJFXmLZZL9SrRtXV1ovSDBKTgwi6O0eZGp974WehMPSaqnBtbO4OJT0rtW23bCQD0MeYpk2MQJ1dnqUKZQJTTI3hPSLWI8m0HIL9gda1NWWitan0IXapQacKKuaJUlOhD8s4eIN9Fw6mKUnHOKgXnL1MTdEZYmaFjh5iD2X2NsHUMx7TjGJ3pXvAhaPueaSXKGMWqIwI4hvYwTcz2vEMh9z5IuLzQsMuZe8jSkXkkLzUzCJCw53c/BGnnmaGITp28qAdDqOMrdahkS6v7Gx/1H2N26ZXJqfqBQT93BF/8H3V/Lo6Y1QpPUhZDhlRs/Q3YhbNX1agyhRiA3ZbO1Mzig15WeIDm0gX8pJXKECKtC5WgYKCFeipVNsSq0K6dHEkFCIWikv132JB0nISPggFySHdFQrPrIR9oQAtS1QRrELLQuGxtnMxoRDZpBbBKoS8WP8hNcMX3SfRNkAOoQC9lNhmSrBTkVEW7dzKeze/H/@/hyCv9PWOu5BuUh1XjQSdYkdZhD4BnUd4tWQRGIcWr/GOC8oZVZuzf2y85zrX/HYujCr2KEVZm@WTo0qTEkHJZVEafUxN3WKaRqkePuLrxo7c86uk@yjDw15h6hdolMYPymCTqUnskm7ZdIfbY6ka/@gGlWcWalsIL3JF5gkO61U3ZblwU8Z3O4C0/6ZxbhZlnPU0mZUAVVgobJZG6eSB3de10cW7SmCdzy7eZol7ygJ05F7Xtnkmz5CtBWGeilJ8PsY5F0z9aSFO4DN/r3gV5OVG4x8): [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") Print a Tabula Recta!
[Try it online with both the rows and each row itself reversed (integer input)](https://tio.run/##3VjdThNREL7fpyhIIuVnaWkJBIQGUjFwgeJPNCppIShZTURSJUgo2WwoIAnEtIniTwmttIJbqbYFCrWYzNflwotNeYV9kTrbF/D@nGxmz8yZnTnfzmT3zMyGJqeUJ7Wapcb5euz435CRVTydQ16koFdU5aqxS6fYUGagD0NnC69mLS2DQ57hHRPKGGWHq2twyH2duZCTiVHGNiXpwGHrZKg0MTdBJRS82K/mPJaavGVpGiXdPLNWkk5knl8lPUhpNnvFUr9AoxR@UBorlprAFum2TG/z@W1W44duUHF8urKKzRlmZHZwWC376ICJj9LB22GkQjeNczMv48ytVFToYSpZ65tmYYBOHjiD7cvtlpoOL/Hudppsck@Zho7M68oae/L3Ohqwya4oyfsxzplY6k8b8S4@87oSUJCVJaPoEGkgK3EohIKkSG1C4XkpWeonsZJOl5AVChF/V6QGoRDJnHVxoRA5pDnBIkQloQBNSNgTCtCcdFe0AH0QClCbVP0t1n9Iy0gXR2JBWt@RKquinX8CQgF6Ki2JFaCIYAFS@DSXFq1wtfsVlrZSzVXLRtnb1InCOHZHehDxtQ5wdT/5IsTFf72Vwdzg5B1K@Ocraz7ZSIShD1qaNtwPtd6ioHR41G5ZvEfUviXsqj/SFW5cXFSGG@uMB/FLDTqVUDJP6r2FPhn7b7Dnxf4YJejYbnG4Oi01SWeImyU6eohtFK23u5Z6xjbNGLbmO7q9OOqYQmqW0maOiohiZxkb@GbGWp7hkJUvosEANGzRwX3EKI8MEpeamcd6XyuLP@LUX/fQS8cuNtrSZhSx2tjb3x6QXc2POq6xbGx@ZLSaQyTEiviD7wvm14Vxo0ypHjpgyIiZhb9RM2/@sg2VRhHvdjqaOTkUfqNyreb2uP8B): [number](/questions/tagged/number "show questions tagged 'number'") Am I a Rude Number?
[Try it online with both the rows and each row itself reversed (string input)](https://tio.run/##3VhbTxNREH7fX1GQRC5luZVAQGggFQMPKF6iUUkLAZtVYyVVgoSSzYabJBADieKlhFZaqVuplgKFWkzm6/Lgw6b8hfNHcLZ/wPdzspk9M2d25nw7k90zEwqPjWuTl5dCj/L12PW/oSKjtbX2e5CAWdK1q9YOnWBVC8IcgMkWXoWEkcY@z/COCaWtoqu5va@/5Tpz4TomVhFbFKeUy9FJU2F0apQKyHmwV862CT1@SxgGxVt4JhbidUg/u0pmgJJs9orQv8CgBH5QEgtCj2GdTEdmur0@hzX4oRuUH5koLWEtyIzKDvbLRS@lmHgpGbgdQSJ80zqzD1SctmglHWaECmJlzc710vGDukDjfKPQk5E53t12jUPuaRMwkX5dWmZPvi5XFdbYFcV5P9YZE6H/dBDv4DOva34NGVWx8i6ZBjIKh0IqSJrilgrPS0Xon@RKOlNBRipE/F1RqqRCpHLWRaVC5FKmJIsQFaQCNKpgVypAU8pd2QL0QSpAbqX8W67/kJFWzg/lgrSyrZSWZDv/@KUC9ESZkytAi5IFSOPTXFK2wtXpVwhjoZwtF62ip6YVuRHsDHZi0dvQy9X92IswF/@VVgZzfWN3KOabLi17VSsWgdknDGOgB3qlRUHJyJDTsniPDecWc6r@xfZI9eysNlBdYdoQvTBgUgEF@7jSW@hWsfcGux7sDVOMjpwWR3Or0ON0iqhdoMOH2EJevN0R@inbtDexPt3U4cFh0zgSIUraWcpjA9vzWMU3e7P@KfZZ@Xwj4IeBdUrdxyYdII3YhWEfYKW7gcUfceKreOiio2Y2Wu@28liq7upp9KvNtY@arrFseHpwqJzFYpgV8QffZ@yvMyNWkRKdlGLI2LRzfzfsA/uXY6gwhGhHnauWk0PjN6peXgZDoeDzyX8): [string](/questions/tagged/string "show questions tagged 'string'") Don't google "google"
[Try it online with both the rows and each row itself reversed (no input)](https://tio.run/##3VjdThNREL7fpyhIIoWyFCiBgNBAKgYuUPyJRiUtBCWriUiqBAklmw0FJIGYNlH8KWkrreBWqm2BQi0m83W58GJTXmFfpM72Bbw/J5vZM3NmZ863M9k9M3PBqWnlSa1mqTG@Hjv@N2Rkla7OYQ9S0CuqctWI0yk2lVnoI9DZwqs5S8vgkGd4x4QyRtnh7h4a7rjOXNDJxChjh5J04LB1MlSanJ@kEgoe7FdzXZaavGVpGiU7eGatJp3IPL9KeoDSbPaKpX6BRin8oDRWLTWBbdJtme7y@mxW44duUHFiprKGrVlmZHZwWC176YCJl9KB2yGkgjeNczMv46xDqajQQ1SyNrbMwiCdPHAG2lbaLDUdWubd7TbZ5J4yAx2Z15V19uTrczRgi11RkvdjnDOx1J824jg@87riV5CVJaPoEGkgK3EohIKkSC6h8LyULPWTWEmnS8gKhYi/K1KDUIhkzrqYUIgc0rxgEaKSUIAmJewJBWheuitagD4IBcglVX@L9R/SMtLFkViQNnalyppo5x@/UICeSstiBSgsWIAUPs2lRStc7X6Fpa1Wc9WyUfY0daIwgfhoL8Le1kGu7qdeBLn4r7cymBuaukMJ30Jl3SsbiRD0IUvTRgag1lsUlA6N2S2L94jYt4Rd9Ye7Q41LS8pIY53pQuxSg04llMyTem@hX8b@G@x5sD9OCTq2WxzuTktN0hliZomOHmIHRett3FLP2KYZxfZCe48HR@3TSM1R2sxRERHsrmAT38xoyzMcsvJFJOCHhm06uI8o5ZFB4lIz89job2XxR5z66h766NjNRltcRhFrjX0DbX7Z3fyo/RrLxhdGx6o5hIOsiD/4vmh@XZwwypTqpQOGjKhZ@Bsx8@Yv21BpDLEep6OZk0PhNyrXav8A): [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") Sing Happy Birthday to your favourite programming language
[Try it online rotated 90 degrees clockwise (integer input)](https://tio.run/##lZhbS1RRFMff/5/idIEybfIWRVcMM@qhsgtFNahRySnIxJKKimEws0CJgu6Kmlo2k1Ne0pws2Gumhx4O9hXmi9iZXvttMN/87T1r77X22v@19unoajsfXlxZSVgutPuXLFPqGyqls1XJzmQiSJRSE5a5FlouIcsF//5ZTkCDUCHQFsXmcPZGoKXUG7Rtr1VBeFjbyEo6KxtE8590yPMDl4eB4vd4@6OeX0SfYcCNKprBpUf06wn50K9oFvga2VMKhUrpNOAdcpOAG7XdE2Y3DgOFByouAb@hZtp6VjcJZxS9BX4BZ4eyD4BPyn7gzoc8JxKoC@B62X2PmeVptEL5cUcHgd5VN5qe0GHgm@N9U07e0y6cvQVoq84CrcCrdFrVlJ7zSgDeoxag0aw2k4d9/dpNtvPagWFay0livZSBKRUXME2qgNZoE9le9MQ6gTGJZuS@8OUnf47ILQLu8uSljasRo2JfAR@TvcSDN7r0bkKVgPdqJ1LrA7y8xILlJvU7zWZG2IxlycyU3AxrB@pbQqfwUo2yvrXLBlhUMWCFXkz0C2oF2qyfJNhuQaWHwzBwQDbl2ftl2mMak7dcKKKnKOX2js/jEeAq3fPcuiFPQTB0NiNH19EGFE17du@o3luPOjiDjQqRfdR5mj6OuhiH0uY8btUDX@dtG7bwHrv5Tg5wxPD4Nng06UrMF/mCcJpVyOhESj2jshee/DuD2unmPA1MHqOT5qbqKOtheVlWxDrVkoBMozjbey7U9bL3NH2WtTyuTY5kK4m1upONJzGZYtM2xgd4C@MyyNYDrMyxDO/kU7IMLfpChRTVsiXszsubieY5yfJY5LBN/usTbWc/15AazqR9qgPawC3c1rgRpoJTje1GoKbVR8VlddvjJXF7jEuWp9@l6VPa6nu0kKMdHkevcyEuL8tKUxZ/0vgm2TOeznbasUcO2dlHXA7cV8@Da1hJFM9OXDLJHaSl2J/d3J81ob7wO2ufGoDWcvrXYUxCFUf4WZ3Ahmgv5nPhAeJupI1IUREDHUfahrSBn6ipIeQhe5JCjBGNbff1r/r1F@jqf/ji2/UepJVI@azwXgf4NA/wqRmbGEbczJNnEdciXY@0Hil@HAi07MHTng8YPavOjnP8CaoscuXvVC13Wgq9P@eWv9nzEzbm8p3xwBrLlVKvquJ@qLgQ/7uyUlP9Bw): [number](/questions/tagged/number "show questions tagged 'number'") Fibonacci function or sequence
[Try it online rotated 90 degrees clockwise (no input)](https://tio.run/##lZjbTlNBFIbv/6fYHhJFaVXAaDwGgxi9UPEQjdogxkO2GpGgRAmapkFEE4jRxLMEUPDQSpWDIhVNZrVceLGDr9AXqbve@k2C3PHNdM2sNWv@tWa3d7adCc9VKknLh3bnvGXL/UPlTK421ZFKBslyetyyV0PLJ2X54N8/ywtoECoE2qrYHM5eDbScfom27YVqCA9rE1nJ5GSv0Pwn7fP8wBVgoPQj3v6o5xfRZxhwo4qmcOkR/XpIPgwomga@TPaIQqFyJgN4i9x7wE3a7AmzG4OB4l2V5oFfVwttPacbhLOKXgM/i7ND2QfAR2U/cedDnhMJ1AlwpeyOx8ziJFqh/OjRXqC31IWmx7UfeCLeN@XkbW3D2euAntZJoDV4lY5rPaXnVyUB71Ar0GhaCfKwf0DbyXZBWzBMyzlJrI8yMK3SLKZJLdANWkO25zyxTmJMoim5L3z5yZ8DcnOAOz15aWNqwqjYN8CHZM/w4I0uvRvXWsA7tRWp9QNenGfBcu/1O8NmRtiM5cjMhNwUawfqW1LH8FKNsr5dkA2yqGLAin2Y6Gd1GmiLFkiw3azK94ZhYI9swrP3i7THDCZvtVBEj1DK7S2fx33AtbrtuXVDnoJg6GxWjq6jDSqa9OzeUb23XrVzBhsVIvuoMzR9DHUxDqXNeNxqAL7C2zas4z128Z0c5Ijh8a3yaNKlmM/xBeE0q5HRiZR7R2VPPfl3ArXTzXgamAJGJ8NN1UHWw@qyrIj1qiMBmURxtndcqBtk72j6NGt5XJscyVYKa3UHG09hMsWm7Q0f4E2Myyu2HmBljmV4K5@SZWnRpyqmqZbNY3de3Uz0lZOsgEUO2@S/PtF2dnMN2cCZtEv1QBu5hdsYN8JUcNZjuxGoeelRcTl1e7wkbg9wyer0WzR9Qht9jxZytN3j6DUuxNVlWWmq4k8a3yx7zNPZzgXskUN29j6XA/fN8@AaVgrFswOXTHEHaWn2Zzv3Z82oL/zO2qVGoHWc/vUYk1ClEX5WJ7Eh2on5XLyLuAtpE1JUxECHkbYhbeQnanoIeciepBFjRGPb/QNLfv0FuvIfvvh2vQPpWqR8VnivA3yaB/jUjE0MI27hydOI65CuRNqAFD8OBFr04EnPB4zeJWfHKf4EVRW56neq1p7WYt/CzOJ3e3LE3rhCRzywzPLl9PPauB8qzcb/ViqVROJKe@JyW/fNPw): [number](/questions/tagged/number "show questions tagged 'number'") Count up forever
[Try it online rotated 90 degrees clockwise and then each row reversed (integer input)](https://tio.run/##lZhbT5NBEIbv31@BaKIolHM0IhgMYvBCxUM0aoMQ1HyaiAQlaNA0DSdNIAYSzxBAQbRIFUQrFU2@abnwosG/0D@CW2999oLe9dnt7M7s7Duz7epp7wiubm1FLBnctkQ@Nh8pikS7o6X5@GJ@ZMoS12wwsGREliz6/2NJBYCL1AYwwLluReVjr2Fkj@wVGrdpoCVyOwa@31n/RFuf9PzguLI/AYdpz/x8bFbhLAzkPrulZ2hgRTYK/Pe4dtD0L6Iw2IQO0nbicTXR/t97wnxAmWGaP6e7gLPrMopCqywBuE@d5NEbTIU@nSM/P7iNT9HAL4xL4Tx2Ae/xmRlEM5vL6sfseAC0xdmeB96rMqAn9BD3PYmzD@kK0HKVAL2kC3iRwm@AK9QANKLcF8Btyo9QzpYpTAOuxzAd5CQpViZGBzOEWZJNqRJwqWwN8F5FPLHOrWBM@PJ/1Un0p4cmr8nmPIlJUWnSafL@O567vVBImWZxHQa8D2mdNtfJxojC96xXZOVP3GNmRuES8UWWjnAFz8jpm4sYDJzXddY3FFUbU2aIA9aJed4K9IrCFOCNcR2jg3407dm6LcniwG94KsVelPLcBJ6HvVMp4cd86x566oFNKaT5Ni4bo8CnfGVuWTZAP5jnFO6SfaR15xTSdergUJb73FrVTsA13rYB91iOl7LXE7Ex7ebju@nRJOMGYw3F/l@aDWCapXz59xy18yI3MOGqCw7FOJfWKU9Lhcs6Raz2COLmMgxUyRZQnGu4UBtVLFvg0uS0PEp4Rt1Yq6PbsF3DJ2hvXWAmYeAed3YLrMMRPqY62XOyklCW5DkT82wmwCzLfcMiZ2mPFdcnH@XdVHINOcKZ1Ai4WrXcwFVgI7yI0S3msDQrXMSgsJv3ZU8Q8/RiGZXEBx71qVUXO3rH4yiv6ioxSn9Bapo9Eo9C9hRLbsFMgD2yPUZnw@9cDrLTnEiknlFcsptbyKjHnxh3aPUoMM2YooV3VhXwRpQ6l/4BhgSf1dkZ7IgimM@HkWaGEfcibULqFJHwGaTtSBs9L7Qp5AF7EmORTLDtkVHkPUhvbcMX364bkO7bxll5XqAHkLawiWnErTyZ/1CoQroLaQ3S7Do/pdd9L2yMc3xAl7ehxJYsDGRTrhUqzcdeWnKH@9odpu3tWXu2@WNjNTPU1t9W@GNra6uy8i8): [number](/questions/tagged/number "show questions tagged 'number'") Is this number a prime?
[Try it online rotated 90 degrees clockwise and then each row reversed (no input)](https://tio.run/##lZhbT5NBEIbv31@BSKIIFAWMRESCQQxeqHiIRm1Ag5pPE5GgRA2QpgFEEojBxDMEEBAsWuWglYom37ReeNHgX@gfwa23PntB7/rsdnZndvad2XZ2X7kaXNvailgyuGOJfGw@UhSJdkXL8/Gl/PCkJa7bYGDJiCxZ9P/HkgoAF6kNYIBz3YrKx97AyG7ZazRuU0BL5XYM/ICz/om2PuH5wXFlfwAO0575@diMwhkYyH12S0/TwIpsFPjvce2g6auiMNhTHaTtxONqov0vesJcq8wjmj@ne4CzGzKKQqssAfi@Osijt5gK93WO/HzvNj5JAz8xLoXzKAHe7TMziGY2l9WL2dEHtMXZngfeowqgJ9SP@57A2YfUDrRSpUAv6QJepPAr4L06DDSi3CrgNuWHKWcrFKYB12OYDnKSFCsTo4MZwizJprQPcLlsHfAeRTyxzq1gTPjyf9FJ9KebJq/L5jyJSVFp0mny/hueu71USJlmcTUALkNap80NsjGscJH1iqz8iXvMTCv8SHyJpSNcwTNy@uYiBgPndYP1DUXVxpQZ4oB1YJ63Am1XmAL8a1zH6KAfT3m2bh9lceA3PZViD0p57imeh71TOeERvnX9nnpgkwppvo3LxijwKV@ZW5YN0A/mOYU7ZR9o3TmFdJ2ucigrfW6taSfgGm/bgHusxEvZ44nYmHbx8d3yaJJxg7GOYv8vzQYwzVK@/HuB2nmRG5hwzQWHYpxL65SnpcJlnSJWewRxcxkGqmQLKM41XKiNKpYtcGlyWh4lPK0urNXRbdiu4RO0WReYCRh4wJ3dAutwhI@pTvaCrCSUJXnOxDybCTDLcl@xyFnaY8X1yUd5N/u4hhzhTGoEXK393MDtxUZ4CaNbzGFpVriEQWE3H8qeIObpxTIqiX0e9dmvTnb0rsdRXtVVYpT@gtQ0eyQehewZltyCmQB7ZBtBZ8NvXA6yU5xIpJ5RXLKLW8iox58Yd2j1KDDNmKKFd1YV8EaUOpf@AYYEn9XZaeyIIpjPDUgzjxD3IG1C6hSR8BmkV5A2el5ok8gD9iTGIplg28OjyLuR3t6GL75dH0Zato2z8rxAa5G2sIkpxK08mf9QqEJagrQGaXaDn9Ibvhc2xjk@oMvbUGJLFgayKdcKledjryy5w33tCtM2e9aeb37/tZYZauttK/yxtbX1Fw): [quine](/questions/tagged/quine "show questions tagged 'quine'") Print the last, middle and first character of your code
[Try it online rotated 90 degrees counterclockwise (no input)](https://tio.run/##lZhZT1NBFMffz6coSKIIFGSJBgSCQYw@qLhEozYscUk1EZuqQQPkpimLJBADieICgQoIFqmyyCaYzGl58OEGv8L9Inivr/7moX3rbyZnZs78539mble8ozN67/Aw7DnzbT1t2YH99YOf@vaazpqdmOdMFmjGc96XeslUbtP/K5oJ/f8LGqLA74iXSAIPycEK413EOcbVSIuQViLVNcSt3Hka8XmkpzhEP@JGpCVIG5B6zhTyDqSPkcY58tAILyWNOOsgjuY166Y81nIVqZlB3Iz0Oa9kMI@9CgMMS45moRnpBRzljFZhMir9g5UAfkZagFZLPc1jTpQ2S9MSAZx1JIbTps5HxewAzk2LmQdutjAlOiwXcEjfb4A/EH3D69Ex4C2WMEH/GYvJeYklaHnK57pLaihMYokXuyyFllFfUvfXiG1ObJZQGbldHDRkWWgFL7RGqoA2iU6iRP@Qck@w/M@ykP5VImqIi7sBuBiTEkRBv/LTgrPRCamj5Kbw/JtF0QXM7gvbkmZp0CUsdGaHo0fkItAYO2JEzI88YusaF@5qqaDeC1h1D1b8g5dCqzPbmJgUK@myuKiNRELMOm/TLVbehG3YTWpIpsR7NY0q85xt3kG2mkfijqN76ijNP42Vql3KqfO8nLS4D6npiOg6JuEjRteEdNKgfkmZo@5fpYvniOVAk@Ku4GxmxNCW6ChbvJ8xnbIsq89i/cPAS0U/A27k7WuW45bJP@RU6rJFfyyzc7KPi92UdsCt0gb0rii5cHaApacjYhax5N6wHZ1xvBGZVT4fSuXGLHMlPtjlGuLvx6rFh4c4TB1GKUGKCfMlrO/wUOoW4Ct4A@21GKJ/Q0NHjEst0Evs5bk9NGd31eJJYVSvbkspemduk@@yA3yFLORTV4tZqefSVEaSGxpBnbtrWJobMCdmQ44Bvim30ezLcd9PAy2z5LoPa3UZ2rz/PsenZi/ekXtsL2y8wPnvMHz9FVmE6Yf5ZQmjX6DhunSjStxPaE3dLJJWtg78OPBMDBWi7CA@zIN6gP7WbHln1bK/hcSlDwoF8nuMTRX9KqgU7ne@wPB@BFWdH1x7qI6gP16pPOeb9dpQTEuYFkqDfsCDFKTZlzFKge7nbRg8yt@g/Gd1WDNR7b@vaW9oyp9xaSQWCYeCD1uafhLVTPjw8C8): [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") Build me a brick wall!
[Try it online rotated 90 degrees counterclockwise and then each row reversed (no input)](https://tio.run/##lZhbT5NBEIbv51cUJBEECnKIBASCQYxcqHiIRiUc4iHVRCSoQQLkS8NJEoiBRPEAAQQEi1RpkUJFk52WCy8a/AvfH8Gttz6bSO/67HZ2Z3b2ndl29XR0hu4eHvrebDrhDy0W@d5bjebYr90mqUtX9fXB9/2t1Ehbf5vvrQTFDgT@/WhUbgMOCcCAHx5CfrDJeA9xmnEF0jykZUg1jriFJ88jPo@0ik0MI65HWoi0juPszSHvQPoIaQ9bHptgVyKIUx7i0JF23XAEX64gNQuIG5E@Y09GHWcVBBoUjVLiLkgI8ICUc0TLMBhn8GKFpQJ4k@gy4FrRCC3pScoD3orb7pbjODc9TyeQFLNDfEV0HGNCSzbLfcybWYc/r6SJ8BRPz9pxiNyCPMGor0sX32s7BAOVohvoLC@bK/oScJ9jep@Ydbxs6T1MjQAuWepwtJIdbQBcjjmqs3IS8O@wnOX0Zy9tJvXQ/KQUAM5sO8w4omIFS2d4O2YReI2YNRQAFMlVx2aei9LJ6ZKYJFa6VrbeDfgCTraKiKbNN9E4G6/gwq2rwEvlYBPLbjneu0UbF4qu2ZVLnElW8Oi0k3xKZgtT76ZjWZ0R2w/RQAKTzH8xzwfoe7vy0KE0JJ6ZaTEoZJPSjpXKrAAucajPKTmGyeR772nNLdEwWjdUUjpFP5OVZd5jl@gQlwPfW6DI2ESbpB8kHBGbcrk1x@I/KEU0e1zqCX@URj4@3v0JDuUDV/5tyDlHmpkEDOxPSQvgdrkDtE1SI7RmWHSCU49qrllz7P06NkQ6zRfExMRQRdR1OdjjQlzPNQRlOBNzmBlDMzVICzmDbcDoTuobuUx4RwawA8X@LKuIPayHFwFXS/oHa3kmhuIcdHVRu5i8pJ1F2KClE9xB6gjfulyMSjXXplqxrw/gxZKJY6LXYWU22xiTG0DzUe5v4cGXSDHQ0zLoiHUx1mr70kahH8CnZj/2yI4Xtn1ecQuX9/@vv7@VGs38lGuEP2Ga9KIyZT5wkvSydrTIU/5zIDVKl2HZURCqUMqtvlU73lkB1rcc8ijOovprylXmYtzAZL46anr2RPjyJx2/aLZLf3E1Vdw2KL3oCkTfUSgcYc7HRLDpLm3YnYfQNj6rNSpBjYYeayT7P1Ug2NrdWmRd8cfmNHJPh0MaDR4e/gE): [string](/questions/tagged/string "show questions tagged 'string'") "Hello, World!"
## Explanation:
In general, I mostly rely on the builtin `q`. This will stop the program, making everything after it no-ops.
In addition, for the four main rotations, I split them up into integer/string/no input with:
```
.ïi # If the (implicit) input is an integer:
# Do something with the integer-input
ëĀi # Else-if the (implicit) input-string is NOT empty:
# (using the Python-truthify builtin `Ā`)
# Do something else with the string-input
ë # Else (there is no input):
# Do something else without input
```
For the two clockwise rotations it's similar, but only with integer or no input (since there aren't any other challenges available with input from the list in the challenge).
And for the two counterclockwise rotations it's just a kolmogorov-complexity output without input.
Some things I had to fix for the rotations include:
* Adding an additional space between the `.ï` and `i` at the start of the first line, and a space on each subsequent line. Without this space, the middle character for subprogram of the *Print the last, middle and first character of your code* challenge would have a newline character as the center, which isn't possible without screwing up the layout. With that added space, the middle character in that rotation also becomes a space (the first and last characters are both `.`).
* Adding `\”` at the end of the final line. This is to close this string and discard it for the programs with all rows and each row itself reversed, which will now contain a leading `””\` followed by a bunch of no-op spaces.
* For most rotations I reuse the `.` for the `.ï` (is\_integer check), but for one rotation it's `.…` instead. `.` opens up 2-byte builtins, but since `.…` doesn't exist, the `.` is a no-op instead in this case.
**As for an explanation of each individual program:**
*[ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") Do you want to code a snowman?*: `…( )7ÝJ»•αγʒδÓ₂©8¥ŽQxΣxêÿ•sÅвJIvN”</[(0._-=:"ÆŸ,*”0¶:º•DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλݺ•20в趡Nè4äyè.;`
[See this answer of mine](https://codegolf.stackexchange.com/a/177700/52210), except that the actual newline is replaced with a `0`, which we replace to a newline after creating the string with `0¶:`.
*[ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") It took me a lot of time to make this, pls like. (YouTube Comments #1)*: `ηû»`
[See the second program in this answer of mine (provided by *@Grimmy*).](https://codegolf.stackexchange.com/a/180517/52210)
*[string](/questions/tagged/string "show questions tagged 'string'") 1, 2, Fizz, 4, Buzz*: `тÝ3Å€"Fizz"}5Å€á”ÒÖ”J}¦»`
[See this answer of *@Grimmy*.](https://codegolf.stackexchange.com/a/186380/52210)
*[ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") It's my Birthday :D*: `_i“Ûà€‰€ž€¢‡Í! :D“ćuìëdiU„ $„ |}…-~-`)X·>δ∍»}`
[See this answer of *@Grimmy*](https://codegolf.stackexchange.com/a/191540/52210), with additional trailing `}` to close the if-statement.
*[string](/questions/tagged/string "show questions tagged 'string'") Covefify a string*: `1ú.γžOså}R`¦??н©?н®ì.•gÍĆdQ¸G•Â‡D?,`
[See this answer of *@Grimmy*.](https://codegolf.stackexchange.com/a/198765/52210)
*[kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") Hare Krishna Hare Krishna Krishna Krishna Hare Hare*: `“«Î‡Ä¦í¥Â“#€¦`«'kì)™•1¢₂P•3вè4ô»`
[See this comment of mine on the answer of *@Emigna*.](https://codegolf.stackexchange.com/questions/117842/hare-krishna-hare-krishna-krishna-krishna-hare-hare#comment432049_117855)
```
“«Î‡Ä¦í¥Â“ # Push dictionary string "drama share irish dna"
# # Split it on spaces: ["drama","share","irish","dna"]
€¦ # Remove the first character of each word:
# ["rama","hare","rish","na"]
` # Push them separated to the stack
« # Merge the last two together: "rishna"
'kì '# Prepend a "k": "krishna"
) # And wrap everything on the stack into a list again:
# ["rama","hare","krishna"]
™ # Titlecase each: ["Rama","Hare","Krishna"]
•1¢₂P• # Push compressed integer 27073120
3в # Convert it to base-3 as list: [1,2,1,2,2,2,1,1,1,0,1,0,0,0,1,1]
è # Index each integer into the list of words
4ô # Split the list of words into parts of size 4
» # Join each inner list by spaces, and then each string by newlines
# (after which the result is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“«Î‡Ä¦í¥Â“` is `"drama share irish dna"`; `•1¢₂P•` is `27073120`; and `•1¢₂P•3в` is `[1,2,1,2,2,2,1,1,1,0,1,0,0,0,1,1]`.
*[number](/questions/tagged/number "show questions tagged 'number'") You're on a 8 day streak!*: `₄внŽ4$2ôQàI8Å?+>„ans∍`
[See this answer of mine.](https://codegolf.stackexchange.com/a/165283/52210)
*[string](/questions/tagged/string "show questions tagged 'string'") No A, just CAPS LOCK*: `„AaS¡Dvć?.š`
[See this this answer of *@Emigna*](https://codegolf.stackexchange.com/a/158160/52210), although without `õ?` and with `.š` instead of `š`, since his answer is built in the legacy version of 05AB1E instead of the new one.
*[kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") Print a Tabula Recta!*: `A₂F=À`
[See this answer of *@Adnan*](https://codegolf.stackexchange.com/a/86994/52210), although with `₂F` instead of `Dv`, since I personally prefer to keep my programs as straight-forward as possible despite codegolfing (where `₂` is the builtin for `26`, and `F` loops that many times).
*[number](/questions/tagged/number "show questions tagged 'number'") Am I a Rude Number?*: `32B4å`
[See this answer of mine.](https://codegolf.stackexchange.com/a/180532/52210)
*[string](/questions/tagged/string "show questions tagged 'string'") Don't google "google"*: `'Š¹ÊigëF`
Although there is [this pretty old answer of *@Adnan*](https://codegolf.stackexchange.com/a/76257/52210) which worked on one of the earliest versions of 05AB1E when he posted it back in 2016, it doesn't even work anymore in the latest legacy version on TIO from around mid-2017, let alone in the latest 05AB1E version. So instead I now use this (which is also 2 bytes shorter anyway):
```
'Š¹ '# Push the dictionary string "google"
Êi # If the (implicit) input-string is NOT equal to "google":
g # Pop and push the length of the (implicit) input-string
# (which will be output implicitly as result)
ë # Else:
F # Start a loop using the (implicit) input-string,
# which will result in an error if it isn't an integer
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'Š¹` is `"google"`.
*[kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") Sing Happy Birthday to your favourite programming language*: `”to€î”Д¬Ž 05AB1E”s)”ŽØ¢© ”ì»`
[See this 05AB1E answer of *@Grimmy*.](https://codegolf.stackexchange.com/a/191407/52210)
*[number](/questions/tagged/number "show questions tagged 'number'") Fibonacci function or sequence*: `Åf`
```
Åf # Given the (implicit) input-integer `n`, get the n'th Fibonacci number
# (after which it is output implicitly as result)
```
*[number](/questions/tagged/number "show questions tagged 'number'") Count up forever*: `∞€,`
[See this answer of *@Sagittarius*.](https://codegolf.stackexchange.com/a/197473/52210)
*[number](/questions/tagged/number "show questions tagged 'number'") Is this number a prime?*: `p`
```
p # Given the (implicit) input-integer, check if it's a prime number
# (1 if truthy; 0 if falsey)
# (after which it is output implicitly as result)
```
*[quine](/questions/tagged/quine "show questions tagged 'quine'") Print the last, middle and first character of your code*: `.…. .`
As I already mentioned earlier, I added an additional no-op space to the program so the middle character in this orientation would be a space character, instead of a newline character. The first and last characters are `.`, so we'll have the following sub-program:
```
. # No-op, since `.…` isn't an available 2-byte builtin
…. . # Push 3-char string ". ."
q # Stop the program, making everything after that no-ops
# (after which the result is output implicitly)
```
*[kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") Build me a brick wall!:* `.…_|_ĆƵм×Tä»`
[See this answer of *@Adnan*](https://codegolf.stackexchange.com/a/99032/52210), although golfed by 2 bytes by replacing `"_|__"` with `…_|_Ć` (push 3-char string `"_|_"`; and then enclose, appending its own first character) and `175` with `Ƶм` (compressed integer).
*[string](/questions/tagged/string "show questions tagged 'string'") "Hello, World!"*: `”Ÿ™,‚ï!”`
[See this answer of *@Adnan*](https://codegolf.stackexchange.com/a/67457/52210), except with trailing `”` to close the string.
The `]` you see before the `q` in each program is to close all open if-else statements and loops before doing this `q`.
I'm unable to fit anything more in it from the list in the challenge description. The ones left are three ([kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'")/[ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'")) that require you to output something without input (which I have already used in all eight rotations) and four [quine](/questions/tagged/quine "show questions tagged 'quine'")-related challenges, which are just impossible with this kind of layout in 05AB1E.
If there would have been more challenges taking integer/string inputs, those could have been added as well.
[Answer]
# perl -M5.010 -Mbigint, 8 orientations, 8 18 tasks, 1644 2840 bytes
```
####################################################iA;"/sv)=-=f{.{ei#
if(eof()){say+("11 *25 *\n7 4*10 *5 *10 4*" .##cAc##f.e[^ag.(-po$./lf#
"\n5 4*12 7*12 4*\n3 6*12 7*12 6*\n2 9*9 9*".##'+b##(.x^(yk$$$orp\*^s(#
"9 9\*\n 47\*\n49\*\n49\*\n49\*\n 47\*\n 5\*7 21\*".##@wM##eYi$$$k3x_d =).ee#
"7 5*\n4 4*7 3*4 5*4 3*7 4*\n7 **7 *6 3*6 *".##@@E##o;tvc1g)[>#2$.+{o#
"7 **\n")=~s/(\d+)(\D)/$2 x$1/gre}else{chomp(##4`c##f/}]*.px1=%._(?$f#
$_=<>);if(/\D/){/^google/&¨$_=length}else##":B##(.$"$(b ]00.>?(_(#
{$_=sprintf"00%b",$_;$_=/00100(.{5})*$/?1:0}}##VQl##){_;v(s2,;#$1{?=)#
say;#[447}E<vFX**gd's<kN6iiX#gS0qnsHgj'M%um$###>fr##)2=$*(z)$son;s{<)#
=pod#+RvC!y-9UwQ7ImGlBV03'UoBoqY:#OR`6z&C_;0###$I7##{6<v({t}xa+-$as>{#
[$1=~y,a-zA-Z,A-Za-z,r]ige}};say;#zG}B2|M}TI###X^4##$}>=$sde[yQ2nya;{#
"ur new baby! :D"}}else{s[a([^aA]*)a?] ##l"}###/)u##_(;"cpvl0$s;=$ycs#
$/,grep$_,@x}else{$_="Congratulations on yo".##"(O##=?$[)lfs]x9s$1$ha#
' $'x$_,' |'x$_,'-'x$x,'~'x$x,'-'x$x);$_=join##ZSo##j{v$)ize+[Ja_}&oy#
;if(/^-?\d+$/){if($_){$x=1+2*($_<0?1:$_);@x=(##)<V##os=v$ts{$0Jy;)}m+#
if(eof()){$_="Hello, World!"}else{$_=<>;chomp##WJ+##iaa]c/}@x]^!$()p+#
###############################################JvE##nye"*/-x[}@!p?(;$#
###############F+g@,ZHTSgmA|[\N"0`EV(>QJ'=b(9]+FJY##"$i;(,>=1#>$&!?i_#
###########.###lq{$LWnQj&g|l27@'o}Tr@VFDBI`K#np#7g##"&oi$b{(]6>p&)!f;#
#9Tj=~7D#Sxy{##.YTb}.:7dj+t|4-8Fo\GZJ?E=L7CWYq-RVu##,}ufvp$0){/}=/)(r#
#7$_j;&Q,A$b###<M+agLQ5{_6z^mL6V:VVo;Azb`4<5tAUx9###A)y()c2,wwd}$x//e#
#L[vlh(sa#ya(##hOy>[A&.[usZ_Xzkgn^{qdp|2B{T-g5&$u+##.(;#/g}1h;0#n};\d#
#,zQS#wBpraB.##(Qrc\!&X(_i[Cd1o:vuq76kWY/g0v>xso8|##.?$/)d|)id'[%e/Do#
#{x]V;Gzdos."##eXBcnsw2l?ImMzjJ;0NO045|JIrUh\sT@wh##Z!ca{t|;lCxd$l^/}#
###LuyK/nf;)k##G{3|#3B)J\n"rG__@*w0,6h6m6\MLggprbN##,)=[#f$@eiU\_s()}#
#";M!aBwa x3r##Oj@;),oZ-Yh6gBXx*B-Aq|!Xg;vx!@O7V^_###/###.2x#####e####
#t"]#sLTrr$xa##p79<GL"e"STDrRWLVRHuQY`_zmq;wDu`3cD####################
#ru}~;b'Ggy)h#########################################################
#io#=rgr,/a/S###rof zzuBzziF:zzuB:zziF:_$?3%_$?5%_$?51%_$yas{))(foe(fi
#BYyr!vay_s$ ###Xat(\'7O(>#;a:na?/$*)...(]81[1^|8^/~=><yas}tixe;001..1
# a!l+7m$;.y###iv&.:!Pd.MSjhr6,|E+>cjA(%?NuLB"}ss#8H?<Otd~Bw0zy>#dop=
#yosrrm#m/")b###$#;yas}")".]]7[c$[)" ","___",'" "'," : "(."( n\".]]5
#pt;ae{;oy!6a##[c$[)"$,"\\","$,">"(.")".]]6[c$[)" ","< >","[ ]"," :"
#p yePVaMbkxB##."$(."(".]]4[c$[)"$,"/","$,"<"(./$.]]5[c$[)"$,"$,"/","$
#ayaD!~m,ar""##(.")".]]3[c$[)"-","O","o","."(.]]1[c$[)"$,"_",".",","(.
#Has!u#dyBao(##]]2[c$[)"-","O","o","."(."(".]]4[c$[)"$,"$,"\\","$(./$.
#"d;oodnd/ho(##]]0[c$[)")_*_(","\\_/ ",".....","_===_"(."$./$.]]0[c$[)
#=hytYoadsSd=##"___ ","_ ","___ ",""(."$=_$;g/./~=><}1-_${pam=c@{esle
#_"a!!pra~ x##}5=x _$;g//$..|..^/s;2=x _$;/$.)81x"|___"(=_${))(foe(fi
#$.sss=GD=""$#########################################################
```
Before explaining how it works, let me tell how I created the monster
above. I started off with 8 programs, each doing 1 to 3 tasks. Which task they do depends on the input (all input is read as a single line from `STDIN`) they get: void, an integer, or a string. 8 programs handle void input, 6 handle integer input, and 4 handle string input. If there would be more tasks which take integer and/or string input, we could have handled 24 inputs.
Now, we take the 8 programs, and combine them in the following way:
```
###################PP=PP#
PROGRAM 1 TOP ##RRpRR#
PROGRAM 1 BOTTOM ##OOoOO#
=pod ##GGdGG#
PROGRAM 2 BOTTOM ##RR RR#
PROGRAM 2 TOP ##AA AA#
###################MM MM#
# # # #
# M M # #44 33#
# O O # # #
# T T # #TB BT#
#PT TP# #OO OO#
#OO OO# #PT TP#
#TB BT# # T T #
# # # O O #
#77 88# # M M #
# # # #
#MM MM###################
#AA AA## POT 6 MARGORP
#RR RR## MOTTOB 6 MARGORP
#GGdGG## dop=
#OOoOO## MOTTOB 5 MARGORP
#RRpRR## POT 5 MARGORP
#PP=PP###################
```
Any 'gaps' (whether from short lines, or how the programs are laid out) are filled with random characters, protected by comment characters.
Any lines starting with `=pod` prevent Perl to see the rest of the program; this way we get to have two programs per rotation; flipping the program in the x-axis exposes the other program.
A few things need to be taken care off: programs should finish with semi-colon or a right-paren which closes a block. That way, the final statement is finished, and only then, Perl will recognized the `=pod` as the start of a `POD` section. Second, if we have a construct of the form `s[pattern][replacement]`, with a newline between the `s[pattern]` and `[replacement]`, we must add a space after `s[pattern]`. Otherwise, we may end up with `s[pattern]#`, and that `#` Perl will not see as a comment, but as a delimiter for the replacement part. With a space before the `#`, Perl will treat it as a comment.
Up to the tasks!
## No rotations, no mirroring
```
if(eof()){say+("11 *25 *\n7 4*10 *5 *10 4*" .
"\n5 4*12 7*12 4*\n3 6*12 7*12 6*\n2 9*9 9*".
"9 9*\n 47*\n49*\n49*\n49*\n 47*\n 5*7 21*".
"7 5*\n4 4*7 3*4 5*4 3*7 4*\n7 **7 *6 3*6 *".
"7 **\n")=~s/(\d+)(\D)/$2 x$1/gre}else{chomp(
$_=<>);if(/\D/){/^google/&¨$_=length}else
{$_=sprintf"00%b",$_;$_=/00100(.{5})*$/?1:0}}
say;
```
### No input
Without input, this does the "In Honor of Adam West" task. We're using a simple encoded string, where repeated characters are encoded as `NNc`, which means `NN` times the character `c`. The string is decoded and printed.
[Try it online!](https://tio.run/##nZZpd6LIGoC/@yuwqqKAyGJUEhG37JmkM@mkzeJCUBAxCgZcQCQ/ffq@6Jmcnnvny2041MZbTxXvVsxNb1r6@RP/xmU3FST4K0bNq6OIj0wbp@wRbbojmmEiXw9zNJIkii2UKLbryFSRlUSKhQ5URRZRPMbD5hDjEW92@rrF0/m5S3hhOsIp1HVKiXyBkpOiCPMPqfJXvwz9AnXMHsODAJPNDTCm@aBPh@@EENebs32fBkwi0HWoogxl8fgfxX6QokqsTBWkHaaxvsXYfLEB8X4YaAalMrxpAkYGKZgG@5CpQ7YIvSLU8m5fMsVCiy3DQJnaYxpnGLvKYjWULKZTwwXC5yJ3h2FhAmLUT1@gu0aOobunjEAKVEAkwfLM2Jz6ZjQcu7M5jXHxLdGNEPdYfh5I6gGv0XUCuiGaWq0xCmha6J4KTCT0Lde1pqaQyRi2qcDrqelYi/GOhjGqtBLdEEToAdUTRb5WpzXQTQSC/tyzncUIieLBAHFESyYLoiiJIs1HpZhhiVCXKmIcY9y@n2LMRJqyov0Cp2AiRXWVwSkws4I7xaIcn1VX588saxlZv/r@rWzbz9h6ED8c/9KaZG8PljMCLlMbeYApqISlNwzxXUfxoypg1Llr4Nz31Uk6zB//WN/LV7OLaastHmZ/uC3346WC776/lTeZE00RAUOuZIyjcnVFR4s40HN5ovu1CKc6RFI/Q07Pb5r5Vw4eaHFez7bMOFZ2W91cxK3C9jZ@vALMc78IrLimEt8wO@F9wQl1BTBo6VGOuaYG@iBMU5VTFO9N43d0Gly12WMZvd6jMJ4iUA0WmCXGGq2g4Xw1FYmvqCQc@mApgQOrzonGNYI9APSLTlzH8vTFcqovbNfxKdehQjfxG0TfYazWSYeZjvxecOwTiYx1nMpSJBsAJEtt93UeqoDLfu6rXY9JTDdxbQfj1wcX40m0Ioy9MXOda12LM26IUzuP6efr4HgE3AZ6RGMiEqhSrsBCuyqCrWFIaQQquB9TbYMX@@qKLPyIiNehwsSz3K8RnnzMpTmduhz15HpTI42@PrJaU3ZujPHTdQ4Sha73hkLcCHr9NKGZOWD@z1RzvYKYckITsUI@6MSN9LxOK@R/MOc5q8G9Xj4@WLPmttP9hsS3szZdu7/OqgP6uJc7v34BPRNbobmaKuEayaTrtvYPDBgCTz8icvPk3E8y1nZakBtZN370Gu3z09bV2x/YmWPZAkzGtckgonvl2jzDpEcKYI4fJ@qnfIofgjAC1MvjIOYrsjHJLbbF/NG52714va6fqTfyydPLR/57G/yGi5ej1ZyIEMixKjC0BxiZaBMlc881CeQ1XL3N6dbNfSnSypv@7KbcrrTbrtLcDN6K1dKi@SM4BqEmE9LMsMCt10ZMAkGAtIVvOqvpmPZ1HOpg0PFdWOs0M3xn6b9qz5t3y@lHH8Z8W2hFj3mrlCFLsBRPK1iwYmkMYebEStcADLe5f8Dr1tzTW6Ac@t4bdtOZZ1qzOyeG5FZWyw@5/P70Iljiqhb47tEWMHVwMWPL2Ea2c2AKp5D9cBT02srFxnB9HkGafW4NHX9dmNavZrebybUifrsTi6Xt9ZX3Y9z1HxvrMbhyeqhHi60yPQkMMu0L8c5SN8vwD8EZKcw7xhfR4RYftphryKvehaY12LXIlcflWbl7e2NZc2/wDVTMqB08Ig3T/tHVfJpJMEi5TeuttU4Fh5CR7iYNheHc1/zLuGy1ngO2lW9@bNPPlrIK0o07ud3XkjhP3KMQ7NzETIoUXqAe9m8ePY8EOsZz@bh6cYNM9PB46n1/uml/v1zev7xpm9mHsj5dvh0OT//NuVPYW8afyiB7YYXMGP/ulcK2i1XP8jhBFx5gwHNH1GazbG029nklaVR2LY3UDw@gKO0KCcpQ9yOGoUeuSY/sFG69hF56pYeaT6gkS@oLupuV7@gaVvSKo9cFwjI8z9O9I6kj9bdHfeFTrVUBEi/swFTgAOF5KYUpSk9Pc/KMKHyY/C2sMnwl/afB3z5Mxl6Z257lasNJkz6of1vetFDs@/josl69WxifrbW4CWvYcOdqCoeu73kzPBMQk0QDwUqyEmIQ3@vJnSGkS0RRFOKQpmmIyyIKZTlEVShE84imnG4iV0rh@ULRzUhxw3QZLLWfRzjU7cJMqGuJ@I5Z/pVZpWpQdqgeSpgIMFRo/tnWbwfvAZyrPJyqsEoyrfiFFPbEKhAFkiz@9ebvlymsh/pp@nPG6R5CyfG8X/pwL5kHmTt4XHiADi@kL4S2G@PgpvkUvtT99BIbYUt3IcJ7vcK/A/57h1/fvdshBIOhuK7hGMJ4jxH3kozGajRKZDUhUQafXImiVVXVEizZf@BePIXVcbh4cXXDfzBUyI9gj51Z/jZOUu1mqRpRLIHfeU0s5TUSzfWZOmxEpj81U1hDejoN2eaToiDW4pIaULsJsBa/5fm@4CuF/RiMMEdSgLaJ6WnA/urFhPd9X704VREivx1TP3/@5c535/TP/G2Jh18jqAe2Bb9N/wE "Perl 5 – Try It Online")
### Integer input (non negative)
Now we determine whether the given number is a Rude Number. We take the number, get the binary representation, prepend `00`, and look whether the result contains `00100` followed by `N`s `0`s and `1`s, where `N` is a multiple of 5.
[Try it online!](https://tio.run/##nZZpd6LIGoC/@yuwqqKAyGJUEhG37JmkM@mkzeJCUBAxCgZcQCQ/ffq@6Jmcnnvny2041MZbTxXvVsxNb1r6@RP/xmU3FST4K0bNq6OIj0wbp@wRbbojmmEiXw9zNJIkii2UKLbryFSRlUSKhQ5URRZRPMbD5hDjEW92@rrF0/m5S3hhOsIp1HVKiXyBkpOiCPMPqfJXvwz9AnXMHsODAJPNDTCm@aBPh@@EENebs32fBkwi0HWoogxl8fgfxX6QokqsTBWkHaaxvsXYfLEB8X4YaAalMrxpAkYGKZgG@5CpQ7YIvSLU8m5fMsVCiy3DQJnaYxpnGLvKYjWULKZTwwXC5yJ3h2FhAmLUT1@gu0aOobunjEAKVEAkwfLM2Jz6ZjQcu7M5jXHxLdGNEPdYfh5I6gGv0XUCuiGaWq0xCmha6J4KTCT0Lde1pqaQyRi2qcDrqelYi/GOhjGqtBLdEEToAdUTRb5WpzXQTQSC/tyzncUIieLBAHFESyYLoiiJIs1HpZhhiVCXKmIcY9y@n2LMRJqyov0Cp2AiRXWVwSkws4I7xaIcn1VX588saxlZv/r@rWzbz9h6ED8c/9KaZG8PljMCLlMbeYApqISlNwzxXUfxoypg1Llr4Nz31Uk6zB//WN/LV7OLaastHmZ/uC3346WC776/lTeZE00RAUOuZIyjcnVFR4s40HN5ovu1CKc6RFI/Q07Pb5r5Vw4eaHFez7bMOFZ2W91cxK3C9jZ@vALMc78IrLimEt8wO@F9wQl1BTBo6VGOuaYG@iBMU5VTFO9N43d0Gly12WMZvd6jMJ4iUA0WmCXGGq2g4Xw1FYmvqCQc@mApgQOrzonGNYI9APSLTlzH8vTFcqovbNfxKdehQjfxG0TfYazWSYeZjvxecOwTiYx1nMpSJBsAJEtt93UeqoDLfu6rXY9JTDdxbQfj1wcX40m0Ioy9MXOda12LM26IUzuP6efr4HgE3AZ6RGMiEqhSrsBCuyqCrWFIaQQquB9TbYMX@@qKLPyIiNehwsSz3K8RnnzMpTmduhz15HpTI42@PrJaU3ZujPHTdQ4Sha73hkLcCHr9NKGZOWD@z1RzvYKYckITsUI@6MSN9LxOK@R/MOc5q8G9Xj4@WLPmttP9hsS3szZdu7/OqgP6uJc7v34BPRNbobmaKuEayaTrtvYPDBgCTz8icvPk3E8y1nZakBtZN370Gu3z09bV2x/YmWPZAkzGtckgonvl2jzDpEcKYI4fJ@qnfIofgjAC1MvjIOYrsjHJLbbF/NG52714va6fqTfyydPLR/57G/yGi5ej1ZyIEMixKjC0BxiZaBMlc881CeQ1XL3N6dbNfSnSypv@7KbcrrTbrtLcDN6K1dKi@SM4BqEmE9LMsMCt10ZMAkGAtIVvOqvpmPZ1HOpg0PFdWOs0M3xn6b9qz5t3y@lHH8Z8W2hFj3mrlCFLsBRPK1iwYmkMYebEStcADLe5f8Dr1tzTW6Ac@t4bdtOZZ1qzOyeG5FZWyw@5/P70Iljiqhb47tEWMHVwMWPL2Ea2c2AKp5D9cBT02srFxnB9HkGafW4NHX9dmNavZrebybUifrsTi6Xt9ZX3Y9z1HxvrMbhyeqhHi60yPQkMMu0L8c5SN8vwD8EZKcw7xhfR4RYftphryKvehaY12LXIlcflWbl7e2NZc2/wDVTMqB08Ig3T/tHVfJpJMEi5TeuttU4Fh5CR7iYNheHc1/zLuGy1ngO2lW9@bNPPlrIK0o07ud3XkjhP3KMQ7NzETIoUXqAe9m8ePY8EOsZz@bh6cYNM9PB46n1/uml/v1zev7xpm9mHsj5dvh0OT//NuVPYW8afyiB7YYXMGP/ulcK2i1XP8jhBFx5gwHNH1GazbG029nklaVR2LY3UDw@gKO0KCcpQ9yOGoUeuSY/sFG69hF56pYeaT6gkS@oLupuV7@gaVvSKo9cFwjI8z9O9I6kj9bdHfeFTrVUBEi/swFTgAOF5KYUpSk9Pc/KMKHyY/C2sMnwl/afB3z5Mxl6Z257lasNJkz6of1vetFDs@/josl69WxifrbW4CWvYcOdqCoeu73kzPBMQk0QDwUqyEmIQ3@vJnSGkS0RRFOKQpmmIyyIKZTlEVShE84imnG4iV0rh@ULRzUhxw3QZLLWfRzjU7cJMqGuJ@I5Z/pVZpWpQdqgeSpgIMFRo/tnWbwfvAZyrPJyqsEoyrfiFFPbEKhAFkiz@9ebvlymsh/pp@nPG6R5CyfG8X/pwL5kHmTt4XHiADi@kL4S2G@PgpvkUvtT99BIbYUt3IcJ7vcK/A/57h1/fvdshBIOhuK7hGMJ4jxH3kozGajRKZDUhUQafXImiVVXVEizZf@BePIXVcbh4cXXDfzBUyI9gj51Z/jZOUu1mqRpRLIHfeU0s5TUSzfWZOmxEpj81U1hDejoN2eaToiDW4pIaULsJsBa/5fm@4CuF/RiMMEdSgLaJ6WnA/urFhPd9X704VREivx1TP39Kh9Jf7nx3VP/M35Z4@DuCemBb8Of0Hw "Perl 5 – Try It Online")
### String input
For other inputs, if the input equals `google`, we die. Otherwise, we print the length of the input.
[Try it online!](https://tio.run/##nZZpd6JIF4C/@yuwqqKAyGJUEhG3pLNN0pl00mZxISiIGAUDLiCSnz79XvRMTvc782UaDrVx66nibsXc9KalHz/wb1x2U0GCv2LUvDqK@Mi0ccoe0aY7ohkm8vUwRyNJothCiWK7jkwVWUmkWOhAVWQRxWM8bA4xHvFmp69bPJ2fu4QXpiOcQl2nlMgXKDkpijD/kCp/9svQL1DH7DE8CDDZ3ABjmg/6dPhGCHG9Odv3acAkAl2HKspQFo9/KfaDFFViZaog7TCN9Q3G5rMNiLfDQDMoleFNEzAySME02IdMHbJF6BWhlnf7kikWWmwZBsrUHtP4grGrLFZDyWI6NVwgfC5ydxgWJiBG/fAFumvkGLp7ygikQAVEEizPjM2pb0bDsTub0xgXXxPdCHGP5eeBpB7wGl0noBuiqdUao4Cmhe6pwERC33Jda2oKmYxhmwq8npqOtRjvaBijSivRDUGEHlA9UeRrdVoD3UQg6M8921mMkCgeDBBHtGSyIIqSKNJ8VIoZlgh1qSLGMcbtuynGTKQpK9ovcAomUlRXGZwCMyu4UyzK8Zfq6uyJZS0j61ffvpZt@wlb9@K7419Yk@zNwXJGwGVqIw8wBZWw9IYhvusoflQFjDp3DZz7tjpJh/nj7@s7@XJ2Pm21xcPsd7flvj9X8O231/Imc6IpImDIpYxxVK6u6GgRB3ouT3S/FuFUh0jqR8jp@U0z/8LBAy3O69mWGcfKbqub87hV2N7ED5eAeeoXgRXXVOIbZie8KzihrgAGLT3KMdfUQB@EaapyiuK9afyOToOrNnsso9d7FMZTBKrBArPEWKMVNJyvpiLxFZWEQx8sJXBg1TnRuEawB4B@0YnrWJ6@WE71he06PuU6VOgmfoPoW4zVOukw05HfC459IpGxjlNZimQDgGSp7b7OQxVw2Y99tesxiekmru1g/HLvYjyJVoSxN2auc6VrccYNcWrnMf18HRyPgNtAj2hMRAJVyhVYaFdFsDUMKY1ABfdjqm3wYl9dkYUfEfEqVJh4lvs5wpOPuTCnU5ejHl1vaqTR50dWa8rOjTF@vMpBotD13lCIG0GvnyY0MwfMf0w1VyuIKSc0ESvkg07cSM/rtEL@gTnLWQ3u5eLh3po1t53uVyS@fmnTtburrDqgj3u5s6tn0DOxFZqrqRKukUy6bmu/YMAQePoeketH526SsbbTgtzIuvGD12ifnbYuX//AzhzLFmAyrk0GEd0r1@YZJj1SAHP8MFE/5FN8H4QRoJ4fBjFfkY1JbrEt5o/O3O75y1X9i3otnzw@v@e/tcFvuHg5Ws2JCIEcqwJDe4CRiTZRMndck0Bew9WbnG5d35Uirbzpz67L7Uq77SrNzeC1WC0tmt@DYxBqMiHNDAvcem3EJBAESFv4urOajmlfx6EOBh3fhrVOM8N3lv6L9rR5s5x@9G7Mt4VW9JC3ShmyBEvxtIIFK5bGEGZOrHQNwHCbu3u8bs09vQXKoe@8YTedeaI1u3NiSG5ltXyXy2@Pz4IlrmqB7x5tAVMHFzO2jG1kOwemcArZD0dBr62cbwzX5xGk2afW0PHXhWn9cnazmVwp4tdbsVjaXl1638dd/6GxHoMrp4d6tNgq05PAINO@EO8sdb0M/xCckcK8YXweHW7xYYu5grzqnWtag12LXHlcnpW7N9eWNfcGX0HFjNrBI9Iw7e9dzaeZBIOUm7TeWutUcAgZ6XbSUBjOfck/j8tW6ylgW/nm@zb9ZCmrIN24ldt9LYnzxD0Kwc5NzKRI4QXqYf/6wfNIoGM8l4@r59fIRPcPp963x@v2t4vl3fOrtpm9K@vT5evh8PTfnDuFvWX8oQyy51bIjPHvXilsu1j1LI8TdOEeBjx3RG02y9ZmY59VkkZl19JI/fAAitKukKAMdT9iGHrkmvTITuHWc@ilV3qo@YRKsqS@oLtZ@ZauYUWvOHpdICzD8zzdO5I6Un971Bc@1FoVIPHCDkwFDhCel1KYovT0NCfPiMKHyd/CKsNX0n8a/M39ZOyVue2XXG04adIH9a/L6xaKfR8fXdSrtwvjo7UWN2ENG@5cTeHQ9T1vhmcCYpJoIFhJVkIM4ns9uTOEdIkoikIc0jQNcVlEoSyHqAqFaB7RlNNN5EopPF8ouhkpbpgug6X28wiHul2YCXUtEd8xyz8zq1QNyg7VQwkTAYYKzT/b@s3gLYBzlYdTFVZJphU/kcKeWAWiQJLFP9/8/TKF9VA/TX/MON1DKDme90sf7iXzIHMLjwsP0OGF9InQdmMc3DSfwhe6n15iI2zpLkR4r1f4d8D/7/Dzu3c7hGAwFNc1HEMY7zHiXpLRWI1GiawmJMrgkytRtKqqWoIl@w/ci6ewOg4Xz65u@PeGCvkR7LEzy9/GSardLFUjiiXwO6@JpbxGork@U4eNyPSnZgprSE@nIdt8UBTEWlxSA2o3AdbitzzfF3ylsB@DEeZICtA2MT0N2J@9mPC@76vnpypC5Ldj6sePX064v9z57tD@kb8p8fCfBPXAtuAf6n8 "Perl 5 – Try It Online")
## No rotation, mirrored.
If we mirror the program, we effectively end up with:
```
if(eof()){$_="Hello, World!"}else{$_=<>;chomp
;if(/^-?\d+$/){if($_){$x=1+2*($_<0?1:$_);@x=(
' $'x$_,' |'x$_,'-'x$x,'~'x$x,'-'x$x);$_=join
$/,grep$_,@x}else{$_="Congratulations on yo".
"ur new baby! :D"}}else{s[a([^aA]*)a?] #
[$1=~y,a-zA-Z,A-Za-z,r]ige}};say;
```
### No input.
The program prints out `Hello, World!`. Nothing creative going on here.
[Try it online!](https://tio.run/##pZb5d6JKFsd/96/AqoqCIotxSUTcYmd7SeelkzaLC0FBxCgQcAGR/OnTc8HTffrNvHPmzEwpVVRR9ani3u@96ujuovzjByac53nyRVdGiOD/taSwgtR02nHVT4ryMY7Ksk8pRDJ4nnDcnuNGvCcVD2MwwpyIPtorioJoWSEhw9BTW6enZgrLs2D1Yqua96DJGCOYQiEWKVRSHzqI5hCREzjHf8qNeiQWAOKoS3nSCnVvoacw0iTb1iyNn9k0xsOh0J@QPoMYJafQgBgMFD5GcXGJybIsKwmXg9P9nJ7Cl6qXXmMt6KgHTPGAKcCSO7jsGBEvoxEsKh0eEjb@DgbwjNAxLoXVQO2mP5es6iKEMcxn4vnHfw8bDsVfICUZY@FDA8ahAv3Pnno7fvc7GHMx/l935lGyex3Rhxcp/36m5CFgVpKqh5IdpCsqxr8mHE7Mogb6ecDK4RmVGL9ONaDuU0OoqRpK4cD2XHeJlzxixqAAgqVA9aLDyurvK2M3s1lEoWy8kkrsRVmDeF45hSlKTS/y1SWRuAAw5ibD1dJ/atztw3zmVtj9l3xjMm/TR82v65sOijwPn1w263cr7bOzFXZBA2u2I6dw5yVw0xs1UDxCAeZZXdGDbPWObmBJrVlqkyc5BnxND0/Evjjan4wS5cQnXpm@LgmCyHFiCps2ll3DZXmVfwCMa0@p3W7d2e3M81p8U0vuFNI8PoKqnFQi1AD6XcXuOvqUxtkLI2Bm/0dMrdAQezePrkt88JRTPa1f3CAdPTx23W9PN71vl@v7lzdlt/yQtt312/Gk@/cYJN2m1c5WpfxjF@O7eUtiWPu18DKrGJ1nP9cptD/26WdD2vjp1l21N1JgFQ8XV/QTgn7AYHyzDv7granEvGN8ER7v8XGHuR5YyL1QlFZuK7CVWWVZGdzeGIbjjr9izDJyH09JSze/DxSPZiLAhP6wJ13sNNvjIBj0587E8rbFRfNqebubX0vC1zuhVN5fX7nfZwPvsbUFA76mJ2q42kuLM18jixEfY9jd/QPediDjdDiIqXt3MkhnnmnF7J9pol3brD@qlfenF94QNg3fs0/28D5NwjPanjG1bP9I57s2YG76m8WM9lQcqBDhs7ug0W9nuP7ae1Wed@@GNQo/NGdf7ISPBaOcIes8YGgJ80YkziQBW5E00ABTJcpcytyzbRLHQv02rxo39@VQqexGy5tKr9br2VJ7N34r1cur9nf/FCa1mYBmJkV2u9Ui4vO8DpjTx7n8We3iBz8IYaOXx3HE1araPL/alwon5/bg4vW6@UW@qZ49vXwUvvXWYOJoPd04RGBCPpJ5hnYTT/0sYBq8@AjJzZN1P88Y@0Wx2sra0aPb6p13O1dvf2DLwVUDMm3GNsk4pIeVhpNh0lPpL5i4nOeNFvt6@fhgLNv7/uArEt6@9OjG/XVWHtOnw/z59QtgiCnRbEMWcYNk0k1T@TfMfyrXmy8YW4GOcnzB70ettNOkJYJT5pTW7SnNMCFRZHSpLxY2Sz3Z7kJLo0hfeHo8Xm9Ik5m9dDB@ugZPmao6nPBRyx@O0oRmnDxOScDhR4XmQMuDGELoEQWQvizmizm4rwtNsQZDUsuXQRBMvYex7ckbsvJCIlwHEhMtAZOlSNYnCpul9oe2AI3PZj8PTdJjJDjR3DYtEPCDjfE83BDG3On5/rWqRBk7wCnCs4arOwBo@b9eAp3ZluGqq/VCXZm25VG2RQU2Alci@g5juQmpdTH1hv6pR0QyU3EKrV3K0rfUWB0HaarWRdEB5vVVuj9S28McozaHkBcXKIpjmwHdKLSEJs5mIRBPkkkw8XCqT0T5M2DVwq5deGXhgjvWHZqGHkWSpwYS3l1EneL@Nnq8inPsqARpP2rIxNP0fnBftAJVCnFKdmwN579tztJB4fT79r56tbxYdHrCcfa73bE/Xmr47ttbZZc5UyCAgHBVxTis1Dd0uIp8NV8gqtcATLJhv1SqRl/qm/PnXM7Qsl79/WvFNJ@x8SB8WN6lMc/eHq2X8f@WxhRyG1OUSY7eMcSzLckL6wxOxRb1HNe0VlMkCEdjxBIldgwPKV8QaC4sR0yO8OB1IQLj9O4XgAkVaUN7RVbCRAybMmAScTGJegZdEA4/MmzbWOh8JqOZegxc6JaxmiWGB0/VOvEPPYHf6DE1FASu0aQVGjxVpXI5yJiM/OnxNIiQoQddhidFyiciD1o4OC4RMciv9DbBeMpHwxzn@KJ8xCl0k0wTTBkwJaqUq1LHuRL0StBWoT@w4i3gqsBAhcrFumm1IKZsabWZiAbTb@Ai4fIhZD90Sp3CAqpUjWGnf6kOgxSQq1RRPGC2t5CwX0xCyPuxr2iUzHA6pC00sMqws1ikqnEVn@GYqvzqV6BfhI3izWJMNj@ObeOP6OAdULbr5EYe/XuEg@vzNBJFKlcsU8kbAV2gctCBppRDFGAm7dg2nA4CNzi64Njw320x/a/zTVLMtoR4b8PIBXkacqFu4h8//mE7Sfj9KNyWOdAKtGPTAB39Ew "Perl 5 – Try It Online")
### Integer input
We do the "It's my Birthday :D" task. If the input equals `0`, we print out `Congratulations on your new baby! :D`. For the input (`N`) is positive, we start printing out `N` candles, then a cake of width `2 * N - 1`. If the input is negative, we print a candleless cake, with width `3`. All pretty straightforward.
[Try it online!](https://tio.run/##pZb5d6JKFsd/96/AqoqCIotxSUTcYmd7SeelkzaLC0FBxCgQcAGR/OnTc8HTffrNvHPmzEwpVVRR9ani3u@96ujuovzjByac53nyRVdGiOD/taSwgtR02nHVT4ryMY7Ksk8pRDJ4nnDcnuNGvCcVD2MwwpyIPtorioJoWSEhw9BTW6enZgrLs2D1Yqua96DJGCOYQiEWKVRSHzqI5hCREzjHf8qNeiQWAOKoS3nSCnVvoacw0iTb1iyNn9k0xsOh0J@QPoMYJafQgBgMFD5GcXGJybIsKwmXg9P9nJ7Cl6qXXmMt6KgHTPGAKcCSO7jsGBEvoxEsKh0eEjb@DgbwjNAxLoXVQO2mP5es6iKEMcxn4vnHfw8bDsVfICUZY@FDA8ahAv3Pnno7fvc7GHMx/l935lGyex3Rhxcp/36m5CFgVpKqh5IdpCsqxr8mHE7Mogb6ecDK4RmVGL9ONaDuU0OoqRpK4cD2XHeJlzxixqAAgqVA9aLDyurvK2M3s1lEoWy8kkrsRVmDeF45hSlKTS/y1SWRuAAw5ibD1dJ/atztw3zmVtj9l3xjMm/TR82v65sOijwPn1w263cr7bOzFXZBA2u2I6dw5yVw0xs1UDxCAeZZXdGDbPWObmBJrVlqkyc5BnxND0/Evjjan4wS5cQnXpm@LgmCyHFiCps2ll3DZXmVfwCMa0@p3W7d2e3M81p8U0vuFNI8PoKqnFQi1AD6XcXuOvqUxtkLI2Bm/0dMrdAQezePrkt88JRTPa1f3CAdPTx23W9PN71vl@v7lzdlt/yQtt312/Gk@/cYJN2m1c5WpfxjF@O7eUtiWPu18DKrGJ1nP9cptD/26WdD2vjp1l21N1JgFQ8XV/QTgn7AYHyzDv7granEvGN8ER7v8XGHuR5YyL1QlFZuK7CVWWVZGdzeGIbjjr9izDJyH09JSze/DxSPZiLAhP6wJ13sNNvjIBj0587E8rbFRfNqebubX0vC1zuhVN5fX7nfZwPvsbUFA76mJ2q42kuLM18jixEfY9jd/QPediDjdDiIqXt3MkhnnmnF7J9pol3brD@qlfenF94QNg3fs0/28D5NwjPanjG1bP9I57s2YG76m8WM9lQcqBDhs7ug0W9nuP7ae1Wed@@GNQo/NGdf7ISPBaOcIes8YGgJ80YkziQBW5E00ABTJcpcytyzbRLHQv02rxo39@VQqexGy5tKr9br2VJ7N34r1cur9nf/FCa1mYBmJkV2u9Ui4vO8DpjTx7n8We3iBz8IYaOXx3HE1araPL/alwon5/bg4vW6@UW@qZ49vXwUvvXWYOJoPd04RGBCPpJ5hnYTT/0sYBq8@AjJzZN1P88Y@0Wx2sra0aPb6p13O1dvf2DLwVUDMm3GNsk4pIeVhpNh0lPpL5i4nOeNFvt6@fhgLNv7/uArEt6@9OjG/XVWHtOnw/z59QtgiCnRbEMWcYNk0k1T@TfMfyrXmy8YW4GOcnzB70ettNOkJYJT5pTW7SnNMCFRZHSpLxY2Sz3Z7kJLo0hfeHo8Xm9Ik5m9dDB@ugZPmao6nPBRyx@O0oRmnDxOScDhR4XmQMuDGELoEQWQvizmizm4rwtNsQZDUsuXQRBMvYex7ckbsvJCIlwHEhMtAZOlSNYnCpul9oe2AI3PZj8PTdJjJDjR3DYtEPCDjfE83BDG3On5/rWqRBk7wCnCs4arOwBo@b9eAp3ZluGqq/VCXZm25VG2RQU2Alci@g5juQmpdTH1hv6pR0QyU3EKrV3K0rfUWB0HaarWRdEB5vVVuj9S28McozaHkBcXKIpjmwHdKLSEJs5mIRBPkkkw8XCqT0T5M2DVwq5deGXhgjvWHZqGHkWSpwYS3l1EneL@Nnq8inPsqARpP2rIxNP0fnBftAJVCnFKdmwN579tztJB4fT79r56tbxYdHrCcfa73bE/Xmr47ttbZZc5UyCAgHBVxTis1Dd0uIp8NV8gqtcATLJhv1SqRl/qm/PnXM7Qsl79/WvFNJ@x8SB8WN6lMc/eHq2X8f@WxhRyG1OUSY7eMcSzLckL6wxOxRb1HNe0VlMkCEdjxBIldgwPKV8QaC4sR0yO8OB1IQLj9O4XgAkVaUN7RVbCRAybMmAScTGJegZdEA4/MmzbWOh8JqOZegxc6JaxmiWGB0/VOvEPPYHf6DE1FASu0aQVGjxVpXI5yJiM/OnxNIiQoQddhidFyiciD1o4OC4RMciv9DbBeMpHwxzn@KJ8xCl0k0wTTBkwJaqUq1LHuRL0StBWoT@w4i3gqsBAhcrFumm1IKZsabWZiAbTb@Ai4fIhZD90Sp3CAqpUjWGnf6kOgxSQq1RRPGC2t5CwX0xCyPuxr2iUzHA6pC00sMqws1ikqnEVn@GYqvzqV6BfhI3izWJMNj@ObeOP6OAdULbr5EYe/XuEg@vzNBJFKlcsU8kbAV2gctCBppRDFGAm7dg2nA4CNzi64Njw320x/a/zTVLMtoR4b8PIBXkacqFu4h8/RPEftpME4I/CbZkDtUA7Ng1Q0j8B "Perl 5 – Try It Online")
### String input
Now we do the "No A. just CAPS LOCK". We repeatedly find strings which are delimited by `a` (either case), with no `a` in between (with some trickery to make it work for the end of the string as well. We throw away the bounding `a`s, and flip the case of the string between the `a`s.
[Try it online!](https://tio.run/##pZb5d6JKFsd/968oqyoKioDGJRFxi53tJZ2XTtosLgQFEYNgwAVE8qdPz0VP9@k3886ZMzOlVFFF1aeKe7/36kJ3rdKPH4TynufJFx0ZY0r@15IgClaTyYWrfiLkExKVZB8pVDIEgfL8jueHgicVDmMwwp7kfbxTFAUzskJDlmUmjs5MzASRp8HyxVE170GTCcEwBWEOK2hfHzqY4TGV93Be@JTrtSifA8hCncvjZqh7lp4gWJMcR7M1YeowhAwGYm9MeyxmlYzCAKLfV4QYxcclJsuyrOy5PJzu5/QEuVS95IpoQVs9YAoHTA6W3MHlxIh4GYNhUfHwkHLxt9@HZ5SJcQmiBmon@TnnVBdjQmA@G88//nvYYJD/BVL2Yxx8GMAsUKD/2VVvR@9@mxA@xv/rzgLe717DzOFFSr@faf8QMEtJ1UPJCZJllZBfEw4n5nAd/zxg@fAM7Y1fQ3Woe2gANariBAkcz3XnZC5gdgQKoEQKVC86rKz8vjJ2M5fGCKfjlWhvL2T343mlBEFITVrZypxKfAAYc53iq8k/Nf72YTZ1y9zuS7Y@nrWYo8bX1U0bR55HTi4btbul9tneiNugTjRnISdI@yVwk2s1UDyKAPOsLpl@unLH1ImkVm21IdAMC75mBif5Xn64OxnulROfeGn6uiSKeZ7PJ4jpENk1XE5QhQfAuM4Ebber9nZrnlfjm@r@TqGN4yOoSvsqDzWAflexu4o@pVH6wgjY6f8RU0s8IN7No@tSHzy1qJzWLm6wjh8eO@63p5vut8vV/cubsp1/SJvO6u143Pl7DJZuk2p7oyL/2CXkbtaUWM55zb1My0b72c@0c62PXfLZkNZ@snlX6Q4VWCXAxRf8PUE/YAi5WQV/CPZEYt8JuQiPd@S4zV73bexeKEozsxG58rQ8L/dvbwxj4Y6@EsKxco9MaFM3v/cVj2EjwIT@oCtdbDXH4yEY9Of22PY2BatxNb/dzq4l8eudWCztrq/c79O@99jcgAFfk2M1XO4k68zXqDUUYgy3vX8gmzZknDYPMXXvjvvJ1DOjmL0zLe9U16uPSvn96UUwxHXd95yTHbxPgwqstmNNLd070oWOA5ib3tqaMp5KAhUifHoX1HutFN9bea/K8/bdsIfhh7bYFdrhY84opegqCxhGIoIR5aeSSOxI6muAqVBlJqXuuRaNY6F2m1WNm/tSqJS3w/lNuVvtdh2ptR29FWulZeu7fwqTWmzAsOMCt9loEfUFQQfM6eNM/qx0yIMfhLDRy@Mo4qsVbZZd7oq5k3Onf/F63fgi31TOnl4@ct@6KzBxtJqsF1RkQyGSBZZx9576WcA0xPoI6c2TfT9LGTurUGmmnejRbXbPO@2rtz@IvSAVAzJtyjHpKGQG5foixSYn0l8wcTnPGk3u9fLxwZi3dr3@Vyy@feky9fvrtDxiTgfZ8@sXwFBTYri6nCd1mko2TOXfMP@pXK@/EGIHOs4IOb8XNZOLBiNRkjAnjO5MGJYNqSLjS92yHA49Oa6lJXGkW54ej9fq0njqzBeEPF2Dp0xVHYyFqOkPhknKsIssSUjAEYa5Rl/LghhC6FEFkL6czxYycF8TG/kqDElNXwZBsLUuIY4nr@nSC6l4HUhsNAdMGtG0TxUujXaHNgeNz6U/D82@x0pwoplj2iDgB4eQWbimrLnVs71rVYlSTkASVOAMV18AoOn/egl85tiGqy5Xlro0HdtDjo0CB4MrMXNHiNyA1GpNvIF/6tE8naokgVcusvUNGqmjIImqHRwdYF5PZXpDtTXIsGpjAHnRwlEc2yzoRmEkPF6sLZF6kkyDsUcSPZqXPwNOzW1buVcOLrjj3IFp6FEkeWogke1F1C7sbqPHqzjHDouQ9qO6TD1N7wX3BTtQpZAk5IWjkey39VkyyJ1@39xXruYXVrsrHqe/O23n46VK7r69lbepMwUCCAhXFULCcm3NhMvIV7M5qnp1wOw37BWLlehLbX3@nMkYWtqrvX8tm@YzMR7ED9u7NGbp26PVPP7fUp9AbmMLMs0wW5Z6ji15YY0lidii3sI17eUEi@LRCHNUiR0jQMoXRYYPSxGboQJ4XYzAON17CzChIq0Zr8BJhObDhgyYvbjYvXr6HRCOMDQcx7B0IZXSTD0GWrptLKd7w4Onqu34h57Cb/QIDUSRrzcYhQFPVVAmAxmTlT89gQERsky/wwq0gHyaF0ALB8ftRQzyK76NCZkI0SDDL/y8fMQrTINO9pgSYIqomKmg40wRekVoK9Dv2/EWcJVhoIwysW6aTYgpR1qux3mD7dVJgfLZELIfPkWnsAAVKzHs9C/VYRABuYIK@QNmcwsJ@8WklL4f@4qGZJbXIW3hvl2CnfMFVImr@AzHqPyrX4Z@ATaKN4sx6ewoto0/ZIJ3QDnuIjP0mN8jHFyfZXA@jzKFEtq/EdBFlIEONMUMRoAZt2Lb8DoI3OCZ3MKB/27W5L/ON/titiQseGtWzsmTkA91k/z48TjV0cfKHL@jketsbDRxfDRbzRcQj2vdRUt4bKnbIB7n/@Es9qH6I3db4kFX0I5MAzT3Tw "Perl 5 – Try It Online")
## Rotating 90° counter clockwise, no mirroring
We then end up with effectively:
```
if(eof()){{say++$_;redo}}
else{$_=<>;chomp;if(/\D/)
{/^.+?(?{say$&})(?!)/;/^(
..*).(?{say$1})(?!)/x}else
{$p=$_>1;$n=$_;$p&&=$n%$_
for 2..$n-2;say!!$p}}
```
### No input
With no input, we enter an infinite loop, where we increment `$_` and print the result.
[Try it online!](https://tio.run/##fZbvV6LcFsff@1cczz4lIB7AVEYRNWtqpqemp6lxKkBCRaRRMFBDkf70O/fQzIu77r3zuEpYyw97f/dPztKN5vWfP@EfPr6i1zGhlHd9KPhTzg2nHM@naexsy2Via5E7CbOMgVO6tFqYI8Z8CgV3HrspsfV2RxvPwsVSY09K5qnEM5CjoYVELJGYg0IqDWm5y3Vze@Qw47lukZc0acgx0FUmFGORjl0XCpQKPP3NKb@5JMv9AIQyYFHCnJGGzCJZ6sTuKBoJ2FUjy8NDnQQHxM41yh2TWSRyj2mchhGqUkqCSlVjVotFsmSBGBMz16htA0vE2BozjfoynMCBDGH5Jm5eXAx7nY40kUvJNwby7g4hQkVL56FQqTDHupxbI4khWxk00ldtcuLnYCJzBsaYLhioc@x3xRLfqfL7Pf868@csFkj9VyZRNImTQoGn5IhPUJV/jzTtJToniwqv9RKAeNWnIsGmtCRQ2Hg/fnjLUbxbTTbTXZxVOimpZvs9qQI42RuHsY1pakPhPX@U47g0Xs79lSSJo@XYm6ymFGAbT3CHZ/khOhRYDchYIBuBXXie3XJkw0t8mjcFcVYIGcy5zdKDjSHZWFgjGx0b73es2CA5BgPt7XWrTQimFQwFzU38VfarKxjsuH643mpkrDPwoN1GeIxFTmEajyl90CSaVhvZf3UGgNLpYtHgCc7s/@xHZvU59AOWOfbwo8gs1vVPIq4b2G4z8J86vPv2oYQswuud/T@DRAKMrLGh6ywYGI@uPo7780itra/DQfnjg7eG8n72xT4FexgjRA2ivyUMPC6/9p5aN9PPQ567bV9sLtRBc/3hdTQcw8GHGGOijG1JyS2Wer0aHnTIvYQf@e8XZ/A1IWEvGhxBfZ@VeMkyMP3wfzSWl5Vvh/HdUn2C7pBlh1o1kY3a/4JW8HJcT2Lveg1E6WPCUQt7lIGUfTg3H2OgAbeEJjysvI7p9VgwxqU9xpxFNdZmgFgLL@OMyJ8z7OsL4P76Xq9sZpfFVzhQ1rbRxmyiJAZiQRAWc3mh3eEwTEIYPZ207@RvV4kGRx@@2A1MMbU1BgpNBYVua21n8@1zbwb6Z7WWepG5eYGu1cVsCjmq565rqNqYZcrByRUgXRtDqX/51Jc@N7QFEO5AtIiIKclrjZpIGM@6V4d7CGxeg4tTfVR9uFh4O7Apxxznf4iBsqAepSuptKuikE0u3Jx93O2/7xv3NrToMcJiyIk0L6HSFJDrkedG30IaaUNn0D1e/qjPik9wRp8Rz5KCOT0PBtUbcSB4T1k35ls6cL0LbdKoNfYP4PNjhCWRIlzNNVaRMHf5T1/PnSBhPT@IHsMXVRZfbmAndHKBWMJ5euoBQu48i693fEi6BD7enQ/Sl2v5eA07UuY58Vq0xTh3bQZqptcDAMFP5BSeMnMwXH95rXyClvTRwARjE@eVQYIpuHb60tKsVantghyGrWAjC/2v0O/uSYeFbaJhnp6GIESEyg/bY6dix4BLZwOvpfWEAawdcYzzsO28exSkIk/jbl8cZ14ic/jS@9D4EV7YySXsgoYhGhVRfAeFak2VXNkL4@Fa5Fww1crlTnm277/DrhWpbFEwi/kU1hQUKL4Mfc1YJQLbytXa4n6yO2caW87MwmP@mhUSUB5NYJKJch9mnEOqGPbz/dA@uYq8CM60Z0s02AYQc9@qagrJoex/y5woKRfheL/aPRoL3DgFH24prhFRwHmfBUioIQaWXMMrKRNYeOVG7H8OZnew61xh0xpjG@WJNKtNVJWkxpEXB2/6HLzDZ3ttd82HW9hxlDcto8K/g4JSU4mrf5H9NCwlEdw@T1KDm1@wpdi/nrB2PGJhe@@lCQRpbv8YWO6JSEK4u1Hr9L7KP7qwVv/ORGzx/K@uaJhHvEfa/SjGSfodPgWtm8PD136IYVcqxoSzDLaeGcjaDJ2GWjwX5zrhETx@p5fHxfhIZKUxWw7zzZKeD41w1KyZoV0637l2YosgXmaeYQbAnwPi6JaneDxG@dCgoCZwHpksKhkpMY09MnI64/Fea8N0dagZHG8Y9vvQmEGdH4reZydLKxxLT3pX3kb9o14TQmcDzG9VtnVAiFVREUxUlrCgPmK3NJ1D@eXh6vrmPn1WIbr3yRhTy7Lr@VqpCbVJOhJuKqex6LtwNqftGeeeXy/fF5xBOcvCGQM51BRM/uD@9bg1t9NPf9rpBShXa0ecJJ99E5FLePxncKsESDqVN83HYpZI@UsrZWcZ/CNyZrdoO3L6mOP0hBTAEUw1NnG7UtkmpfzcQfNfKX@U8BKhfCNhG3GCcAFiVRDepOnH7fGoty8TZjEhWyfWfn3j4i/TDEyRWtO5VVbcOSKa5K/g22OIwimKPMkmUm5eit/0AvDVGuKngXpSGdklMz9tgegsJ4ETnYvbxSK8EreTiXPKQAXVsO/XNg4iYjcHT2/i/k56vStFjgqas3h/iOVRCIJAi2pfxdelXcmPZeoh93r@V/9y5G3Ki3TwBpNwyVxPa6Zp8kujvHVdMpwy8E2bgZZHEhXnkft3cR0@FOMChIi9Gjox@z2IEilkoP48vx2si/CmR8XIcU@L4SoH3XqzLrR1baIjr8TlZ6Nne3NjXV6xg1Vu9vc/08h2JNLtbahEIpnmGu@IsUtAw8wlCldo60xmmDKNZlNVbeIsyVpCfq6xqV6KKeBV5PfRdrl0PmHdZiX0841O0lhne7Ok@X9qip8//xUuV34YxD8rV3UqKzK7jnzPD1b/Bg "Perl 5 – Try It Online")
### Integer input (non-negative)
We will now determine whether the given number is a prime number. We do this by checking whether non of the integers between (but not including) `1` and the input number evenly divides the input number. We then print the result (`1` if it's a prime, an empty line if it's not).
[Try it online!](https://tio.run/##fZZtd5paFsff@ymOZ59EQDyAT1QRNTZN2tykuWlSmwSQoCKSKhhQgyL56NM5pPfFrJm515UIa/lj7/9@5KzcaNH49Qv@4eMregMTSnnXh4I/49xwxvF8msbOrlwmtha50zDLGDijK6uNOWIsZlBwF7GbElvvdLXJPFyuNPakZJ5KPAM5GlpIxBKJOSik0oiWe1wvt0eOM57rFXlJk0YcA11lSjEW6cR1oUCpwNO/OOUvLslyPwChDFiUMGekIbNIVjqxu4pGAnbVyOr4WCfBEbFzjXLXZBaJ3GcaZ2GEqpSSoFLVmNVikaxYIMbUzDVqu8ASMbYmTKO@CqdwJENYvolbFxejfrcrTeVS8p2BvLtHiFDR0nkoVCrMsS7n1khiyFYGzfRVm370czCROQNjTJcM1Dn2u2KJ71T5/Z5/nfsLFguk/iuTKJrESaHAU1LjE1Tl3yNN@4nOyaLCa/0EIF4PqEiwKa0IFLbez5/eahzv19PtbB9nlW5KqtnhQKoATvbGYWxjmtpQeM8f5TgujVcLfy1J4ng18abrGQXYxVPc5Vl@iA4FVgMyEchWYBeeZ7cc2fISn@ZNQZw1QgZzbrP0YGNEthbWyFbHxvsdKzZIjsFAe3fd7hCCaQVDQXMTf5397goGO64fbnYamegMPOp0EJ5gkVOYxhNKHzSJptVm9l@dAaB0e1g0eIIz@z/7kVl9Dv2AZY49/Cgyiw39s4gbBrY7DPynDu@9fSghi/B69/DPIJEAI2ti6DoLBibjq0@TwSJS65vrcFj@9OBtoHyYf7VPwR7FCFGD6G8JA0/Kr/2n9s3sy4jnbjsX2wt12Np8eB2PJnD0IcaYKBNbUnKLpX6/joddci/hR/7HxRl8S0jYj4Y1aByyEi9ZBqYf/o/G8qry/Ti@W6lP0Bux7FCrLrJR@1/QCl5OGknsXW@AKANMOGphjzKQsg/n5mMMNOBW0IKHtdc1vT4Lxri0J5izqMbaDBBr4VWcEflLhn19CdwfPxqV7fyy@ApHysY2OphNlMRALAjCciEvtTschkkI46ePnTv5@1WiQe3DV7uJKaa2xkChpaDQbW/sbLF77s9B/6LWUy8yty/Qs3qYTSFH9dx1HVWb80w5@ngFSNcmUBpcPg2kL01tCYQ7Ei0iYkryWqMWEibz3tXxAQKb1@DiVB9XHy6W3h5syjHH@R9ioCyotXQtlfZVFLLJhZuzT/vDj0Pz3oY2PUFYDDmR5iVUWgJyPfLcHFhIIx3oDnsnq5@NefEJzugz4llSMKfnwaBGMw4E7ynrxXxbB65/oU2b9ebhAXx@grAkUoSrucYqEhYu//nbuRMkrOeH0WP4osriyw3shW4uEEs4T08jQMhdZPH1ng9Jj8Cnu/Nh@nItn2xgT8o8J16Lthjnrs1AzfRGACD4iZzCU2YOR5uvr5XP0JY@GZhgbOK8MkgwBddOX9qatS51XJDDsB1sZWHwDQa9A@mysE00ytPTFISIUPlhd@JU7Bhw6WzotbW@MISNI05wHradd4@CVORp3O2L4yxKZAFf@x@aP8MLO7mEfdA0RKMiiu@gUK2rkit7YTzaiJwLplq53CvP9v0P2LcjlS0KZjGfwrqCAsWXYaAZ60RgW7laX95P9@dMY9uZW3jCX7NCAsqjCUwyVe7DjHNIFcNhcRjZH68iL4Iz7dkSDbYBxNy3qppCciz73zMnSspFODms94/GEjdPwYdbiutEFHDeZwES6oiBJdfwSsoUll65Gftfgvkd7LtX2LQm2EZ5Is1qC1UlqVnz4uBNX4B3/Gxv7J75cAt7jvKmZVT4d1BQ6ipx9a@yn4alJILb52lqcIsLthQH11PWjjUWtvdemkCQFvbPoeV@FEkIdzdqg95X@UcXNuqfmYgtnv/dFU2zxnukM4hinKQ/4HPQvjk@fh2EGPalYkw4y2DrmYGszdBpqMULcaETHsHjD3p5UoxrIiuN2XaYb5b0fGiEWqtuhnbpfO/aiS2CeJl5hhkAfw6Iozue4skE5UODgrrAeWS6rGSkxDT2ydjpTiYHrQOz9bFmcLxh2O9DYwYNfiR6X5wsrXAsPeldeRcNav0WhM4WmN@qbOuAEKuiIpioLGFBfcRuabaA8svD1fXNffqsQnTvkwmmlmU38rVSF@rTdCzcVE5j0XfhbEE7c849v169LziDcpaFMwZyqCWY/NH960l7Yaef/26nF6Bcrdc4ST77LiKX8PjvwZ0SIOlU3rYei1ki5S@tlJ1l8M/Imd@i3dgZYI7TE1IARzDV2MSdSmWXlPJzB81/pXwt4SVC@WbCNuIU4QLEqiC8SbNPu5Nx/1AmzGJCdk6s/f7Gxd@mGZgita5z66y4d0Q0zV/BtycQhTMUeZJNpNy8FL/pBeCrdcTPAvVjZWyXzPy0BaKzmgZOdC7ulsvwStxNp84pAxVUx75f3zqIiL0cPL2JB3vp9a4UOSpozvL9IZZHIQgCLap/E19XdiU/lqnH3Ov5H4PLsbctL9PhG0zDFXM9q5umya@M8s51yWjGwDdtDloeSVRcRO6fxU34UIwLECL2aujG7PcgSqSQgfrz4na4KcKbHhUjxz0thuscdButhtDRtamOvBKXn42e7e2NdXnFDla52b/@mUa2I5Fu70IlEsks13hHjH0CGmYuUbhGO2c6x5RpNFuqahNnRTYS8nONLfVSTAGvI3@AdquV8xnrNiuhn290ksY625slzf@7pvj1S639K1yt/TCIf1WuGlRWZHYd@54frP8N "Perl 5 – Try It Online")
### String input
Now we do the YouTube Comments #1 task. We do this by finding all sub strings of the given string, which are anchored at the beginning. This is done by use a regexp (`/^.*?/`), printing the match (`/(?{say $&})/`) and then failing the match (`/(?!)/` (it can never happen that the current position isn't followed by an empty string)). This cause Perl to backtrack and try the next match. The quantifier modifier `?` makes Perl try the shortest strings first. This takes care of the first half (including the full line). For the second half, we use `/^(..*)./`, which does almost the same thing, except it only matches sub strings which are followed by at least one other character (so, it skips the full string), and it tries it in "longest first" order.
[Try it online!](https://tio.run/##fZZtd6JIFsff@ynKupUIiAUYlVZEjZ1O0pmkM@mkzQMgQUUkrWBADYrko29vkZ4Xe3Z3xpMI5/jj3v99pJZuNK//@gX/8PEVvY4JpbzrQ8Gfcm445Xg@TWNnWy4TW4vcSZhlDJzSpdXCHDHmUyi489hNia23O9p4Fi6WGntSMk8knoEcDS0kYonEHBRSaUjLXa6b2yOHGc91i7ykSUOOga4yoRiLdOy6UKBU4OlfnPIXl2S5H4BQBixKmDPSkFkkS53YHUUjAbtqZHl4qJPggNi5RrljMotE7jGN0zBCVUpJUKlqzGqxSJYsEGNi5hq1bWCJGFtjplFfhhM4kCEs38TNi4thr9ORJnIp@cFA3t0hRKho6TwUKhXmWJdzayQxZCuDRvqmTT77OZjInIExpgsG6hz7XbHED6r8cc@/zfw5iwVS/41JFE3ipFDgKTniE1TlPyJNe4nOyaLCa70EIF71qUiwKS0JFDbez5/echTvVpPNdBdnlU5Kqtl@T6oATvbOYWxjmtpQ@Mgf5TgujZdzfyVJ4mg59iarKQXYxhPc4Vl@iA4FVgMyFshGYBeeZ7cc2fASn@ZNQZwVQgZzbrP0YGNINhbWyEbHxscdKzZIjsFAe3vdahOCaQVDQXMTf5X97goGO64frrcaGesMPGi3ER5jkVOYxmNKHzWJptVG9l@dAaB0ulg0eIIz@z/7kVl9Cf2AZY49/CQyi3X9XMR1A9ttBv5Th3ffP5WQRXi9s/9nkEiAkTU2dJ0FA@PR1Zdxfx6ptfV1OCh/efTWUN7PvtknYA9jhKhB9PeEgcflt95z62b6dchzt@2LzYU6aK4/vY2GYzj4FGNMlLEtKbnFUq9Xw4MOeZDwE39/cQrfExL2osER1PdZiZcsA9NP/0djeVn5cRjfLdVn6A5ZdqhVE9mo/S9oBa/H9ST2rtdAlD4mHLWwRxlI2Ydz8zEGGnBLaMLjyuuYXo8FY1zaY8xZVGNtBoi18DLOiPw1w76@AO6P@3plM7ssvsGBsraNNmYTJTEQC4KwmMsL7Q6HYRLC6Plz@07@cZVocPTpm93AFFNbY6DQVFDottZ2Nt@@9Gagf1VrqReZm1foWl3MppCjeu66hqqNWaYcfL4CpGtjKPUvn/vS14a2AMIdiBYRMSV5rVETCeNZ9@pwD4HNa3Bxoo@qjxcLbwc25Zjj/A8xUBbUo3QllXZVFLLJhZvTL7v9/b7xYEOLHiMshpxI8xIqTQG5Hnlp9C2kkTZ0Bt3j5c/6rPgMp/QF8SwpmNPzYFC9EQeC95x1Y76lA9e70CaNWmP/CD4/RlgSKcLVXGMVCXOXP/9@5gQJ6/lB9BS@qrL4egM7oZMLxBLO01MPEHLnWXy940PSJfDl7myQvl7Lx2vYkTLPideiLca5azNQM70eAAh@IqfwnJmD4frbW@UcWtIXAxOMTZxXBgmm4Nrpa0uzVqW2C3IYtoKNLPS/Q7@7Jx0WtomGeXoaghARKj9uj52KHQMunQ68ltYTBrB2xDHOw7bz7lGQijyNu311nHmJzOFb71PjZ3hhJ5ewCxqGaFRE8QMUqjVVcmUvjIdrkXPBVCuXO@XFfriHXStS2aJgFvMprCkoUHwZ@pqxSgS2lau1xcNkd8Y0tpyZhcf8NSskoDyawCQT5SHMOIdUMezn@6H9@SryIjjVXizRYBtAzH2rqikkh7L/I3OipFyE4/1q92QscOMEfLiluEZEAed9FiChhhhYcg2vpExg4ZUbsf81mN3BrnOFTWuMbZQn0qw2UVWSGkdeHLzrc/AOX@y13TUfb2HHUd60jAr/AQpKTSWu/k3207CURHD7MkkNbn7BlmL/esLa8YiF7X2UJhCkuf1zYLmfRRLC3Y1apw9V/smFtfpnJmKL5393RcM84j3S7kcxTtJ7OA9aN4eHb/0Qw65UjAlnGWw9M5C1GToJtXguznXCI3i6p5fHxfhIZKUxWw7zzZKeD41w1KyZoV0627l2YosgXmaeYQbAnwHi6JaneDxG@dCgoCZwHpksKhkpMY09MnI64/Fea8N0dagZHG8Y9sfQmEGdH4reVydLKxxLT3pX3kb9o14TQmcDzG9VtnVAiFVREUxUlrCgPmG3NJ1D@fXx6vrmIX1RIXrwyRhTy7Lr@VqpCbVJOhJuKiex6LtwOqftGeeeXS8/FpxBOcvCGQM51BRM/uDh7bg1t9Pzv9vpBShXa0ecJJ/@EJFLePz34FYJkHQib5pPxSyR8pdWys4y@GfkzG7RduT0McfpCSmAI5hqbOJ2pbJNSvm5g@a/Uv4o4SVC@UbCNuIE4QLEqiC8S9Mv2@NRb18mzGJCtk6s/f7Gxd@mGZgitaZzq6y4c0Q0yV/Bt8cQhVMUeZJNpNy8FL/rBeCrNcRPA/VzZWSXzPy0BaKznAROdCZuF4vwStxOJs4JAxVUw75f2ziIiN0cPLmJ@zvp7a4UOSpozuLjIZZHIQgCLap9F9@WdiU/lqmH3NvZH/3LkbcpL9LBO0zCJXM9rZmmyS@N8tZ1yXDKwHdtBloeSVScR@6fxXX4WIwLECL2aujE7PcgSqSQgfrL/HawLsK7HhUjxz0phqscdOvNutDWtYmOvBKXn41e7M2NdXnFDla52b/@mUa2I5Fub0MlEsk013hHjF0CGmYuUbhCW2cyw5RpNJuqahNnSdYS8nONTfVSTAGvIr@Ptsulc451m5XQzzc6SWOd7c2S5v9dU/z6de7O56GI7sNoPin@K1yu/DCIf1Wu6lRWZHYd@Z4frP4N "Perl 5 – Try It Online")
## Rotating 90° counter clockwise, mirrored
Then we effectively get:
```
if(eof()){$_=join"",A..Z,
A..Y;/.{26}(?{say$&})(?!)/
;exit}$_=<>;$v=aeiouy;$c=
"[^$v]";$v="[$v]";if(
/^($c*$v*($c))$c*($v)/){
say$1.((({split//,bpcgdtf.
vgkkgpbsztdvfzs}->{$2}||$2
).$3)x 2)}else{@x=(0,1);@x
=($x[1],$x[0]+$x[1])while
--$_>=0;say$x[0]}
```
### No input
This prints out the "Tabula Recta". It does so by creating a string consisting of all the letters `A` to `Z`, followed by the letters `A` to `Y` (so, 51 letters in total). We then find all sub strings of length 26 and print them, using the same trick as above.
[Try it online!](https://tio.run/##fZZhd5pKE8ff@ynWnU1cEBc0KlVEjUmTNjdpbpo0TQJIiCKSKhhQgyL56E@fJe2Le@659@5RloM/Z/8zOzPswo1mjZ8/wcd8kDTWDUxKmg//MgowMVuqahNnQVYy8if8WUs9l1LAy8gfoM1i4XzCuk0QQgWgAZ90exNWI4lMKGdviLFNQMOr8B6FS7RxxlPMCuA2Wg2xo2tjHXkl6nLw2V5fWecXVgYbJ9Z@fwsQIlEUuzHAWxAlcshB/Xl2fbsqwpseFSPHPS6GyyIHJ3XTNIWFUd64LhnmMt@0KbwbioqzyP2zyCXkIBWDINCi@lfpdWFXco3qPn09/WNw/uSty/P09g3G4UIvgFBFdez79bWDiNQTOHh8FQ@28utNKXJU0Jz5OHCiUw7W6kiYBOpR5ckumTkIkrN4/1HazOfhhbQZj53jAqRIret0mRW3joTGKeeuDyEKJyjyZJvImydnIMdvfOlYFcU3efJxc/jU35UJBxOSe/Lrios/Imd6jXABHNFUYxN3KpVNUiI2AMuNMOEgEWTChGaCw3Ccg5tqgORjZd16KGaJrHOLKVCGfxnK/4Mp1RNSgHKtfkBl5eSbhFwi4H/PC4paoins3b0etmd2@unfQVwX6@P0SbyqHMeS78LJjHWm1D29XLwDBqOWhTMOVkUTlWUsqg/YLU1mUH65v7i8ukufVYjufDLCzLLsRg6aQUMYSt5nJ0srdAZeelPeRIODfgtCZw2E4Jpi6xxEQV2kHhnPKxkpkRD65MnpjkY7rQOT5b5mUMEw7ISD4kGrboZ26XTr2oktgXSeeYYZgHAKiLKNwPBohBAHa0hEx6EWz6SZTgQED9/Z@WExPpDOYWu2HYwZX93mYKNpHgge6QyiGCfpd/gUtK/2918HIYZtqRgTahmGRHKNYiDKM/vHreUeSVzjzZXaYHc14cGFlfpnJmFLELCWa6zWVeLqXxQ/DUtJBNfP49Sgs7MKhsHlmK98gLHtcdCstVBNlpsHXhy86Tw8@8/2yu6Z99ewpUwwLaMiIJmDARLraF/xS67hlapjmHvlZux/DqY3sO1eYNMaYfsdVFVTTDj4LXOipFyEw91y@2DMcfMYfLhmuE4kEf92xiTj6l2YUYfUMOxmu6F9dBF5EZxoz5ZkGNiWGAfrVRRUfQUGmrFMxAyMWn1@N96eDr5C25laeCRcUpyDYq2uyq7ihfFwJfFOYaqV82312b77Dtt2pPJoc693eVIgFXkavX5xnFmJzOBL/0PzR3hmJ3xngqYhGRVJsnOLSlMUI8KU@82hU7FjwKWTW6@t9cVbWDnSCAu5RfbujCm6dvrS1qxlqeOCEobtYK2IXOOgtyNdLIUmGuYazUDN9EYAIPqJksJjZt4OV19eK5@gLX/kDRZjE@dxbPD@6M6y@HIrhKRH4OPN6W36cqkcrmBLygKVLiVbivOleZ7NXOHT11MnSKo23EYP4YuqSC9XsBW7mHGJ8q@kQI1mHIjeY9aLhbYOtH@mjZv15u4efGGEsCwxhGt5eFoicj3y3BxYSCMd6N72Dhc/GtPiI5ywZ5Q7jWleM4qoHqRLubStoZDYXbg6@bjdfd8172xos0PEnaYSy2sGtZA4mvYu9ncQ2IIGZ8f6U@3@bO5twWY018g/ec3UUa05zap7RxeAdG0EpcH540D@3NTmQOieZBGJV01eM2KrikK3vbKz2ea5PwX9s1pPvchcv0DP6mFLwpTpeZph/lKYz5S5dsP7WxLC0@NR50b5dpFocPDhi93kKzM7Dw/iXi3ijCifM@zrc6B/fG9U1tPz4ivsVVe20cGMkXxnGB/UzfKGxAK6gBbcL72u6fWPwTbO7RGmFtPypf8@rODlsJHE3uUKSHWACWUW9tg/gOVF5dt@fLNQH6E3xJLBrLokCxwclfr9Or7tkjsZPwjfz07ga0LCfnR7AI1dVhJky8DsAwcPy6/9x/bV5PNQoNeds/WZettafXh9Go5g70PM3@bVkS1Xc4tPFx9Hg1mk1leX4W354723gvJu@sXmzgxjhJhB9LfkHzT@ZfCoYGSNDF3H/w323j6UkEUEvcur0J9QN5xQQUiJrT@HfoCxdMjYg8TBhv5Jwg3eADp8r/nDe01maa2Z0V4aOxuynwm0VxRkgGq3x@MjEJxxUHMTf5lxa52uRta64/rhaqORUf4K2@t0EB5hifIKKWBjSNYWziFsvN9xMSA7BgftzWW7w1sF472yIA8pGYlkLfJJEPgtJWtBFtJ3r50lQrwvY5tCIVdVZZTSNF7M/KUsS0@LkTdeThjAJh7jroAlQnjNrL0fP7zFU7xdjteTbZxVuimpZbsdqQE42Rvl/QSzlGsUGDkQElQTMncWu2k/0akiVQWtnwDEywHjC5vygqeZTkliVC2JXxWr/H4vvE79WX5SSv1XHlXJJE4KhUqF16iuaLnWnM2gmb5q46P8QCckCjV4AbA5TzN9EY5hT4GwfBW3zs6G/W5XHiul5FsOuluECJMsnYOTMEI1XhVBpZZbLRbJIuP9eWxykGqbgFchtkY8PClZ6HzxqkYCPmtksb@vk2AvP4XAROmaXCRR@hMoMCYK7PcuV3/vcvIeAYBQASzJmBppyC3KQ1bu/S0fNL5f3KJbHfN2IrGR60LhPXq/cmI0DeeLfKtl81jOz16UhRaSsExi@td8zG2Wy1xn5I7DLC/0CVtYbUyJMZv8d4b7Vb2BCWOC68PPn/8LF0s/DOKflYsGU6oKn598zw@W/wc "Perl 5 – Try It Online")
### Integer input (non negative)
In this case, we calculate the `N`th Fibonacci number, where `N` is the input. We do this by keeping track of two numbers, initialized to `(0, 1)`, and `N` times replacing `(n, m)` by `(m, n + m)`.
[Try it online!](https://tio.run/##fZZhd5pKE8ff@ynWnU1cEBc0KlVEjUmTNjdpbpo0TQJIiCKSKhhQgyL56E@fJe2Le@659@5RloM/Z/8zOzPswo1mjZ8/wcd8kDTWDUxKmg//MgowMVuqahNnQVYy8if8WUs9l1LAy8gfoM1i4XzCuk0QQgWgAZ90exNWI4lMKGdviLFNQMOr8B6FS7RxxlPMCuA2Wg2xo2tjHXkl6nLw2V5fWecXVgYbJ9Z@fwsQIlEUuzHAWxAlcshB/Xl2fbsqwpseFSPHPS6GyyIHJ3XTNIWFUd64LhnmMt@0KbwbioqzyP2zyCXkIBWDINCi@lfpdWFXco3qPn09/WNw/uSty/P09g3G4UIvgFBFdez79bWDiNQTOHh8FQ@28utNKXJU0Jz5OHCiUw7W6kiYBOpR5ckumTkIkrN4/1HazOfhhbQZj53jAqRIret0mRW3joTGKeeuDyEKJyjyZJvImydnIMdvfOlYFcU3efJxc/jU35UJBxOSe/Lrios/Imd6jXABHNFUYxN3KpVNUiI2AMuNMOEgEWTChGaCw3Ccg5tqgORjZd16KGaJrHOLKVCGfxnK/4Mp1RNSgHKtfkBl5eSbhFwi4H/PC4paoins3b0etmd2@unfQVwX6@P0SbyqHMeS78LJjHWm1D29XLwDBqOWhTMOVkUTlWUsqg/YLU1mUH65v7i8ukufVYjufDLCzLLsRg6aQUMYSt5nJ0srdAZeelPeRIODfgtCZw2E4Jpi6xxEQV2kHhnPKxkpkRD65MnpjkY7rQOT5b5mUMEw7ISD4kGrboZ26XTr2oktgXSeeYYZgHAKiLKNwPBohBAHa0hEx6EWz6SZTgQED9/Z@WExPpDOYWu2HYwZX93mYKNpHgge6QyiGCfpd/gUtK/2918HIYZtqRgTahmGRHKNYiDKM/vHreUeSVzjzZXaYHc14cGFlfpnJmFLELCWa6zWVeLqXxQ/DUtJBNfP49Sgs7MKhsHlmK98gLHtcdCstVBNlpsHXhy86Tw8@8/2yu6Z99ewpUwwLaMiIJmDARLraF/xS67hlapjmHvlZux/DqY3sO1eYNMaYfsdVFVTTDj4LXOipFyEw91y@2DMcfMYfLhmuE4kEf92xiTj6l2YUYfUMOxmu6F9dBF5EZxoz5ZkGNiWGAfrVRRUfQUGmrFMxAyMWn1@N96eDr5C25laeCRcUpyDYq2uyq7ihfFwJfFOYaqV82312b77Dtt2pPJoc693eVIgFXkavX5xnFmJzOBL/0PzR3hmJ3xngqYhGRVJsnOLSlMUI8KU@82hU7FjwKWTW6@t9cVbWDnSCAu5RfbujCm6dvrS1qxlqeOCEobtYK2IXOOgtyNdLIUmGuYazUDN9EYAIPqJksJjZt4OV19eK5@gLX/kDRZjE@dxbPD@6M6y@HIrhKRH4OPN6W36cqkcrmBLygKVLiVbivOleZ7NXOHT11MnSKo23EYP4YuqSC9XsBW7mHGJ8q@kQI1mHIjeY9aLhbYOtH@mjZv15u4efGGEsCwxhGt5eFoicj3y3BxYSCMd6N72Dhc/GtPiI5ywZ5Q7jWleM4qoHqRLubStoZDYXbg6@bjdfd8172xos0PEnaYSy2sGtZA4mvYu9ncQ2IIGZ8f6U@3@bO5twWY018g/ec3UUa05zap7RxeAdG0EpcH540D@3NTmQOieZBGJV01eM2KrikK3vbKz2ea5PwX9s1pPvchcv0DP6mFLwpTpeZph/lKYz5S5dsP7WxLC0@NR50b5dpFocPDhi93kKzM7Dw/iXi3ijCifM@zrc6B/fG9U1tPz4ivsVVe20cGMkXxnGB/UzfKGxAK6gBbcL72u6fWPwTbO7RGmFtPypf8@rODlsJHE3uUKSHWACWUW9tg/gOVF5dt@fLNQH6E3xJLBrLokCxwclfr9Or7tkjsZPwjfz07ga0LCfnR7AI1dVhJky8DsAwcPy6/9x/bV5PNQoNeds/WZettafXh9Go5g70PM3@bVkS1Xc4tPFx9Hg1mk1leX4W354723gvJu@sXmzgxjhJhB9LfkHzT@ZfCoYGSNDF3H/w323j6UkEUEvcur0J9QN5xQQUiJrT@HfoCxdMjYg8TBhv5Jwg3eADp8r/nDe01maa2Z0V4aOxuynwm0VxRkgGq3x@MjEJxxUHMTf5lxa52uRta64/rhaqORUf4K2@t0EB5hifIKKWBjSNYWziFsvN9xMSA7BgftzWW7w1sF472yIA8pGYlkLfJJEPgtJWtBFtJ3r50lQrwvY5tCIVdVZZTSNF7M/KUsS0@LkTdeThjAJh7jroAlQnjNrL0fP7zFU7xdjteTbZxVuimpZbsdqQE42Rvl/QSzlGsUGDkQElQTMncWu2k/0akiVQWtnwDEywHjC5vygqeZTkliVC2JXxWr/H4vvE79WX5SSv1XHlXJJE4KhUqF16iuaLnWnM2gmb5q46P8QCckCjV4AbA5TzN9EY5hT4GwfBW3zs6G/W5XHiul5FsOuluECJMsnYOTMEI1XhVBpZZbLRbJIuP9eWxykGqbgFchtkY8PClZ6HzxqkYCPmtksb@vk2AvP4XAROmaXCRR@hMoMCYK7PcuV3/vcvIeAYBQASzJmBppyC3KQ1bu/S0fNL5f3KJbHfN2IrGR60LhPXq/cmI0DeeLfKtl81jOz16UhRaSsExi@td8zG2Wy1xn5I7DLC/0CVtYbUyJMZv8d4b7Vb2BCWOC68PPn1VF@V@4WPphEP@sXDSYUlX4/OR7frD8Pw "Perl 5 – Try It Online")
### String input
Now we "Covfefify a string". We start of by grabbing the parts of the string we need (`/^($c*$v*($c))$c*($v)/`, where `$c` and `$v` are character classes matching consonants and vowels). We find the replacement consonant by doing a lookup (`{split//,bpcgdtfvgkkgpbsztdvfzs}->{$2}||$2` -- the string is split into a list of characters, the surrounding `{}` turns the list into a hash ref; the `->{$2}` indexes the second captures; if there is no match, the `||$2` makes it return the second capture -- this takes care of consonants which are replaced by themselves). Then it's a matter of constructing the final string.
[Try it online!](https://tio.run/##fZZhd5pKE8ff@ynWnU1cEBc0KlVEjUmTNjdpbpo0TQJIiCKSKhhQgyL56E@fJe2Le@659@5RloM/Z/8zOzPswo1mjZ8/wcd8kDTWDUxKmg//MgowMVuqahNnQVYy8if8WUs9l1LAy8gfoM1i4XzCuk0QQgWgAZ90exNWI4lMKGdviLFNQMOr8B6FS7RxxlPMCuA2Wg2xo2tjHXkl6nLw2V5fWecXVgYbJ9Z@fwsQIlEUuzHAWxAlcshB/Xl2fbsqwpseFSPHPS6GyyIHJ3XTNIWFUd64LhnmMt@0KbwbioqzyP2zyCXkIBWDINCi@lfpdWFXco3qPn09/WNw/uSty/P09g3G4UIvgFBFdez79bWDiNQTOHh8FQ@28utNKXJU0Jz5OHCiUw7W6kiYBOpR5ckumTkIkrN4/1HazOfhhbQZj53jAqRIret0mRW3joTGKeeuDyEKJyjyZJvImydnIMdvfOlYFcU3efJxc/jU35UJBxOSe/Lrios/Imd6jXABHNFUYxN3KpVNUiI2AMuNMOEgEWTChGaCw3Ccg5tqgORjZd16KGaJrHOLKVCGfxnK/4Mp1RNSgHKtfkBl5eSbhFwi4H/PC4paoins3b0etmd2@unfQVwX6@P0SbyqHMeS78LJjHWm1D29XLwDBqOWhTMOVkUTlWUsqg/YLU1mUH65v7i8ukufVYjufDLCzLLsRg6aQUMYSt5nJ0srdAZeelPeRIODfgtCZw2E4Jpi6xxEQV2kHhnPKxkpkRD65MnpjkY7rQOT5b5mUMEw7ISD4kGrboZ26XTr2oktgXSeeYYZgHAKiLKNwPBohBAHa0hEx6EWz6SZTgQED9/Z@WExPpDOYWu2HYwZX93mYKNpHgge6QyiGCfpd/gUtK/2918HIYZtqRgTahmGRHKNYiDKM/vHreUeSVzjzZXaYHc14cGFlfpnJmFLELCWa6zWVeLqXxQ/DUtJBNfP49Sgs7MKhsHlmK98gLHtcdCstVBNlpsHXhy86Tw8@8/2yu6Z99ewpUwwLaMiIJmDARLraF/xS67hlapjmHvlZux/DqY3sO1eYNMaYfsdVFVTTDj4LXOipFyEw91y@2DMcfMYfLhmuE4kEf92xiTj6l2YUYfUMOxmu6F9dBF5EZxoz5ZkGNiWGAfrVRRUfQUGmrFMxAyMWn1@N96eDr5C25laeCRcUpyDYq2uyq7ihfFwJfFOYaqV82312b77Dtt2pPJoc693eVIgFXkavX5xnFmJzOBL/0PzR3hmJ3xngqYhGRVJsnOLSlMUI8KU@82hU7FjwKWTW6@t9cVbWDnSCAu5RfbujCm6dvrS1qxlqeOCEobtYK2IXOOgtyNdLIUmGuYazUDN9EYAIPqJksJjZt4OV19eK5@gLX/kDRZjE@dxbPD@6M6y@HIrhKRH4OPN6W36cqkcrmBLygKVLiVbivOleZ7NXOHT11MnSKo23EYP4YuqSC9XsBW7mHGJ8q@kQI1mHIjeY9aLhbYOtH@mjZv15u4efGGEsCwxhGt5eFoicj3y3BxYSCMd6N72Dhc/GtPiI5ywZ5Q7jWleM4qoHqRLubStoZDYXbg6@bjdfd8172xos0PEnaYSy2sGtZA4mvYu9ncQ2IIGZ8f6U@3@bO5twWY018g/ec3UUa05zap7RxeAdG0EpcH540D@3NTmQOieZBGJV01eM2KrikK3vbKz2ea5PwX9s1pPvchcv0DP6mFLwpTpeZph/lKYz5S5dsP7WxLC0@NR50b5dpFocPDhi93kKzM7Dw/iXi3ijCifM@zrc6B/fG9U1tPz4ivsVVe20cGMkXxnGB/UzfKGxAK6gBbcL72u6fWPwTbO7RGmFtPypf8@rODlsJHE3uUKSHWACWUW9tg/gOVF5dt@fLNQH6E3xJLBrLokCxwclfr9Or7tkjsZPwjfz07ga0LCfnR7AI1dVhJky8DsAwcPy6/9x/bV5PNQoNeds/WZettafXh9Go5g70PM3@bVkS1Xc4tPFx9Hg1mk1leX4W354723gvJu@sXmzgxjhJhB9LfkHzT@ZfCoYGSNDF3H/w323j6UkEUEvcur0J9QN5xQQUiJrT@HfoCxdMjYg8TBhv5Jwg3eADp8r/nDe01maa2Z0V4aOxuynwm0VxRkgGq3x@MjEJxxUHMTf5lxa52uRta64/rhaqORUf4K2@t0EB5hifIKKWBjSNYWziFsvN9xMSA7BgftzWW7w1sF472yIA8pGYlkLfJJEPgtJWtBFtJ3r50lQrwvY5tCIVdVZZTSNF7M/KUsS0@LkTdeThjAJh7jroAlQnjNrL0fP7zFU7xdjteTbZxVuimpZbsdqQE42Rvl/QSzlGsUGDkQElQTMncWu2k/0akiVQWtnwDEywHjC5vygqeZTkliVC2JXxWr/H4vvE79WX5SSv1XHlXJJE4KhUqF16iuaLnWnM2gmb5q46P8QCckCjV4AbA5TzN9EY5hT4GwfBW3zs6G/W5XHiul5FsOuluECJMsnYOTMEI1XhVBpZZbLRbJIuP9eWxykGqbgFchtkY8PClZ6HzxqkYCPmtksb@vk2AvP4XAROmaXCRR@hMoMCYK7PcuV3/vcvIeAYBQASzJmBppyC3KQ1bu/S0fNL5f3KJbHfN2IrGR60LhPXq/cmI0DeeLfKtl81jOz16UhRaSsExi@td8zG2Wy1xn5I7DLC/0CVtYbUyJMZv8d4b7Vb2BCWOC68PPn6Nw7UaO5/4vXCz9MIh/Vi4aTKkqfH7yPT9Y/h8 "Perl 5 – Try It Online")
## Rotate the program, no mirroring
We effectively end up with:
```
if(eof()){$_=("___|"x18).$/;$_ x=2;s/^..|..$//g;$_ x=5}
else{@c=map{$_-1}<>=~/./g;$_=$".(""," ___"," _"," ___"
)[$c[0]].$/.$".("_===_","....."," /_\\","(_*_)")[$c[0]]
.$/.($","\\",$",$")[$c[4]]."(".(".","o","O","-")[$c[2]]
.(",",".","_",$")[$c[1]].(".","o","O","-")[$c[3]].")".(
$","/",$",$")[$c[5]].$/.("<",$","/",$")[$c[4]]."(".($".
": ","] [","> <"," ")[$c[6]].")".(">",$","\\",$")[$c[
5]]."\n (".(" : ",'" "',"___"," ")[$c[7]].")"}say;
```
### No input
We now "Build me a brick wall!". We start off by concatenating the string `___|` 18 times by it self, adding a newline, then doubling the line. We remove the first two characters, and the last two characters before the final newline. We then print the result 5 times.
[Try it online!](https://tio.run/##nZZpe6LIFoC/@ytKqqKFC4trIuIWs06WSSdtFheCgohRMOACIvnpt@9Bp@fpuc98ue1jLVSd89ZyFljozqz44wf@3R9hGLl9IbuuyxEcM8dUt8eUZQOiyJRRFGXHeOIxyxFeIgry5Jzk8gOO23EwwhuHsWKIsYfQl@os4nGVUXBMn7l60BjJc3UBoKwYVmvyF8/tFWTCcJRhMgwCetQg5ecDxrL26Gqq/br0JzKOsV0y6gr9PqzF7bUUWZYjaS76RVq80utBS5WUwjI/xTGm9oTXLM22JY3BsUidEhCLZEn030sWAMzQCBuhbCj3ULKHydwBo7Z8Da/irnoJGArTmb2w8jdEBMi/AvIRnQU6xgzjqJn5V7yt@iqORRvhf91H8XBAylT3o4fJf@4QDo9xy/sY3qqdP3UfLXCMqSCQ7aMu1DVU3V8kOqiVfi7N1A7Ew7n3cxirpbhvS4GuSkvARIszPQvt7wFFzCSDmGSG@Wmcv5jlAzN0VV/CBPxmyDL8HM8dx7V9HJMXtoZr/lbYtL605X21fnmMXTdkWjeru/oRbU5HtfTZLlNyJtPHW077M17hEmsTMD4nkXk5PYurCOGYyHGiIEi6Zy6jlfZeMzjeDcSueNynYHM2Rfi6alVUCdfofTnZo0v1BTCIuIqvruOO/9r61YsBQpQjsViHel/loaqcm9ttpbWCKupFHTS2HcA88iqfcQxHxraJY78dUxPWNy6SQ@krXDn/jmmP8u@r9kb6nG@V99eH1eW3zs3zN6f99MjozM1F9aS8AEt5xHGeblzcZ5YHjL5X9nLgDZiHogw65ftG3FtLxkt899nMtlLeS8soTV6zb3aGlRrTe4ydvIfUTUuN30oQDDhkqav0vpt6g4xxV2YzGN8NnYVh3Nz2SvPSpJQRNqmGolw4jNW7Zlt5vMsHFxh/sNLY4v/wVzewMGD4wYxo3ulM2i0DdRR/g2NvGk9ub/LdubreFQvC/Z0gXU@3t/Or@iy3ca1R6wX2z3CurW0vpE7fCwBjt3n9qJvUTHansTypw8l2x7br1daCwb8@f5TKn6t1xRa1066p0JdEvDdyHiCmuBZkm9YGPz5sM4DRelJoYUGaiKHBY4kCJr0iiaKRfQpaud1C@wwGlvGxfVHe3FWXSzS7Nf9@AhGu@lh16WS27t4ARud5j4TaZpPJjVjqs0046on3vbksVgvvw21TsjudSqd0Mx9sS0pQfLgx1PRtNYoG0sw8JKSpQsqAcSjLyyEfsAJZrMerEK541fmW/Xx9Pi3fyGf167eLnn1@nC3slumpVq5w4fDpFbYc@N4jbpe/5OnTCWCkcZxNLGqlPg2GxLQTkB@NMl5Y@I/3q1b7vNNwnkI72SjnZjsjMX2wnm9I8DmD3XC/eFoMK2Y9niA1LMq1DJVMApjX6/N0/4QO5eT1Q412zt4F5q7X3TXnxuPT5VumYaTP/8dhY5hItL6IN8Kul@VTjO5bGJ@tr//PyIjh9IKlJD7oe42QH/VVFZJA@voZ48XcnoykWlVWSKC7Mz1k4trMsZ9Rxp7N9EsmGmdZOrZ1OjYBMw9Zyb8WSOAuyVp2bYw7VRYMKnsNiVVIRawLVYXQVC4tyh6oQn9sBuBiaa1Xzw54eJJi2LcToaJed9P61mTJOphibD@CK1umPYUVJdYjXjKbzETN16GBJwWaHTq0BCVjWJ0QkbgnXt8dzyBd1mWM7yncM8fYPrJs5Fq2uVRnq6XqGJZ9yvx9SK8BkIXuGBmexLA78oksuUSYrRcjRqIK@A0bxXnIgFlRv66yqX5THXSp2nUPgJBpV1DcH6pDtNEt5KyYGA4k1bdyD35X11wi10JI14VBlCWvnsLbXa4VXmyx5KuuFIa6YfadzDarvmWbGSjQy/hfski6gKm5KsmmVS9cBnRdLQUYl6@i1C9IymliW3r/do8rr592y/6ezAud1uxiflV@2Hw/yfrx0/W3NNbshRzDbDVwJct2CbulKSLnwEjOuBZ9ecxXR7fJqXHpWp/Co4FfTLN091F1k5qRSr2cr6tnYblQ6O63Chi5HogES5mcS9eSEgBm9tCBqwkFsDVPUmxYDDgqCPAC4SPTKSTDDI8EgRkvLdNZuNGdxzBVaL3GCUIfDeGtSqLXc6sCltpf5mRpWPosUtZNLZHg9Zlh28YAAplv9/Yew@4dNIbHpE4V7kgWvQWX6of8GOPRewHcb@/GB9OAVXmReChHeLbdoyw4HuXdL5mFvJpKoTJYyg7SHMnhWpc1xNF6KYEXnzUakd@kUCmVh4LKkSgoFKCXR4VUEUoe@gVUgNHiHqPrHCsjTfHyH4QQ8xXS7O3mgBFzIFtECGTLhag@Kfyj@msQnQCGuoPUwrEB8eHTgRfdzTCd3GNAAEoOREsoJ6bKUVVC@f2@fj4XUNHqAWY8g681e5GlnAGuqnPR3TRHgEEMyAhiChVTUVPYnwsVcykkigxNg5l/jXBTD7hgLGdldu3yjNQ0f@dN/OPHf@zF0rQt90f2tsiBc0A7NA3TWv4X "Perl 5 – Try It Online")
### Other input
It's time to build a snowman. We split the input on characters (which is assumed to be a string consisting of `1`s, `2`s, `3`s, and `4`s). It's then just a matter of combining the pieces of the snowman by getting the right parts from a series of lists.
[Try it online!](https://tio.run/##nZZpe6LIFoC/@ytKqqKFC4trIuIWs06WSSdtFheCgohRMOACIvnpt@9Bp@fpuc98uc1jLVSd89ZyFlzozqz44wf@3YcwjNy@kF3X5QiOmWOq22PKsgFRZMooirJjPPGY5QgvEQV5ck5y@QHH7TgY4Y3DWDHE2EPoS3UW8bjKKDimz1w9aIzkuboAUFYMqzX5i@f2CjJhOMowGQYBPWqQ8vMFY1l7dDXVfl36ExnH2C4ZdYV@H9bi9lqKLMuRNBc9kRav9HrQUiWlsMxPcYypPeE1S7NtSWNwLFKnBMQiWRL99pIFADM0wkYoG8o9lOxhMnfAqC1fw6u4q14ChsJ0Zi@s/A0RAfKvgHxEZ4GOMcM4amb@FW@rvopj0Ub4X/dRPByQMtX96GHynzuEw2Pc8j6Gt2rnT91HCxxjKghk@6gLdQ1V9xeJDmqln0sztQPxcO79HMZqKe7bUqCr0hIw0eJMz0L7e0ARM8kgJplhfhrnL2b5wAxd1ZcwAb8Zsgw/x3PHcW0fx@SFreGavxU2rS9teV@tXx5j1w2Z1s3qrn5Em9NRLX22y5ScyfTxltP@jFe4xNoEjM9JZF5Oz@IqQjgmcpwoCJLumctopb3XDI53A7ErHvcp2JxNEb6uWhVVwjV6X0726FJ9AQwiruKr67jjv7Z@9WKAEOVILNah3ld5qCrn5nZbaa2ginpRB41tBzCPvMpnHMORsW3i2G/H1IT1jYvkUPoKV86/Y9qj/PuqvZE@51vl/fVhdfmtc/P8zWk/PTI6c3NRPSkvwFIecZynGxf3meUBo@@VvRx4A@ahKINO@b4R99aS8RLffTazrZT30jJKk9fsm51hpcb0HmMn7yF101LjtxIEAw5Z6iq976beIGPcldkMxndDZ2EYN7e90rw0KWWETaqhKBcOY/Wu2VYe7/LBBcYfrDS2@D/81Q0sDBh@MCOadzqTdstAHcXf4NibxpPbm3x3rq53xYJwfydI19Pt7fyqPsttXGvUeoH9M5xra9sLqdP3AsDYbV4/6iY1k91pLE/qcLLdse16tbVg8K/PH6Xy52pdsUXttGsq9CUR742cB4gprgXZprXBjw/bDGC0nhRaWJAmYmjwWKKASa9Iomhkn4JWbrfQPoOBZXxsX5Q3d9XlEs1uzb@fQISrPlZdOpmtuzeA0XneI6G22WRyI5b6bBOOeuJ9by6L1cL7cNuU7E6n0indzAfbkhIUH24MNX1bjaKBNDMPCWmqkDJgHMrycsgHrEAW6/EqhCtedb5lP1@fT8s38ln9@u2iZ58fZwu7ZXqqlStcOHx6hS0HvveI2@Uvefp0AhhpHGcTi1qpT4MhMe0E5EejjBcW/uP9qtU@7zScp9BONsq52c5ITB@s5xsSfM5gN9wvnhbDilmPJ0gNi3ItQyWTAOb1@jzdP6FDOXn9UKOds3eBuet1d8258fh0@ZZpGOnz/3HYGCYSrS/ijbDrZfkUo/sWxmfr6/8zMmI4vWApiQ/6XiPkR31VhSSQvn7GeDG3JyOpVpUVEujuTA@ZuDZz7GeUsWcz/ZKJxlmWjm2djk3AzENW8q8FErhLspZdG@NOlQWDyl5DYhVSEetCVSE0lUuLsgeq0B@bAbhYWuvVswMe3qQY9u1EqKjX3bS@NVmyDqYY24/gypZpT2FFifWIl8wmM1HzdWjgTYFmhw4tQckYVidEJO6J13fHM0iXdRnjewr3zDG2jywbuZZtLtXZaqk6hmWfMn8f0msAZKE7RoYnMeyOfCJLLhFm68WIkagCfsNGcR4yYFbUr6tsqt9UB12qdt0DIGTaFRT3h@oQbXQLOSsmhgNJ9a3cg9/VNZfItRDSdWEQZcmrp/B2l2uFF1ss@aorhaFumH0ns82qb9lmBgr0Mv6XLJIuYGquSrJp1QuXAV1XSwHG5aso9QuScprYlt6/3ePK66fdsr8n80KnNbuYX5UfNt9Psn78dP0tjTV7IccwWw1cybJdwm5pisg5MJIzrkX/POaro9vk1Lh0rU/h0cAvplm6@6i6Sc1IpV7O19WzsFwodPdbBYxcD0SCpUzOpWtJCQAze@jA1YQC2JonKTYsBhwVBPiA8JHpFJJhhkeCwIyXluks3OjOY5gqtF7jBKGPhvBVJdHnuVUBS@0vc7I0LH0WKeumlkjw@sywbWMAgcy3e3uPYfcOGsNjUqcKdySL3oJL9UN@jPHovQDut3fjg2nAqrxIPJQjPNvuURYcj/Lul8xCXk2lUBksZQdpjuRwrcsa4mi9lMCLzxqNyG9SqJTKQ0HlSBQUCtDLo0KqCCUP/QIqwGhxj9F1jpWRpnj5D0KI@Qpp9nZzwIg5kC0iBLLlQlSfFP5R/TWITgBD3UFq4diA@PDpwIvuZphO7jEgACUHoiWUE1PlqCqh/H5fP98LqGj1ADOewb81e5GlnAGuqnPR3TRHgEEMyAhiChVTUVPYnwsVcykkigxNg5l/jXBTD7hgLGdldu3yjNQ0f@dL/OOHCE@hIIr/sRdL07bcH9nbIgdOAu3QNExr@V8 "Perl 5 – Try It Online")
## Rotated 180°, mirrored.
Effectively, we have:
```
if(eof()){say$_%15?$_%5?$_%3?$_:Fizz:Buzz:FizzBuzz for
1..100;exit}say<>=~/^8|^1[18](...)*$/?an:a;
```
### No input
Without input, the program does the FizzBuzz challenge. Nothing special going here, we loop numbers from 1 to 100, if 15 divides it evently, "FizzBuzz" is printed; if 5 divides it evently, "Buzz" is printed; if 3 divides it evenly, "Fizz" is printed, else, the number itself is printed.
[Try it online!](https://tio.run/##pZZpf6LIFoff@ymwqqIFIotxSUTcsmeSzqSTNosLQUEkUTDgAiL56LfvwUz37bkzL@5S@VUVtZynlvM/FeemNy19/45tMxKisZpX2ZUvIqVl4/8hpfB4KgrEneepYOmDrimMMR61RhgLDOKKjCRzTIlLqiJTcXrQKHCMLCOaC3U/Ylk6dk06tlOY@gNu7rmEkLeQDgKBYjzMZQGDuEPmEHIBrMtMQeYqSVFm9qFd/NkuMiWnh1LYNAVWZQwt2H8DlP1kYny9bu4wcoGpcCWGAbtKMSkPi38q/uhkDgHjRjmBFHC9y1ryaLVQXIxPmp8YpsztQwYWtzsRnAs6ikAuQl2BdgIrMRXAjEmDasKeKgdzgevHYnI3L0WM6XzmTkaR6U/N2PQsUSYBUyAie9yjbM7oUdH/UFkEGG6HoRpt1AVJ6jNDShBJ7qZdRRjv7CcLyzGnqkYU0zYyGdGcWq5rDcSIFY97ItytwtZrMJzCrNqIZIIVvuDTlaJFLMbT2w7GcSxV5YZIODYuRQKVJFmSxASoER4N9yQJjReO7c196IsAU4t8xXF9wm4oR9QCYLxxHbRAZsu96@yrde4779KdhR9tu/zlreZnDYvjHk9XtZO4Uix2sQKuT@Go7uskn9ODeBHRVa0cYVy5IICRFO0osym/fL3B1ad3t@1@y@5Lnfb0bHZRuV1/O8yH6aPV1xw23LkKGEUPncJt2DUNn6j1GAjFwSNgLu7j622hHZ9tdgsqcWxadt/jN3n9Od/iIcMXH36oMummsD8Kiar4RJqu5iOkUA3jJSsCJkZTjJl@Q2e5fgsETvWu/@m4GB1XmXQ41IfM2nQYbwme0idEJv5h0PfHU7ZLGirGNxQlunFDxnEZ33HthT5dLnTPctwjlNzoDhY0eY3MQQu8CJ4K3Uys6ZfdnLmxWbKKXjF2754xdmz3NXEMG5Agm8/ySfXxWUFLg2rLfNaEyaZwbhazSngpkchfkJXqg4o7NXAXVYOmwmoEvC7VNEK5Qk5WAxJBF@gFhENAhI38YKcewMxZStKDftCMxVFf1@GhyF0@YLwTsbIT1@chUNqYeu4Dw7vTqXm@O9wvEU4U2pinm3E3yIscMkMHYmp1@V@/N5rdSGdIHctqnaeKTeB2ny5Pc/1DOlSzl7d12jl5kdCXXnfbmll39@fPfNPKnf4Fo4zTbGZeL/dpNCS2mwGMVcFzB//2ctE@Pu00vfvYzTYrhenWyrzeOg9XJHoHKWDhTxiPsqIaQ7BJZL4aL2MedNP5mn9/ejiqXKknjcvns557epAvbhe5V6NSFeLh/RMgojC4w8eVD/X1/hAwpigGJDbWa74wYmnItgB@GHxrLUq14stw01LcTqfaKV/NBpuyFpVuryw9d12DSUPS4m8zyqtGKoAxekrsQABN5NgSsUJhodySZEpW/j5qF7Zz4z0aONbb5lF79pddIdPq1sObCQhCD7Hu08l01b0CjHssmnvdrGGzWwPE0ADM9sD1g/pKssSnh7dy5X25qrqycdS1NfqYSfdG3i08SkJb9@btNb673fCAicXBlBjB0VTZLiJ9lAYBT9bNe783@eZdXG5LRenmi6Rcvm6uZxeNaWHtO6P2IzzYSPBdY3OmdPpBlGBY6mu9b7bZJGPcVVm44i9Db25ZV9e98qw8KfPSmmtq2pkHL@Yl297H2/3oDOM3Vhk74m/h8mrnKUjmzmlBIXFhEtvaoFO5aaaDlWI9prfvrXybCx7bVnnylH92eVZpvt7A27YfMPq6raevFfSJ@fd0PNp/WR6vlffZRnt5ul2ef@1cPXz1ju/vkImuzmqHlTnGekA87/7Kx320@HvMf5QmbGidZYfKR7z0cMoeU9MdU5aNfD0k2p5cakC5K/ahqJ7am021vYQi@Uo@mLHrAeZO1EXeszwVuzZOyYIAT75iBvYiBlCtrn6Ig4PtQO7KB30qCALLEbGhO1VdwXV6U8n26EJP3liG@Fqor9Je@NTGKXXuGrgebqR1@8NY3NQa5wfY92PUvlp@aezR1uuonjvZ8mVv8np3LRi/p6tCZpX86ggFhcwquWlaZxicKvX7Auo5DEUCRUyVQXwWMSjLI03TEI8YhkHwtI66lWQei5IdKzj5xzFkkTjDM8/z3RCnUGKJ@kwXyjpT@9Wy/GkJ@DriCYz0ekm9GwNPldOhq0SmrizmOJUMi7tZf0xItkdEsK192oo/R4oJNtk1QaCwdvA2vNY7v5shAxiYz8OfAFn7aSCDAd31uZBvIOc/B/Z/bBCCAXk6P/tIH@uhDphk5X/t@C8r/x2s0O9DhLt6OzTwMu3r5zi165c@D0ISM01V1eRyhSQlVyVqyQqIapzGoh/TE8xENBzDdRUDgsGc@mbUHKkzfR4RLS/HO@UIoqUQTd1xE9QPt2k/Ghirxp1v6O7TIpyov6oYzGji5i0K5AMWdgcgJlALii8OBGErQM8ODn2lGCKZYT7gxUmndaT9HzFFEFKPz1Tf9wWCv3//hztf2K7jf89flwT4LQT10LZsZ/FP "Perl 5 – Try It Online")
### Other input (assumed to be a non-negative integer)
This does the "You're on a 8 day streak!" task. If the input starts with `8`, or starts with either `18` or `11` followed by `3 k` digits for some `k >= 0`, we print "an", else we print "a".
[Try it online!](https://tio.run/##pZZpf6LIFoff@ymwqqIFIotxSUTcsmeSzqSTNosLQUEkUTDgAiL56LfvwUz37bkzL@5S@VUVtZynlvM/FeemNy19/45tMxKisZpX2ZUvIqVl4/8hpfB4KgrEneepYOmDrimMMR61RhgLDOKKjCRzTIlLqiJTcXrQKHCMLCOaC3U/Ylk6dk06tlOY@gNu7rmEkLeQDgKBYjzMZQGDuEPmEHIBrMtMQeYqSVFm9qFd/NkuMiWnh1LYNAVWZQwt2H8DlP1kYny9bu4wcoGpcCWGAbtKMSkPi38q/uhkDgHjRjmBFHC9y1ryaLVQXIxPmp8YpsztQwYWtzsRnAs6ikAuQl2BdgIrMRXAjEmDasKeKgdzgevHYnI3L0WM6XzmTkaR6U/N2PQsUSYBUyAie9yjbM7oUdH/UFkEGG6HoRpt1AVJ6jNDShBJ7qZdRRjv7CcLyzGnqkYU0zYyGdGcWq5rDcSIFY97ItytwtZrMJzCrNqIZIIVvuDTlaJFLMbT2w7GcSxV5YZIODYuRQKVJFmSxASoER4N9yQJjReO7c196IsAU4t8xXF9wm4oR9QCYLxxHbRAZsu96@yrde4779KdhR9tu/zlreZnDYvjHk9XtZO4Uix2sQKuT@Go7uskn9ODeBHRVa0cYVy5IICRFO0osym/fL3B1ad3t@1@y@5Lnfb0bHZRuV1/O8yH6aPV1xw23LkKGEUPncJt2DUNn6j1GAjFwSNgLu7j622hHZ9tdgsqcWxadt/jN3n9Od/iIcMXH36oMummsD8Kiar4RJqu5iOkUA3jJSsCJkZTjJl@Q2e5fgsETvWu/@m4GB1XmXQ41IfM2nQYbwme0idEJv5h0PfHU7ZLGirGNxQlunFDxnEZ33HthT5dLnTPctwjlNzoDhY0eY3MQQu8CJ4K3Uys6ZfdnLmxWbKKXjF2754xdmz3NXEMG5Agm8/ySfXxWUFLg2rLfNaEyaZwbhazSngpkchfkJXqg4o7NXAXVYOmwmoEvC7VNEK5Qk5WAxJBF@gFhENAhI38YKcewMxZStKDftCMxVFf1@GhyF0@YLwTsbIT1@chUNqYeu4Dw7vTqXm@O9wvEU4U2pinm3E3yIscMkMHYmp1@V@/N5rdSGdIHctqnaeKTeB2ny5Pc/1DOlSzl7d12jl5kdCXXnfbmll39@fPfNPKnf4Fo4zTbGZeL/dpNCS2mwGMVcFzB//2ctE@Pu00vfvYzTYrhenWyrzeOg9XJHoHKWDhTxiPsqIaQ7BJZL4aL2MedNP5mn9/ejiqXKknjcvns557epAvbhe5V6NSFeLh/RMgojC4w8eVD/X1/hAwpigGJDbWa74wYmnItgB@GHxrLUq14stw01LcTqfaKV/NBpuyFpVuryw9d12DSUPS4m8zyqtGKoAxekrsQABN5NgSsUJhodySZEpW/j5qF7Zz4z0aONbb5lF79pddIdPq1sObCQhCD7Hu08l01b0CjHssmnvdrGGzWwPE0ADM9sD1g/pKssSnh7dy5X25qrqycdS1NfqYSfdG3i08SkJb9@btNb673fCAicXBlBjB0VTZLiJ9lAYBT9bNe783@eZdXG5LRenmi6Rcvm6uZxeNaWHtO6P2IzzYSPBdY3OmdPpBlGBY6mu9b7bZJGPcVVm44i9Db25ZV9e98qw8KfPSmmtq2pkHL@Yl297H2/3oDOM3Vhk74m/h8mrnKUjmzmlBIXFhEtvaoFO5aaaDlWI9prfvrXybCx7bVnnylH92eVZpvt7A27YfMPq6raevFfSJ@fd0PNp/WR6vlffZRnt5ul2ef@1cPXz1ju/vkImuzmqHlTnGekA87/7Kx320@HvMf5QmbGidZYfKR7z0cMoeU9MdU5aNfD0k2p5cakC5K/ahqJ7am021vYQi@Uo@mLHrAeZO1EXeszwVuzZOyYIAT75iBvYiBlCtrn6Ig4PtQO7KB30qCALLEbGhO1VdwXV6U8n26EJP3liG@Fqor9Je@NTGKXXuGrgebqR1@8NY3NQa5wfY92PUvlp@aezR1uuonjvZ8mVv8np3LRi/p6tCZpX86ggFhcwquWlaZxicKvX7Auo5DEUCRUyVQXwWMSjLI03TEI8YhkHwtI66lWQei5IdKzj5xzFkkTjDM8/z3RCnUGKJ@kwXyjpT@9Wy/GkJ@DriCYz0ekm9GwNPldOhq0SmrizmOJUMi7tZf0xItkdEsK192oo/R4oJNtk1QaCwdvA2vNY7v5shAxiYz8OfAFn7aSCDAd31uZBvIOc/B/Z/bBCCAXk6P/tIH@uhDphk5X/t@C8r/x2s0O9DhLt6OzTwMu3r5zi165c@D0ISM01V1eRyhSQlVyVqyQqIapzGoh/TE8xENBzDdRUDgsGc@mbUHKkzfR4RLS/HO@UIoqUQTd1xE9QPt2k/Ghirxp1v6O7TIpyov6oYzGji5i0K5AMWdgcgJlALii8OBGErQM8ODn2lGCKZYT7gxUmndaT9HzFFEFKPz1Tf9wWCv3@XDyRJ@oc7X9iu43/PX5cE@EEE9dC2bGfxTw "Perl 5 – Try It Online")
## Rotated 270° counter clockwise, no mirroring.
We end up with:
```
$_="Happy Birt"
."hday to You";
say;say;say
s!to!Dear!r=~
s!You!Perl!r;say;
```
This does only one thing, sing "Happy Birthday". The string "Happy Birthday to You" is created, and printed twice. Then it's printed with "to" replaced by "Dear", and "You" by "Perl". Then the original string is printed once again.
[Try it online!](https://tio.run/##fZZhe5rKEsff51OsO5u4IC5gVKqIGpsmbU7SnDRpmgSQEEUkVTCgBkXy0W/vkp4X97n3nrOPIj78mP3P7MzsLrx41vj1C/5mBHqZYNNIMoL5CGCPOAb@7C4WGzQI4iWGTDrXWhycBEhekYVLHE1rWRPYY3g6djdoGaH7aIV1SLcmueEgnRApVqONYyCEQgp7ibvR//pCbl@c21dr55mDHi37yBjrRkdstBoeB0vLqHTsuXEpNt6gtLq9nj0bHIzkNA7fAJKuKIooKkA@ZelP7lkpfjcNU/2t0DgknrepmAvBsqw612gsojG83Wbzytp/Oh/8cfpKD7RCY9VZvErf6rEehqHINZ7Gbjieuzpobly@eZW3g@TqmINCTyLIXdeDANeRKsDesTseb6SLaD7fSO8vLVypiKNglZ2n6kctnAioXuOg8ZbIA/dpIxNH9mM0iWI4uuZgNkaSuy3lS2rUNZTBHkbXUzf@WcKFJyT9feUgqez6T0ebTxP5TRS1pADHUYTTpsCILKSHAivMMwCHlNNNtdrBVqJZosuXMDUoxcXT36Yxo5Bxi4ac5qWH1lo5llGobmDv75ICC8RD0vcTRaaH9Vrl78HPmTNrH73e7QuW2EI8jpBj26bMfH@6uDz16LTDZifgBVJyXL0Sn7JxXaxjDjYc22Z4RIK7GLTn7O7q8uL@pQKzSdnDD5qI5QqyRJWDhqPUMCGwdiNo9Q8H8aZyk/kwo9Usd7/40lBohFYBpo5pCtTUD5YT6Oi70ajrPpE@RKRM8up8THwq1kPEQYRGI8yEDaMITgUILdPPzyWQnNTxtqdlJ7LqrUORgw6fl2Hstq0tnEuHSenonP14ACQQYybNEj06RiKqcZBIpmlTkpTKW8DR4PXg4KodfoYfWYqTeNAhvnBoNRsc1LEg2FjK/9RW4D0ItTvW0K5uuEbpo2ff/nRmshiKhUbfwfiQzz2@HACuns2omY2fryFOy1EWKF8Nj2h1tdAoI6Fq2pbA6Bau762es3KeD3h4jLcw8Q@bslxDrZr1Djp4ZFv4oruFm2n4JUiaFX8OY7Xsm145UA5QXURh4QwWJVLH7BoCOG7iufmwXe6OoFRJYzf/zsFUtDSNg0xysGlK9rN@ArEfX3x0hrvZDnCNuDSP7tQxsX47wzC9FEbYnrpt@DY43Y7v5vWaCbmYLk19AEqghkitc3DHveYx1@L2Fn7cOc/q9ryqWbxTSKthEvmKJ2v1WuE1cySpakpmM@Qrkzpn0c/mh/5XmJHyzHVfrqnuIw2p7yC3KOCR5K7gVuzrbf/2pIwhcaru0eZeYSQWxabCwSGyIgl3ya434BpFZR22o0gBr1Ne2nr7JXM80Xp3RsYW14jNT3IbPldfv66Gt1b@CJmSBiJA2DByLbQKjYnkSJcSFSpkC6sj5fIluz29@QSkRyJhe5nkM4/3x99JIXORDHfFLVy9SIr2Ej3Et@CoaeiefvsseDOeZcXUNYyYJGM0EgK43zXrzbF@1qdgtIWklz/6Ypg0G6iY2qBFNxfQMzuBx9K08XNx1LvtQofoyB40n4nvIbH1XjNMotxtdMTa4Nw1dz92208nV9B1SIRq27K8zA41sQgPKgTyD2UObP352X3tyTg@A11wQtgdXPSmIxG1Co0OrxiJ2NI@JTDXm1/kweP5oAwj3UBw8XFfzafNGirWmhiMYsnGPbsHL2sr9rO69sWAaf95M8udVduLkNoqnNEdxiduOl8/HIKeXnxXbjofH58gSnk3vNHnymzOt4WipciEMdwxnZW6D6@l8@m62vjxB4W5EeD8i0LyZMGDUmgkOrMpHjnnpgPHfd/q@st7aMGChqzoW7lHGR9F9vjYZpTggUpgdeknaePoJbT/pw3ugSBLdZuZEh724FFb3CQH36uLyv8BPzBs2rJQzncNOLyN@xFJv8HJ2Q/hAct3pHuL6/1@ecRBVXZGKt@Ukw/7MBo@vX5YtW61s/VZ55oKwy@Tq/Zj/7VyVCzhm0FMhlAy5M44X6e7Cqz8@0@V2@hyVdfi2WD06eKpsIgNwxzZCPM4wT8MXoVdQyA2Kn946/0z6HR4A2hg6bPR4P@lB8aOJIzDIHo2HJIJAp1EHp0EHMwxEXh0el0VQBZKPSrkB2TjJlmP5s1axmT9nr/MQZVKeIRRp7NfbFgjom9WUeC5xpro3Q63mi@D1NO5M1XGG0WnfblxOGi6Mj93BDq218TEBVzcDU28B5Q3cclEaOm@e50JsrAmVBwRQRjx3zXht3Qo85ohRMJCF4@TDQCbLMf@aPEkyfIymC2SjFLK1EIx15gxzLsKfctdgBrZ7fIaybrVPNlO1uPlNnla@D9/@mueZgvZ4pOzwTIBSPu6oEoKNdJ@5iUzLxdqKBUOCRP2IHOJJfHIvQbFNu3NgumrYKtmSiq2wq/S@z01eJrNeRFikyqpUJzdPo7116zJD1UFxbXpisErt1rloGFLjCC09Qrwe1pWxnK32x@enbWSq0oEyj6MowW3SEc25lUYbnTKQWvMu3K@IKVSYa1WDXlF1VAcTfZg0ld4fLDVVSZQnDn2Q2IcHCyI7hAjJLrKJzYWJNuDKDMpliUMSsR9KTxN/1px9a8VZ4LI2B543ohxi2ysesWRbCjr/5UZvQobytwiTYiMJWRHrNAoyMeWXCz2Yh5NR7@z4j2iXOPMJBS37QUrNOZ5NPZirq9SKez9Zz4GnsAYwQ1DDf4pw3/9@le0WAZRmPyqXjSYoir89ynwg3D5bw "Perl 5 – Try It Online")
## Rotated 270° counter clockwise, mirrored.
Effectively, we end up with:
```
$x=(("Baby Shark".(
" doo"x6).$/)x3).Baby.
" Shark!";say$x;say$x
=~s/Baby/$_/gr for
Daddy,Mommy,Grandpa,
Grandma;
```
This sings Baby Shark. It creates the string "Baby Shark doo doo doo doo\n", repeated thrice, followed by "Baby Shark!". This is printed, then it's printed another four times with Baby replaced by "Daddy", "Mommy", "Grandpa", and "Grandma" repectively.
[Try it online!](https://tio.run/##fZZvd5rKFoff@ynG2ZPIIA5oVKqIGpsmbU7SnDRpmgSQoCKSKhhQgyL56Ld3yOmLu@4657BUEB72/Paf2TNLN5o3fv0C36WMEdzQqz78y1GA6dwgAm5bSzbl/7MsnLiRZpNyeevEaUqpMA1dYeoXQIiJjCVkhUzgIJVPTJnf15aLcDbWuh3dJqkbz90CuO6YSRizSdXloDCUNZkWewLNDklusyf0ymwopwUIU0PAsoRBCQHyd7PkN1n9TTIqMsY19hXCLZpdJddok4OA6IeHS8J16gHRql1@XhJuURhbGEtWsNVyjebE4A4tSbHIrWm1SkAYq6EonBaA6pbECEI7l3Lwe1JSJnK32x@en7fi63IIygFMwqXOwQXDGBuCkuSg/3GivaZNyCzFSHKNmqLzwSuVAqQOMSUu8tVPOejO/dkrtaqcKr@z0vu1wC2SpWxiIrHBKgZI@hqtSoqgJ/336GW0hhJ6RBgtgJ0ybGMsvGUOQI3s91mNpN1KFu@mm8lqF4@W3s@f3qYAOuHRoV08ibcAbLqaeOPlSJLllT9fxqkgCOw9njw8Nh/YQGjlkDz5KZXphgjimFA65ucN4Zc8XwXAFYYJ6bSvtjbnDEeGPNXY2hAD6xvyfjU0MNdYFSQ8xqjTOeCgPibadh36rpND7zWRrfzE1TiYYUINCfe6VYD/q4esWUuZrD0wdszBjo2NBpY@6w1uUXrkN3lUAz98zivsf@px39UpsVDpw1vv3ysc67oxthAGmfw7mLzpxGAIxUMbTuyvs30Z1t7Dp/JdeLWuq9F8MP50ORpzsCrb4yrBOP5wAOPh6PXDunWnnm/OOzcCHX6ZXref@q/lYw5@YNiwZFrK9g04uov6IUm@wen5D/qI5XvSvcP1fr@UW6SyVLcYj8@wB0/q8jY@/F5Zlv9GI/OwxQSCB1UC6ysvThrHL4H1NyDRmCXgsX1hcGf6ntn1Vg/QgqUQsBzIXIHxg4MynxW4Y9jr6gG8Fi9mm0rjxx8CLHQfZ18UksVLPgEQBzWbYYab9tcPR6All9@V287HpxGESRjiW22hzBeiKOJ8aJ0JfBbintWDl40ZeWld/aLDrP@8nWf2uu2GqNoSOWgThiViSQcCgYXW/CIPni4GJRhrOoLLjwfVbNasoToHEW8n@UdgNuy8xflDbaSfnING7QD2h5e92VhErVxjwiQhlDA6Zm2w75v7H/vdp9Nr4HM0RLVdSV6lR6qocFAXuFeYomd2Ck/FWePn8rh314UO0ZA1aD4Tz0Viq8rBGkZMkjEaUx8e9s16c6Kd9wXQ2zTuZU@eGMTNBsqd0bCMc41dcQfXL5KivoSP0R2fIUngnH37TN25iGq5xliypStJoGWyg/WxcvWS3p3dfgLSIyHdXcXZ3EUoaOSZwSbGBBuf5DZ8rrx@XQ/vzOwJUiXxRYCgoWdqYOZDD5HJne6SfW8A3waisgnaYaiA2ymtLK39ktquaIr50MzOncZjyVnDndjX2t7daQlDbFec4@2Dwkgkik3lHZSkiiEZzWAHF4l9Hv5sfuh/hTkpzR3n5UbQPKSiPDz73CIhatTewY97@7m6u6ioJriCtB7Goae4slqv5Rp58q7oGFszp801nu0m94t6jfdnMVkZ2gAUvxqgap5rJvEGYEjWs3YKkRddfrSH@/kecI04QhbeVyfEDN6dIViUSB2zG/DhpIkXxuNutT@GYjmJnOy7rxwmoqmqeRyRjceWiS@7O7idBV/8uFn2FjCpljzDLXEQ1UUUvIO0YlgmZcIObh7Mnr22nw89mOtvQewdNWW5hlo1k4Me9/qIV@TkasB75flcMNLJ8w1ESSlMfeWr7hK1Xv2rKCi1sJT9qa7BfaS1e9ZQr28hJNJH17r7ac9l8bczkmFYAomLpR3gcPB6eHjdDj7DjzTBcTToEI8emc28KHgL57MGO22TZ0Y6iovHF@zHIyBK9Lk0j7XwBPE6y@cMGo8xo1smIDijEJiGl11IINmJ7e7OSnZo1ltHucbENgwqGNrhagodbT8ed50R6XONJZJVFhPiCWI9yDXqtlLjo8PGCaHVPxpE2/JtysMjVNLM@eJJQ9oIzLwoGrZlMTwm/n0E6nN6f311@fBShvm05OJHVcRyGZliDmbYsgRmvLes5dWZK8w6bH4Kri/FJ5VrcZRO6mI9byn/cHxO7Xn7@PX@gJpiCwn/DGJKXCR9P1Vk4aheK0OBJLog4IEz2qKbmRP9xHxXky/cupxkxcfWRjmRUVDdQgGjCe9vSZMyItPkiLL8HZbvQkrJtlLpYDNWTdHJwXdDRazFzpYkf/1yi6S874@Ot5@m8psoqjEU9LdYzo3IxJa9CE3DCI5v8uV4giRnV8xWgl5XUQqFE2cy2UqX4WKxlc4iJ5gsHSl3hpole1T5qAZTiuo1CoX3hwtHA9WJSrev8m4QX5/kYE8iyNnUfR/XUZWD@jKcwNtduihvvNHF4I@zV@FQzTdpFXv5Kn2rR1oQBCKPY1x8CNfFP/lmshjlnmgw0944OB0S192WjSU1TbM@zcFVWDxxnagY6W9QXN/dzJ91DoZyEgX8jbjLFwUUcpAb@f3l26fLC@t6Yz/nOyWh5CF9oukdsdFquFBgeDZxtmgVIi4Ba5DsDHKba5wSKaqGW1tHvD9yjcTW8WdnudyigR@tMKTShdrKNfpIXpOlQ2xVbZnTfy4KXyvx7qrHKcnXAh9@/fpPuFz5YRD/qlw2mFJV@Hnke36w@i8 "Perl 5 – Try It Online")
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 4 orientations, 4 tasks, 1205 bytes
## In Honor of Adam West
```
>52*" ** * *** * ** "v v.:>1
v" **** *** ***** *** **** "*52< <1+^
>52*" ***** ********************* ***** "v
v" *********************************************** "*52<
>52*"*************************************************"v
v"*************************************************"*52<
>52*"*************************************************"v
v" *********************************************** "*52<
>52*" ********* ********* ********* "v
v" ****** ******* ****** "*52<
>52*" **** ******* **** "v
v" **** * * **** "*52<
>52*" * * "v
> ^v **25"A"<
v-1,\_@#:<<
> ^v *2"s"<
>52*"EEEEE DDDD CCCC BBBB AAA "v
v"A A B B C D D E "*52<
>52*" EEEE D D C BBBB AAAAA"v
v"A A B B C D D E "*52< <,,,,,,,,,,,,,,@
>52*"EEEEE DDDD CCCC BBBB A A"v v"Hello, World!"*25
```
[Try it online!](https://tio.run/##pZTLqsIwEIb3fYpx3I1VaKEbCcV4Ad/AjSiI9WzKERTz@jVpkjaJF4z@EJjMJR@ZDDlUp9v/X9U0ZZETghaRNeyevH2fgAJATKZllgg0mX0OWQ95h3RJSEXOAFg22iUGT/4Bj3JjCq@4FCfN1USKVUuMr/qV@MsdnU4ChL195tFE6wJH9MplXzPpx@jDWjNGZn4e6sibOz8cEiHMDeRGJBHeqLTGTjjkvECO7G2hGGfpdj8bThmLBFCOVzTXWSlp91KqNRZSJnUupS3OuW4eVxsdNEtWdLSlWQCrsHEdqc9xajsSV/qSBCz1NIu7ZAuUH43AdVXX5xQ250t9HKB8jqa5Aw "Befunge-93 – Try It Online")
Nothing special here. We push the 650 characters which needs to be printed
on the stack, then use a loop to print 650 characters.
## 5 Favorite Letters
Mirroring the original program vertically gives us:
```
>52*"EEEEE DDDD CCCC BBBB A A"v v"Hello, World!"*25
v"A A B B C D D E "*52< <,,,,,,,,,,,,,,@
>52*" EEEE D D C BBBB AAAAA"v
v"A A B B C D D E "*52<
>52*"EEEEE DDDD CCCC BBBB AAA "v
> ^v *2"s"<
v-1,\_@#:<<
> ^v **25"A"<
>52*" * * "v
v" **** * * **** "*52<
>52*" **** ******* **** "v
v" ****** ******* ****** "*52<
>52*" ********* ********* ********* "v
v" *********************************************** "*52<
>52*"*************************************************"v
v"*************************************************"*52<
>52*"*************************************************"v
v" *********************************************** "*52<
>52*" ***** ********************* ***** "v
v" **** *** ***** *** **** "*52< <1+^
>52*" ** * *** * ** "v v.:>1
```
[Try it online!](https://tio.run/##pVPBisJADL33K2K8xbrQQi8yFKtd8A/2sriwWL0UBcX5/ZpOp51M6RZmfTCQJi/vzYT0tzo/r5eqafIsJfxsAQYlwwR7RpeCHcMERXtQg8ZDVde3GL5u9/q0QEqzSGNhGdxgD6tAj9IeAOOElKUKVOxhG5nrwHAd1yTE3HVaoP6XdRT08NYK2AlmkPfBUduAUnygmm3S6yT@/tkuN0oFirM8jx0LtE8RZPpTRlbM4AYpojFLJlxZDG@is/ueSHmO05TJ1NiRaEydzXSOFAbpSKEwjuFd7zq@80Y7sfH0PLqoic3xS4IxfAtS98eDSlZHb2Md0VNyC@h2j3dff2zypGle "Befunge-93 – Try It Online")
As above; it pushes the 230 characters to be printed on the stack, and
then uses a loop to print 230 characters. It will reuse part of the loop
from the solution above.
## Count up forever
Mirroring the original program horizontally give us:
```
1>:.v v" ** * *** * ** "*25>
^+1< <25*" **** *** ***** *** **** "v
v" ***** ********************* ***** "*25>
<25*" *********************************************** "v
v"*************************************************"*25>
<25*"*************************************************"v
v"*************************************************"*25>
<25*" *********************************************** "v
v" ********* ********* ********* "*25>
<25*" ****** ******* ****** "v
v" **** ******* **** "*25>
<25*" **** * * **** "v
v" * * "*25>
<"A"52** v^ >
<<:#@_\,1-v
<"s"2* v^ >
v" AAA BBBB CCCC DDDD EEEEE"*25>
<25*" E D D C B B A A"v
v"AAAAA BBBB C D D EEEE "*25>
@,,,,,,,,,,,,,,< <25*" E D D C B B A A"v
52*"!dlroW ,olleH"v v"A A BBBB CCCC DDDD EEEEE"*25>
```
[Try it online!](https://tio.run/##tZPLasMwEEX3@YrJdDd1CzZ4E0SImgb6B9mEFErdbEwCKdXvu1IlWZrIMnFJLgikeVwfPfzRfP0cD03XgVe5XDwrAIVuTeQnfk1sHQqQqno5641g/1gKAFHVhK4xtJCPEPPsi1BFRlaGiLhJqjiXEllZIpqmYSKaqhGi6V73JrrNGUU31UdHI2NEvjDOUC6Uf0f8OY65DL5sTpS6EftBeDpPBJddF4ozGSKUWFcRidr7WVqcSIjFw@p9V5RParBY4DdWdKWz3pOU0s5ftFx4rfU3edWyoY3R8H7YKW9snxvOzvq7AWA@KFFliKT0SIFo3eeDswEKJ7wqmMT/iPS14PyzPZ@2UJzatnlDZYhcxfVn1HW/ "Befunge-93 – Try It Online")
Uses a tiny loop. In the loop it duplicates the top of the stack, prints it, then adds 1 to the top of the stack. Rinse and repeat. `1` is pushed on the stack before entering the loop.
## Hello, World
Rotating the original program by 180° gives the following program:
```
52*"!dlroW ,olleH"v v"A A BBBB CCCC DDDD EEEEE"*25>
@,,,,,,,,,,,,,,< <25*" E D D C B B A A"v
v"AAAAA BBBB C D D EEEE "*25>
<25*" E D D C B B A A"v
v" AAA BBBB CCCC DDDD EEEEE"*25>
<"s"2* v^ >
<<:#@_\,1-v
<"A"52** v^ >
v" * * "*25>
<25*" **** * * **** "v
v" **** ******* **** "*25>
<25*" ****** ******* ****** "v
v" ********* ********* ********* "*25>
<25*" *********************************************** "v
v"*************************************************"*25>
<25*"*************************************************"v
v"*************************************************"*25>
<25*" *********************************************** "v
v" ***** ********************* ***** "*25>
^+1< <25*" **** *** ***** *** **** "v
1>:.v v" ** * *** * ** "*25>
```
[Try it online!](https://tio.run/##tZPLqsIwEIb3PsWccTenCi10I6FYL@AbuBEPiNVNUVDM69fEpM2kjeUU9IeAc83XGXMoTo/LuaiqNCH8OZa36xaia1kWG5QgMQcAfQAWSmC0VHr9WCkZ11oLKUmzkbLmkScBIkkJX3mmzh7bzvS3x9yXoxxBQIpIq0W0bOKuswaChqijDxJBDTRoRl0ivGNCddd97Q4n@5ViNp7/7aJ40kUUmKNaLTnens4SmUFv7@OR8Pc009XZxG63tdzhwoEJWyK/h7EDrn8QhQuDrvdERO2iXk8fEQ1TmIiGqodoeK9vE31mRnYj7e14hSzW3dr@Nxbsn@0XsLrGZkmcKM5mU8nemkv2urlH4t6HJqqqJw "Befunge-93 – Try It Online")
This will push the necessary characters on the stack, and then prints those characters (no loop).
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 4 orientations, 4 tasks, 1794 bytes
We are (ab)using the fact that (ba)sh is a true interpreter: it reads a line of code, and execute it. This means, once it has encountered an `exit`, it will never see the rest of the program, and won't complain it cannot parse it.
## 5 Favorite Letters
```
echo " AAA BBBB CCCC DDDD EEEEE";# eedw
echo "A A B B C D D E ";# xcoh
echo "AAAAA BBBB C D D EEEE ";# ih i
echo "A A B B C D D E ";# toxl
echo "A A BBBB CCCC DDDD EEEEE";# =e
exit ;# $$
x([
;(
dx1
o+
n1]
e)
)
### ;;;;
;;; ####
"
c" #; tixe
\! #;" ** * *** * ** " ohce
,d #;" **** *** ***** *** **** " ohce
ol #;" ***** ********************* ***** " ohce
lr #;" *********************************************** " ohce
lo #;"*************************************************" ohce
eW #;"*************************************************" ohce
H #;"*************************************************" ohce
"" #;" *********************************************** " ohce
#;" ********* ********* ********* " ohce
oot#;" ****** ******* ****** " ohce
hhi#;" **** ******* **** " ohce
ccx#;" **** * * **** " ohce
eee#;" * * " ohce
```
[Try it online!](https://tio.run/##pdJBT8MgFAfwO5/iCTtsTy87Lx46t8Rv4EE9KH0JTRpJtMn49vW1lEFbE9fyT2hegV9Jgc@PH9O2pI0FCUVRQJ8jx1fwxOmLE8d3nbvIg@KSqLwIrzvq@XFojCHkNDTW3cNrp60JugiLx7X/1JxBVwaq9Ws31tVzfet/AzySIFc1sDBebzYCVsdtXzP0YZuBS7fP0PY@A3/t3zM07TIw7IRSauV2cwS3dZqXVUIKLUGt@kJTORJvd6zl0IMYivCOo/c4QYI1msRDGTRixL5CjEUcwUTb2msc43nSsauuv3uNy3LVttO4NIOmlxz9DDlaypz/Bkj2PNnbf3rCidnGn/dkZpw874rnbUwV7tqNOr1rWrv0pqaTcXRJx8PhxIiinsyeJB3xum1/AQ "Bash – Try It Online")
## Count up forever
Rotating this by 90° counter clock wise, we end up with
```
while [ 1 ] ;# eeeeeeeeeeeeee
do x=$((x+1));# xccccccccccccc
echo $x;done ;# ihhhhhhhhhhhhh
exit ;# tooooooooooooo
"""""""""""""
***
###### *****
;;;;;; *******
""""" ********
E E *********
E E E **********
E E E **********
E E E ** *********
EEEEE * *********
****** *
****** *
***** *
*****
*****
DDD ******
D D *******
D D ********
D D *******
DDDDD ******
******
*******
**********
**********
***********
C C ***********
C C ***********
C C **********
C C **********
CCC *******
******
******
*******
********
*******
B B ******
B B B *****
B B B *****
B B B ***** *
BBBBB ****** *
****** *
* *********
** *********
**********
**********
AAAA *********
A A ********
A A *******
A A *****
AAAA ***
""""" """""""""""""
;;;;;;;;;;;;;;
ooooot ##############
hhhhhi #; tixe
cccccx #; "!dlroW " ohce
eeeeee #;"c\,olleH" ohce
```
[Try it online!](https://tio.run/##rZXNboQgFEb39yludRYztJtZmy4UTPoGXbRdtEqCiSlJa1Le3gJ2OlB@jNM5LlRO8AqBj7fXTzHPX2IYOT7hEV8QqxK5B/QS1f1uv1e3x8NBa9W5AO@ExJ2qevnOTe9BuABXw4QntJ6kCwD@pXAJtYEQAqUlaNemsoRCK/tNjCkCrX5po8q4NuW2SkLc7xo861ZNDF2j75da@5DWOcMYi9YD08yiEx4YQtb7sKBQekLWTE7FbU4SR1L9Tq8jMSu9P6KUbh3nJrM69FyfRl/ROk1KXWKWFdwYrrU58tvO27L/WE21JhEwNdbJCU@7mMJUsZ/cDCIwn7eVB9jQPuc5lh5gI384OTeDp0FxsAeGOuviph8/5CMWKEXHYTlvfnXRPd/JceQPi57nbw "Bash – Try It Online")
## In Honor of Adam West
Rotating this once again by 90° counter clockwise, and we get:
```
echo " * * ";#eee
echo " **** * * **** ";#xcc
echo " **** ******* **** ";#ihh
echo " ****** ******* ****** ";#too
echo " ********* ********* ********* ";#
echo " *********************************************** ";# ""
echo "*************************************************";# H
echo "*************************************************";# We
echo "*************************************************";# ol
echo " *********************************************** ";# rl
echo " ***** ********************* ***** ";# lo
echo " **** *** ***** *** **** ";# d,
echo " ** * *** * ** ";# !\
exit ;# "c
"
#### ;;;
;;;; ###
)
)e
]1n
+o
1xd
(;
[(x
$$ #; tixe
e= #;"EEEEE DDDD CCCC BBBB A A" ohce
lxot #;" E D D C B B A A" ohce
i hi #;" EEEE D D C BBBB AAAAA" ohce
hocx #;" E D D C B B A A" ohce
wdee #;"EEEEE DDDD CCCC BBBB AAA " ohce
```
[Try it online!](https://tio.run/##pZLBTsQgEIbv8xQju4cVveyZeHBdE9/Ag3pQOgkkjSTaRN6@DoVtgVSTtn86Ccz8HxPofLx/m74nbRwKnCTxL@UVoXZEBAUtWbU7T0xlpr3WOV2ycT@TutDWmImet86mIt05N9JS1uZ/M0xfULlMAUUhEi2XKtD4tIV@pi20a7fc@6stH7x@2ALIasODY@uyUSktmXPcZ6ZAN7f1mJbzPFKyNgT66hXI2w5XKPxvDbhBAnasdaxSCjjUOprbAl7zR/B2/AS8cXD0DeBBwcvBA@73g2vx6Z31PIZ3sYcSj0GxcmYNiwdWcp9Yw@I@hEBnNEHrXRfpUIn0OUVUxE8pStqisYkee8/RWe@gRBun/frePw3RsnuH5hjpvv8F "Bash – Try It Online")
## Hello, World!
A final rotation of 90° counter clockwise, and we get:
```
echo "Hello,\c";# eeeeee
echo " World!" ;# xccccc
exit ;# ihhhhh
############## tooooo
;;;;;;;;;;;;;;
""""""""""""" """""
*** AAAA
***** A A
******* A A
******** A A
********* AAAA
**********
**********
********* **
********* *
* ******
* ****** BBBBB
* ***** B B B
***** B B B
***** B B B
****** B B
*******
********
*******
******
******
******* CCC
********** C C
********** C C
*********** C C
*********** C C
***********
**********
**********
*******
******
****** DDDDD
******* D D
******** D D
******* D D
****** DDD
*****
*****
* *****
* ******
* ******
********* * EEEEE
********* ** E E E
********** E E E
********** E E E
********* E E
******** """""
******* ;;;;;;
***** ######
***
"""""""""""""
ooooooooooooot #; tixe
hhhhhhhhhhhhhi #; enod;x$ ohce
cccccccccccccx #;))1+x(($=x od
eeeeeeeeeeeeee #; ] 1 [ elihw
```
[Try it online!](https://tio.run/##pZTBTsMwDEDv/grT7rAZLjtXHLaCxB9wAA7QRkqlapGgEvn7MrdbY7fJGOJVkZK8NKndyB/vX7bvTWUdZk@mbd3da5UVOY6YARg1PrvPtr7JcNK@YsD4psPApBvLQK4I6zrHQKGATCJ2xWECxj4R4YzdETjLpcYdjpoo6k@artMUO3qSNBuEt/QIeXReKrqzs/cMUCq0PT/pyP@oI15aUgNKqkU/nteyLEVCZrbkplL5i6b/6dRfUwGkgtSf/sCo5GjNTWfysr78Ni4OF1Z2SczGLp6@nHLPR0bfZKX5Sf@qKzWmNGqtww11IaZPVSV1/8eaFKqKLj8ATtJhXoTq1XgDVtKwNgdXF36FzlYGKok/6s1me@vX69W9R1eDUQybv@EWX9C0jf3u@x8 "Bash – Try It Online")
On TIO, this will actually print `Hello,\c`, followed by `World!` on a newline. Whether `\c` is supported is implementation defined according to POSIX.1, and so is the alternative, the `-n` option. The intention is to surpres the newline `echo` by default emits. (And on my system, the builtin `echo` omits a newline when encountering `\c`, but doesn't recognize `-n` -- and the standalone utility does both). YMMV.
] |
[Question]
[
According to [this site](http://grammar.yourdictionary.com/capitalization/rules-for-capitalization-in-titles.html#8Xf7g96YSUq87kkL.99) a general rule recommended by *The U.S. Government Printing Office Style Manual* is
>
> Capitalize all words in titles of publications and documents, except
> a, an, the, at, by, for, in, of, on, to, up, and, as, but, or, and
> nor.
>
>
>
This might not be true as I'm unable to find such a recommendation in the [Style Manual](https://www.gpo.gov/fdsys/search/pagedetails.action?granuleId=&packageId=GPO-STYLEMANUAL-2008), but let's use this rule anyway.
---
**The Challenge**
Given an input string consisting of lower case words delimited by spaces, output the capitalization of the string according to the following rules
* The first and last word is capitalized.
* All other words are capitalized, except *a*, *an*, *the*, *at*, *by*, *for*, *in*, *of*, *on*, *to*, *up*, *and*, *as*, *but*, *or*, and *nor*.
The input string will contain at least one word and each word contains at least one letter and only characters from `a` to `z`.
This is a code golf challenge, so try to use as few bytes as possible in the language of your choice. You may write a full program or a function to accomplish the task.
**Testcases**
```
"the rule of thumb for title capitalization" -> "The Rule of Thumb for Title Capitalization"
"programming puzzles and code golf" -> "Programming Puzzles and Code Golf"
"the many uses of the letter a" -> "The Many Uses of the Letter A"
"title" -> "Title"
"and and and" -> "And and And"
"a an and as at but by for in nor of on or the to up" -> "A an and as at but by for in nor of on or the to Up"
"on computable numbers with an application to the entscheidungsproblem" -> "On Computable Numbers With an Application to the Entscheidungsproblem"
```
[Answer]
## Python 2, 118 bytes
Look ma, no regex!
```
for w in`input()`.split():print[w.title(),w][`w`in"'a'an'and'as'at'the'by'but'for'nor'in'of'on'or'to'up'"].strip("'"),
```
Input must be wrapped in quotes. Output has a trailing space and no trailing newline (I assume that's okay). [Verify all test cases on Ideone](http://ideone.com/zgCcW9).
### Explanation
Let's take the input `a or an` as our example.
Using Python 2's ``x`` shortcut for `repr`, we wrap the input in single quotes: `'a or an'`. Then we split on whitespace and iterate over the words.
Inside the loop, we take the `repr` *again*. For the first and last words, this gives `"'a"` and `"an'"`. For other words, it gives `'or'`. We want to avoid capitalizing words if they fit the latter pattern and are in the short-words list. So we can represent the word list as the string `"'a'an'...'up'"` and know that the `repr` of any short word will be a substring.
``w` in "..."` gives a boolean value, which we can treat as `0` or `1` for the purposes of indexing into the list `[w.title(), w]`. In short, we title-case the word if it is at the beginning, at the end, or not in the list of short words. Otherwise, we leave it alone. Fortunately, `title()` still works as expected with input like `'a`.
Finally, we strip any single quotes from the word and print it with a trailing space.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~68~~ 61 bytes
Saved 7 bytes thanks to *Adnan*
```
™ð¡Dg<UvyN__NXQ_“a€¤€€€›€‹€‡€†€‚€‰€„€¾€ƒ€œ€³€—š¯“#™yå&&il})ðý
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oSiw7DCoURnPFV2eU5fX05YUV_igJxh4oKswqTigqzigqzigqzigLrigqzigLnigqzigKHigqzigKDigqzigJrigqzigLDigqzigJ7igqzCvuKCrMaS4oKsxZPigqzCs-KCrOKAlMWhwq_igJwj4oSiecOlJiZpbH0pw7DDvQ&input=dGhlIHJ1bGUgb2YgdGh1bWIgZm9yIHRpdGxlIGNhcGl0YWxpemF0aW9u)
**Explanation**
`“a€¤€€€›€‹€‡€†€‚€‰€„€¾€ƒ€œ€³€—š¯“` is a dictionary string translated as `a an the at by for in of on to up and as but or nor`.
```
™ # title case input string
ð¡ # split on spaces
Dg<U # store index of last word in X
vy # for each word
N__ # is it not first index?
NXQ_ # is it not last index
“...“ # the compressed string
# # split on spaces
™ # convert to title case
yå # is current word in this list?
&& # and the 3 previous conditions together
il # if all are true, convert to lower case
} # end loop
)ðý # wrap stack in list and join by spaces
```
[Answer]
# GNU sed ~~81 74~~ 73 Bytes
Includes +1 for -r
```
s/\b./\u&/g
:;s/.(And?|A[st]?|The|By|But|[FN]or|In|O[fnr]|To|Up) /\L&/;t
```
The first line capitalizes the first letter of every word. The second switches all of the required words back to lowercase.
[Try it Online!](http://sed.tryitonline.net/#code=cy9cYi4vXHUmL2cKOjtzLy4oQW5kP3xBW3N0XT98VGhlfEJ5fEJ1dHxbRk5db3J8SW58T1tmbnJdfFRvfFVwKSAvXEwmLzt0&input=dGhlIHJ1bGUgb2YgdGh1bWIgZm9yIHRpdGxlIGNhcGl0YWxpemF0aW9uCnByb2dyYW1taW5nIHB1enpsZXMgYW5kIGNvZGUgZ29sZgp0aGUgbWFueSB1c2VzIG9mIHRoZSBsZXR0ZXIgYQp0aXRsZQphbmQgYW5kIGFuZAphIGFuIGFuZCBhcyBhdCBidXQgYnkgZm9yIGluIG5vciBvZiBvbiBvciB0aGUgdG8gdXAKb24gY29tcHV0YWJsZSBudW1iZXJzIHdpdGggYW4gYXBwbGljYXRpb24gdG8gdGhlIGVudHNjaGVpZHVuZ3Nwcm9ibGVtCmEgYSBh&args=LXI)
[Answer]
# Retina, ~~69~~ 66 bytes
Capitalize the first letter of every word, then change the selected words to lowercase if they're not the first or last word. There's a space at the end of the last line.
```
T`l`L`\b.
+T`L`l` (And?|A[st]?|The|By|But|[FN]or|In|O[fnr]|To|Up)
```
[**Try it online**](http://retina.tryitonline.net/#code=VGBsYExgXGIuCitUYExgbGAgKEFuZD98QVtzdF0_fFRoZXxCeXxCdXR8W0ZOXW9yfElufE9bZm5yXXxUb3xVcCkg&input=dGhlIHJ1bGUgb2YgdGh1bWIgZm9yIHRpdGxlIGNhcGl0YWxpemF0aW9uCnByb2dyYW1taW5nIHB1enpsZXMgYW5kIGNvZGUgZ29sZgp0aGUgbWFueSB1c2VzIG9mIHRoZSBsZXR0ZXIgYQp0aXRsZQphbmQgYW5kIGFuZAphIGFuIGFuZCBhcyBhdCBidXQgYnkgZm9yIGluIG5vciBvZiBvbiBvciB0aGUgdG8gdXAKb24gY29tcHV0YWJsZSBudW1iZXJzIHdpdGggYW4gYXBwbGljYXRpb24gdG8gdGhlIGVudHNjaGVpZHVuZ3Nwcm9ibGVt)
This also works with a `.` instead of the first space.
There are a lot of regexes with the same length, but I can't find a way to trim it anymore...
[Answer]
## JavaScript (ES6), ~~141~~ ~~138~~ ~~135~~ 133 bytes
*Saved 3 bytes thanks to mbomb007*
```
s=>s.replace(/(\w+)( ?)/g,(a,w,n,i)=>i&&n&&/^(a[nst]?|the|by|in|of|on|to|up|and|but|[fn]?or)$/.exec(w)?a:a[0].toUpperCase()+a.slice(1))
```
### Test cases
```
let f =
s=>s.replace(/(\w)(\w*)( ?)/g,(a,l,w,n,i)=>i&&n&&/^(a[nst]?|the|by|in|of|on|to|up|and|but|[fn]?or)$/.exec(l+w)?a:l.toUpperCase()+w+n)
console.log(f("the rule of thumb for title capitalization"));
console.log(f("programming puzzles and code golf"));
console.log(f("the many uses of the letter a"));
console.log(f("title"));
console.log(f("and and and"));
console.log(f("a an and as at but by for in nor of on or the to up"));
console.log(f("on computable numbers with an application to the entscheidungsproblem"));
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 58 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“Ð/ṃƇ¬þṄẊƙ€,⁽ṙƬ®OṪJ"ɦ3×kf3Ṙç%ġu’b26ịØaṣ”z
e€¢¬T;2Ḷ¤
ḲŒtǦK
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=4oCcw5Av4bmDxofCrMO-4bmE4bqKxpnigqws4oG94bmZxqzCrk_huapKIsmmM8OXa2Yz4bmYw6clxKF14oCZYjI24buLw5hh4bmj4oCdegpl4oKswqLCrFQ7MuG4tsKkCuG4ssWSdMOHwqZL&input=&args=dGhlIG1hbnkgdXNlcyBvZiB0aGUgbGV0dGVyIGE)** or [run all tests](http://jelly.tryitonline.net/#code=4oCcw5Av4bmDxofCrMO-4bmE4bqKxpnigqws4oG94bmZxqzCrk_huapKIsmmM8OXa2Yz4bmYw6clxKF14oCZYjI24buLw5hh4bmj4oCdegpl4oKswqLCrFQ7MuG4tsKkCuG4ssWSdMOHwqZLCsOH4oKsWQ&input=&args=WyJ0aGUgcnVsZSBvZiB0aHVtYiBmb3IgdGl0bGUgY2FwaXRhbGl6YXRpb24iLCJwcm9ncmFtbWluZyBwdXp6bGVzIGFuZCBjb2RlIGdvbGYiLCJ0aGUgbWFueSB1c2VzIG9mIHRoZSBsZXR0ZXIgYSIsInRpdGxlIiwiYW5kIGFuZCBhbmQiLCJhIGFuIGFuZCBhcyBhdCBidXQgYnkgZm9yIGluIG5vciBvZiBvbiBvciB0aGUgdG8gdXAiLCJvbiBjb21wdXRhYmxlIG51bWJlcnMgd2l0aCBhbiBhcHBsaWNhdGlvbiB0byB0aGUgZW50c2NoZWlkdW5nc3Byb2JsZW0iXQ)
### How?
A compressed string with spaces separating the words would be `47` bytes, splitting it costs `1` byte, for `48` bytes.
Two unseparated compressed strings of the words of length `2` and `3` (with an 'a' on the end of one) respectively would be `40` bytes plus `2` to split each and `1` to join them, for `45` bytes.
One base 250 number as described below is `32` bytes, then `3` to convert to base 26, `3` to index into the lowercase alphabet and `3` to split it on the unused character, `'z'`, for `41` bytes.
So, the lookup for the words not to capitalise:
`“Ð/ṃƇ¬þṄẊƙ€,⁽ṙƬ®OṪJ"ɦ3×kf3Ṙç%ġu’`
was formed like so:
Take those words and join them with a separator:
`s="a an the at by for in of on to up and as but or nor"`
Next label `'a'` as `1`, `'b'` as `2` with the separator as `0`:
```
alpha = ' abcdefghijklmnopqrstuvwxyz'
x = [alpha.index(v) for v in s]
x
[1,0,1,14,0,20,8,5,0,1,20,0,2,25,0,6,15,18,0,9,14,0,15,6,0,15,14,0,20,15,0,21,16,0,1,14,4,0,1,19,0,2,21,20,0,15,18,0,14,15,18]
```
Convert this into a base `26` number (the last letter used is `'y'` plus a digit for the separator, Python code for this is:
`n=sum(v*26**i for i,v in enumerate(x[::-1]))`
Convert that into a base `250` number (using a list for the digits):
```
b=[]
while n:
n,d = divmod(n,250)
b=[d]+b
b
[16,48,220,145,8,32,202,209,162,13,45,142,244,153,9,80,207,75,35,161,52,18,108,103,52,205,24,38,237,118]
```
Lookup the characters at those indexes in jelly's codepage:
```
codepage = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQR TUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”'''
r=''.join(codepage[i-1] for i in b)
r
'Ð/ṃƇ¬þṄẊƙ€,⁽ṙƬ®OṪJ"ɦ3×kf3Ṙç%ġu'
```
(note: since the actual implementation is bijective, if `b` had any `0` digits one would need to carry down first)
The rest:
```
ḲŒtǦK - Main link: title string
Ḳ - split on spaces
¦ - apply to indexes
Ç - given by calling the last link (1) as a monad (with the split title string)
Œt - title case (first letter of each (only) word to upper case)
K - join on spaces
e€¢¬T;2Ḷ¤ - Link 1, find indexes to capitalise: split title string
e€ - is an element of, for €ach
¢ - the result of calling the last link (2) as a nilad
¬ - logical not
T - get the truthy indexes (indexes of words that are not in the list)
; - concatenate with
¤ - nilad followed by link(s) as a nilad
2Ḷ - range(2) -> [0,1]
(we always want to capitalise the first index, 1, and the last index, 0)
“Ð/ṃƇ¬þṄẊƙ€,⁽ṙƬ®OṪJ"ɦ3×kf3Ṙç%ġu’b26ịØaṣ”z - Link 2, make the word list: no arguments
“Ð/ṃƇ¬þṄẊƙ€,⁽ṙƬ®OṪJ"ɦ3×kf3Ṙç%ġu’ - the base 250 number
b26 - convert to base 26
ị - index into
Øa - lowercase alphabet
ṣ - split on
”z - literal 'z' (the separator 0 indexes into `z`)
```
[Answer]
# PHP, 158 Bytes
10 Bytes saved by [@Titus](https://codegolf.stackexchange.com/users/55735/titus)
```
foreach($w=explode(" ",$argv[1])as$k=>$v)echo" "[!$k],$k&&$k+1<count($w)&&preg_match("#^(a[snt]?|and|[fn]or|up|by|but|the|to|in|o[rnf])$#",$v)?$v:ucfirst($v);
```
Previous version PHP, 174 Bytes
```
foreach($w=explode(" ",$argv[1])as$k=>$v)$k&&$k+1<count($w)&&in_array($v,[a,an,the,at,by,"for",in,of,on,to,up,"and","as",but,"or",nor])?:$w[$k]=ucfirst($v);echo join(" ",$w);
```
[Answer]
# TI-Basic, 295 + 59 + 148 = 502 bytes
*Now you can capitalize on your calculator. Great for school :)*
**Main Program, 295 bytes**
Basically, the trick to matching words so all `A` don't become `a` is to enclose with spaces, such as replace `" A "` with `" a "`. This also automatically makes it so that the first and last words stay capitalized, because they do not have a space on both sides and will thus not match any of the words. (Genius, right? And super long because lowercase letters are two bytes each...)
```
"("+Ans+")→Str1
"@A ~ a@An ~ an@The ~ the@At ~ at@By ~ by@For ~ for@In ~ in@Of ~ of@On ~ on@To ~ to@Up ~ up@And ~ and@As ~ as@But ~ but@Or ~ or@Nor ~ nor@→Str2
For(I,2,length(Ans
If "@"=sub(Str2,I-1,1
Then
" "+Str1+"~"+sub(Str2,I,inString(Str2,"@",I)-I)+" "
prgmQ
Ans→Str1
End
End
```
**Subprogram (`prgmQ`), 59 bytes:**
```
Ans→Str9
inString(Ans,"~
sub(Str9,Ans,length(Str9)-Ans+1→Str8
Str9
prgmR
Repeat Str9=Ans+Str8
Ans+Str8→Str9
prgmR
End
```
**Subprogram (`prgmR`), 148 bytes:**
```
Ans→Str0
inString(Ans,"~→Z
inString(Str0,"~",Ans+1→Y
inString(sub(Str0,1,Z-1),sub(Str0,Z+1,Ans-Z-1→X
sub(Str0,1,-1+inString(Str0,"~
If X
sub(Str0,1,X-1)+sub(Str0,Y+1,length(Str0)-Y)+sub(Str0,X+length(sub(Str0,Z+1,Y-Z-1)),Z-X-length(sub(Str0,Z+1,Y-Z-1
```
P.S. `~` represents token `0x81` and `@` represents token `0x7F`, learn more [here](http://tibasicdev.wikidot.com/one-byte-tokens).
[Answer]
# Java 7, ~~271~~ ~~259~~ 258 bytes
```
String c(String x){String a[]=x.split(" "),s=" ",r=w(a[0])+s;for(int i=0,l=a.length-1;i<l;r+=(!s.matches("^(a[nst]?|the|by|in|of|on|to|up|and|but|[fn]?or)$")|i==l?w(s):s)+" ")s=a[++i];return r;}String w(String w){return(char)(w.charAt(0)-32)+w.substring(1);}
```
**Ungolfed & test code:**
[Try it here.](https://tio.run/nexus/java-openjdk#hVJNj5swEL3vr5iiHmyRomx7W4qi/oCc9ohYyRADlvyB7HHZJM5vTweWnrFkzch@8@bNszstQoDz/fmOXtkBOrYln/y@ZaJuqs8iTFohyyDjh1BROPhqZqI@NjwPZe88UxZBVceDrkShpR1w/PFaqt@69HnFvoXCCOxGGVj2QWU2YHNKOMrUXpOyyfXJ2YQuxSkJe0ltxFT3tjk5z79nPKmq0qeZBf4WeL6ICJWo81w1pZcYvQVfPja58/8JZn7/umTdKDxnc7HEP8iO/OPXT57PRYhtWLHslZePJ8AUW606CCiQwl@nLmCEshtj3YDg9xegdQYDFVg5w5nxcj16vwaUpnARi4nQqC0zRccyGhJ81BJcDzhG0wK5BaiQjjoxKRRa3aifsxnfoZq8G7wwZpluireblgHILejcRcLgdL/LsIgxwl4hBqpdFUnQElF6EPvVi@hd1KJo2/tYQn2BaRIEenZor6tByoKlQBKdhcUwEooO4rTLSfjOmSmiaMliS45LH2BWOK7NJvrI3er3wrfQSouBvqa6RDsE8pjKzNbl8fJ4/gM)
```
class M{
static String c(String x){
String a[] = x.split(" "),
s = " ",
r = w(a[0]) + s;
for(int i = 0, l = a.length-1; i < l; r += (!s.matches("^(a[nst]?|the|by|in|of|on|to|up|and|but|[fn]?or)$") | i == l
? w(s)
: s) + " "){
s = a[++i];
}
return r;
}
static String w(String w) {
return (char)(w.charAt(0) - 32) + w.substring(1);
}
public static void main(String[] a){
System.out.println(c("the rule of thumb for title capitalization"));
System.out.println(c("programming puzzles and code golf"));
System.out.println(c("the many uses of the letter a"));
System.out.println(c("title"));
System.out.println(c("and and and"));
System.out.println(c("a an and as at but by for in nor of on or the to up"));
System.out.println(c("on computable numbers with an application to the entscheidungsproblem"));
}
}
```
**Output:**
```
The Rule of Thumb for Title Capitalization
Programming Puzzles and Code Golf
The Many Uses of the Letter A
Title
And and And
A an and as at but by for in nor of on or the to Up
On Computable Numbers With an Application to the Entscheidungsproblem
```
[Answer]
# Groovy, 131 129
Two bytes saved thanks to carusocomputing
```
{it.split()*.with{a->a in "a an the at by for in of on to up and as but or nor".split()?a:a.capitalize()}.join(" ").capitalize()}
```
[Answer]
## C#, 305 bytes
Lots of room for improvement still but here you go:
```
s=>{;var b=s.Split(' ');b[0]=((char)(b[0][0]-32))+b[0].Substring(1);int i=0,n=b.Length;for(;++i<n;)if(!"a,an,the,at,by,for,in,of,on,to,up,and,as,but,or,nor".Split(',').Contains(b[i]))b[i]=((char)(b[i][0]-32))+b[i].Substring(1);b[n-1]=((char)(b[n-1][0]-32))+b[n-1].Substring(1);return string.Join(" ",b);};
```
[Answer]
# Ruby, ~~123~~ ~~117~~ ~~111~~ 102 bytes
```
->s{s.gsub(/ .|^./,&:upcase).gsub(/ (A[nts]?|The|By|In|To|Up|And|But|[NF]or|O[rnf])(?= )/,&:downcase)}
```
Sorry for all the edits - this should be the last one.
[Answer]
# Python, 177 bytes
Delivered in function format for byte saving purposes. This is not an especially competitive answer, but it is one that doesn't require `repr()` or `regex` trickery. It is also version-agnostic; it works with Python 2 or 3.
Though it is perhaps a very by-the-rules solution.
```
def t(s):
w="a an the the at by for in of on to up and as but or nor".split()
l=[(s.title(),s)[s in w]for s in s.split()]
for x in(0,-1):l[x]=l[x].title()
return' '.join(l)
```
[Answer]
# PHP, ~~109~~ 142 bytes
```
<?=preg_replace_callback("# (A[snt]?|And|[FN]or|Up|By|But|The|To|In|O[rnf])(?= )#",function($m){return strtolower($m[0]);},ucwords($argv[1]));
```
A merger of [user59178´s](https://codegolf.stackexchange.com/a/97669#97669) and [mbomb007´s](https://codegolf.stackexchange.com/a/97573#97573) answer.
uppercases the first letter of every word, then lowercases all words from the list surrounded by spaces.
Unfortunately, the callback has to operate on the complete set; this costs 29 bytes.
[Answer]
## Racket 353 bytes
```
(define(cap i)(set! i(string-append i))(define c(string-ref i 0))(string-set! i 0(if(char-upper-case? c)c(integer->char(-(char->integer c)32))))i)
(let*((ex(list"a""an""the""at""by""for""in""of""on""to""up""and""as""but""or""and""nor"))(sl(string-split s)))
(string-join(for/list((i sl)(n(in-naturals)))(cond[(= n 0)(cap i)][(member i ex)i][(cap i)]))))
```
Ungolfed:
```
(define (f s)
(define (cap i) ; sub-fn to capitalize first letter of a word
(set! i (string-append i))
(define c (string-ref i 0))
(string-set! i 0
(if (char-upper-case? c)
c
(integer->char (-(char->integer c)32))))
i)
(let* ((ex (list "a""an""the""at""by""for""in""of""on""to""up""and""as""but""or""and""nor"))
(sl (string-split s)))
(string-join
(for/list
((i sl)
(n (in-naturals)))
(cond
[(= n 0) (cap i)]
[(member i ex) i]
[(cap i)]
)))))
```
Testing:
```
(f "the rule of thumb for title capitalization")
```
Output:
```
"The Rule of Thumb for Title Capitalization"
```
[Answer]
# Java 7, ~~431 317~~ 311 bytes
*Thanks to @KevinCruijssen for **114** bytes.*
*Thanks to @RosLup for saving **6** bytes.*
```
String c(String s){String v="",x,l[]=s.split(" "),b[]={"a","an","the","at","but,"by","for","in","of","on","to","up","as","or","and","nor"};int i=0,f=0,z=0;for(String c:l){for(f=0;f<b.length;z=c.equals(b[f++])|z>0?1:0);x=(char)(c.charAt(0)-32)+c.substring(1);v+=(z>0?i<1|i>l.length-2?x:c:x)+" ";i++;}return v;}
```
# ungolfed
first answer above 250 bytes
```
static String c(String s) {
String v = "", x, l[] = s.split(" "),
b[]={"a","an","the","at","by","for","in","of","on","to",
"up","and","as","or","nor","but"};
int i , f , z = i = f = 0;
for (String c : l) {
for (f = 0; f < b.length; z = c.equals( b[f++] ) | z > 0 ? 1 : 0);
x = (char)(c.charAt(0) - 32) + c.substring(1);
v += (z > 0 ? i < 1 | i > l.length - 2 ? x : c : x) + " ";
i++;
}
return v;
}
```
[Answer]
# PHP, ~~117~~ ~~118~~ 112 bytes
```
<?=strtr(ucwords(preg_replace("# (?=(a[snt]?|and|[fn]or|up|by|but|the|to|in|o[rnf]) )#","!",$argv[1])),'!',' ');
```
Uses the behaviour of `ucwords()` and escapes the relevant words that are surrounded by spaces then deletes the escape characters.
I copied the `(a[snt]?|and|[fn]or|up|by|but|the|to|in|o[rnf])` from Jörg Hülsermann's answer but as the approach is completely different I'm posting it as a separate answer.
edit: bug noticed by Titus, fixing it cost 1 byte. also: 6 bytes saved thanks to his helpful comment about strtr
[Answer]
## *Pure* `bash` - 253
(no external programs called) - needs bash v4
```
declare -A b;for x in A An The At By For In Of On To Up And As But Or Nor;do b[$x]=1;done
while read -a w;do
n=${#w[@]};o[0]=${w[0]^}
for((i=1;i<n-1;i++)){
g=${w[$i]^};((${b[$g]}))&&o+=(${g,,})||o+=($g);}
((n>1))&&o[$n]=${w[-1]^}
echo ${o[@]};o=()
done
```
normal view with comments
```
#create the "blacklist"
declare -A b
for w in A An The At By For In Of On To Up And As But Or Nor
do
b[$x]=1
done
# logic:
# read each line (split by words) into array
# and each word is assigned capitalized to the new output array
# but the blacklisted ones
#read each line to array w (split on spaces)
while read -a w
do
n=${#w[@]} # get the number of words
o[0]=${w[0]^} # copy the capitalized word1
for((i=1 ; i<n-1 ; i++)) { # loop over 2 up to last -1 words
g=${w[$i]^} # for the given word
# check if it is in the blacklisted ones
# if yes - convert to lowercase, if not leave as it is
# and append to the output array
(( ${b[$g]} )) && o+=(${g,,}) || o+=($g)
}
# capitalize the last word if here is more words
(( n>1 )) && o[$n]=${w[-1]^}
# make a line from the words
echo ${o[@]}
o=() #cleanup
done
```
output
```
Title
And and And
The Rule of Thumb for Title Capitalization
Programming Puzzles and Code Golf
The Many Uses of the Letter A
A an and as at but by for in nor of on or the to Up
On Computable Numbers With an Application to the Entscheidungsproblem
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 71 bytes
```
£`a e by f up d ¿t n`¸aX >0©Y¦0©YĦZl ?X:Xg u +XÅ}S
```
[Try it online!](https://tio.run/nexus/japt#JY0xCsJAAAS/MqQVQVsLfYQIZ5cLSVSQO9FLYWFnxMaobxAEf5BOWB8WD4Vld2GK6fRILTqiW4Fqsj2lGnRGV3RBd6pN5Dk6oXcgQqcmVWsN44Fecz3/PVO7pj@cmJFZUNEzn/ow7brEYl1Mjt1hA1kVfhK/ZeVwcXyJd8QTlgXBR1/yBQ)
### Explanation:
```
£`a e by f up d ¿t n`¸aX >0©Y¦0©YĦZl ?X:Xg u +XÅ}S
£`...`qS aX >0&&Y!=0&&Y!=UqS l -1?X:Xg u +Xs1}S
£ }S // Split at spaces and map each item X by this function:
`...` // Backticks are used to decompress strings
qS // Split the decompressed string at spaces.
aX >J // If this contains X
&&Y!=0 // and the index is non-zero (it's not the first word)
&&Y!=UqS l -1 // and the index is not the length of the input -1 (it's not the last word),
?X // return X.
:Xg u +Xs1 // Else, return X capitalized. (Literally X[0].toUpperCase() + X.slice(1))
}S // Rejoin with spaces
```
One of my favorite Japt features is its string compression, which uses the [shoco library](http://ed-von-schleck.github.io/shoco/).
You can compress a string by wrapping it in `Oc"{string}"` → `Oc"a an the at by for in of on to up and as but or nor"`
Then decompressing it with backticks or `Od"{compressed string}"` → `Od"a e by f up d ¿t n"`
[Answer]
## *Pure* `bash` - ~~205~~ ~~192~~ 181 bytes
```
tc(){
while read -a x
do x=(${x[@]^})
for ((i=1;i<${#x[@]}-1;i++))
do
case "${x[i]}" in
A|A[nts]|The|By|[FN]or|In|O[fnr]|To|Up|And|But)x[i]=${x[i],};;
esac
done
echo ${x[@]}
done
}
```
Like [jm66's answer](https://codegolf.stackexchange.com/a/113666/53016) `tc` accepts standard input.
[Answer]
# [Actually](http://github.com/Mego/Seriously), 79 bytes
```
' ,ÿsd@p@`;0"A0An0The0At0By0For0In0Of0On0To0Up0And0As0But0Or0Nor"síu'ù*ƒ`Moq' j
```
[Try it online!](http://actually.tryitonline.net/#code=JyAsw79zZEBwQGA7MCJBMEFuMFRoZTBBdDBCeTBGb3IwSW4wT2YwT24wVG8wVXAwQW5kMEFzMEJ1dDBPcjBOb3Iic8OtdSfDuSrGkmBNb3EnIGo&input=InRoZSBydWxlIG9mIHRodW1iIGZvciB0aXRsZSBjYXBpdGFsaXphdGlvbiI)
Explanation:
```
' ,ÿsd@p@`;0"longstring"síu'ù*ƒ`Moq' j
' ,ÿs title case input, split on spaces
d@p@ pop first and last words to stack
`;0"longstring"síu'ù*ƒ`M for every word except the first and last:
;0"longstring"s duplicate word, split the long string on 0s
íu 1-based index of word in list (0 if not found)
'ù* "ù"*(index)
ƒ execute the resulting string as a function (lowercases word if it's in the list)
oq' j put the first and last word back in the list, join with spaces
```
[Answer]
## Batch, 323 bytes
```
@echo off
set s=
for %%w in (@%*@)do call:w %%w
echo%s%
exit/b
:w
for %%s in (a an the at by for in of on to up and as but or nor)do if %%s==%1 set s=%s% %1&exit/b
set w=%1
set w=%w:@=%
set f=%w:~0,1%
for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do call set f=%%f:%%c=%%c%%
set s=%s% %f%%w:~1%
```
With comments:
```
@echo off
rem Start with an empty output string
set s=
rem Wrap the parameters in @ signs to identify the first and last words
for %%w in (@%*@) do call :w %%w
rem Ignore the leading space when printing the result
echo%s%
exit/b
:w
rem Check whether this is a word that we don't change
for %%s in (a an the at by for in of on to up and as but or nor) do if %%s==%1 set s=%s% %1&exit/b
set w=%1
rem Delete any @ signs from the first and last words
set w=%w:@=%
rem Get the first character
set f=%w:~0,1%
rem Case insensitively replace each upper case letter with itself
for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do call set f=%%f:%%c=%%c%%
rem Concatenate with the rest of the word
set s=%s% %f%%w:~1%
```
] |
[Question]
[
# Challenge
I'm under attack by the larcenous Midnight Crew and I need to summon the [Catenative Doomsday Dice Cascader](https://www.homestuck.com/extras/20) in order to defend myself. Since I'm low on space, I need the code to be as short as possible.
The algorithm for the Catenative Doomsday Dice Cascader is as follows:
First, the six sided die in the Prime Bubble is rolled, and the result will determine how many iterations of the next step take place.
Start with a six sided die. For as many times as the roll of the Prime Bubble die, multiply the number of sides on the next die by the result of the roll of the current die.
For example, if on your first roll of the six-sided die your roll is 2, then your next die will have 6\*2 = 12 sides.
Your goal is to write a function or program that takes no input and outputs the final result of the last die rolled. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest byte count in each language wins!
# Examples
Example #1 (Taken directly from the link above):
```
The Prime Bubble rolls a 6, meaning that the Cascader will iterate six times
#1: We always start with a 6 sided die, and it rolls a 2, so the next die has 6x2=12 sides
#2: The 12 sided die rolls an 8, meaning that the third die has 12x8=96 sides
#3: The 96 sided die rolls a 35, meaning that die 4 has 96x35=3360 sides
#4: The 3360 sided die rolls a 2922, so die 5 has 3360x2922 = 9,817,920 sides
#5: The 9.8 million sided die rolls a 5,101,894, so the final die has 50,089,987,140,480 sides
#6: The 50 trillion sided die rolls a one. Hooray.
Since the last die rolled gave a 1, your function or program should output 1.
```
Example #2
```
The Prime Bubble rolls a 2, meaning that the Cascader will iterate twice.
#1: We always start with a 6 sided die, and it rolls a 4, so the next die has 6x4 = 24 sides
#2: The 24 sided die rolls a 14
Since the last die rolled gave a 14, your function or program should output 14.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~76~~ 69 bytes
```
from random import*
R=randint
v=6;exec"p=R(1,v);v*=p;"*R(1,6)
print p
```
[Try it online!](https://tio.run/##FY2xDsIwDERn/BVWlzQRC0h0IPJP9A9Qm0KGxpYVRfD1IZ5Od7p7J7/64XLvG@@J1DnXD@UT9VX2IfkU1hpgJQtyqdBoiembtklonW/X5mMLJHEK5hYPoqOF0gcJ4GDFjLkY7p3mh3/CxcZob/0P "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~43~~ 37 bytes
*-6 bytes thanks to nwellnhof*
```
{(6,{roll 1..[*] @_:}...*)[1+6.rand]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rDTKe6KD8nR8FQTy9aK1bBId6qVk9PT0sz2lDbTK8oMS8ltvZ/cWKlQpqG5n8A "Perl 6 – Try It Online")
Anonymous code block that returns the doomsday dice result.
### Explanation:
```
{ } # Anonymous code block
( )[1+6.rand] # Take a random number from
...* # The infinite list of
6,{roll 1..[*] @_:} # Cascading dice values
6, # Starting from 6
{roll :} # And choosing a random value from
1.. # One to
[*] @_ # The product of every value so far
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes
```
(r=RandomInteger)@{1,Nest[r@{1,#}#&,6,r@5]}
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Zl@1@jyDYoMS8lP9czryQ1PbVI06HaUMcvtbgkugjEUq5VVtMx0ylyMI2t/V@iYKuQVheSmJSTWmdoYMAVUJSZV6LvUPIfAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
1+[:?(*1+?)^:(?`])@6x
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbWjrew1tAy17TXjrDTsE2I1Hcwq/mtycRWlFpZmFqUqqOeV5qYWZSarcxUl5qXk52ZWpaqrc3GlJmfkK@joKWikKRloKhgbKKgoGPwHAA "J – Try It Online")
*+6 bytes thanks to a logic problem spotted by FrownyFrog*
NOTE: J has no niladic verbs. However, this verb will work the same no matter what argument you give it. In the TIO example, I'm calling it with `0`, but I could have used `99` or `''` just as well.
## how
* `1+` add one to...
* `[:?` a single roll of an n-sided die (sides reading `0` to `n-1`), where the number `n` is determined by...
* `(*1+?)` take the current argument `y` and roll `?` to produce a random number between `0` and `y-1`. `1+` makes that `1` to `y`, inclusive. Finally the `*` creates a J hook, which will multiply that by `y` again.
* `^:` do the above this many times...
* `(?`])` `?` roll the initial argument, which is `6`, to determine how many times to repeat. If we roll `0` (corresponding to a `1` on the Prime Bubble), the argument will pass through unchanged. The `]` indicates that `6`, unchanged, will be the starting value of repeated `(*1+?)` verb that determines the die value for the final roll.
* `@6x` attaches the constant verb `6`, so that we can call it with anything, and the `x` forces J to use extended integer computation which we need for the possibly huge numbers.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 32 bytes
**Solution:**
```
*|{x,1+1?x:(*).x}/[*a;6,a:1+1?6]
```
[Try it online!](https://tio.run/##y9bNz/7/X6umukLHUNvQvsJKQ0tTr6JWP1or0dpMJ9EKJGgW@/8/AA "K (oK) – Try It Online")
Start with 6 and "1 choose 6", iterate over "1 choose 6" times:
```
*|{x,1+1?x:(*).x}/[*a;6,a:1+1?6] / the solution
{ }/[n; c ] / iterate over lambda n times with starting condition c
1?6 / 1 choose 6, between 0..5 (returns a list of 1 item)
1+ / add 1 (so between 1..6)
a: / store as 'a'
6, / prepend 6, the number of sides of the first dice
*a / we are iterating between 0 and 5 times, take first (*)
(*).x / multi-argument apply (.) multiply (*) to x, e.g. 6*2 => 12
x: / save that as 'x'
1? / 1 choose x, between 0..x-1
1+ / add 1 (so between 1..x)
x, / prepend x
*| / reverse-first aka 'last'
```
You can see the iterations by switching the [over for a scan](https://tio.run/##y9bNz/7/n6u6QsdQ29C@wkpDS1OvojYmWivR2kwn0QokaBbL9f8/AA "K (oK) – Try It Online"), e.g.
```
(6 3 / 1 choose 6 => 3, so perform 3 iterations
18 15 / 1 choose (6*3=18) => 15
270 31 / 1 choose (18*15=270) => 31
8370 5280) / 1 choose (270*31=8730) => 5280
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
6X×$5СXX
```
A niladic Link which yields a positive integer.
**[Try it online!](https://tio.run/##y0rNyan8/98s4vB0FdPDEw4tjIj4/x8A "Jelly – Try It Online")**
Saving a byte over the more obvious `6X×$6X’¤¡X`
### How?
```
6X×$5СXX - Link: no arguments
6 - initialise left argument to 6
5С - repeat five times, collecting up as we go: -> a list of 6 possible dice sizes
$ - last two links as a monad = f(v): e.g [6,18,288,4032,1382976,216315425088]
X - random number in [1,v] or [6,6,6,6,6,6]
× - multiply (by v) or [6,36,1296,1679616,2821109907456,7958661109946400884391936]
X - random choice (since the input is now a list) -> faces (on final die)
X - random number in [1,faces]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
X6DLΩF*DLΩ
```
The random choice builtin for large lists is pretty slow, so may result in a timeout if the Prime Bubble roll is for example a 6.
[Try it online](https://tio.run/##MzBNTDJM/f8/wszF59xKNy0Q@f8/AA) or [try it online with added prints to see the rolls](https://tio.run/##MzBNTDJM/f8/wszF59xKpYCizNxUBafSpKScVIWi/JwcKwUle1s3LRelICBHITNPoSgxLz1VIdpQ5/D@WJAkSJvt//8A). (TIO uses the legacy version of 05AB1E, since it's slightly faster.)
**Explanation:**
```
X # Push a 1 to the stack
6 # Push a 6 to the stack
D # Push another 6 to the stack
L # Pop the top 6, and push a list [1,2,3,4,5,6] to the stack
Ω # Pop and push a random item from this list (this is out Prime Bubble roll)
F # Loop that many times:
* # Multiply the top two values on the stack
# (which is why we had the initial 1 and duplicated 6 before the loop)
D # Duplicate this result
LΩ # Pop and push a random value from its ranged list again
# (after the loop, output the top of the stack implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
6×X$X’$¡X
```
[Try it online!](https://tio.run/##y0rNyan8/9/s8PQIlYhHDTNVDi2M@P8fAA "Jelly – Try It Online")
[Jonathan Allan's answer](https://codegolf.stackexchange.com/a/186306/41024) claims that it's
>
> Saving a byte over the more obvious `6X×$6X’¤¡X`
>
>
>
. In fact, we don't need to make such a big modification. Therefore, this is an alternative approach to Jonathan Allan's answer, and, also, a resting place for my initial invalid 6-byter. :(
[Answer]
# [Perl 5](https://www.perl.org/), 54 bytes
```
$a=6;map$a*=$r=1+int rand$a,0..rand 6;say 1+int rand$r
```
[Try it online!](https://tio.run/##K0gtyjH9/18l0dbMOjexQCVRy1alyNZQOzOvRKEoMS9FJVHHQE8PxFIwsy5OrFRAkir6//9ffkFJZn5e8X9dX1M9A0MDIJ2UmQ5UAQA "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
⊞υ⁶F⊕‽⁶⊞υ⊕‽ΠυI⊟υ
```
[Try it online!](https://tio.run/##bYyxCoAgFAD3vsLxCbW6ODa1SX8gahioL57a778kaGu9O85FSw5tYja9RuizUFJPB5KArTgKOZQWPOy2eMygpJTiC3@8IfTdNeijGxtDZ2mw2trA4PVSzczLnR4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⁶
```
Push 6 to the predefined list.
```
F⊕‽⁶
```
Repeat a random number of times from 1 to 6...
```
⊞υ⊕‽Πυ
```
... push a random number between 1 and the product of the list to the list.
```
I⊟υ
```
Output the last number pushed to the list.
Alternative approach, also 16 bytes
```
≔⁶θF‽⁶≧×⊕‽θθI⊕‽θ
```
[Try it online!](https://tio.run/##bcyxCoAgEADQva9wvINaW5yiqSGI6AcOMxPyLJV@/xqirf3xzE7JRDpEupy9Y2hrdaGutpgUzMRrDNAiqpHOF8ze7QUWH2yu1cAm2WC52PXDF@I7TMlzgZ5ygX@GqEWkuY8H "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁶θ
```
Set the number of sides to 6.
```
F‽⁶
```
Repeat a random number between 0 and 5 times...
```
≧×⊕‽θθ
```
... multiply the number of sides by a random number from 1 to the number of sides.
```
I⊕‽θ
```
Print a random number from 1 to the number of sides.
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
from random import*
r=randint
a=6
for i in" "*r(0,5):a*=r(1,a)
print(r(1,a))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocRXZggQy80q4Em3NuNLyixQyFTLzlBSUtIo0DHRMNa0StWyLNAx1EjW5CoqAyjQgHM3//wE "Python 3 – Try It Online")
-2 bytes thanks to TFeld
[Answer]
# [R](https://www.r-project.org/), 43 bytes
```
s=sample
for(i in 1:s(k<-6))T=s(k<-k*T,1)
T
```
[Try it online!](https://tio.run/##K/r/v9i2ODG3ICeVKy2/SCNTITNPwdCqWCPbRtdMUzPEFszK1grRMdTkCvn/HwA "R – Try It Online")
`k` keeps track of the current number of faces on the die. Uses the fact that `T` is initialized as `1`.
I tried a few other things, but couldn't beat this simple, straightforward approach.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
6×X$6X’¤¡X
```
[Try it online!](https://tio.run/##y0rNyan8/9/s8PQIFbOIRw0zDy05tDDi/38A "Jelly – Try It Online")
### Explanation
```
¤ | Following as a nilad:
6X | - A random number between 1 and 6
’ | - Decrease by 1 (call this N)
6 | Now, start with 6
$ ¡ | Repeat the following N times, as a monad
× | - Multiply by:
X | - A random number between 1 and the current total
X | Finally, generate a random number between 1 and the output of the above loop
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
r=6;rand(2..7).times{r*=$s=rand 1..r};p$s
```
[Try it online!](https://tio.run/##KypNqvz/v8jWzLooMS9Fw0hPz1xTryQzN7W4ukjLVqXYFiSsYKinV1RrXaBS/P8/AA "Ruby – Try It Online")
**Explanation**
```
r=6 # Set dice number to 6
rand(2..7).times{ } # Repeat X times, where X=dice roll+1
r*=$s=rand 1..r # Multiply dice number by a dice roll
# Save the most recent dice roll
p$s # Print last dice roll (this is why
# we did the last step one extra time)
```
[Answer]
# Java 10, ~~214~~ ~~93~~ 86 bytes
```
v->{int r=6,n=0;for(var d=Math.random()*6;d-->0;n*=Math.random(),r*=++n)n=r;return n;}
```
[Try it online](https://tio.run/##bZA9bsMwDIX3nILIJNmx4S4ZKig3SJYAXdoOquwkSmXK0B9QBD67K8lZCnQhQL5Hvg@8iyiae/@9SC2cg6NQ@NgAKPSDvQg5wCm3ANrgFSR5M6qHSFmazZtUnBdeSTgBAoclNodH2gTL9zvkHbsYS6Kw0POj8LfWCuzNSGi1Z33THDqG1V9hZyte10iRW2YHHywCsnlhOWkKXzolPQNj5hgTLDl7q/D6/gmCrqQFwGjtEtFLx8rs/OP8MLYm@HZKdq@RFEu9hTUbkjQF714/cEvXnQyfbylerAxUYQZa1H9vYisJBq3p80Hz8gs) or [try it online with additional print-lines to see the steps](https://tio.run/##bVE9b8IwFNz5FU@ebPIhsjBgmaE7qCpSF8rgJIaaOi/IcSJViN@ePgekqhWLJd@d7707n/Wgs3P9NVZOdx1stMXrDMBiMP6oKwPbeJ0AqPh7a2sYhCToNqOjCzrYCraAoGAcsvU16rxapqgWctAearXR4TP3Guu24WK@lMfW8913F0yTt33IL56eOOTs1dvGwEtfls6Ab51bAUs4kYLXSSGErLNsvZCo7thfW0@K9IkritTPFYr/FGdvNIFSAVmcDOyLlCU@YQcaKqQ3ofcIKG@jjDEvfeko5iPtEEtoqCi@C@R12h9Ai9@W4uod1VEs5IQ92WqSJAzu6wNRlz50qw9k4v4mdhS9rJqkEuyUHcTEPvXEvOLYOycev3MbfwA).
-128 bytes by using `int` instead of `java.math.BigInteger`. \$6^{32}\$, the largest possible result, doesn't fit inside an `int` nor `long`, which is why `BigInteger` was used initially. OP allowed to use `int` and assuming it's infinitely large, so that saved more than 125 bytes here. :) ([Here the previous **214 bytes** version using `BigIntegers`.](https://tio.run/##bZFBawIxEIXv/orBU2LdqBehhrVQ6KFQFWrppe0hbuIam02W7GSLiL/dJqtQD70EJvPyHt/LXrQi28vvs65q5xH2cWaVwB0bcIDRCO4m94AONgdUWeGCxV5hRNPAQmh77AFoi8pvRaFgmUa4cXjU5XPclspDQd6dltBSHjWnXjwaFKgLWIKFHM5tNj/eyDG3wZihz5G1wgS12pIp5VvnSSs8yHyR7L2w0lWEDqZcZtl8zDHKhZQE2Wr5RONrOR8/eFYFg7o2B4J0hjSZcBID1A/8JRLPNhpflC1xR@gwLTuOgNqw12sQpaxwVS28enPE05hIuVcYvAXPT2eesOqwMRHrStcm6Co2RdbotS0/vkDQS02xN/DOmCbiT8a8u1sfGlQVcwFZHeVoLOkkd324wEJc1QGb2aft08ubxJO8dN5JOeiuC6Dd9l9PywqS@qXX3zidfwE))
**Explanation:**
```
v->{ // Method with empty unused parameter & integer return-type
int r=6, // The range in which to roll, starting at 6
n=0; // The roll itself (which must be initialized, therefor is 0)
for(var d=Math.random()*6;// Roll the Prime Bubble Dice
d-->0 // Loop that many times:
; // After every iteration:
n*=Math.random(), // Roll a random dice in the range [0, n)
r*=++n) // Increase `n` by 1 first with `++n`, so the range is [1,n]
// And then multiply `r` by `n` for the new range
n=r; // Set `n` to `r`
return n;} // After the loop, return `n` as result
```
[Answer]
# [PHP](https://php.net), 59 bytes
```
$r=$q=rand(1,$s=6);while($l++<$q)$r=rand(1,$s*=$r);print$r;
```
expanded:
```
$r=$q=rand(1,$s=6);
while($l++<$q)$
r=rand(1,$s*=$r);
print$r;
```
Not sure if I'm supposed to include the open tag.
On my machine, it crashes if `$s*$r` is too large, so it doesn't print on `$q>=5` sometimes... because the numbers get so big. Not sure of a fix.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
uhO=*|Z6GO6hO6
```
[Try it online!](https://tio.run/##K6gsyfj/vzTD31arJsrM3d8sw9/s/38A "Pyth – Try It Online")
```
uhO=*|Z6GO6hO6
O6 Random number in range [0-6)
u Perform the following the above number of times...
hO6 ... with starting value G a random number in range [1-6]:
* G Multiply G with...
|Z6 The value of Z, or 6 if it's the first time through (Z is 0 at program start)
= Z Assign the above back into Z
O Random number in range [0-Z)
h Increment
Implicit print result of final iteration
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 136 bytes
```
class A{static void Main(){var r=new System.Random();int i=r.Next(6),j=6;while(i-->0)j*=1+r.Next(j);System.Console.Write(r.Next(j)+1);}}
```
[Try it online!](https://tio.run/##PcuxCsIwEADQX8mYWBPs0iVEEGcddHAO6YEX0gRyR6uUfntcivPjBdKhVGgtJE8kLiuxZwxiLjiKm8cs1Tr7KqrLsIjnlxgm8/B5LJNUFjMLdNXc4cNyUMfoBru8MYFErc8nFQ@u73aOyu79WjKVBOZVkUH@ueuV3bbWfg "C# (.NET Core) – Try It Online")
I'm *pretty* sure this works, given the assumption of infinite integer length that we're fond of here. If I have to actually handle the overflow, I'd need to bust out an entirely different class.
[Answer]
# [Julia 1.0](http://julialang.org/), 60 bytes
```
g(b=big(6),r=rand)=(for i in 1:r(0:5) b=b*r(1:b) end;r(1:b))
```
`b=big(6)` makes it work with arbitrary sized integers
[Try it online!](https://tio.run/##yyrNyUw0rPj/P10jyTYpM13DTFOnyLYoMS9F01YjLb9IIVMhM0/B0KpIw8DKVFMBqEarSMPQKklTITUvxRrC1PzvUJyRX66QrqH5HwA "Julia 1.0 – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 13 bytes
```
:(ṛ×
6₅ṛ(↑ₓ(ṛ
```
[Try it online!](https://tio.run/##S0/MTPz/30rj4c7Zh6dzmT1qagWyNB61TXzUNBkk@P8/AA "Gaia – Try It Online")
] |
[Question]
[
Program the shortest code that will calculate the average BPM (Beats per Minute) using 8 data points of time passed. This is my first post, and I haven't seen a question similar to this. Since I am a fan of rhythm games, it would be nice to have a small handy tool to calculate BPM using your own keyboard and your own sense of rhythm (if you have one...)
# Challenge
* All inputs must be singular. (i.e. Only pressing "enter" as "input")
* Your program must take at least 9 inputs. (To create 8 data points of time passed.)
* Your program should output the BPM of the keypresses rounded at 2 decimal points. (i.e. 178.35)
* **Timing starts at first input. Not start of program**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
# Example Input and Output
Provide at least one example input and output. Make sure they match your own description of what the input should look like.
Input:
```
> [Enter-Key]
# User waits 1 second
... 7 more inputs
> [Enter-Key]
```
Output:
```
> 60
```
**Current winner is [KarlKastor](https://codegolf.stackexchange.com/a/135955/72656) at 22 Bytes using Pyth**
**Even though the winner was using Pyth, the Matlab answer was a notable answer.**
[Answer]
# MATLAB/Octave, ~~58 56~~ 55 bytes
Thanks @LuisMendo for -1 byte!
```
input('');tic;for k=1:7;input('');end;fix(48e3/toc)/100
```
You have to press enter 9 times. (Also works in Octave.)
Here you see it in action, left MATLAB, right Octave:

[Answer]
# JavaScript (ES6), ~~77~~ 74 bytes
```
(i=8,n=Date.now,t)=>onclick=_=>(t=t||n(),i--||alert((48e6/(n()-t)|0)/100))
```
Creates an `onclick` event on the global `window` object. Send beats by clicking anywhere in the window.
## Test Snippet
```
let f=
(i=8,n=Date.now,t)=>onclick=_=>(t=t||n(),i--||alert((48e6/(n()-t)|0)/100))
f()
document.write("Running... click anywhere here")
```
```
*{user-select:none}
```
[Answer]
# Python 3, 93 92 81 bytes
Saved 11 bytes thanks to [Felipe](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista).
```
import time
a,*l,b=[input()or time.time()for i in' '*9]
print(round(480/(b-a),2))
```
[Answer]
# Bash + common Linux utilities, 58
```
script -tt -c'sed -n 9q'
sed '1c2k0
s/ 2/+/;$a480r/p' t|dc
```
[Answer]
## **Javascript, 100, 84 thanks to [Powelles](https://codegolf.stackexchange.com/users/52433/powelles), 82 bytes thanks to [Justin Mariner](https://codegolf.stackexchange.com/users/69583/justin-mariner)**
```
z=>{(a=alert)();i=0;s=(n=Date.now)();while(i++<8)a();a((48e4/(n()-s)).toFixed(2))}
```
```
(z=>{(a=alert)();i=0;s=(n=Date.now)();while(i++<8)a();a((48e4/(n()-s)).toFixed(2))})();
```
[Answer]
# Java 1.5+, ~~345~~ ~~339~~ ~~361~~ 337 bytes
-34 bytes thanks to Michael for pointing out I forgot to fix my imports
```
import java.awt.event.*;class B{public static void main(String[]a){new java.awt.Frame(){{addKeyListener(new KeyAdapter(){long x=System.currentTimeMillis();int b=0;public void keyPressed(KeyEvent e){if(e.getKeyChar()==' '&&b++==9){System.out.println(Math.round(6000000.0*b/(System.currentTimeMillis()-x))/100.0);}}});setVisible(1>0);}};}}
```
Listens to the user as they press the space bar. Then, when the user has pressed it 9 times, prints back to the user the current BPM:
[](https://i.stack.imgur.com/UIXMX.png)
*Image has debug messages not present in golfed code.*
---
# Ungolfed:
```
import java.awt.event.*;
class B {
public static void main(String[] a) {
new java.awt.Frame() {
{
addKeyListener(new KeyAdapter() {
long x = System.currentTimeMillis();
int b = 0;
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == ' ' && b++ == 9) {
System.out
.println(Math.round(6000000.0 * b
/ (System.currentTimeMillis() - x)) / 100.0);
}
}
});
setVisible(1 > 0);
}
};
}
}
```
---
Kinda fun to try and get a highscore...
```
KEY PRESS0 AT 250ms.
KEY PRESS1 AT 343ms.
KEY PRESS2 AT 468ms.
KEY PRESS3 AT 563ms.
KEY PRESS4 AT 672ms.
KEY PRESS5 AT 781ms.
KEY PRESS6 AT 880ms.
KEY PRESS7 AT 989ms.
485
```
[Answer]
# C# (.NET Core), ~~193~~ ~~206~~ ~~189~~ ~~186~~ ~~155~~ ~~143~~ 137 bytes
*-47 bytes thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder)*
*-4 bytes thanks to [Nazar554](https://codegolf.stackexchange.com/users/29636/nazar554)*
*-16 bytes thanks to [Luc](https://codegolf.stackexchange.com/users/15738/luc)*
*-2 bytes thanks to [Kamil Drakari](https://codegolf.stackexchange.com/users/71434/kamil-drakari)*
```
_=>{var x=new long[9];for(int i=0;i<9;){Console.ReadKey();x[i++]=DateTime.Now.Ticks;}return Math.Round(48e8/(x[8]-x[0]),2);}
```
Also added to byte count:
```
using System;
```
Whole program:
```
namespace System
{
class A
{
static void Main()
{
Func<int, double> f = _ =>
{
var x = new long[9];
for (int i = 0; i < 9; )
{
Console.ReadKey();
x[i++] = DateTime.Now.Ticks;
}
return Math.Round(48e8 / (x[8] - x[0]), 2);
};
Console.WriteLine(f(0));
}
}
}
```
[Answer]
## C++, 150 bytes
```
#include<iostream>
#include<ctime>
#define G getchar()
void f(){G;auto s=clock();G;G;G;G;G;G;G;G;std::cout<<round(6000/(double(clock()-s)/8000))/100;}
```
[Answer]
# Python + curses, 122 bytes
```
import curses as C,time as T
s=C.initscr()
C.cbreak()
t=0
exec's.getch();t=t or T.time()'*9
print'%.2f'%(540/(T.time()-t))
```
Requires the `curses` module to be loaded.
-9 bytes thanks to Felipe Nardi Batista
[Answer]
## vba, 57
```
msgbox"":x=timer:for i=1to 8:msgbox"":next:?480/(timer-x)
```
press enter, or click on the OK in the message box.
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
from timeit import*;print('%.2f'%(480/timeit('input()',input(),number=8)))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehJDM3NbNEITO3IL@oRMu6oCgzr0RDXVXPKE1dVcPEwkAfokBDPTOvoLREQ1NdB8rQySvNTUotsrXQ1NT8/58LBgA "Python 3 – Try It Online")
This will give you silly numbers in TIO since it runs all the inputs at once but it does work. `timeit()` returns the execution time of the statement `'input()'` in seconds excluding the setup parameter `input()`.
[TIO with a 1s delay](https://tio.run/##NYo7CoAwEAV7T5FGsivivxCClxEiLphkiWvh6SP@XjUzPD5lDb5PiRyHKErI2WyJwT1Eot5eGI7kBXRedYvOYRib@j2AJs@HAJrbq32zlqFFXX659IebbZxGREwp@3cB "Python 3 – Try It Online") per input for validation.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 22 bytes
```
wJ.d0 mw8.Rc480-.d0J2
```
(yes there's a leading space)
Input is 'enter' presses.
If additional output is allowed I can remove the spaces and get a score of 20 bytes.
[](https://i.stack.imgur.com/QUrao.png)
## explanation
```
wJ.d0 mw8.Rc480-.d0J2
w # take the first input
# (space) throw the result away
J.d0 # store the current system time in J
mw8 # take 8 inputs and throw the result away
-.d0J # difference of current time and J
c480 # divide 480 by this
.R 2 # round to 2 decimal places
```
[Answer]
# Java 8, ~~180~~ 135 bytes
*-45 bytes thanks to @SocraticPhoenix suggesting to use `System.in` directly.*
```
x->{System.in.read();long t=System.nanoTime(),i=0;for(;i++<8;System.in.read());System.out.printf("%.2f",4.8e11/(System.nanoTime()-t));}
```
An anonymous lambda function with an unused argument that must be assigned to a functional interface method that throws an `Exception` (example below). Reads from console; beats are sent by pressing `enter`.
## Ungolfed w/ Surrounding Test Code
```
public class A {
interface F{void f(Object x) throws Exception;}
public static void main(String[]a) throws Exception {
F f =
x->{
System.in.read();
long t=System.nanoTime(),i=0;
for(;i++<8;System.in.read());
System.out.printf("%.2f",4.8e11/(System.nanoTime()-t));
}
;
f.f(null);
}
}
```
[Answer]
# C#, 117 bytes
There's already a [C# (.NET Core) answer](https://codegolf.stackexchange.com/a/135496/15738) that this one builds on. Added interpolated string (that .NET Core seems to lack) for output and shaved some bytes by using long array instead of DateTime.
```
_=>{var d=new long[9];for(var i=0;i<9;){Console.ReadKey();d[i++]=DateTime.Now.Ticks;}return$"{48e8/(d[8]-d[0]):n2}";}
```
## Humane version
```
class Program
{
static void Main()
{
Func<int, string> f = _ =>
{
var d = new long[9];
for (var i = 0; i < 9;)
{
Console.ReadKey(); // Switch these two to "automate" key presses.
//Thread.Sleep(100);
d[i++] = DateTime.Now.Ticks;
}
return $"{48e8 / (d[8] - d[0]):n2}";
};
var result = f(1);
Console.WriteLine();
Console.WriteLine(result);
Console.ReadKey(true);
}
}
```
[Answer]
# R, ~~79~~ 84 bytes
```
scan();s=Sys.time;x=s();replicate(8,scan());cat(round(60/as.numeric((s()-x)/8),d=2))
```
Only works when using enter, since that will end scan immediately. Explicitly uses `print` for its `digits` argument, handling the rounding.
```
> scan();s=Sys.time;x=s();replicate(8,scan());cat(round(60/as.numeric((s()-x)/8),d=2))
1:
Read 0 items
numeric(0)
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
[[1]]
numeric(0)
[[2]]
numeric(0)
[[3]]
numeric(0)
[[4]]
numeric(0)
[[5]]
numeric(0)
[[6]]
numeric(0)
[[7]]
numeric(0)
[[8]]
numeric(0)
[1] 439.47
```
[Answer]
# Ruby, 58 bytes
```
gets;t=Time.now;8.times{gets};p (480/(Time.now-t)).round 2
```
] |
[Question]
[
Related to: [Make a ;# interpreter](https://codegolf.stackexchange.com/q/121921/2867) and [Generate ;# code](https://codegolf.stackexchange.com/q/122139/2867)
## `;#` - A Whirlwind Guide
This is a simple language with two commands. Its only data structure is an accumulator, which is initialized to 0.
1. **`;`** Increment the accumulator
2. **`#`** Calculate the value of the accumulator modulo 127, and print the corresponding ASCII character. Then, reset the accumulator to 0.
The source code may contain additional characters (printable ASCII + whitespace), but these are treated as comments and have no effect on program execution.
## Challenge
Since most computers do not come with `;#` preinstalled, it would be very useful to have a tool that can convert `;#` code into a different language. In this challenge, you shall write a program to accomplish this.
## Input
Some `;#` source code, taken via argument or STDIN. This source code may contain (comment) characters other than `;` or `#`.
## Output
Code, in the same language as your submission, which, when executed, prints/returns the same string as the original `;#` code. This resultant code may output a trailing newline after the target string, if that is more convenient for your language.
## Notes
One thing to look out for is escape sequences, such as code that prints backslashes or prints quote marks. Also look out for `;#` code that could contain things that look like keywords or commands in your language.
## Additional restrictions
All programs must terminate (I normally consider this a default, but someone asked about it so I'm stating it here).
## Examples
```
input: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
output (python): print(";#")
input: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
output (element): \'`
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 126 bytes
```
+++[->+++++<]>[->++++>+++<<],[+<++++++[-<++++>>------<]>[<]<<[>>>>>[--<--.++>]<+.-<.<<<<]>[->>-<<]>>[[-]<]>[>>++++[-->]<[<]],]
```
[Try it online!](https://tio.run/##nYxBCoBADAMf47Hb/YAhHyk9qCCI4EHw/Wu7@gBxDiUkaeZz2o71WvbWRMSUksD5yjyAFxP0JCpdkNrJJhwwJhaGao3YIVVREfQtagqaqadBPlsaxfj34q2N/xm@dG4 "brainfuck – Try It Online")
The output program will fail in the TIO implementation if the `;#` output exceeds 65536 characters. I also made a 130-byte version which outputs `[+]` instead of `<`, avoiding this problem:
```
++[------>++>+<<]>+++++<,[+<++++++[-<++++>>------<]>[<]<<[>>>>>[--<.>]<+++.---<.>.<++.--<<<<]>[->>-<<]>>[[-]<]>[>>++++[-->]<[<]],]
```
### Explanation
```
+++[->+++++<]>[->++++>+++<<] initialize tape with 60 and 45
,[ for each input byte:
+<++++++[-<++++>>------<] subtract 35 (#) from byte
>[<]<<[ if byte was #
>>>>>[--<--.++>] output + (43) a number of times equal to accumulator
<+.-<.<<<< output . (46) and < (60)
]
>[->>-<<]>> subtract 24 from what's left of byte
[[-]<] check difference and clear if nonzero
>[ if byte was originally 59 (;)
>>++++[-->]<[<] add 4 to accumulator cell, then subtract 2 if nonzero. Since BF cells are mod 256, this creates an accumulator mod 127.
]
,]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~76~~ 69 bytes
### Code
Input is surrounded by quotes.
```
for y in input('print').split("#")[:-1]:print`chr(y.count(";")%127)`,
```
[Try it online!](https://tio.run/nexus/python2#@5@WX6RQqZCZB0QFpSUa6gVFmXkl6pp6xQU5mSUaSspKmtFWuoaxVmDxhOSMIo1KveT80jygnLWSpqqhkblmgs7//0rWVALK1vQA9LFl2FtGqn3KA@X6QR0qo6mMXEuUlQA "Python 2 – TIO Nexus")
### Explanation
The first part of the output is essentially done by the input, using `input('print')`. We split the input on hashtags and discard the last element. We print the representation of **ord(y%127)**, where **y** is the number of occurrences of the semicolon. We append the `,` at the end of the print to make sure that this does not print a newline.
This would give the following Python code for the `Hello, World!`-program:
```
print'H' 'e' 'l' 'l' 'o' ',' ' ' 'W' 'o' 'r' 'l' 'd' '!'
```
Which can be [tried online](https://tio.run/nexus/python2#@19QlJlXou6hrqCeCsQ5UJwPxDpADILhUH4RVC4FiBXV//8HAA).
[Answer]
# Whitespace, 291 bytes
```
NSSTTNNSTNNSTNNSTTNNSSTSNSSNSNSTNTSTTTSSSTSSSTTNTSSTSNSNTSSSSNSSSTTSSSNTSSTNTSSSTNNSNTSNNSSSSSNSNNNSTSSNNSTSTNNSTSTNNSTSNNSTTNNSTSNNSTNNSTSTNNSTTNNSTNNSTNNSNTTNNSSSSTNNSTSSNNSTSNNSTTNNSTSNNSTSSNNSNTSNNSSTNSSSTSTSNTNSSNTNNSSSSNNSTNNSTNNSSNSSSTSSSSSNTNSSNTNNSSSTNNSTSNNSTSNNSSSNSSSTSSTNTNSSNTN
```
Replace S by space, T by tab and N by a newline.
Generating whitespace in whitespace is not the most efficient thing in the world. Generating any kind of dynamic code requires significant bit-twiddling which, in a language without bitwise operations, would cause the code size to explode. Therefore, this program does not attempt to do something smart, instead opting for just translating the source program one to one. It disassembles to the following:
```
early:
call S
call S
call N
start:
push 0
dup
ichr
get
push 35
sub
dup
jz hash
push 24
sub
jz semi
jmp start
hash:
pop
call SSS
call TTT
call TTT
call T
call N
call T
call S
call TTT
call N
call S
call S
jmp early
semi:
call SSS
call T
call N
call T
call SSS
jmp start
N:
push 10
pchr
ret
SSS:
call S
call S
S:
push 32
pchr
ret
TTT:
call T
call T
T:
push 9
pchr
ret
```
The code generated by the program looks like:
```
push 0
push 1
add
push 1
add
push 1
add
push 1
add
push 1
add
push 1
add
push 1
add
push 1
add
push 1
add
push 1
add
push 1
add
push 127
mod
pchr
push 0
push 1
add
...
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~19~~ ~~20~~ 28 bytes
Bugfix, broke if there was no `#` at the end
Bugfix, implemented `mod 127`
```
Í;û127}
éiA0Í#/0
ò/;
x
```
[Try it online!](https://tio.run/nexus/v#@3@41/rwbkMj81quwyszHcWkDaQP9yrri4kZcB3epG/NVcH4/781@UCZGDUA "V – TIO Nexus")
[Try Generated Code](https://tio.run/nexus/v#@58pZmopZmwqbfD/PwA "V – TIO Nexus")
Explanation:
```
Í;û127} ' Delete runs of 127 `;`s (mod 127)
éi ' Insert an `i` in front of input
A<C-v><esc>0<esc> ' Append <esc>0 to input
Í#/<C-v><C-v>0 ' Replace all `#` with `<C-v>0`
ò ' Recursively
/; ' Go to the next `;`
<C-a> ' Increment the next number come across
```
In V, in insert mode, any ASCII character can be inserted by code by using `<C-v><Code>`. The V code replaces all `#` with `<C-v>0`, where the zero is a pseudo-accumulator per `#`. Each `#` resets the accumulator to 0 so having one per works out fine. Then the code does an increment for each semicolon found, which just increments the next number it finds, which would be the next accumulator. The `0` is appended to the end so that the instruction doesn't fail for `;`s without a following `#`.
Hexdump:
```
00000000: e969 4116 1b30 1bcd 232f 1616 300a f22f .iA..0..#/..0../
00000010: 3b0a 7801 ;.x.
```
[Answer]
## JavaScript (ES6), ~~101~~ 100 bytes
```
s=>`_=>'${s.replace(/[^#;]/g,``)}'.replace(/;*(#?)/g,(l,c)=>c&&String.fromCharCode(~-l.length%127))`
```
Given an input string, deletes all the unnecessary characters, then returns the source of the following function:
```
_=>'...'.replace(/;*(#?)/g,(l,c)=>c&&String.fromCharCode(~-l.length%127))
```
Where `...` represents the cleaned `;#` source. Edit: Saved 1 byte thanks to @l4m2.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20 19 18~~ 16 bytes
-1 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)
-2 thanks to [carusocomputing](https://codegolf.stackexchange.com/users/59376/carusocomputing)
-2 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
'#¡¨vy';¢ƵQ%„çJJ
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fXfnQwkMryirVrQ8tOrY1UPVRw7zDy728/tfa6oXp/LemElC2pgegjy3D3jLi7FMeKDcPwrAYTVuUW5IIVAIA "05AB1E – Try It Online") (includes output of executed 05AB1E code)
```
'#¡ # Split on #
¨ # remove the last element
vy # For each...
';¢ # count the number of ;s
ƵQ% # Mod by 127
„çJ # Push çJ
J # Join stack and output implicitly
```
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
```
lambda s:"print"+`''.join(chr(x.count(';')%127)for x in s.split('#')[:-1])`
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQbKVUUJSZV6KknaCurpeVn5mnkZxRpFGhl5xfmleioW6trqlqaGSumZZfpFChkJmnUKxXXJCTCZRRVteMttI1jNVM@F@UWqxgq5AGVE0pULYeDEZYA/3GBQ4WBaDXuFIrUpNBjP8A "Python 2 – TIO Nexus") (includes output from executing the transpiled Python code)
Thanks to ovs for many many bytes!
## Explanation
This program transpiles the #; code by splitting on #s (`s.split('#')[:-1]`), counting the number of semicolons in each chunk mod 127 (`x.count(';')%127for x in ...`), and converting that into the respective ASCII character (`chr(...)`). That list is then concatenated (`''.join(...)`), converted into a Python representation of the string (the backticks) and inserted into a skeleton Python program for printing strings (`"print"+...`).
[Answer]
# [Haskell](https://www.haskell.org/), ~~106~~ 102 bytes
```
';'!(x:a)=x+1:a;'#'!a=0:a;_!a=a;h s="main=putStr"++(show$""++(toEnum.(`mod`127)<$>init(foldr(!)[0]s)))
```
[Try it online!](https://tio.run/##nZAxD4IwEIX3/oqjkNAGQ8DFhFo3N50cCZEmYEqEltAS@fcIamKcRN9yb3h39/JJYa5lXY@jz3yHDImgfAjiRDDf9R3Bo8mdpymYBMNxIyrF296ebIeDgBipbx6endV71TchyRtd5PF6Q7ferlKVJRddFx1xaBplhlI62tJYAxxSwOx/uUsyGMFLqyXPPvO/bn8t/L6XITRznCA0oj0CefI8KAhBUngAQuMd "Haskell – Try It Online")
**Ungolfed**
```
step ';' (x:acc) = x+1:acc
step '#' acc = 0:acc
step _ acc = acc;
semicolonHash s = toEnum . (`mod` 127) <$> init (foldr step [0] s)
toHaskell s = "main = putStr " ++ (show $ "" ++ semicolonHash s)
```
[Answer]
# [Cubically](https://github.com/aaronryank/cubically), ~~138~~ 137 bytes
```
+1/1+54@6:5+1/1+5@6/1+52@6:4/1+5@6:1/1+54@6:4/1+5@6:5+2/1+4@6(~-61/1=7&6+5/1+51=7?6{+3/1+5@6}:5+3/1+3=7?6{+52@6:5+1@6-1@6+1@6:5+2/1+4@6})
```
[Try it online!](https://tio.run/##Sy5NykxOzMmp/P9f21DfUNvUxMHMyhTCdDADkUZAARMI1wquAiZgqm0EZAFFNOp0zYCytuZqZtqmIEkg096sWtsYorAWqBLENIaIgg0F2uJgpgvEIBphUq3m///W5ANlYtQAAA)
Note: You may need to replace `&6` with `?6&` for it to work on TIO. `&6` is in the language spec, though.
### How it works
```
+1/1+54@6 Output 'R'
:5+1/1+5@6 Output '3'
/1+52@6 Output 'D'
:4/1+5@6 Output '1'
:1/1+54@6 Output 'R'
:4/1+5@6 Output '1'
:5+2/1+4@6 Output '+'
( Loop indefinitely
~ Get next character
-61/1=7&6 If input is -1 (EOF), exit program
+5/1+51=7?6{ If input is `;`
+3/1+5@6 Output '0'
} End if
:5+3/1+3=7?6{ If input is '#'
+52@6 Output '@'
:5+1@6 Output '6'
-1@6 Output '-'
+1@6 Output '6'
:5+2/1+4@6 Output '+'
} End if
) End loop
```
Output program:
```
R3D1R1 Set top face to 1
+00... Add top face to notepad, aka increment notepad
@6 Output notepad as character
-6 Set notepad to 0
...
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 33 bytes
```
{";"∧"+₁"|"#"∧"%₁₂₇g~ạw0"}ˢ;"0"↔c
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6kUFKUmFdckJmTWqxQkq@gVG7/qG3Do6amh7s6ax9unfC/Wsla6VHHciXtR02NSjVKymCOKpADVPOoqT297uGuheUGSrWnF1krGSg9apuS/P9/tJI1@UCZGDVKOkrUUkU9Vw0VW4a9ZaTapzxQrh/UoTKaysi1RFkpFgA "Brachylog – Try It Online")
I felt too tired to explain this two years ago, but Razetime reminded me.
```
;"0"↔c Prepend a 0 to
{ }ˢ each element of the input
"+₁" mapped to +₁
";"∧ if it's a semicolon,
|"#" if it's a hash
∧"%₁₂₇g~ạw0" %₁₂₇g~ạw0,
ˢ or nothing otherwise.
+₁ add 1
%₁₂₇ mod 127,
g~ạ convert from codepoint to character,
w print,
0 start over from 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25 24 16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)! (Use of `p` in place of `;€`)
```
ṣ”#Ṗċ€”;%127p”Ọ
```
A full program printing equivalent Jelly code (as a monadic link it returns a list of lists of mixed types).
The first example is at **[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuYqP9w57Uj3o6Y1QLa1qqGReQGQ8XB3z////60JgOT83NzUvBI8KpStCYMQfxd/K@XiktK0NAA "Jelly – Try It Online")** which yields [this program](https://tio.run/nexus/jelly#@29q@XB3j7EpkPj/HwA "Jelly – Try It Online").
### How?
Counts up the `;`s in each run between `#`s takes each modulo 127 and appends a cast to ordinal instruction, the monadic `Ọ` atom, after each.
Jelly implicitly pipes each value to STDOUT as it runs through a program like that i.e. `72Ọ101Ọ108Ọ108Ọ111Ọ44Ọ32Ọ119Ọ111Ọ114Ọ108Ọ100Ọ33Ọ` would print `Hello, world!`.
```
ṣ”#Ṗċ€”;%127p”Ọ - Main link: list of characters
”# - literal '#'
ṣ - split the result at #s
Ṗ - pop (remove the last result, list of trailing non-# characters)
”; - literal ';'
ċ€ - count for €ach
%127 - modulo 127 (vectorises)
”Ọ - literal 'Ọ' (Jelly's cast to ordinal monadic atom)
p - Cartesian product - making a list of lists like [[72,'Ọ'],[101,'Ọ'],...]
- implicit print (this smashes, printing something like: 72Ọ101Ọ...)
```
A note regarding input: Jelly can take string input in Python format (it will first attempt to evaluate input as Python code). The empty program may be input as `""`, and the hash-only programs as `"#"`, `"##"`, etc. Escape sequences are required for input containing backslashes and quotes.
[Answer]
# C, ~~98~~ ~~96~~ ~~99~~ ~~98~~ 97 bytes
+3 bytes because I forgot C isn't interpreted :(
```
c,a;f(){printf("f(){puts(\"");for(;~c;c=getchar())c==59?a++:c==35?a=!printf(&a):a;puts("\");}");}
```
---
Running with:
```
echo ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#" | ./a.out
```
Will print:
```
f(){puts("Hello, World!");}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
”‘x
f”;L%127Ç;“Ọø”
ṣ”#Ç€ṙ-
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYe6jhhkVXGlAhrWPqqGR@eF260cNcx7u7jm8AyjG9XDnYiClfLj9UdOahztn6v7//98aDpLzc3NT80qsKQHKSOyAAGd3haD85OxiRYqMBAA "Jelly – TIO Nexus")
[And try that Jelly code here!](https://tio.run/nexus/jelly#@/9wd8/hHY8aZgw/NMx99v8/AA "Jelly – TIO Nexus")
```
ṣ”#Ç€ṙ- Main link, input is a string of ";;;;;;#lala;;;;;;;;;#"
ṣ”# Split input on char #
Ç€ Call helper link 1 for each segment
ṙ- Rotate returns 1 to the right (SPLIT introduces an empty element which is moved up front)
f”;L%127Ç;“Ọø” Helper link 1, determines the number of increments
f”; Throw out all but semicolons
L%127 Take the count mod 127
Ç Call helper 2
;“Ọø” Add a Jelly link that prints characters and splits print statements
”‘x Helper 2, receives the count of ;'s
”‘ Return the character ‘ (Jelly's increment command
x Once for each ; in the input
```
The Jelly output becomes code like `Ọø‘‘‘‘‘‘‘‘‘‘‘‘‘Ọø‘‘‘‘‘‘‘‘‘‘Ọø`, which prints chr(13)+chr(10)
[Answer]
# PHP, 72 bytes
```
for(;~$c=$argn[$i++];)echo[Z=>'$n++;',B=>'echo~$n=~chr($n%127);'][a^$c];
```
[Answer]
# ><>, ~~106~~ ~~81~~ 77 bytes
This is my first golf in ><> (fish)! A pretty interesting language I have to say. A lot of fun!
```
0n01.
>i:1+?!v:";"=?v"#"=?v
^ ;o";"< .37<
^oo"1+"
^oooooooo'"~"1+%o0' <
```
[Answer]
# C# 169 Bytes
Golfed:
```
class P{static int Main(string[] args){var r="Console.Write(";foreach(var y in args[0].Split('#')){r+=(char)(-1+y.Split(';').Length%127);}System.Console.Write(r+");");}}
```
Human readable version:
```
class P
{
static int Main(string[] args)
{
var r="Console.Write(\"";
foreach (var y in args[0].Split('#'))
{
r +=(char)(-1+y.Split(';').Length% 127);
}
System.Console.Write(r+"\");");
}
}
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 17 bytes
```
⌡(¶{gÉ'8=£♣(%$''\
```
[Try it online!](https://tio.run/##y00syUjPz0n7//9Rz0KNQ9uq0w93qlvYHlr8aOZiDVUVdfWY///VrckHysSoUedSJ0tVcn5ubmpeCVbF/wE "MathGolf – Try It Online")
## Explanation
```
⌡ decrement twice
( decrement
this transforms ";;;#;;#" -> "888 88 "
¶ split string on spaces
{ foreach...
gÉ filter using next 3 characters
'8 push single character "8"
= pop(a, b), push(a==b)
this filters out all non-";"
£ length of array/string with pop
♣ push 128
( decrement
% modulo
$ pop(a), push ord(a) or char(a) (gets character with code)
'' push single character "'"
\ swap top elements
```
Since any character can be put on the stack (and thus the output) using `'<char>`, this will output a sequence of such code blocks.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~32~~ 28 bytes
```
35lF4$Yb"@g59=z]xv127\!&D99h
```
[Try it online!](https://tio.run/##y00syfn/39g0x81EJTJJySHd1NK2KraizNDIPEZRzcXSMuP/f3VlawhQVlZOTEoGMYBYHQA "MATL – Try It Online")
Completely different approach based on `strsplit` rather than an automaton-type program.
```
Yb % strsplit
4$ % with 4 inputs, namely:
35 % Split on '#'
lF % Do not (F) collapse delimiters (l).
% And of course the implicit program input.
"@g ] % Loop over strings, convert each to a normal char array
59=z % How many equal to 59 ';'?
xv!127\ % Delete last element, concatenate and flip to horizontal, mod 127
&D % Convert to MATL representation
99h % Append a 'c' to output ASCII.
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `Ṫ`, 18 bytes
```
\#€Ṫƛ\;O₇‹%\C+\₴+,
```
Good, but definitely could be improved.
Outputs the codepoint, followed by a C to convert to a character, and then a print symbol.
[Try it Online!](http://lyxal.pythonanywhere.com?flags=%E1%B9%AA&code=%5C%23%E2%82%AC%E1%B9%AA%C6%9B%5C%3BO%E2%82%87%E2%80%B9%25%5CC%2B%5C%E2%82%B4%2B%2C&inputs=%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3Baaaaaaaaaaaaaaaaaaaaaaa%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23&header=&footer=)
[Answer]
# [Nim](http://nim-lang.org/), 97 bytes
```
var a=0
for c in stdin.readAll:
if c==';':a+=1
if c=='#':echo "stdout.write chr ",a mod 127;a=0
```
[Try it online!](https://tio.run/##y8vM/f@/LLFIIdHWgCstv0ghWSEzT6G4JCUzT68oNTHFMSfHikshM00h2dZW3VrdKlHb1hDOV1a3Sk3OyFdQAqrPLy3RKy/KLElVSM4oUlDSSVTIzU9RMDQytwaa/P@/NflAmRg1AA "Nim – Try It Online")
[Example resulting code](https://tio.run/##y8vM/f@/uCQlv7REr7wosyRVITmjSMHUkgtDzNiU6/9/AA "Nim – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 16 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
';'⁺Ṇ'#"ṇȷ%C¢"WṆ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSclM0InJUUyJTgxJUJBJUUxJUI5JTg2JyUyMyUyMiVFMSVCOSU4NyVDOCVCNyUyNUMlQzIlQTIlMjJXJUUxJUI5JTg2JmZvb3Rlcj0maW5wdXQ9JTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTIzJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTNCJTIzJmZsYWdzPQ==)
or [verify the resulting Thunno 2 code](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMiU4MSVCQSVFMSVCOSU4NyVDOCVCNyUyNUMlQzIlQTIlRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTIlODElQkElRTElQjklODclQzglQjclMjVDJUMyJUEyJmZvb3Rlcj0maW5wdXQ9JmZsYWdzPQ==)
#### Explanation
```
';'⁺Ṇ'#"ṇȷ%C¢"WṆ '# Implicit input
';'⁺Ṇ # Transliterate ";" -> "⁺"
⁺ # Increment top of stack
# (which starts at 0)
'#"ṇȷ%C¢"WṆ '# Transliterate "#" -> "ṇȷ%C¢"
ṇȷ # Push compressed integer 127
% # And modulo top of stack by that
C # Cast to character using ASCII value
¢ # And print it without a newline
# Implicit output
```
[Answer]
# [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 57 bytes
```
"print%q"%gsub(a,".-#",#char(len(gsub(e,"[^;]",""))%128))
```
## Explained
```
"print%q"%gsub(a,".-#",#char(len(gsub(e,"[^;]",""))%128))
gsub(a,".-#", ) -- Replace all groups of characters followed by a # in the input with...
gsub(e,"[^;]","") -- Remove all non-; characters, removing comments
len( ) -- Effectively count all ; in the group
char( %128) -- Modulo 128, convert to a char.
# -- As a function. Effectively runs the ;# code.
"print%q"% -- returns a string consisting of print followed by the string-formatted ;# code.
```
[Try it online!](https://tio.run/##SyxKykn9/1@poCgzr0S1UEk1vbg0SSNRR0lPV1lJRzk5I7FIIyc1TwMsnKqjFB1nHauko6SkqalqaGShqfkfqNeafKBMjBolAA "ARBLE – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 25 bytes
```
'#@s⌠';@c7╙D@%⌡MdX$"♂cΣ"o
```
[Try it online!](https://tio.run/nexus/actually#@6@u7FD8qGeBurVDsvmjqTNdHFQf9Sz0TYlQUXo0syn53GKl/P/WxyY5/FeyphJQtqYHoI8tw94yUu1THijXD@pQGU1l5FqSqKwEAA "Actually – TIO Nexus") (includes output from executing the transpiled Actually code)
Explanation:
```
'#@s⌠';@c7╙D@%⌡MdX$"♂cΣ"o
'#@s split on "#"
⌠';@c7╙D@%⌡M for each chunk:
';@c count ";"s
7╙D@% mod by 127 (2**7-1)
dX discard last value
$ stringify
"♂cΣ"o append "♂cΣ":
♂c convert each value to an ASCII character
Σ concatenate
```
[Answer]
# [shortC](//github.com/aaronryank/shortC), 48 bytes
```
c,a;AR"AP\"");O;~c;c=G)c==59?a++:c==35?a=!R&a):a
```
[Answer]
# Fourier, 32 bytes
```
$(I~S{59}{`^`}S{35}{`%127a0`}&i)
```
[**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=JChJflN7NTl9e2BeYH1TezM1fXtgJTEyN2EwYH0maSk)
This was quite an easy challenge since Fourier is *basically* a superset of ;#:
```
;# command > Fourier equivalent
; > ^ (Increment the accumulator)
# > %127a0 (Modulo accumulator by 127, output corresponding code point and set accumulator to zero)
```
[Answer]
## CJam, 14 bytes
```
q'#/);';fe=:c`
```
Explanation:
```
q e# Read input
'#/ e# Split on '#'
); e# Delete last element
';fe= e# Count occurrences of ';' in each
:c e# Convert each to character (code point)
` e# Escape
```
[Answer]
# APL, 31 bytes
```
{⍕'⎕UCS',⌽127|+/¨';'=⍵⊂⍨'#'=⍵}⌽
```
Output:
```
({⍕'⎕UCS',⌽127|+/¨';'=⍵⊂⍨'#'=⍵}⌽) ';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#'
⎕UCS 59 35
⍝ evaluate the output
⍎({⍕'⎕UCS',⌽127|+/¨';'=⍵⊂⍨'#'=⍵}⌽) ';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#'
;#
```
Explanation:
* `⌽`: reverse the input
* `{`...`}`: pass it to this function:
+ `⍵⊂⍨'#'=⍵`: partition at each `#` in the string (from the beginning, which is why it had to be reversed first)
+ `+/¨';'=`: count the `;`s in each partition
+ `127|`: modulo 127
+ `⌽`: reverse it again
+ `'⎕UCS',`: prepend the string `⎕UCS`, which is the Unicode function.
+ `⍕`: string representation
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47+1=48 bytes
```
$_=gsub(/.*?#/){"$><<#{$&.count(?;)%127}.chr;"}
```
+1 byte for `-p`.
[Try it online!](https://tio.run/##KypNqvz/XyXeNr24NElDX0/LXllfs1pJxc7GRrlaRU0vOb80r0TD3lpT1dDIvFYvOaPIWqn2/3/rQQXS8vNJUa4MpZOt861zgTDVOs@6BL9S8sG//IKSzPy84v@6BQA "Ruby – Try It Online")
-30 bytes thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork)!
[Answer]
# Pyth, ~~25~~ ~~23~~ 24 bytes
```
j\\+"jk["mC%/d\;127Pcw\#
```
*+1 bytes thanks to @FryAmTheEggman*
[Try it!](https://pyth.herokuapp.com/?code=j%5C%5C%2B%22jk%5B%22mC%25%2Fd%5C%3B127Pcw%5C%23&input=%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23&test_suite=1&test_suite_input=%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%0A%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23&debug=0)
handles characters that have to be escaped by only using 1-char-strings.
Sample outputs:
```
jk[\"
jk[\H\e\l\l\o\,\ \W\o\r\l\d\!
```
Uses [my ;# interpreter](https://codegolf.stackexchange.com/a/122025/56557).
[Answer]
# C, 150 bytes
```
#include<stdio.h>
c;n=0;main(){puts("#include<stdio.h>\nmain(){");while(~(c=getchar()))c-35?c-59?:n++:(printf("putchar(%d);",n%127)&(n=0));puts("}");}
```
Expanded:
```
#include<stdio.h>
c;
n=0;
main(){
puts("#include<stdio.h>\nmain(){");
while( ~(
c=getchar()
))
c-35?
c-59?
:
n++
:
( printf("putchar(%d);",n%127)
&(n=0))
;
puts("}");
}
```
It's a complete program that (should) terminate, ignore comments and produce always correct output code.
I assume EOF=-1
Tested on SystemResque-Cd 4.9.6, compiled with gcc 4.9.4
] |
[Question]
[
Given two integers greater than one, A and B, output four mathematical expressions in this order:
1. The plain expression A^B (A to the power B). e.g. if A = 2 and B = 3, `2^3`.
2. The expansion of A^B in terms of repeated multiplications of A. e.g. `2*2*2`.
3. The expansion of A^B in terms of repeated additions of A. e.g. `2+2+2+2`.
4. The expansion of A^B in terms of repeated additions of 1. e.g. `1+1+1+1+1+1+1+1`.
The four expressions may be output in any reasonable way as long as they are in order and clearly distinct. For example, you might put them in a list, or print them on separate lines
```
2^3
2*2*2
2+2+2+2
1+1+1+1+1+1+1+1
```
or perhaps on one line separated by equals signs:
```
2^3=2*2*2=2+2+2+2=1+1+1+1+1+1+1+1
```
Spaces may be inserted next to math operators so
```
2^3 = 2 * 2 * 2 = 2 + 2 + 2 + 2 = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
```
would be equally valid output when A = 2 and B = 3.
You may use symbols alternative to `^`, `*`, and `+`, but *only if* the new symbols are more idiomatic for your language (e.g. `**` instead of `^` in Python).
You may assume that A and B are sufficiently small so that A^B will not overflow your language's default integer type (given that that type has a reasonable maximum, 255 at least).
**The shortest code in bytes wins.**
# Test Cases
One output per line. The input can be inferred as the first expression is always A^B.
```
2^2 = 2*2 = 2+2 = 1+1+1+1
2^3 = 2*2*2 = 2+2+2+2 = 1+1+1+1+1+1+1+1
2^4 = 2*2*2*2 = 2+2+2+2+2+2+2+2 = 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
2^5 = 2*2*2*2*2 = 2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2 = 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
3^2 = 3*3 = 3+3+3 = 1+1+1+1+1+1+1+1+1
3^3 = 3*3*3 = 3+3+3+3+3+3+3+3+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
3^4 = 3*3*3*3 = 3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3 = 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
3^5 = 3*3*3*3*3 = 3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3 = 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
4^2 = 4*4 = 4+4+4+4 = 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
4^3 = 4*4*4 = 4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+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
10^2 = 10*10 = 10+10+10+10+10+10+10+10+10+10 = 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
13^2 = 13*13 = 13+13+13+13+13+13+13+13+13+13+13+13+13 = 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+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 3.6](https://docs.python.org/3.6), ~~88~~ 74 bytes
-2 bytes thanks to Dada (use `~`)
-5 bytes thanks to Erwan (use f-strings from Python 3.6)
```
lambda a,b:f"{a}^{b}={a}{f'*{a}'*~-b}={a}{f'+{a}'*~-a**~-b}=1"+"+1"*~-a**b
```
*online ide anyone?*
### How?
This is an unnamed function taking the two integer inputs `a` and `b` each greater than `0` (even though the specification is only for those greater than `1`).
In Python 3.6 a new feature is available, namely [formatted string literals](https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings) or "f-strings". These allow run-time evaluated string construction. A leading `f` (or `F`) creates such a construct, e.g. `f"blah"` or `f'blah'`. Inside an f-string anything between a pair of braces, `{...}`, is an expression to be evaluated.
As such `f"{a}^{b}={a}{f'*{a}'*~-b}={a}{f'+{a}'*~-a**~-b}=1"` evaluates each of `a`, `b`, `a`, `f'*{a}'*~-b`, `a`, and `f'+{a}'*~-a**~-b}` as expressions, keeping the `^`, `=`, `=`, and `=1` as strings,all of which gets concatenated together.
The `a` and `b` expressions evaluate to the representations of `a` and `b` respectively.
The `f'*{a}'` and `f'+{a}'` in turn are also f-strings inside these expressions, which evaluate to `a` with a leading `'*'` and a leading `'+'` respectively
To create the required number of `a`s and operations for the `*` and `+` portions note that there will be `b` `a`s multiplied together and `a**(b-1)` `a`s added together. Each case then requires one less operator sign than the number of `a`s. So we can repeat the f-strings `f'*{a}`and `f'+{a}'` (using `*`) as many times as there are operators and prepend each with a single `a`. `(b-1)` is `~-b` and `(a**(b-1))-1` is `~-a**~-b`.
The same is done for the `1`s using `(a**b)-1` being `~-**b`, but we don't need the overhead of f-strings since `1` is constant, so a standard string repeated is concatenated with `+`.
---
Prior Python versions, 81:
```
lambda a,b:'%s^%s=%s=%s=1'%(a,b,('*%s'%a*b)[1:],('+%s'%a*a**~-b)[1:])+'+1'*~-a**b
```
**[Try it online!](https://tio.run/nexus/python3#PczNCgIhFIbhdV2FGznHnyBH2whzJf2AUsJAzcTouls350iBfPA@HEzjpT7DK94DCzp64PnG89ifAY4NNYLkGXiQUZyNv7ZWvYOUn0NHoUAZaNks1rSsrDxyYdPMEAc9CN3W0jraU1tLbsktuSV35I7cHCnMdiv8fvdep7ng9rf4RUJJ/QdR6xc)**
[Answer]
# Cubix, ~~238 234 217 151 110~~ 100 bytes
*Saved 14 bytes thanks to ETHProductions*
```
u'^.:s+.;;;\-?W?rsos\(rrOIO:ur>'=o;^u.;;.>$.vUo^'rsu1;;@!\q?s*su;;IOu*+qU../;(*\(s.;<..r:''uq....qu\
```
Expanded:
```
u ' ^ . :
s + . ; ;
; \ - ? W
? r s o s
\ ( r r O
I O : u r > ' = o ; ^ u . ; ; . > $ . v
U o ^ ' r s u 1 ; ; @ ! \ q ? s * s u ;
; I O u * + q U . . / ; ( * \ ( s . ; <
. . r : ' ' u q . . . . q u \ . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
```
# Try it online!
[Try it here](https://ethproductions.github.io/cubix/?code=dSdeLjpzKy47OztcLT9XP3Jzb3NcKHJyT0lPOnVyPic9bztedS47Oy4+JC52VW9eJ3JzdTE7O0AhXHE/cypzdTs7SU91KitxVS4uLzsoKlwocy47PC4ucjonJ3VxLi4uLnF1XA==&input=Miwz&speed=10)
# Explanation
The code consists of 8 steps, with two loops. I'll go over the code part by part.
# Step 1 (A^B)
```
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
I O : u . . . . . . . . . . . . . . . .
U o ^ ' . . . . . . . . . . . . . . . .
; I O u . . . . . . / ; ( * \ . . . . .
? ? r : . . . . . . ? . . . \ ? ? ? ? ?
. . . . ? . . . . . ? . . . . . . . . .
? ? ? ? ?
. . . . .
. . . . .
. . . . .
. . . . .
```
This is the cube with the parts that are irrelevant to the first step removed. The question mark shows the no-ops the IP will visit, to make its path more clear.
```
IO:'^o;IO:r*(; # Explanation
I # Push the first input (A)
O # output that
: # duplicate it
'^ # Push the character "^"
o # output that
; # pop it from the stack
I # Push the second input (B)
O # output that
: # duplicate
r # rotate top 3 elements
* # Push the product of the top two elements
( # decrease it by one
; # pop it from the stack (making the last
# two operations useless, but doing it
# this way saves 10B)
```
Now, the stack looks like this: `A, B, A, B`
# Step 2 (prepare for print loop)
The print loop takes 3 arguments (the top 3 elements on the stack): `P`, `Q` and `R`. `P` is the amount of repetitions, `Q` is the separator (character code) and `R` is the number to repeat. Luckily, the loop also takes care of the requirement that the resulting string should end in `R`, not `Q`.
We want to repeat `A*` exactly `B` times, so the separator is `*`. Note that the stack starts as `A, B, A, B`. Once again, I removed all irrelevant instructions. The IP start at the `S` pointing north.
```
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . r . . . . . . . . . . . . . . .
. . . . r . . . . . . . . . . . . . . .
. . . . * . . . . . . . . . . . . . . .
. . . . ' . . . . . . . . . . . . . . .
. . . . S . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
'*rr # Explanation
'* # Push * (Stack: A, B, A, B, *)
rr # Rotate top three elements twice
```
The stack is now `A, B, B, *, A`.
# Step 3/6/8 (the print loop)
## Concept
```
E . . . . .
? r s o s u
\ ( r r O <
. . . . . S
```
The IP enters the loop through `S`, pointing north, and exits the loop at `E`, pointing north again. For this explanation, the stack is set to `[..., A, B, C]`. The following instructions are executed. Note that the IP can't leave the loop before the question mark, so the first four instructions will always be executed.
```
Orr(?rsos # Explanation
O # Output `C`
rr # Rotate top three elements twice (Stack: [..., B, C, A])
( # Decrease A by one (Stack: [..., B, C, A-1])
? # If top of stack (A) > 0:
r # Rotate top of stack (Stack: [..., A-1, B, C])
s # Swap top elements (Stack: [..., A-1, C, B])
o # Output top of stack (B) as character code
s # Swap top elements (Stack: [..., A-1, B, C]
#
# ... and repeat ...
```
## Implementation
Here's the cube again, with the irrelevant parts removed. The IP starts at `S`, pointing east.
```
. . . . .
. . . . .
. . . . .
? r s o s
\ ( r r O
. . . . . S ' = o ; ^ u . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
```
As you can see, the IP comes across four instructions before it enters the loop. Since the character code is removed again, we reach the loop with the exact same stack as we entered this part.
```
'=o; # Explanation
'= # Push =
o # Output
; # Pop from stack
```
Inside the loop, the explanation above holds.
# Step 4 (differentiating the IPs)
Since we use the above loop multiple times, and they all cause the IP to end up in the same spot, we have to differentiate between multiple runs. First, we can distinguish between the separator (first run has a `*`, whereas runs two and three have a `+` as separator). We can differentiate between runs 2 and 3 by checking the value of the number that is repeated. If that is one, the program should terminate.
## First comparison
Here's what it looks like on the cube. The IP starts at S and points north. The stack contains `[..., * or +, A or 1, 0]`. The number 1 shows where the IP will end up if this is the first loop (pointing north) and the number 2 shows where the IP will end up if this is the second (or third) loop (pointing east).
```
u ' . . .
s + . 1 .
; \ - ? 2
S . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
;s'+-? # Explanation
; # Delete top element (0)
s # Swap the top two elements (Stack: 1/A, */+)
'+ # Push the character code of +
- # Subtract the top two elements and push
# that to the stack (Stack: 1/A, */+, +, (*/+)-+)
? # Changes the direction based on the top
# item on the stack. If it's 0 (if (*/+) == +)
# the IP continues going right, otherwise, it
# turns and continues going north.
```
If the IP now is at `1`, the stack is `[A, *, +, -1]`. Otherwise, the stack is `[A or 1, +, +, 0]`. As you can see, there still is an unknown in the stack of the second case, so we have to do another comparison.
## Second comparison
Because the IP has gone through step 5, the stack looks like this: `[A^(B-1) or nothing, A or 1, +, +, 0]`. If the first element is `nothing`, the second element is `1`, and the reverse holds too. The cube looks like this, with the IP starting at S and pointing east. If this is the second loop, the IP ends up at `E`, pointing west. Otherwise, the program hits the `@` and terminates.
```
. . . . .
. . . . ;
. . . S W
. . . . .
. . . . .
. . . . . . . . . . . . . ; . . . . . .
. . . . . . . . . E @ ! \ q . . . . . .
. . . . . . . . . . . . ( * . . . . . .
. . . . . . . . . . . . q u . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
```
The instructions executed that don't do anything to the control flow are listed below.
```
;;q*q(!@
;; # Delete top two elements (Stack [A^(B-1)/null, A/1, +])
q # Send top element to the bottom (Stack [+, A^(B-1)/0, A/1])
* # Push product of top two elements
# (Stack [+, A^(B-1)/0, A/1, A^B/0])
q # Send top element to the bottom
# (Stack [A^B/0, +, A^(B-1)/0, A/1])
( # Decrease the top element by 1
# (Stack [A^B/0, +, A^(B-1)/0, (A-1)/0])
! # If (top element == 0):
@ # Stop program
```
The stack is now `[A^B, +, A^(B-1), A-1]`, provided the program didn't terminate.
# Step 5 (preparing for "A+" (repeat A^(B-1)))
Sadly, Cubix doesn't have a power operator, so we need another loop. However, we need to clean up the stack first, which now contains `[B, A, *, +, -1]`.
## Cleaning up
Here's the cube again. As usual, the IP starts at S (pointing north), and ends at E, pointing west.
```
. . . ? .
. . . ; .
. . . S .
. . . . .
. . . . .
. . . . . . . . . . . . . . . . > $ . v
. . . . . . . . . . . . . . . . . . . ;
. . . . . . . . . . . . . . . . . . E <
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
;; # Explanation
;; # Remove top 2 elements (Stack: [B, A, *])
```
## Calculating A^(B-1)
Another loop which works roughly the same as the print loop, but it's a bit more compact. The IP starts at `S`, pointing west, with stack `[B, A, *]`. The IP exits at `E` pointing north.
```
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . . . . . . . . . . . E . . . . .
. . . . . . . . . . . . . . ? s * s u .
. . . . . . . . . . . . . . \ ( s . ; S
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
```
The loop body is the following.
```
;s(?s*s # Explanation
; # Pop top element.
s # Shift top elements.
( # Decrease top element by one
? # If not 0:
s # Shift top elements again
* # Multiply
s # Shift back
#
# ... and repeat ...
```
The resulting stack is `[A, A^(B-1), 0]`.
## Cleaning up the stack (again)
Now we need to get to the print loop again, with the top of the stack containing `[..., A^(B-1), +, A]`. To do this, we execute the following. Here's the cube again,
```
. . ^ ? :
. . . . .
. . . . .
. . . . .
E . . . .
. . . . . s . . . . . . . . ; . . $ . .
. . . . . + q U . . . . . . S . . s . .
. . . . . ' u q . . . . . . . . . ? . .
. . . . . . . ? . . . . . . . . . ? . .
. . . . . . . ? . . . . . . . . . ? . .
. . ? . .
. . ? . .
. . ? . .
. . ? . .
. . ? . .
;:$sqq'+s # Explanation
; # Delete top element (Stack: [A, A^(B-1)])
: # Copy top element
$s # No-op
qq # Send top two elements to the bottom
# (Stack: [A^(B-1), A^(B-1), A])
'+ # Push +
# (Stack: [A^(B-1), A^(B-1), A, +])
s # Swap top two elements
# (Stack: [A^(B-1), A^(B-1), +, A])
```
# Step 7 (preparing for last loop)
The stack is now `[A^B, +, A^(B-1), A-1]`, the IP starts at `S`, going west, and ends at `E`, going right.
```
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . . E . . . . . . . . . . . . . .
. . . . . . u 1 ; ; S . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
```
The instructions executed:
```
;;1 # Explanation
;; # Delete top two elements
1 # Push 1
```
The stack now looks like `[A^B, +, 1]`, and the IP is about to enter the print loop, so we're done.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 46 bytes
```
XH'^'i'='XJ2G:"H'*']xJ&Gq^:"H'+']xJ&G^:"1'+']x
```
[Try it online!](https://tio.run/nexus/matl#@x/hoR6nnqluqx7hZeRupeShrqUeW@Gl5l4YB@JoQzhAtiGY/f@/EZcxAA "MATL – TIO Nexus")
Stretching the limits of "reasonable way" here, but the expressions are separated.
## Explanation
First expression:
```
XH'^'i'='XJ
XH % implicitly take input A, save it to clipboard H
'^' % push literal '^'
i % take input B
'=' % push literal '='
XJ % copy '=' to clipboard J, we'll use this twice more so it's worth it
```
Second expression:
```
2G:"H'*']xJ
2G % paste the second input (B) again
:" % do the following B times
H % paste A from clipboard H
'*' % push literal '*'
] % end loop
x % delete the final element (at the moment we have a trailing *)
J % paste '=' from clipboard J
```
Third expression:
```
&Gq^:"H'+']xJ
&G % paste all of the input, ie push A and B
q % decrement B
^ % power, giving A^(B-1)
:" % do the following A^(B-1) times
H % paste A from clipboard H
'+' % push literal '+'
] % end loop
x % delete the final element (at the moment we have a trailing +)
J % paste '=' from clipboard J
```
Fourth expression:
```
&G^:"1'+']x
&G % paste all of the input, ie push A and B
^ % power, giving A^B
:" % do the following A^B times
1 % push 1
'+' % push '+'
] % end loop
x % delete the final element (at the moment we have a trailing +)
% (implicit) convert all to string and display
```
[Answer]
## JavaScript (ES7), 78 bytes
Takes input in currying syntax `(a)(b)`. Outputs a string.
```
a=>b=>a+'^'+b+(g=o=>'='+a+('+*'[+!o]+a).repeat(b-1))()+g(b=a**~-b)+g(b*=a,a=1)
```
### Test cases
```
let f =
a=>b=>a+'^'+b+(g=o=>'='+a+('+*'[+!o]+a).repeat(b-1))()+g(b=a**~-b)+g(b*=a,a=1)
console.log(f(2)(2));
console.log(f(2)(3));
console.log(f(2)(4));
console.log(f(2)(5));
console.log(f(3)(2));
console.log(f(3)(3));
console.log(f(3)(4));
console.log(f(3)(5));
console.log(f(4)(2));
console.log(f(4)(3));
console.log(f(10)(2));
console.log(f(13)(2));
```
[Answer]
## Ruby, 52 bytes
```
->a,b{[[a,b]*?^,[a]*b*?*,[a]*a**~-b*?+,[1]*a**b*?+]}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes
```
mUð¹'^²J'*¹«²×'+¹«X¹÷ׄ+1X×)€¦
```
Explanation:
```
mU # Store a^b in variable X
ð # Push a space character to the stack (will be deleted at the end, but this is needed to keep the character count low)
¹'^²J # Push the string "a^b" to the stack
'*¹« # Push the string "*a" to the stack
²× # Repeat b times
'+¹« # Push the string "+a" to the stack
«X¹÷× # Repeat a^b / a times
„+1 # Push the string "+1" to the stack
X× # Repeat a^b times
) # Wrap stack to array
€¦ # Remove the first character from each element in the array
```
[Try it online!](https://tio.run/nexus/05ab1e#@58benjDoZ3qcYc2ealrHdp5aPWhTYenq2uDWBGHdh7efnj6o4Z52oYRh6drPmpac2jZ//9GXMYA "05AB1E – TIO Nexus")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~156~~ 149 bytes
```
#define q for(x=0;x
x,y;p(a,b,c){printf("%c%d",x?b:61,c),x+=a;}e(n,i){x=1;p(0,0,n);p(0,94,i);y=!!i;q<i;y*=n)p(1,42,n);q<y;)p(n,43,n);q<y;)p(1,43,1);}
```
*-2 bytes* if we can ignore 0 powers; `y=!!i` may become `y=1`
[Try it online!](https://tio.run/nexus/c-gcc#bY3NDoIwEAbvPEXBkLS4hxariS6Nz1L@Yg9WIJi0Ep4dW7148DYz2c237dquN7YjI@kfE3WKo0sceByohhoatgyTsXNPs7zJ2wzctb6cROjg9krj2lELhi1OifDBgYNlHzjLkNGrNDU4VgZ9oSwbqABZxpOx8hjUgjz8qIgqGK5bmCR3bSyN8ALS3PRUFJ6RJSGEdLQEGXaec@xUcIbffAT@L0soA67bGw "C (gcc) – TIO Nexus")
[Answer]
# Java 7, 170 bytes
```
String c(int a,int b){String s="=",r=a+"^"+b+s+a;double i=0,x=Math.pow(a,b);for(;++i<b;r+="*"+a);r+=s+a;for(i=0;++i<x/a;r+="+"+a);r+=s+1;for(i=0;++i<x;r+="+1");return r;}
```
**Ungolfed:**
```
String c(int a, int b){
String s = "=",
r = a+"^"+b+s+a;
double i = 0,
x = Math.pow(a,b);
for(; ++i < b; r += "*"+a);
r += s+a;
for(i = 0; ++i < x/a; r += "+"+a);
r += s+1;
for(i = 0; ++i < x; r += "+1");
return r;
}
```
**Test code:**
[Try it here.](https://ideone.com/B8xNea)
```
class M{
static String c(int a,int b){String s="=",r=a+"^"+b+s+a;double i=0,x=Math.pow(a,b);for(;++i<b;r+="*"+a);r+=s+a;for(i=0;++i<x/a;r+="+"+a);r+=s+1;for(i=0;++i<x;r+="+1");return r;}
public static void main(String[] a){
System.out.println(c(2,2));
System.out.println(c(2,3));
System.out.println(c(2,4));
System.out.println(c(2,5));
System.out.println(c(3,2));
System.out.println(c(3,3));
System.out.println(c(3,4));
System.out.println(c(3,5));
System.out.println(c(4,2));
System.out.println(c(4,3));
System.out.println(c(10,2));
System.out.println(c(13,2));
}
}
```
**Output:**
```
2^2=2*2=2+2=1+1+1+1
2^3=2*2*2=2+2+2+2=1+1+1+1+1+1+1+1
2^4=2*2*2*2=2+2+2+2+2+2+2+2=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
2^5=2*2*2*2*2=2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
3^2=3*3=3+3+3=1+1+1+1+1+1+1+1+1
3^3=3*3*3=3+3+3+3+3+3+3+3+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
3^4=3*3*3*3=3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
3^5=3*3*3*3*3=3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
4^2=4*4=4+4+4+4=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
4^3=4*4*4=4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+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
10^2=10*10=10+10+10+10+10+10+10+10+10+10=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
13^2=13*13=13+13+13+13+13+13+13+13+13+13+13+13+13=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+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]
# [Brainfuck](https://github.com/TryItOnline/tio-transpilers), 372 bytes
```
,.>++++++++[>++++++++++++>++++++++>+++++<<<-]>--.<,.>>---.>++>++++++++[<<<<------>>>>-]<<<<-[<.>>>>.>>+<<<<<-]<.>>>.<<++++++++[<------>-]<[>+>>>>+<<<<<-]>>>>>>>+<[->[-<<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<]>[-<+>]<<]>[<+>>+<-]>[<+>-]<<<<<<<<++++++++[>++++++<-]>>>>+>>-[<<<<<.>>>.>>-]<<<<<.>>.>>>>[<+>-]<<[->[->+>+<<]>>[-<<+>>]<<<]>>>++++++++[<<<++++++>>>-]<<<+>>-[<<.<.>>>-]<<.
```
[Try it online!](https://tio.run/nexus/brainfuck#XVBLFgMhCDuQhUVflzwu4vP@x7BJwE5nWGj4JET3y3N0zB9i5B1EhK008wADt5F3UYN9RSJsKZ/hzHCQTgEVPOLiNQktrOf0Gc2KEdNyWvBCVm01WYQS4WIJ@WjE6qAGUZnR7OOhvQXDpgeUu2OfmfwfERkpC6vWD62Wnf@f6H9roZZ3qbPie78/Xw "brainfuck – TIO Nexus")
# Notes
1. The two inputs must be chosen in such a way, that `A**B` does not exceed `255`. This is because brainfuck can only store values of one byte.
2. If one input is bigger than 9, use the next ASCII character. `10` becomes `:`, `11` becomes `;` etc. This is because Brainfuck can only take inputs of one byte.
# Explanation
Here is my somewhat commented code. I'll expand on this later.
```
,. print A
> +++++ +++
[
> +++++ +++++ ++ set up 96 (for ^ sign)
> +++++ +++ set up 64 (for = sign)
> +++++ set up 40 (for plus and * sign)
<<< -
]
> --. print ^
< ,. print B
>
> ---. print =
> ++ prepare *
> +++++ +++ convert B from char code
[
<<<< ----- -
>>>> -
]
<<<< - print loop "A*"
[
< .
>>>> .
>> +
<<<<< -
]
< . print final A
>>> . print =
<< +++++ +++ convert A from char code
[
< ----- -
> -
]
<
[ duplicate A
> +
>>>> +
<<<<< -
]
>>>>> exponentiation (A**(B minus 1))
>>+<[->[-<<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<]>[-<+>]<<]<
>>
[ duplicate
< +
>> +
< -
]
>[<+>-] move
<<<<< <<< +++++ +++ convert A to char code
[
> +++++ +
< -
]
>>>> + convert * to plus sign
>> - print loop "A plus"
[
<<<< < .
>>> .
>> -
]
<<<<< . print final A
>> . print =
>>>> move
[
< +
> -
]
multiply A**(B minus 1) by A
<<[->[->+>+<<]>>[-<<+>>]<<<]
>>> +++++ +++ generate the char code for 1 (49)
[ generate 8*6 = 48
<<< +++++ +
>>> -
]
<<< + add one
>> - print loop "1 plus"
[
<< .
< .
>>> -
]
<< . print final 1
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~38~~ ~~35~~ 34 bytes
33 bytes of code, +1 for `-n` flag.
```
Ya**b[gJ'^aRLbJ'*aRLy/aJ'+1XyJ'+]
```
Takes A and B as command-line arguments; prints one expression per line. [Try it online!](https://tio.run/nexus/pip#@x@ZqKWVFJ3upR6XGOST5KWuBaQq9RO91LUNIyqBZOz///918/4b/zcGAA "Pip – TIO Nexus")
### Explanation
`Ya**b` is setup code: yank `a**b` into the `y` variable. After that, we have a list (in `[]`) containing our four expressions:
* `gJ'^`: take full ar`g`list (here, a list containing `a` and `b`) and `J`oin it on `^`
* `aRLbJ'*`: use `R`epeat`L`ist to create a list with `b` copies of `a`, then `J`oin it on `*`
* `aRLy/aJ'+`: use `RL` to create a list with `y/a` (i.e. `a**(b-1)`) copies of `a`, then `J`oin it on `+`
* `1XyJ'+`: `1`, string-multiplied by `y`, `J`oined on `+`
The list is printed with newline as the separator thanks to the `-n` flag.
[Answer]
## Javascript ~~115~~ ~~113~~ 104 bytes
Thanks to @Neil and @TuukkaX for golfing off one byte each and @ETHproductions and Luke for golfing off 9 bytes
```
a=>b=>[a+'^'+b,(a+'*').repeat(b-1)+a,(a+'+').repeat(Math.pow(a,b-1)-1)+a,1+'+1'.repeat(Math.pow(a,b)-1)]
```
[Try it Online](https://tio.run/nexus/javascript-node#S7P9r5Gok6RpaxedqK0ep66dpKMBZGipa@oVpRakJpZoJOkaamongkW1EaK@iSUZegX55SDNQAUQNYZAJYbq2JSAFMT@T87PK87PSdXLyU/XSNMw1jHW1EnTMIFQRjqmmpr/AQ)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
*⁹’,¤;@
,`;1ẋ"ç
,W;çj"“^*++”Y
```
**[Try it online!](https://tio.run/nexus/jelly#ATIAzf//KuKBueKAmSzCpDtACixgOzHhuosiw6cKLFc7w6dqIuKAnF4qKyvigJ1Z////MTP/Mg "Jelly – TIO Nexus")**
### How?
```
*⁹’,¤;@ - Link 1, get list lengths: a, b
¤ - nilad followed by link(s) as a nilad
⁹ - right: b
’ - decrement: b-1
, - pair with right: [b-1, b]
* - exponentiate: [a^(b-1), a^b]
;@ - concatenate with reversed arguments: [b, a^(b-1), a^b]
,`;1ẋ"ç - Link 2, create lists: a, b
` - monad from dyad by repeating argument
, - pair: [a, a]
;1 - concatenate 1: [a, a, 1]
ç - last link (1) as a dyad: [b, a^(b-1), a^b]
" - zip with the dyad...
ẋ - repeat list: [[a, a, ..., a], [a, a, ..., a], [1, 1, ..., 1]]
<- b -> <- a^(b-1) -> <- a^b ->
,W;çj"“^*++”Y - Main link: a, b
, - pair: [a, b]
W - wrap: [[a, b]]
ç - last link (2) as a dyad: [[a, a, ..., a], [a, a, ..., a], [1, 1, ..., 1]]
; - concatenate [[a, b], [a, a, ..., a], [a, a, ..., a], [1, 1, ..., 1]]
“^*++” - list of characters: ['^', '*', '+', '+']
" - zip with the dyad...
j - join: ["a^b", "a*a*...*a", "a+a+...+a", "1+1+...+1"]
Y - join with line feeds
- implicit print
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp) repl, ~~178~~ 186 bytes
```
(load library
(d W(q((_ N S #)(i(e # 1)(c N _)(W(c S(c N _))N S(s # 1
(d ^(q((x y)(i y(*(^ x(s y 1))x)1
(d X(q((A B)(list(list A(q ^)B)(W()A(q *)B)(W()A(q +)(^ A(s B 1)))(W()1(q +)(^ A B
```
Using the repl saves 8 bytes in implied closing parentheses at the ends of lines. Defines a function `X` which takes two numbers and returns a list of expressions. Each expression is parenthesized, with spaces around the operators (actually, it's a list of numbers and operator symbols):
```
((2 ^ 3) (2 * 2 * 2) (2 + 2 + 2 + 2) (1 + 1 + 1 + 1 + 1 + 1 + 1 + 1))
```
Hopefully this output format is acceptable. [Try it online!](https://tio.run/nexus/tinylisp#TU0xDoMwENv7CkssPjoF2gfAA7owwASipQMSUgV0IK9P76K0aobY5/PZgctrnLDM923cvJw4oeVKDrihQSac@UQGJ3yoMghbJU0aRD3c4zo@u@7t@oDXS3jm7HGoxZvlEPd1deaqUAuXeX/HDxVX9FJbhRjP//hZNKjSoDp2mex@ssak@g4FioRlwkvCa8Qy7cu0dyaE8AE "tinylisp – TIO Nexus") (with several test cases).
### Explanation
```
(load library)
```
We need two functions from the standard library: `list` and `*`.
```
(d W(q((_ N S #)(i(e # 1)(c N _)(W(c S(c N _))N S(s # 1))))))
```
Define a function `W` (short for "weave") that takes an accumulator `_`, a number `N`, a symbol `S`, and a count `#`. We will use this function to generate most our expressions: for example, `(W () 2 (q +) 3)` will result in `(2 + 2 + 2)`.
If the count is 1 `(e # 1)`, then cons the number to the front of the accumulator `(c N _)` and return that. Otherwise, recurse:
* New accumulator is `(c S(c N _))`: the symbol and the number cons'd to the front of the previous accumulator;
* `N` and `S` are the same;
* New count is `(s # 1)`: count - 1.
The accumulator idiom is needed to achieve [proper tail recursion](https://en.wikipedia.org/wiki/Tail_call), preventing a recursion depth error. (This change is responsible for the +8 to the byte count. The `13^2` case didn't work in the previous version.)
```
(d ^(q((x y)(i y(*(^ x(s y 1))x)1))))
```
Unfortunately, the library has no exponentiation function at this time, so we have to define one. `^` takes `x` and `y`. If `y` is truthy (nonzero), we recurse with `y-1` (`(s y 1)`) and multiply the result by `x`. Otherwise, `y` is zero and we return `1`.
(Note: This function does *not* use proper tail recursion. I assume that the exponents will be small enough that it won't matter. Some experimenting on TIO indicated a maximum exponent of 325, which I would argue should be sufficient for this question. If the OP disagrees, I will change it.)
```
(d X(q((A B)(list(list A(q ^)B)(W()A(q *)B)(W()A(q +)(^ A(s B 1)))(W()1(q +)(^ A B))))))
```
Finally, the function we're interested in, `X`, takes `A` and `B` and returns a list of four items:
* `(list A(q ^)B)`: a list containing `A`, a literal `^`, and `B`;
* `(W()A(q *)B)`: call `W` to get a list of `B` copies of `A`, interwoven with literal `*`;
* `(W()A(q +)(^ A(s B 1)))`: call `W` to get a list of `A^(B-1)` copies of `A`, interwoven with literal `+`;
* `(W()1(q +)(^ A B))`: call `W` to get a list of `A^B` copies of `1`, interwoven with literal `+`.
[Answer]
# Pyth, ~~32~~ 31 bytes
```
AQjMC,"^*++"[Q*]GH*^GtH]G*]1^GH
```
Takes input as `[2,10]`, outputs as `["2^10", "2*2*2*2*2*2*2*2*2*2", "2+2+...`
Explanation:
```
Q = eval(input()) #
G, H = Q # AQ
operators = "^*++" # "^*++"
operands = [Q, # [Q
[G]*H, # *]GH
G**(H-1)*[G] # *^GtH]G
[1]*G**H # *]1^GH
] #
map( lambda d: join(*d), # jM
zip(operators, operands) # C,...
) #
```
[Try it here.](http://pyth.herokuapp.com/?code=AQjMC%2C%22%5E%2a%2B%2B%22%5BQ%2a%5DGH%2a%5EGtH%5DG%2a%5D1%5EGH&test_suite=1&test_suite_input=%5B2%2C2%5D%0A%5B2%2C3%5D%0A%5B2%2C4%5D%0A%5B2%2C5%5D%0A%5B3%2C2%5D%0A%5B3%2C3%5D%0A%5B3%2C4%5D%0A%5B3%2C5%5D%0A%5B4%2C2%5D%0A%5B4%2C3%5D%0A%5B10%2C2%5D%0A%5B13%2C2%5D&debug=1)
[Answer]
# [Perl](https://www.perl.org/), 81 bytes
78 bytes of code + `-n` flag (counted as 3 bytes since the code contains `$'`).
```
$,=$/;print s/ /^/r,map{/\D/;join$&,($`)x$'}"$`*$'","$`+".$`**~-$',"1+".$`**$'
```
[Try it online!](https://tio.run/nexus/perl#U1bULy0u0k/KzNMvSC3KUdDNy/mvomOrom9dUJSZV6JQrK@gH6dfpJObWFCtH@Oib52Vn5mnoqajoZKgWaGiXqukkqCloq6kA6S1lfSAHK06XRV1HSVDKE9F/f9/YwVjLiMFEy5jBRMA "Perl – TIO Nexus")
[Answer]
## R, 147 bytes
```
w=switch;function(A,B)for(s in letters[1:4]){cat(rep(w(s,d=1,a=c(A,B),b=,c=A),w(s,a=1,b=B,c=A^B/A,d=A^B)),sep=w(s,a="^",b="*",d=,c="+"));cat("\n")}
```
Anonymous function that outputs the required, well, outputs, line-by-line. This solution makes extensive use of the `switch` function.
The `switch` function takes an expression (here, `s`) that evaluates to a number or a character string (see `?switch`), followed by the alernatives corresponding to `s`. If an alternative is missing (e.g. `switch(s, a=, b= "PPCG")`, the next non-missing alternative is evaluated (in the example, `s="a"` outputs `"PPCG"`).
The `rep` functions repeats (replicates, actually) its first argument the number of times indicated in the second argument.
`cat`, to finish, concatenate and prints the objects, with a separator that can be chosen with the `sep =` argument. The second `cat` function is here for the line-break.
**Ungolfed:**
```
f=function(A,B)
for(s in letters[1:4]){
cat(
rep(switch(s, d = 1, a = c(A,B), b =, c = A),
switch(s, a = 1, b = B, c = A^B/A, d = A^B)),
sep=switch(s,a = "^", b = "*", d =, c = "+"))
cat("\n")
}
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 42 bytes
```
q_'#/)i*_'**\__:i:*_@0=i/@0=*'+*\'1*'+*]N*
```
[Try it online!](https://tio.run/nexus/cjam#@18Yr66sr5mpFa@upRUTH2@VaaUV72Bgm6kPJLTUtbVi1A1BVKyf1v//xsomAA "CJam – TIO Nexus")
[Answer]
# k, 44 bytes
```
{"^*++"{x/$y}'(x,y;y#x;(x*y-1)#x;(*/y#x)#1)}
```
[Test cases.](http://johnearnest.github.io/ok/?run=%20%7B%22%5E%2a%2B%2B%22%7Bx%2F%24y%7D%27%28x%2Cy%3By%23x%3B%28x%2ay-1%29%23x%3B%28%2a%2Fy%23x%29%231%29%7D.%27%282%202%3B2%203%3B2%204%3B2%205%3B3%202%3B3%203%3B3%204%3B3%205%3B4%202%3B4%203%3B10%202%3B13%202%29)
[Answer]
# [Cardinal](https://esolangs.org/wiki/Cardinal) 202 bytes
```
%:.~:#"^"."=">v
x "~
*.
>~=088v "~
v88+88< ?
8 -
8 x#<
v < 0
> t / <
v~.~ <#"="?<
-
#?"+"^t
0
V
#?"=" >"1"-v
/ { <^"+"?<
> ^
```
Will only work for numbers where the calculated value <256 due to limitations in the values that can be held by pointers in Cardinal
[Try it Online](https://tio.run/nexus/cardinal#VY7BCsMwCIbvPoUYdllJmu4kxSRvsWOeokhh4KtnaRtGJyh@@PFje6zBVkeVAiXKCjveigzuiM9wcbYUmfV3V@aJWbBcyEP3f7g7GfY5BeMI673hjAJqwVBcf6QIeHCFJqobRHgfe6Lu0kJeYcbPkVD7vZv5jKmtLRFeXw)
# Explanation:
## Step 1
```
%:.~:#"^"."="
```
Receives two numbers a and b as input and outputs as "a^b="
Passes a pointer with active value a and inactive value b
## Step 2
```
>v
"~
*.
>~=088v "~
v88+88< ?
8 -
8 x#<
v < 0
> t / <
```
Receives a pointer with active value a and inactive value b printing "a"+("\*a")(b-1) times
Passes a pointer with active value a^(b-1) to the next part
## Step 3
```
v~.~ <#"="?<
-
#?"+"^t
0
V
#?"="
/ { <
> ^
```
Receives a pointer with value of a^(b-1) and outputs "=a"+("+a")repeated(a^(b-1)-1)times+"="
Passes a pointer with value a^b to the next part
## Step 4
```
>"1"-v
^"+"?<
```
Receives a pointer with value a^b and prints out "1"+("+1")repeated a^b-1 times
[Answer]
# Retina, ~~89~~ 88 bytes
```
*`,
^
+`(1+),1
$1*$1,
:`.1+.$
{`^[1+]+
a$&z
+`a(.+)z.1
$1+a$1z*
)`.a.+z.
:`a
+`11
1+1
```
Input is comma separated unary numbers.
[Try it online!](https://tio.run/nexus/retina#FcvBDYAwEAPBv@s4oSSOTvKXVhDoXAfFh7Dv2TVq4gGriX0KoRGaOCvFDOCt5xJvwnF4M7dkd/6QDnmgVzrpxJ6MTSSIWkua2n0)
] |
[Question]
[
Today I realised that I often like to define sections in my code like so:
```
####################
# Helper Functions #
####################
```
But that it's tedious to do. Assuming I have a line such as this:
```
# Helper Functions #
```
What is the shortest set of `vim` keystrokes to wrap it in a `#`? Shift does **not** count as a keystroke in this challenge.
Test cases:
```
Input: "#test test test#"
Output:
################
#test test test#
################
Input: "#this is a nice block comment#"
Output:
##############################
#this is a nice block comment#
##############################
Input: "# s p a c e s must be supported a l s o#"
Output:
########################################
# s p a c e s must be supported a l s o#
########################################
```
[Answer]
## ~~11~~ ~~8~~ 7 keystrokes
```
YpVkr#p
Yp - duplicate current line, leaving the cursor at the lower of the two
V - enter visual line mode
k - go up and select both lines
r# - replace every selected character with #. Leaves visual mode and leaves cursor at the upper line.
p - put the yanked line (the original) on the next line.
```
(thanks to doorknob for reminding Y=yy)
[Answer]
# ~~16~~ ~~15~~ 14 keystrokes
```
Yp
:s/./#/g
<cr>
YkP
```
The straight-forward approach: duplicate the line, replace all characters with `#`, copy the the result and paste it above.
I'm counting `P` and `:` as one keystroke each (instead of two for `Shift`+`p` or `Shift`+`;`). That being said, the question specifies to count "commands", where I'm not sure how to count the substitution.
] |
[Question]
[
The new site header has some bits of source code from various questions as the background. Here are the first 3 lines:
```
--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+. Hello, World! IT'S SHOWTIME TALK TO THE HAND "Hello, World!" YOU HAVE BEEN TERMINATED "9!dlroW ,olleH"ck,@ 72a101a+7aa+3a44a32a87a111a+3a-6a-8a33a Take Circle Line to Paddington Take Circle Line to Wood Lane Take Circle L
alert'Hello, World!' target byteorder little;import puts;export main;section"data"{s:bits8[]"Hello, World!\0";}foreign"C"main(){foreign"C"puts("address"s);foreign"C"return(0);} aeeeaeeewueuueweeueeuewwaaaweaaewaeaawueweeeaeeewaaawueeueweeaweeeueuw H class H{public static void main(String[]a){System.
World!");}}+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+. "Hello, World!"o| :after{content:"Hello, World!" H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#"mCBA?zxxv*Pb8`qo42mZF.{Iy*@dD'<;_?!\}}|z2VxSSQ main(){puts("Hello, W
```
However, a few microseconds of extra load time can cause the user to click away from the site, so the page header download really should be optimized as much as possible.
Write a program that takes no input and produces the (first 3 lines of) text from the new header as output.
* Trailing newline is optional
* Must include the line breaks from the original header
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~601~~ ~~584~~ ~~574~~ ~~564~~ ~~553~~ 539 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
«=¬█j▼sw│╥═7♫çÿñ╦*‼e"!‼╤Å╟D·εWÜå╖L♂@#î╚å♫▐ô;(┤┼»Kî→δäû║h◘│¶zurΘ█┐£ë}∞è┼$÷gôwg¬≤╒Ñ╧]∙ì▄╦╕ís│\☺'┴♫Φ^┐╤å{1█♠₧ï∩∙↑▀⌂d▲╡⌡3J‼¡qâ╧3¥Çƒwe▀≡╔MjZΣΩyüO╬ªÉΩö^Y╡►8K₧óN·ÿjg≈Cö9^◘■~Ä_ßx▐Å┌ Q>/♫╤QΩzN╤V½▓▀◙ß╗╗◄►(╔☺╡┘Ah╙¢√ß▼GΩ→ù◄:─◘#♫úq•ø≤>↨)Å│╤[ïmgBX┤╛v\ⁿ╛å╘╕7d╪TµbW#2¶ø╙╜~êê[↨>K►♪0∞#XJ°ñntG∞⌐V♥Z<ÿº'║☺;┤é⌡♠gáσßÑ+♂z♥‼S9 l≈╫ºÜT»↕▀τ♣¡gWe¥_çà(┬f╜n[╗╤fσ╞R₧▲V▌═◙úKÆÜ▄☺╥s1▼╩ûû╗▌▌Ω■g∞Y╡9╦tè┴y♂w∟⌂┌'╣W▀M╓·uBôúPm◘ ☻ⁿFh<╘sú▲Ö╘¶¿_2♦Θb{╪δC\lô+▀9¶ß§╡╓)ú}○8∟⌡nÑôI )╓îFbH[î║╞e&"¶↓~A#ç╔▄─áσ∙:═Æ▬ª▄ÄêQSNM◙∞Z╜≈±╘▬LIÿ|#.¿Φµ║▌Lväv▓♣;└Æ▲▄♣↕{╪½)╚φ╡♦:oÉ▀j╠ΔP<ç↔|±╦=╣▓Φ▒─4D▄■ìà>↓┐
```
[Run and debug it](https://staxlang.xyz/#p=ae3daadb6a1f7377b3d2cd370e8798a4cb2a1365222113d18fc744faee579a86b74c0b40238cc8860ede933b28b4c5af4b8c1aeb8496ba6808b3147a7572e9dbbf9c897dec8ac524f667937767aaf3d5a5cf5df98ddccbb8a173b35c0127c10ee85ebfd1867b31db069e8beff918df7f641eb5f5334a13ad7183cf339d809f7765dff0c94d6a5ae4ea79814fcea690ea945e59b510384b9ea24efa986a67f74394395e08fe7e8e5fe178de8fda20513e2f0ed151ea7a4ed156abb2df0ae1bbbb111028c901b5d94168d39bfbe11f47ea1a97113ac408230ea3710700f33e17298fb3d15b8b6d674258b4be765cfcbe86d4b83764d854e6625723321400d3bd7e88885b173e4b100d30ec23584af8a46e7447eca956035a3c98a727ba013bb482f50667a0e5e1a52b0b7a03135339206cf7d7a79a54af12dfe705ad6757659d5f878528c266bd6e5bbbd166e5c6529e1e56ddcd0aa34b929adc01d273311fca9696bbddddeafe67ec59b539cb748ac1790b771c7fda27b957df4dd6fa754293a3506d082002fc46683cd473a31e99d414a85f3204e9627bd8eb435c6c932bdf3914e115b5d629a37d09381cf56ea593492029d68c4662485b8cbac665262214197e412387c9dcc4a0e5f93acd9216a6dc8e8851534e4d0aec5abdf7f1d4164c49987c232ea8e8e6badd4c768476b2053bc0921edc05127bd8ab29c8edb5043a6f90df6accff503c871d7cf1cb3db9b2e8b1c43444dcfe8d853e19bf&i=&a=1)
It does at least attempt to use different strategies for different pieces.
I've still got some hope for a few sections, but here's an explanation of the approaches so far.
```
The general approach is to push a bunch of stuff on the stack.
Then join it all together and split it in thirds.
' just a space
`jaH1"jS3!`X compressed literal for "Hello, World!" assigned to the x register
`38dZl;i#D]|@Y@*` compressed literal for "It's showtime talk to the hand"
^ convert to upper case; it compresses better in lower case
n'"|SY Wrap the x register in quotes and save it in the y register
`=j("sx6c1 ob`^ compressed literal for "you have been terminated" in upper
."9 literal for '"9'
yrD register y (quoted hello world), reversed, first character dropped
"ck,@ " literal
"^h{ai{W>bJ,^T+NLDK(G$s@+"! crammed array [725, 101597559, 354, 45325875, 1115935, -65, -85335]
$"5a9+"|t concat as strings, then map '5' to 'a' and '9' to '+'
`='9%[mh++PxF!` compressed literal for " Take Circle Line to "
`~J@[E<`n compressed literal for "Paddington"; copy the one about the circle
`jj_kmZ5` compressed literal for "Wood Lane"
n7T copy " Take Circle Line to " and truncate last 7 characters
"alert'"x'' some literals and x register
`~lLKPq'III^) .tI:G8?uMolVwpnT&u#` compressed literal with commas in place of semi-colons
.,;|t replace with semi-colons, which aren't allowed in compressed literals
`/zOXzN`",data,{s:bits8[],`x\0_;}`cC,main(){`cC,puts(,address,s);` C,return(0);} ".,"|t
compressed literal for "foreign", followed by a string template
"Nm\{<\3VdH,FF:c~7&u!n"96|E carefully chosen string literal interpreted in base 96
"eawu":B encoded in custom base "eawu"
`dzJxVHC"`'{`pS7yzeENLM%_'` two compressed literals with a '{' in the middle
"(String[]a){System." literal
x6) last 6 characters of register x
"`");}}" literal with escaped uote
"0;pKll>r&.sSP}JLNL==(>eP>-2\6fc8|)4&.:,1jA66O{t0>GpALk4I{.iDM:Gr_50ga"
90|E literal of ascii characters decoded in base 90
"[+-><],.":B re-encoded with a custom base of brainfuck
72:/ split at position 72
~ push the right half to the input stack, effectively the beginning
" `yo| :after{content:`y H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#`"mCBA?zxxv*Pb8``qo42mZF.{Iy*@dD'<;_?!\}}|z2VxSSQ main(){puts("
big string template including y register a few times
y9( first 9 characters of y
Lr$ wrap all stacks in array and concatenate
3Mm split into 3 equal parts and print as lines
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 568 bytes
```
“¢lẊḊ%ñẇÄNị¡ẸVþṾɲXØ?^ÆÐX⁷®bWċ’b7ị“-+[>].<”” “3ḅaė;œ»©“×;-¢İiĖƝÞth⁴"Ạ⁺Xṙ{»Œu®“JṁkKɼġʋḲỴ9|ḤḲ»Œu®U“ƭJ&çȯ»” Ȯø“¡ŻAÆ¡ ⁾Ʋ⁵(S0-’b122_⁵ȯ€“”ṭ"3,5,10Ṭ×”+¤j”a“Ƭ>hPḢ¤Ġ2fɠjẆȤ¬ṬwḷÇRy_ỴṬƓO¶~^YG³ẸṂḊỤÇ»®“¡ñA¦ɗɱṪḅạðEṘ/Ḋ_³ṢÑ⁺ċßs³m0>*Ḥıo7Ʋ>[;ɼ⁽¢OẆ9Ɓ€»®“¤Z!ƤḂĊlðiƝṘŻqọ6³Ṣṡḃ8Þœn⁶ʠẉ>yuẆ{»Ḳj“ṢẈ,ẊL»” ø“שK⁸ƁƬ÷FġƬṘ¹^Ẉ§ṭƁḅ’b4ị“wuae”“£¦ƊNỴŻw;ƊFɦȦnœĠÐẇṀu½X*ṠOJ8ȷḍu&)ṫ)⁼ẏµ×ẏ`ȯ»ø“¡-P⁽Rȯ$@°ḤėXƙ€ṭ⁶Vė7-²ɦ{NỌQ’b7ị“+-><].[”⁾ "®“ıȷ®⁻ʂ£Þȷ⁹ṣp°⁷»®ø“Ṛ|ġcßỵiṃ^ɱrÐẏNạŀiUĠ¥ĿSʂĊ⁷Ð+¦ŻvIṖj~ż¹kĿƥð¿ƘeḶZƤLɱ ṭṡ¥⁷ė$ ėƬ ċ⁵Ṛ¿⁷¢²_ṛż⁽p£⁽n#/i½ɱ`M3BƓḳ?¥ạuẹ09ʠ;"J!ṢIMkIoÐȯ²&_ẋẓṗḲ>½Q>ẈȯĠ ŀJṇḢC.(Eı’b128ịØJ“¡ʂh;⁼µ:ȮçṛƤb7ḋ2ṢR»
```
[Try it online!](https://tio.run/##TZMNTxNZFIb/SkWXqFBE2F3AmrpqdEP9QDG6VSIVNxgKLLqrXUI0plN3QVuNuE2csiJOS6lxt0KnUDp3ho/k3Ds3M/0XZ/4Ie6ZosslkZu7NOfe853nPHR@dnJzZ2/OSi1CYRDONRvobrqM5x/@4jFYG8mgaN/gOsh23GuW5U8N8ls9HPaUOq3d/EhkvuXC3h@IoP9g2FL7dcdJLvqcnQBvdaPw5ItSQnQULPtEGV0NBKIhKXLyV7/nSozFP2WhBU/MUM4ps4TFY9l8JWKXICDJl4oK7JfKNDBpVtDb6nqBRpN8vMdcpSH6OtPKPzhpYfkFnlRt@F3nbOs1nIR/wlB1Z9ZTa4WudQV/m8a6uGC2dNS9VpkDKQfa5pbv9u/bjncjKXKWdNiiO02fEFzsL5fDYFTQKUBRa1z1XG0dz1ilCmYKn0ajzucGZGCmjpcwOwObT4Zs/wjrhQpYiimgV@Rw1vtoUxfXTUHJVV0f2D2FBM88r55DljlFkjLJYgb8hDCLDPzyE9V86w0epXaHf75HV8FDI3fKUbSgMkIA@qZD@r@cWbx2QRCUl0pO8EpfUUc62fkXr1ffNM5Hl0XjWy5fs7JSnbDY0NF@EZxJ0DLEmmNTroh9mPm8n6y/ug2xi5Cp8uuAphlRkmdfPi7yktnPAhikWPhI4qVAbPtZv992fToyMNq1fhGUoyTQNz4ZtTYdk@rxbckpTdlZofJ7mClkyAdvRo8i0gUivU0fjVaL1CLJ/j3jKFpqvocZV@tzxff3iaPAKtT/orB36ASo@FjUqFwgCqaCmbgi1JwhVt/SYSr68@r@BbAuGT97uGPJVKTuBliYxoTs0uZ5iNVKwzJecuqcwZMsPoOKPNFFtlkT29xOR/5l/QKsWR/Zs2NV/88W/vkzG2cn4daHBiti91iDwlMfn26BkW7/3I3s7/tTeAjYhduUKr8CuzI2isXlLFi@6eoAEkyOwQilCPRQQqiwH6AopNaoHu76AAlRjyN7Zvt8PYJneUwePxWHb1e9c6j4js2isn4IVEkEess6@hhZqiRwgB/svTfTf5/PErNoaQzODZhaZSg6HYftqmDxz1oQWsJN0r@Zoos92HD4n9P1L0UuweC7SBN1IjYXIBaidoNtELr@TRYJpZLqoxCBYe3v/AQ "Jelly – Try It Online")
I tried to add optimizations per section. The optimized string compressor compresses this to 730 bytes (which *should* be the best possible just using basic Jelly syntactical constructs rather than any actual methods), so it appears I have done something.
(Fun fact: after I posted this answer, Chrome started suggesting translating this page to Vietnamese :P)
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~542~~ 527 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
Hello, World!”³³"ī←≥/ī⁹βņ fi▼pΛtι¤Υ8Th4ΚT~v‛θ5→č■⌡‘o"′]◄⅟ō&÷2}≠Θ←⁷┌∙‽↓æ³ΘZ°β╔¶ļ¹‘U┌⁷ŗo±"ē‛V)≥u∆↕]ē׀~σφ‰τ┘^|i≡»┼y3┐X3Η‛Χ4±2‘o"ΣΤ°ε⁵↑p$J↑³∫ū²▼!⁄B²⌠3τ}σS⁷bu¹1∆Ν²‘ū#Ƨtoŗo"JνΠ◄ī÷$λ⅜Zø@Pθθ╚XΔBPø√:┘¦z#│y⁹oΣ⁄½Λ'7⅞Fģ′σv+&≥μ_¦≠⅔v]lπlsβ╥^D#,℮⁾§Aα‛ķκņ▼%ķW═g!ōΜ¬`}⅛čņ█≠⁄⅔‛mZÆ~⁴πzWl─xτ▼'Η↓#ΗΩ►φL8!Ƨ:e¡′ž|Τr^+≡▒GπεΓW≥7±λxw׀ Κν⁷cP\ιYΤp|A╝æƧO∑b►\÷Q²OΟč⅔⁽(╬( ρn⁽BoG=Υ→m▒‽¤/►iΟ√PqΩ∙φ4√VΥæl‽υΧ$f0╬Dkμ⌠Lāč¾↓′∫Ε╚Βæ║↑Ν▲γB#⁶5⁹B|l↔ƨ╗6Σŗ⁄⅟ω±μξydA┼*ģ⁴Z►xa^■7O═ģΖ4Γ⅞6═¾χ‰⁷‛[‚⅓D⅞π▓z⁶‼Æņ2Υ√θ']7┐⁰īS╗<čfφ┘lθ⁄{=æ⁹Δ<¡⁾Υ□ι¹λzFΗ▲-β▒╤ÆAΩ/xff⁰ΞΠIæ┘*⁾h⁷╗ΧG─`⁾⁄@p*‘p
```
[Try it here!](https://dzaima.github.io/SOGLOnline/?code=SGVsbG8lMkMlMjBXb3JsZCUyMSV1MjAxRCVCMyVCMyUyMiV1MDEyQiV1MjE5MCV1MjI2NS8ldTAxMkIldTIwNzkldTAzQjIldTAxNDYlMDlmaSV1MjVCQ3AldTAzOUJ0JXUwM0I5JUE0JXUwM0E1OFRoNCV1MDM5QVQlN0V2JXUyMDFCJXUwM0I4NSV1MjE5MiV1MDEwRCV1MjVBMCV1MjMyMSV1MjAxOG8lMjIldTIwMzIlNUQldTI1QzQldTIxNUYldTAxNEQlMjYlRjcyJTdEJXUyMjYwJXUwMzk4JXUyMTkwJXUyMDc3JXUyNTBDJXUyMjE5JXUyMDNEJXUyMTkzJUU2JUIzJXUwMzk4WiVCMCV1MDNCMiV1MjU1NCVCNiV1MDEzQyVCOSV1MjAxOFUldTI1MEMldTIwNzcldTAxNTdvJUIxJTIyJXUwMTEzJXUyMDFCViUyOSV1MjI2NXUldTIyMDYldTIxOTUlNUQldTAxMTMldTA1QzAlN0UldTAzQzMldTAzQzYldTIwMzAldTAzQzQldTI1MTglNUUlN0NpJXUyMjYxJUJCJXUyNTNDeTMldTI1MTBYMyV1MDM5NyV1MjAxQiV1MDNBNzQlQjEyJXUyMDE4byUyMiV1MDNBMyV1MDNBNCVCMCV1MDNCNSV1MjA3NSV1MjE5MXAlMjRKJXUyMTkxJUIzJXUyMjJCJXUwMTZCJUIyJXUyNUJDJTIxJXUyMDQ0QiVCMiV1MjMyMDMldTAzQzQlN0QldTAzQzNTJXUyMDc3YnUlQjkxJXUyMjA2JXUwMzlEJUIyJXUyMDE4JXUwMTZCJTIzJXUwMUE3dG8ldTAxNTdvJTIySiV1MDNCRCV1MDNBMCV1MjVDNCV1MDEyQiVGNyUyNCV1MDNCQiV1MjE1Q1olRjhAUCV1MDNCOCV1MDNCOCV1MjU1QVgldTAzOTRCUCVGOCV1MjIxQSUzQSV1MjUxOCVBNnolMjMldTI1MDJ5JXUyMDc5byV1MDNBMyV1MjA0NCVCRCV1MDM5QiUyNzcldTIxNUVGJXUwMTIzJXUyMDMyJXUwM0MzdislMjYldTIyNjUldTAzQkNfJUE2JXUyMjYwJXUyMTU0diU1RGwldTAzQzBscyV1MDNCMiV1MjU2NSU1RUQlMjMlMkMldTIxMkUldTIwN0UlQTdBJXUwM0IxJXUyMDFCJXUwMTM3JXUwM0JBJXUwMTQ2JXUyNUJDJTI1JXUwMTM3VyV1MjU1MGclMjEldTAxNEQldTAzOUMlQUMlNjAlN0QldTIxNUIldTAxMEQldTAxNDYldTI1ODgldTIyNjAldTIwNDQldTIxNTQldTIwMUJtWiVDNiU3RSV1MjA3NCV1MDNDMHpXbCV1MjUwMHgldTAzQzQldTI1QkMlMjcldTAzOTcldTIxOTMlMjMldTAzOTcldTAzQTkldTI1QkEldTAzQzZMOCUyMSV1MDFBNyUzQWUlQTEldTIwMzIldTAxN0UlN0MldTAzQTRyJTVFKyV1MjI2MSV1MjU5MkcldTAzQzAldTAzQjUldTAzOTNXJXUyMjY1NyVCMSV1MDNCQnh3JXUwNUMwJTIwJXUwMzlBJXUwM0JEJXUyMDc3Y1AlNUMldTAzQjlZJXUwM0E0cCU3Q0EldTI1NUQlRTYldTAxQTdPJXUyMjExYiV1MjVCQSU1QyVGN1ElQjJPJXUwMzlGJXUwMTBEJXUyMTU0JXUyMDdEJTI4JXUyNTZDJTI4JTIwJXUwM0MxbiV1MjA3REJvRyUzRCV1MDNBNSV1MjE5Mm0ldTI1OTIldTIwM0QlQTQvJXUyNUJBaSV1MDM5RiV1MjIxQVBxJXUwM0E5JXUyMjE5JXUwM0M2NCV1MjIxQVYldTAzQTUlRTZsJXUyMDNEJXUwM0M1JXUwM0E3JTI0ZjAldTI1NkNEayV1MDNCQyV1MjMyMEwldTAxMDEldTAxMEQlQkUldTIxOTMldTIwMzIldTIyMkIldTAzOTUldTI1NUEldTAzOTIlRTYldTI1NTEldTIxOTEldTAzOUQldTI1QjIldTAzQjNCJTIzJXUyMDc2NSV1MjA3OUIlN0NsJXUyMTk0JXUwMUE4JXUyNTU3NiV1MDNBMyV1MDE1NyV1MjA0NCV1MjE1RiV1MDNDOSVCMSV1MDNCQyV1MDNCRXlkQSV1MjUzQyoldTAxMjMldTIwNzRaJXUyNUJBeGElNUUldTI1QTA3TyV1MjU1MCV1MDEyMyV1MDM5NjQldTAzOTMldTIxNUU2JXUyNTUwJUJFJXUwM0M3JXUyMDMwJXUyMDc3JXUyMDFCJTVCJXUyMDFBJXUyMTUzRCV1MjE1RSV1MDNDMCV1MjU5M3oldTIwNzYldTIwM0MlQzYldTAxNDYyJXUwM0E1JXUyMjFBJXUwM0I4JTI3JTVENyV1MjUxMCV1MjA3MCV1MDEyQlMldTI1NTclM0MldTAxMERmJXUwM0M2JXUyNTE4bCV1MDNCOCV1MjA0NCU3QiUzRCVFNiV1MjA3OSV1MDM5NCUzQyVBMSV1MjA3RSV1MDNBNSV1MjVBMSV1MDNCOSVCOSV1MDNCQnpGJXUwMzk3JXUyNUIyLSV1MDNCMiV1MjU5MiV1MjU2NCVDNkEldTAzQTkveGZmJXUyMDcwJXUwMzlFJXUwM0EwSSVFNiV1MjUxOColdTIwN0VoJXUyMDc3JXUyNTU3JXUwM0E3RyV1MjUwMCU2MCV1MjA3RSV1MjA0NEBwKiV1MjAxOHA_,v=0.12)
Almost all compression, but broken up every now and then because English compression works only on lowercase words and case is important. I still [had to](https://tio.run/##xVZbUxNJFH7e/hXDgNxCAgQ0mAkRkFK03AILF5QQ1iZpYJZJJiYTwr0mK8xClVSpuSGIYHFbC2tLQLnI5WGS8Nh59L3/CHsmrFXr8s5OZjpz@pw@ffo73d8ZD/YP4dD5Od9CJEmu4DrloOQtYOqSvqvvIvMVXjCZw@xwmFwml8PkhA5n/udwONxOt8NhNlscpvxlAcECDcgWp9O4wcZiKPKS2RBNFlRfXx8kobCkhDjRb0d8ZotpL9nseiW8RA/pTlb7qU9kyeMAXVToob5G1@seDdTShUeTQ0xdpAfXmfY6M8eSK@zFe6bOy1cLBmfmkKiUhLjQgBxBiugjnIKlQU6ROWWAcAPY70Ucb@Y5NCKHQRwiXC8hfk4hQZ/oxwrxXgKAqTtulppi08vZueL0vnWCza7QeQOU6D6Lv2Azb5h6wrRYekPfpfNd@ie6wxJxfS9zrB8CAL8YNtH9bOqqkeBvZlO8Z7CigUM2K66uqsYmG8amGlxbi2usuM6Gq6urDdl8A5vrcE0N/u/S9W0@E4OkdpRB/sNsRmNawp2JfVMnc89zGlM/5aZYfL5nXGSz7/UjFj8eqWHxl49raMrYCZu1@rb1f9gBSMGDhPOIQY9EOEn0E47nAtjrFf39igyZvqyNyLKXk7Cf/KhE@t6lzUBX6Rpk@AuLfmHaq0DRfWj1XTazld3Sd@BUFLDoVBO8vVipyU1N5J63Q@p7w/phNaBHl0Chzme3Cs82FfnKNwSWSFBBJdlUiQFRsJ8oXO@IQpAc9JIgQKEoEkECEn0BOahwgbASAokM5yUfFv0ghYhHEWU/4pEXKxjxYyF7r6iE6lxuPpvqruKFCdQnB4nYDya3eWNQadnYv7tQ3m0pjyAfgGsI8aEy4QeDIFHCQT8qrSoTJjiECSHGEwmTcJhECAkbdySCMY4QjEkEQxvJay7scF4k@R5s9MLACOJaOOSRMMzHtYxBDL2S6OFCClbgb0gWvRfrK21XgrBJXG5cNtY@ElKIz6LvXRA7D9FMIJPLYFeX05nnWeBdh9thsK/Z7Ab6dEK/QaUGpbosBvf@Q68X@Ofp15k3grMJR1Me5@wI9wHzoDHkkf0K8SvIbmg41CIQoa1aaKgUOgVZqJQEaB9WBgVJ8ApWoQ1VcaUlxdfsN90FkxPjo9aO4ciQuaKt9VlA9ktFLb@JA33jTQ0Nzop6x8/2m8W2J4UdHdZH7X5LKyn3CKX3iq8VFfK@202Nt0aHh4fK23rrnj6Ta62@rjuWsXsj5Q3e5hKH8Outgu6JC@/t7Q85dIFR2dj3HH6vfJfOyH16QleAMTNb6f0iesSm33alDxra6AE9YImFxzTe1JY@YDMLdiAPfWO0kMV/H4HSItNVODz6CV0ssbHpd3cyq8C8uedDpmJgH3r8q74BxMum40NuKadKIYNl13uaCyvY1F8seqpvNtJtoJ3MPv2a1eAkXsvsd7LEy/6C7Bx9q398OsGmFzNzhmrG8BMFQo@Dva8rrU2y6OecOtopsbg6DJyWPC4BCtNihTRFP7Dk15z2oK7gbNNOdKhoO9nTcboW7DEB6bHk67s5lX6hsU6I0aZv06PhyDeVowv0BA6@p62bHj6ha4HxRpZYSm@cbbaymVe94LE7vf9Q32mly1ApIYzoSSlLfCzlclE/vDfJd@vpOpRRH/iH2qKvVcIQkS4DZm3PIKKZNzmtFoQOup7ekMAiN003i/qqwEfzID0G8nmQiWbm9FNYAwQM7EQTgDx9nd5giVfAWHSJJXfoblMhi@5dB@ibxiWmxc/@ZInUDbqaTeXRWc7NwoKO6emItxG4vRzyEf3cBZEM4x4o77ZWQDezSpO1NAbpugGSfpr7A6qCURfVRRdTF9h0rBl0OZUlY6MwF1OP01pWs8LqZhboQYnbBvWCRT9lttphakdmrg/KSnxego0SnRqrh3DhiyPuANijpzAm@R4@OA7p0egdSE9yxwxbAABKrKW1RvqhcrivD1zRd3TlHgyMz5fDoAEjlkSKbt6F1D6FDvDbECgHFg6g8/O/AQ) split the text up in compressible parts though.
This finally made me fix a bug in the compressor, making it unresponsive sometimes (the result still works in the previous versions though)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 793 bytes
```
--<-<<+[+[<+>--->->->-<<<]>]<<--.<6*+.<<-..<<.<+GG.<<<.+++GG-.<<<+. ^ IT'S SHOWTIME TALK TO THE HAND "^" YOU HAVE BEEN TERMINATED "9!dlroW ,olleH"ck,@ 72a101a+7aa+3a44a32a87a111a+3a-6a-8a33aXine to PaddingtonXine to Wood LaneX¶alert'^' target byteorder little;import puts;export 5;section"data"{s:bits8[]"^\0";}J5(){Jputs("address"s);Jreturn(0);} aeeeaeeewueuueweeueeuewwaaaweaaewaeaawueweeeaeeewaaawueeueweeaweeeueuw H class H{public static void 5(String[]a){System.¶World!");}}+[-->-[>>+>5*-<<]<--<---]>-G>+G..+++[.>]4*<.+++.6*-.<<-G>>+. "^"o| :after{content:"^" H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe$*c;(I&%$#"mCBA?zxxv$*Pb8`qo42mZF.{Iy$*@dD'<;_?!\}}|z2VxSSQ 5(){puts("Hello, W
5
main
G
.>>
J
foreign"C"
X
Take Circle L
\^
Hello, World!
```
[Try it online!](https://tio.run/##NZHrVtpAEMe/5ymGiHIJiVwF2TSCSglWBUsKWgztQFabGrKYLAZF@lg@gC9GN3g8uzvzn5mds5dfQLnrY2GzkVRVV3VdGSkjXTFUVTW2Q9d127B1XVU1/SCraEJpwmi60m4Lr2uKIpQaS0WDMXSsVB/6ZndodS5aYDXPv4HVBctsgdm8PAV5LMNN94cIBi04brUuwWp9v@hcNq2WKB4mHC9gQ8gxz6OmPH3INaBaxEK@gEoVUSlhuYylItaqWCgU4lg9QLWGpRJeuz4FzqCHjuP695z5n5khYw6co0@v39/QowFPjVPAMbinHCbPnLLAoQF4LuceJe5szgIO8wUPCV1udYWEdMpd5ssOcpRXYX3i8rA2suXxbV4m67NKOrM6izvSsjg8oGEohxlyFlC@CPx0PkPWgJTSeEULuljQiNJFPKMIESOKSCMUNtpWPvbhNqTbDMZZ0RiBCVMPwxDM1Xwx8dwphBy5cE/MdaCS7vNAPH1kY2bVfw45nWnvb0MWeE5CFpdYK6MY6sgwFKOSFWBtPUauqrahtg2lrcUoR5phl7NbqtpBNsYqaoYgK8CxV6jjHafBasp8Tn1ej2mahJJegTT2yZAwsu8RYa/2A@IRhxRJLw/p1N5u/dBO/Fu/vhQHy@hJzfW6j3Pme0nzr/vn7vW40TByX/SL@uFe9WZnMChafV/r0mR2StKdvd3kjjw7OW4evSyXT8lsb1L7/cjKxdnPr9qq85zMNpzTlE5@HSVu1x8H9PtXECP5IGJSz2M5GEoVaYauL7UlzTCkM@mOBdS99@UTWbqWwMIHCiduMPUonEu3Y@mzbft7m81/ "Retina – Try It Online") Well, I tried. The desired output uses all but five printable ASCII characters, but fortunately I could only find five strings with enough repetition to be worth compressing. There are also four characters repeated more than three times in a a row; these are run length encoded. Would be 1 byte longer in Retina 0.8.2 as the four run length encodings cost an extra byte each but it's then no longer necessary to quote the three desired `*`s.
[Answer]
# Deadfish~, 6462 bytes
```
{iiii}iiiiicc{i}iiiiic{d}dddddc{i}iiiiicc{dd}iiic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddd}dc{dd}iiic{ii}dc{dd}iiiccc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{i}iiiiiccc{iii}iiic{ddd}dc{iii}ic{ddd}dddcc{d}dddddccic{i}iiiic{dd}iiicccccciiic{i}iiiicc{d}dddddcicc{i}iiiicc{d}ddddc{i}iiiic{dd}iiiciiic{i}iiiiiicc{d}ddddddc{i}iiiiiicc{d}ddddddc{i}iiiiccc{d}ddddcdddccciiic{i}iiiiiicc{d}ddddddc{i}iiiiiicc{dd}iiicic{i}iiiiccc{dd}iiiciiic{d}ddddc{iiii}c{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicdc{iiii}ic{i}ic{dddd}dddddc{iiii}iiiic{ddddd}dc{iiiii}ic{d}dc{i}dddc{i}ddcdddc{d}dciiiic{d}iic{dddd}iiic{iiiii}iic{dd}ic{i}icdc{dddd}dddc{iiiii}iicdddddc{ddddd}iiic{iiiii}iic{d}ddcdddc{dddd}iiic{iiii}c{d}iiic{i}iiic{d}c{ddd}ddddddciic{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicicddc{iiiiii}dddc{d}ciiiiiic{ddddd}dddc{iiii}c{d}iiic{ii}ic{dd}iiic{dddd}iiic{iii}iiiiciiicc{i}dc{dddd}ddddddc{iiiii}iic{d}dddddc{i}iiicdddddcddddciiiiic{d}dddc{ii}dc{d}dddddcdc{ddd}ddddddciic{ii}iiic{dd}ddddc{{i}ddd}dddc{i}ddciiiiiicdddc{dd}ddddc{ddddd}dddddc{i}iic{{i}ddd}dddcdddcc{d}iiic{ddd}ic{dddd}iic{iiiiii}iiiiic{i}ddc{dddddd}dddc{ii}c{ddd}ddc{ii}iiicdddddc{iiiii}dddc{ddddd}iicdcic{iiiii}ddc{ddddd}ddddc{i}iic{iiii}iicc{ddddd}ddddc{i}ddc{iiii}iiiiiic{dddd}dddddcc{iiii}iiiiic{dddd}ddddddcdc{iiiii}dddc{dddd}dcdc{iiii}iic{ddddd}iiccc{iiiii}ddc{ddddd}ddddc{i}ddc{iiii}iiiiiic{ddddd}ddc{i}dc{iiii}iiic{ddddd}ddc{i}ic{iiii}ic{dddd}ddddddcc{iiii}iiiiiic{dddddd}dddddc{iiiii}iic{i}iiic{i}cddddddc{{d}iii}ic{iii}iiiiic{iiii}ddc{i}dc{d}dddddc{i}dc{d}iiic{{d}iii}ic{iiii}iiiic{iii}dciiiiic{d}ic{{d}iii}ic{{i}dd}iiiicdddddc{{d}ii}ic{iiiii}ddc{ii}dddciiicciiiiiciiiiic{d}iiic{i}iiicdddddcdc{{d}ii}iic{iiiii}iic{i}iiic{i}cddddddc{{d}iii}ic{iii}iiiiic{iiii}ddc{i}dc{d}dddddc{i}dc{d}iiic{{d}iii}ic{iiii}iiiic{iii}dciiiiic{d}ic{{d}iii}ic{{i}dd}iiiicdddddc{{d}ii}ic{iiiii}iiiiic{ii}iiiicc{d}dc{{d}iii}iic{iiii}iiiic{ii}ic{i}iiic{d}ic{{d}iii}ic{iiiii}iic{i}iiic{i}cddddddc{{d}iii}ic{iii}iiiiic{iiii}ddc{i}dc{d}dddddc{i}dc{d}iiic{{d}iii}ic{iiii}iiiic{ii}ic{i}ic{d}iiic{i}iiiciic{{d}ii}iiic{iii}iiic{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiiciiiiiic{d}iiic{{i}dd}iiiic{dd}ic{ii}dddc{d}dcddc{i}iiiiic{{d}ii}ddddc{iiiiii}iiiiiic{ii}iiicdddddc{d}dddddc{i}ciiic{d}ddddcic{i}iiic{{d}ii}ddc{{i}ddd}iiiiiicdddc{i}icc{d}iic{d}iiic{dddd}ddc{iiii}iiiiiiciiiiciiicdciiiciic{{d}ii}ddddc{{i}dd}ciiiiicdcdc{ddddd}ddddddc{iiii}iic{ii}dc{d}iicdciiiciic{{d}ii}ddddc{{i}dd}dddc{d}ddc{i}ddciiiiic{ddddd}dc{iiiii}iiiiiic{d}ddddcddc{ii}dddc{d}dciiiiiicdc{{d}iii}ddddddc{iiiiii}iiiiiicdddc{ii}dc{dd}ic{dddddd}dddc{{i}d}dc{d}iic{dddddd}iiic{iiii}c{i}dddc{i}icdc{dddddd}ic{iii}iiiiiciic{dddddd}ic{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiic{iiiiii}dc{dddd}ddddc{d}ddddc{ii}iiiiic{iiiiii}iiiiiic{dd}dddc{i}dciiic{d}dddciiiicddc{i}dddc{{d}iii}ddddddc{iii}iiic{ddd}dddc{{i}ddd}iiiiic{d}ddc{i}ddciiiiic{{d}iii}cic{{i}dd}iic{dd}dc{i}dciiic{d}dddciiiicddc{i}dddc{{d}iii}ddddddc{iii}iiic{ddd}dddc{{i}dd}ddciiiiicdcdc{{d}iii}dddddcddddddc{iiiiii}iiiciiicc{i}iiiic{d}dddc{i}iiiicc{{d}ii}dc{{i}dd}ic{{d}iii}ddddc{ii}ddc{iiii}iiic{i}dciiic{d}dddciiiicddc{i}dddc{{d}iii}ddddddc{iii}iiic{ddd}dddc{{i}dd}c{d}dddc{i}iiiiicicdddcddddc{{d}iii}c{i}ddc{d}iiic{ii}ddc{iiiiii}iiiiiic{{d}i}dddc{iiiiii}iiiiiciiiicccddddciiiiccc{ii}ddcddc{d}ddddddc{i}iiiiiicc{d}ddddddc{ii}ddc{dd}iicc{i}iiiiiic{d}ddddddcc{i}iiiiiic{d}ddddddc{ii}ddcc{dd}ddccc{ii}iic{dd}iicddddcciiiic{ii}ddc{dd}ddciiiicddddcc{ii}iicddc{d}ddddddc{ii}ddc{dd}iicccddddciiiiccc{ii}ddc{dd}ddccc{ii}iicddc{d}ddddddcc{i}iiiiiic{d}ddddddc{ii}ddc{dd}iiccddddc{ii}iic{dd}iiccc{i}iiiiiic{d}ddddddc{i}iiiiiiciic{{d}i}iiic{iiii}c{dddd}c{{i}ddd}dddc{i}dc{d}dc{ii}ddcc{{d}ii}dddc{iiii}c{iiiii}ic{d}dciiiiic{dd}ic{i}cdddcddddddc{{d}iii}iiic{{i}dd}iiicic{dd}ic{ii}dc{d}dcddddddc{{d}iii}iiic{{i}dd}iiiiiic{d}iiicddddddcdddddc{{d}iii}iic{{i}dd}dddc{d}ddc{i}ddciiiiic{{d}iii}c{iiii}iiic{iii}iiicddc{d}iciiiiic{d}iiic{d}ddciiciiiic{ddddd}ddddddc{{i}dd}iic{dddd}c{iiii}ddcddddddcic{d}dddddc{i}ddc{dddddd}dddc{iiii}ic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicic{i}dddc{ii}ddc{iiiiii}iiiiiicc{{d}ii}ddc{iiiii}ddc{dddd}ddddddcc{ii}dddc{dd}iiic{iiii}iiiiiic{ddd}icc{dd}ic{ii}dc{dd}iiiccccc{i}iiiiicc{iii}iiic{ddd}dddc{d}dddddcc{i}iiiiic{d}dddddccc{iiiii}ddc{ddd}dc{dd}iiicic{i}iiiiiiccc{dd}iciiic{i}iiiiiicc{d}ddddddccdddccc{iiiii}ddc{dddd}dddddc{i}iiiiiic{iii}ic{ddd}dddcccc{d}ddddcdddccciiicdccccccic{i}iiiicc{d}dddddcic{i}iiiiiicccc{dd}iciiic{d}ddddciic{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicic{{i}dd}dddc{i}iiic{{d}i}ddc{ii}iiiiiic{iiii}dciiiiic{i}iiiic{d}dddddc{i}iiic{i}dc{dd}ddddc{i}iicdciiiiiic{d}dddddc{i}dciiiiiic{dddddd}iic{dd}ddddc{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicicddc{iiii}c{d}dddc{iiii}iic{dddd}ddc{ii}ic{ddd}dc{i}ciiiiic{dd}iiic{i}iic{iii}ddc{ddd}iic{iiiii}iic{ddddd}ddc{d}ddc{iiiiii}ic{ddddd}icc{iiiii}iic{ddddd}ddc{ii}iic{ddd}ddddc{{i}ddd}dddc{ddddd}dddddc{iiiii}dc{ddddd}ic{iiii}ic{dddd}dc{d}ic{i}dc{ii}ic{ddd}ddc{d}ddddddc{i}ddcdcdcdc{ii}icdc{iii}iiiiiic{dddddd}c{{i}d}iiicdcdcddc{{d}iii}ddc{iii}iiiiiic{iii}iiiicdcdc{{d}iii}dddcdc{iii}iiiiiicdc{iii}iiiicdcdcdcddc{{d}iii}ddc{iii}iiiiiic{iii}iiiicdcdcddc{ii}iic{dddddd}iicddccddc{dd}iic{ii}dddcdc{ii}dddc{dd}icdc{dd}ic{ii}dddc{iii}iiiic{ddddd}ddddc{iiiii}icc{ddd}ddddddc{iii}iiiicdc{iii}dddc{dddddd}ddddc{iii}iiic{ii}iic{dddddd}ic{iiiiii}dddc{dddd}c{dd}ic{iii}iiic{ddd}dddddcdcdcdcdc{{i}ddd}iiiiic{dddd}ddcdcdcddc{iiiiii}dcddccddc{{d}iii}ddddddc{iiii}ddc{ii}ddc{dddd}ddc{iiii}c{ii}dddcddc{dddddd}icddc{iiiiii}dc{dd}ic{dd}c{dd}ddddc{{i}dd}dddc{ddddd}c{iiiii}ddc{{d}ii}ic{ii}iic{iii}iiiiiic{ddd}ddc{ddd}ic{ii}icdc{iii}iiiiiic{ddd}ddc{ddd}c{iiiiii}dc{iii}iiiccdcddc{{d}iii}ddc{iii}iiiiiic{iii}iiiic{dddd}iiiccddc{ddddd}ic{{i}dd}dddc{d}ddc{i}ddciiiiic{{d}iii}cic{{i}dd}iic{d}dciiiiicdcdc{{d}iii}dddddcddddddc{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{i}iiiiiciiiciiic{d}iiic{dddd}dddc{d}dccc{{i}ddd}cddc{d}ddddc{i}iiicic{{d}iii}iic{iiiii}ic{i}dcddddddciiiic{i}ic{d}ddc{dddddd}iiic{iiiii}iiic{i}ic{d}ddc{ii}ddc{d}iic{d}iic{i}dciiiiiicdc{{d}iii}iic{iiiii}iiiiiic{i}ddc{d}ddddddc{ii}ic{d}dddddc{i}iiiicic{{d}iii}ic{iiiiii}dc{d}ic{ii}ic{dd}dc{ddddd}c{iiiiii}ddciiiiic{d}cic{ii}dc{{d}iii}ddddc{iiiiii}ddc{i}iic{d}iiicdc
```
] |
[Question]
[
The six main [cast members](https://en.wikipedia.org/wiki/List_of_Friends_characters#Main_characters) of the American sitcom [*Friends*](http://www.imdb.com/title/tt0108778/) all [agreed that they would be paid the same salary](http://www.factfiend.com/cast-friends-took-pay-cut-theyd-paid-amount/) throughout the run of the series (after season 2, at least). But that doesn't mean that they all had the same amount of air time or that they all interacted on screen with each other the same amount.
In this challenge, you'll write a program that could help determine which *Friends* friends were *really* the best.
# Setup
Consider watching an episode or scene of *Friends* and noting down exactly who is on screen during each camera shot and for how long.
We'll abbreviate each character's name:
* `C` is for [Chandler](https://en.wikipedia.org/wiki/Chandler_Bing)
* `J` is for [Joey](https://en.wikipedia.org/wiki/Joey_Tribbiani)
* `M` is for [Monica](https://en.wikipedia.org/wiki/Monica_Geller)
* `P` is for [Phoebe](https://en.wikipedia.org/wiki/Phoebe_Buffay)
* `R` is for [Rachel](https://en.wikipedia.org/wiki/Rachel_Green)
* `S` is for [Ross](https://en.wikipedia.org/wiki/Ross_Geller)
Then for every camera shot (or every time a character enters/exits the shot), we'll list who was on screen. For example:
```
504 CRS
200 J
345 MP
980
2000 CJMPRS
```
This is saying that:
* For 504ms, Chandler, Rachel, and Ross were on screen.
* Then for 200ms, Joey was.
* Then for 345ms, Monica and Phoebe were.
* Then for 980ms, none of the 6 main characters were on screen.
* Then for 2 seconds, all of them were.
(This is not from an actual clip, I made it up.)
Note that the following would be equivalent:
```
504 CRS
1 J
199 J
345 MP
980
2000 CJMPRS
```
To analyze which combinations of characters had the most screen time, we look at all 64 possible subsets of the 6 characters and total up the screen time they had. If everyone in a subset appears on screen during a camera shot, **even if there are more characters than just the ones in the subset**, the time for that camera shot is added to that subset's total screen time.
There's an exception for the empty subset - only the scenes with none of the 6 main characters are counted.
So the analysis of the example above would be:
```
980
2504 C
2200 J
2345 M
2345 P
2504 R
2504 S
2000 CJ
2000 CM
2000 CP
2504 CR
2504 CS
2000 JM
2000 JP
2000 JR
2000 JS
2345 MP
2000 MR
2000 MS
2000 PR
2000 PS
2504 RS
2000 CJM
2000 CJP
2000 CJR
2000 CJS
2000 CMP
2000 CMR
2000 CMS
2000 CPR
2000 CPS
2504 CRS
2000 JMP
2000 JMR
2000 JMS
2000 JPR
2000 JPS
2000 JRS
2000 MPR
2000 MPS
2000 MRS
2000 PRS
2000 CJMP
2000 CJMR
2000 CJMS
2000 CJPR
2000 CJPS
2000 CJRS
2000 CMPR
2000 CMPS
2000 CMRS
2000 CPRS
2000 JMPR
2000 JMPS
2000 JMRS
2000 JPRS
2000 MPRS
2000 CJMPR
2000 CJMPS
2000 CJMRS
2000 CJPRS
2000 CMPRS
2000 JMPRS
2000 CJMPRS
```
We can see that `J` (just Joey) had 2200ms of screen time because he had 200 by himself and 2000 with everyone.
# Challenge
Write a program that takes in a string or text file such as
```
504 CRS
200 J
345 MP
980
2000 CJMPRS
```
where each line has the form `[time in ms] [characters on screen]`, and outputs the total amount of time that each of the 64 subsets of the 6 characters spent on the screen, where each line has the form `[total time in ms for subset] [characters in subset]` (just as above).
The input can be taken as a string to stdin, the command line, or a function, or it can be the name of a text file that contains the data.
* The milliseconds numbers will always be positive integers.
* The character letters will always be in the order `CJMPRS` (alphabetical).
* You can optionally assume there is a trailing space when there are no characters in the scene (e.g. `980` ).
* You can optionally assume there is a trailing newline.
* The input will have at least 1 line and may have arbitrarily many.
The output should be printed or returned or written to another text file as a 64 line string.
* The lines may be in any order.
* The character letters do not need to be in the `CJMPRS` order.
* Subsets with 0ms total time **do** need to be listed.
* There may optionally be a trailing space after the empty subset total.
* There may optionally be a trailing newline.
(This problem can of course be generalized to more characters, but we'll stick with the 6 `CJMPRS` *Friends* characters.)
**The shortest code in bytes wins.**
*Note that I actually enjoy Friends and don't think some characters are more important than the others. The statistics would be interesting though.* ;)
[Answer]
## Haskell, 187 bytes
```
f=g.(>>=(q.words)).lines
g t=p"CJMPRS">>=(\k->show(sum.map snd$filter((==k).fst)t)++' ':k++"\n")
q[n]=[("",read n)]
q[n,s]=[(k,read n)|k<-tail$p s]
p s=map concat$sequence[[[],[c]]|c<-s]
```
`f` is a function that takes the input, as a single multi-line string, and returns the multi-line output as single string. Probably plenty left to golf here.
```
λ: putStr test1
504 CRS
1 J
199 J
345 MP
980
2000 CJMPRS
λ: putStr $ f test1
980
2504 S
2504 R
2504 RS
2345 P
2000 PS
2000 PR
2000 PRS
2345 M
2000 MS
2000 MR
2000 MRS
2345 MP
2000 MPS
2000 MPR
2000 MPRS
2200 J
2000 JS
2000 JR
2000 JRS
2000 JP
2000 JPS
2000 JPR
2000 JPRS
2000 JM
2000 JMS
2000 JMR
2000 JMRS
2000 JMP
2000 JMPS
2000 JMPR
2000 JMPRS
2504 C
2504 CS
2504 CR
2504 CRS
2000 CP
2000 CPS
2000 CPR
2000 CPRS
2000 CM
2000 CMS
2000 CMR
2000 CMRS
2000 CMP
2000 CMPS
2000 CMPR
2000 CMPRS
2000 CJ
2000 CJS
2000 CJR
2000 CJRS
2000 CJP
2000 CJPS
2000 CJPR
2000 CJPRS
2000 CJM
2000 CJMS
2000 CJMR
2000 CJMRS
2000 CJMP
2000 CJMPS
2000 CJMPR
2000 CJMPRS
```
[Answer]
# Pyth, 37 bytes
```
Vy"CJMPRS"++smvhdf?q@eTNNN!eTcR\ .zdN
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=Vy%22CJMPRS%22%2B%2Bsmvhdf%3Fq%40eTNNN!eTcR%5C+.zdN&input=504+CRS%0A200+J%0A345+MP%0A980+%0A2000+CJMPRS&debug=0)
### Explanation:
```
"CJMPRS" string with all friends
y create all subsets
V for loop, N iterates over ^:
.z all input lines
cR\ split each line at spaces
f filter for lines T, which satisfy:
? N if N != "":
q@eTNN intersection(T[1],N) == N
else:
!eT T[1] == ""
m map each of the remaining d to:
vhd eval(d[0]) (extract times)
s sum
+ d + " "
+ N + N
implicitly print
```
[Answer]
# SWI-Prolog, 381 bytes
```
s([E|T],[F|N]):-E=F,(N=[];s(T,N));s(T,[F|N]).
a(A):-split_string(A," \n","",B),w(B,[],C),setof(L,s(`CJMPRS`,L),M),x(C,[` `|M]).
w([A,B|T],R,Z):-number_string(N,A),(B="",C=` `;string_codes(B,C)),X=[[N,C]|R],(T=[],Z=X;w(T,X,Z)).
x(A,[M|T]):-y(M,A,0,R),atom_codes(S,M),writef("%t %w\n",[R,S]),(T=[];x(A,T)).
y(_,[],R,R).
y(M,[[A,B]|T],R,Z):-subset(M,B),S is R+A,y(M,T,S,Z);y(M,T,R,Z).
```
This expects to be run as:
```
a("504 CRS
200 J
345 MP
980
2000 CJMPRS").
```
Note that you might need to replace every ``` to `"` and every `"` to `'` if you have an old version of SWI-Prolog.
I could shave off 100+ bytes if I didn't have to use a String as an input.
[Answer]
# Haskell, ~~150~~ 136 bytes
```
import Data.List
f=(subsequences"CJMPRS">>=).g
g l c=show(sum[read x|(x,y)<-map(span(/=' '))$lines l,c\\y==[],c/=[]||c==y])++' ':c++"\n"
```
Usage example:
```
*Main> putStr $ f "504 CRS\n1 J\n199 J\n345 MP\n980\n2000 CJMPRS"
980
2504 C
2200 J
2000 CJ
2345 M
2000 CM
2000 JM
2000 CJM
2345 P
2000 CP
2000 JP
2000 CJP
2345 MP
2000 CMP
2000 JMP
2000 CJMP
2504 R
2504 CR
2000 JR
2000 CJR
2000 MR
2000 CMR
2000 JMR
2000 CJMR
2000 PR
2000 CPR
2000 JPR
2000 CJPR
2000 MPR
2000 CMPR
2000 JMPR
2000 CJMPR
2504 S
2504 CS
2000 JS
2000 CJS
2000 MS
2000 CMS
2000 JMS
2000 CJMS
2000 PS
2000 CPS
2000 JPS
2000 CJPS
2000 MPS
2000 CMPS
2000 JMPS
2000 CJMPS
2504 RS
2504 CRS
2000 JRS
2000 CJRS
2000 MRS
2000 CMRS
2000 JMRS
2000 CJMRS
2000 PRS
2000 CPRS
2000 JPRS
2000 CJPRS
2000 MPRS
2000 CMPRS
2000 JMPRS
2000 CJMPRS
```
Different approach than [@MtnViewMark's answer](https://codegolf.stackexchange.com/a/52721/34531): For all combinations `c` of the characters find the lines of the input string where the difference of `c` and the list from the lines `y` is empty (take care of the special case where no character is on screen (e.g. `980`) -> `c` must be not empty or `c == y`). Extract the number and sum.
[Answer]
# CJam, ~~67~~ 58 bytes
```
"CJMPRS"6m*_.&:$_&qN/_{_el=},:~1bpf{{1$\-!},Sf/0f=:i1bS\N}
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22CJMPRS%226m*_.%26%3A%24_%26qN%2F_%7B_el%3D%7D%2C%3A~1bpf%7B%7B1%24%5C-!%7D%2CSf%2F0f%3D%3Ai1bS%5CN%7D&input=504%20CRS%0A1%20J%0A199%20J%0A345%20MP%0A980%0A2000%20CJMPRS).
[Answer]
# Perl 5 (5.10+), 128 bytes
2 bytes per line of output. `use feature "say"` not included in the byte count.
```
@_=<>;for$i(0..63){@c=qw(C J M P R S)[grep$i&(1<<$_),0..5];
$r=@c?join".*","",@c:'$';$t=0;for(@_){$t+=$1 if/(.*) $r/}say"$t ",@c}
```
Un-golfed:
```
# Read the input into an array of lines.
my @lines = <>;
# For every 6-bit number:
for my $i (0 .. 63) {
# Select the elements of the list that correspond to 1-bits in $i
my @indices = grep { $i & (1 << $_) } 0 .. 5;
my @characters = ('C', 'J', 'M', 'P', 'R', 'S')[@indices];
# Build a regex that matches a string that contains all of @characters
# in order... unless @characters is empty, then build a regex that matches
# end-of-line.
my $regex = @characters
? join ".*", ("", @c)
: '$';
my $time = 0;
# For each line in the input...
for my $line (@lines) {
# If it contains the requisite characters...
if ($line =~ /(.*) $regex/) {
# Add to the time total
$time += $1;
}
}
# And print the subset and the total time.
say "$time ", @characters;
}
```
[Answer]
# K, 95
```
{(+/'{x[1]@&min'y in/:*x}[|"I \n"0:x]'b)!b:" ",?,/{x{,/y{x,/:y@&y>max x}\:x}[d]/d:"CJMPRS"}
```
Takes a string like `"504 CRS\n200 J\n345 MP\n980 \n2000 CJMPRS"`
```
k){(+/'{x[1]@&min'y in/:*x}[|"I \n"0:x]'b)!b:" ",?,/{x{,/y{x,/:y@&y>max x}\:x}[d]/d:"CJMPRS"}["504 CRS\n200 J\n345 MP\n980 \n2000 CJMPRS"]
980 | " "
2504| "C"
2200| "J"
2345| "M"
2345| "P"
2504| "R"
2504| "S"
2000| "CJ"
2000| "CM"
2000| "CP"
2504| "CR"
2504| "CS"
2000| "JM"
2000| "JP"
2000| "JR"
2000| "JS"
2345| "MP"
2000| "MR"
2000| "MS"
2000| "PR"
2000| "PS"
2504| "RS"
2000| "CJM"
2000| "CJP"
2000| "CJR"
2000| "CJS"
2000| "CMP"
2000| "CMR"
2000| "CMS"
2000| "CPR"
2000| "CPS"
2504| "CRS"
2000| "JMP"
2000| "JMR"
2000| "JMS"
2000| "JPR"
2000| "JPS"
2000| "JRS"
2000| "MPR"
2000| "MPS"
2000| "MRS"
2000| "PRS"
2000| "CJMP"
2000| "CJMR"
2000| "CJMS"
2000| "CJPR"
2000| "CJPS"
2000| "CJRS"
2000| "CMPR"
2000| "CMPS"
2000| "CMRS"
2000| "CPRS"
2000| "JMPR"
2000| "JMPS"
2000| "JMRS"
2000| "JPRS"
2000| "MPRS"
2000| "CJMPR"
2000| "CJMPS"
2000| "CJMRS"
2000| "CJPRS"
2000| "CMPRS"
2000| "JMPRS"
2000| "CJMPRS"
```
] |
[Question]
[
A rotation of a string is made by splitting a string into two pieces and reversing their order, for example `"world!Hello, "` is a rotation of `"Hello, world!"`. It is possible to create programs that can be rotated to form a different, but still valid program. Consider this example in python:
```
print ")import sys; sys.stdout.write("
```
It can be rotated to form
```
import sys; sys.stdout.write("print ")
```
Which is itself a valid python program.
Your challenge is to write a program that outputs a rotation of itself, which when run will output the original program. Bonus points to any entry with a cycle length greater than two!
This is code golf, the exact scoring will be: (length of code)/(cycle length - 1).
EDIT: We have a winner (unless someone else is able to beat a score of 4)! I'd still be very interested to see any other solutions, whether they're contenders or not.
[Answer]
# APL (158 characters, score = 4)
```
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0
```
I'm using Dyalog APL here. The number of cycles can be increased by one by adding `0` (0 followed by a space) to the end of the expression and to the end of the string (before `'''`). The cycle length is `(# 0's) + 1`, and the length of the expression is `150 + 4*(cycle length))`. Assuming we continue adding zeros forever, the score is `Limit[(150 + 4*n)/(n - 1), n -> Infinity] = 4`, where `n` is the cycle length.
Here's an example with cycle length=6:
```
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0
0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0
0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0
0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0
0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0
0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0
0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0
0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0
0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0
0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1
0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0
```
### 192 characters, score = 2
```
'''{2≠⍴⍺:¯3⌽(2×1+⍴⍺)⍴(1+⍴⍺)⍴⍺ ⋄ a←⊃2⌷⍺ ⋄ ⍵=0:¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a⋄(-4+⌊10⍟⊃⍺)⌽(2×1+⍴a)⍴(1+⍴a)⍴a}01'''{2≠⍴⍺:¯3⌽(2×1+⍴⍺)⍴(1+⍴⍺)⍴⍺⋄a←⊃2⌷⍺⋄⍵=0:¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a⋄(-4+⌊10⍟⊃⍺)⌽(2×1+⍴a)⍴(1+⍴a)⍴a}01
```
Depending on the implementation, one point of failure could be when the integer prefixed to the string is too large. Theoretically, though, we can add a cycle by adding two characters - a `1` at the end of the string (before `'''`) and a `1` at the end of the entire line.
### 200 characters, score = 1
```
'''{a←{2=⍴⍵:⊃2⌷⍵⋄⍵}⍺⋄(⍺{⍵=9:⍬⋄⍕1+{2=⍴⍵:10×⊃⍵⋄0}⍺}⍵),(¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a),⍺{⍵=9:(⍕9),⍕⊃⍺⋄⍕⌊⍵÷10}⍵}'''{a←{2=⍴⍵:⊃2⌷⍵⋄⍵}⍺⋄(⍺{⍵=9:⍬⋄⍕1+{2=⍴⍵:10×⊃⍵⋄0}⍺}⍵),(¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a),⍺{⍵=9:(⍕9),⍕⊃⍺⋄⍕⌊⍵÷10}⍵}91
```
My APL implementation doesn't have unlimited precision integers by default, so the integer is converted to a float when it becomes too large, causing the output to be wrong. So this one is the most finicky, but theoretically (either by hand or with a different APL interpreter), it should have a score of 1. Just add a `1` to the end of the expression, and you get another cycle.
## Overview (with a shorter quine)
I'm going to give an overview of the first version, because I think it's probably the easiest to comprehend. Before tackling that version, however, we're going to consider a simple [quine in APL](http://www.nyx.net/~gthompso/self_apl.txt):
```
1⌽22⍴11⍴'''1⌽22⍴11⍴'''
```
I've found that one of the best ways to understand some APL expressions is to look at the output throughout the cascade of operators/functions. All operators and functions in APL are right-associative and have the same precedence, so here is is, from right to left:
* `'''1⌽22⍴11⍴'''`: This is just a string literal (a list of characters). `''` is the APL way of escaping single quote marks. Output: `'1⌽22⍴11⍴'`.
* `11⍴'''1⌽22⍴11⍴'''`: Here, we reshape (`⍴`) the string to be of length `11`. Because the string's length is under 11, it is repeated (i.e., `5⍴'abc'` would yield `'abcab'`). Output: `'1⌽22⍴11⍴''`. So we now have two quotation marks at the end - we're getting somewhere!
* `22⍴11⍴'''1⌽22⍴11⍴'''`: Similarly, we now reshape our previous output to be of length `22`. Output: `'1⌽22⍴11⍴'''1⌽22⍴11⍴''`. We're almost there - we just need to move the first single quote to the end.
* `1⌽22⍴11⍴'''1⌽22⍴11⍴'''`: Here, we rotate (`⌽`) the list of characters by `1`. This moves the first character of the string to the end. As another example, `2⌽'abcdef'` returns `'cdefab'`. Output: `1⌽22⍴11⍴'''1⌽22⍴11⍴'''`.
## The rotating quine
That short quine is the main basis for our rotating quine. Now, with that in mind, let's take a look at our quine:
```
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0
```
`{ ... }` defines an unnamed function, which is where we'll be doing the work. Note that functions in APL take a right argument, denoted by `⍵`, and an optional left argument, denoted by `⍺` (think infix). We want to feed this function both our quine string and something to aid us in creating an arbitrary number of cycles. To make things easier on ourselves (and anyone wanting to add cycles), we make the quine string the left argument. The right argument, then, is where we put our list of cycles. 2 or more items separated by a space creates a list, so in this example, we have 2-element list consisting of a `1` and a `0`.
We can see that the function looks similar to the quine from before. We have the same `...⌽...⍴...⍴...` form from before. So that's good - we at least understand that much! Let's delve deeper into the ellipses, starting with everything after the last `⍴`: `⊃,/(~^/¨⍺=0)/⍺`.
* As you can see by looking at the example above, we prefix the string with the 0's from the right-hand side, adding one with each iteration; but we don't care about those right now. We just want the string!
* First, consider what's in the parentheses. (They group like in most other languages, by the way.)
+ `⍺=0` returns a list, in this case, with the same shape as `⍺`, where each element in `⍺` is replaced by a `1` if it is equal to `0`, and a `0` otherwise. This is performed recursively; so if we have a list of a list of a list of characters, the individual characters will be tested against 0, and you will get back a list of a list of a list of binary values.
+ So if `⍺` consists of just our string, we get back a list of 0's. Otherwise, our left argument has some 0's prefixed to it (e.g., `0 0 0 'quinestring'`), so it is a list consisting of 0's and another list, our string. Then our output looks like `1 1 1 <sub-list of zeros>`.
+ `^/¨⍺=0`: We apply the derived function `^/`, which reduces (`/`) using the logical AND (`^`) function, to each (`¨`) element of `⍺=0`. This is to flatten the sub-list of zeros so that we can consider the quine string to be one binary value. Considering the previous example, the output would be `1 1 1 0`.
+ `~`: We binary NOT each of the values from before (e.g., returning `0 0 0 1`).
* `(~^/¨⍺=0)/⍺`: For each element in `⍺`, we replicate (`/`) it the number of times given by the corresponding element in the left argument. This eliminates all of the 0's, leaving us only with our quine string.
* `⊃,/` is some necessary paperwork to ensure that we get back a flattened list of characters, by reducing the result with the concatenation function (`,`). If the input is already a flattened list (i.e., the left argument to our main function is only the string), we get a 1-element list containing that list. In the other case, when we have a list consisting of a sub-list for the string, we get the same thing back (a list with a sub-list). We then unpack this (`⊃`), giving us only the first element of the list (i.e., the sub-list of characters). This might seem unnecessary, but otherwise we would then be trying to reshape a 1-element list!
Next, we look at the length given for the first reshape, within the parentheses:
* `⍺,⍵`: We concatenate the right argument to the first argument
* `⊃,/⍺,⍵`: Same as before - flatten the list.
* `+/0=⊃,/⍺,⍵`: Add up the number of zeros in the list by reducing (`/`) using the addition (`+`) function.
* `2×+/0=⊃,/⍺,⍵`: Multiply that number by two.
* `z←2×+/0=⊃,/⍺,⍵`: Assign (`←`) the result to a variable, `z`. To recap, `z` is now twice the number of zeros found in both the left and right arguments.
* `77+z←2×+/0=⊃,/⍺,⍵`: We then add `77`, for the characters in the quine string, ignoring everything after the space following `1`. Like in the initial quine example, we add 1 to the length of the string to get another single quote.
* The output of this reshape, in this example, is: `'{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 ''`
The argument to the reshape that follows is simple and mirrors the short quine (2 times the length for the first reshape). Our output now is:
```
'{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 ''
```
Now for the final step, where we calculate how much to rotate the output string:
* As you can see by looking at the previous output, we want to rotate it back (a negative amount) to bring the 2 final quotes to the beginning. Because we want a `0` (and another space) to move to the beginning as well, we want to rotate it an additional 3 characters back.
* `+/+/¨⍺=0`: Add up the number of zeros in the *left* argument. The first (from the right) `+/¨` sums each element's count (i.e., a sublist or just an integer), and the second `+/` gives us the sum of that resulting list.
* `5+2×+/+/¨⍺=0`: Multiply by two (to rotate the spaces as well), and add 5 (the result we came up with before).
* Now, we subtract the previous value from the left argument to `-` to handle the case when we hit the end of our cycle:
+ `(3+z)×^/⍵`: AND all of the elements in the right argument together to see if we've reached our end (`1`), and multiply that by `3+z`.
And we're done!
[Answer]
## GolfScript, 10046 / 9999 ≈ 1.0047 (asymptotic score 1)
OK, I'm going to try and beat [D C's APL entry](https://codegolf.stackexchange.com/a/5092) with this:
```
{\''+.,{(;\'.~1'}{'1'9999*@'.~']puts:puts}if}.~
```
The code above is *not* the actual quine — I felt that posting a 10kB one-liner would not be a very good idea. Rather, running the code above once produces the actual 10046-char GolfScript program, which, when iterated as specified in the question, generates 9999 rotations of itself and, finally, itself again.
The length of the cycle (and the program) can be adjusted by changing the constant `9999`. For brevity and convenience, I'll show what the iterated output looks like if the constant is reduced to `9`:
```
111111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~
11111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1
1111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11
111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111
11111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1111
1111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11111
111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111111
11{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1111111
1{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11111111
{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111111111
111111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~
11111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1
1111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11
111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111
etc.
```
As the constant `9999` is increased, the ratio of the program length and cycle length (minus one) tends to one.
I'm pretty sure that *this* solution can't be beaten, at least not asymptotically. ;-)
### How does it work?
GolfScript is a pretty easy language to write quines in, since basically any number literal acts as a quine: for example, the GolfScript program `12345` outputs — you guessed it — `12345`. Also, concatenating multiple quines typically produces a quine. Thus, I could use a simple number like `11111...111` as the repetitive part of my cyclic quine.
However, to get the quine to actually cycle, we need to carry and execute a non-trivial "payload". The simplest GolfScript quine I could think of that can do that is the following:
```
{PAYLOAD'.~'}.~
```
So my plan was to prefix a quine like that with a repetitive numeric constant, and use a payload that chops one digit off the number and moves it to the end of the program. If the program detects that there *is* no numeric constant in front of it (in which case the value below it on the stack will be an empty string, assuming there no input), it will instead prepend a fixed-length numeric constant in front of itself.
There's one additional wrinkle, though — when "wrapping around", the payload must also suppress the output of the number *after* itself. Normally, when a GolfScript program ends, all values on the stack are automatically printed, which would be a problem here.
However, there turns out to be an (AFAIK) undocumented way to avoid that: the interpreter actually calls the predefined function `puts` to do the printing, so redefining that function as a no-op suppresses the automatic output. Of course, this also means that we must first call `puts` ourselves to print the part of the stack we *want* printed.
The final code looks pretty messy (even for GolfScript), but at least it works. I suspect there may be some clever ways I haven't yet thought of to shave a few chars off the payload, but for this version I was mainly just focusing on the asymptotic score.
[Answer]
# [Alice](https://github.com/m-ender/alice), 94 bytes, score --> 1
```
<pp&a0Ra*880R9Z640R8Z5e0R7*a70R6Z060R5Z9e0R4Z4R20R3*79Y3Zea0eZ1R51!Z73
```
Unfortunately, I had to fix a bug in the interpreter to make this work, so this doesn't work on TIO.
## Explanation
This is a straightforward extension of my solution to [Rotation-safe quine](https://codegolf.stackexchange.com/q/121522/8478). Since that solution is a proper, payload-capable quine for *every* rotation of the source code, we can simply shift the source by one character before printing to cycle through all possible rotations. So this solution has byte count = cycle length.
The code we're writing into the grid to do so is
```
@o&~,.^'h%?t"
```
The only difference to the other quine is that we pull up the 94th character to the top of the stack, before printing everything.
We can arbitrarily increase the byte count and cycle length by adding no-ops anywhere in the program, which lets the score tend arbitrarily close to 1.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 127 bytes, asymptotic score = 1
```
000000000
for i in 1,0:exec(s:="i or print(end=-~-len(str(n))%10*'0'+f'\\nfor i in 1,0:exec(s:=%r);n={n//10 or 10**9}'%s)");n=1
```
[Try it online!](https://tio.run/##bZBBbsMgEEX3nGI0kgU4dgPtpqXySZou3BinVNZgYUdyFKVXdyEJyqZIIyFm3v@fGU/zt6eX1zGse99ZaCAg4qryYb0P4MAR6EoZu9i9mEyDDuLzGBzNwlLX1L/1YElMcxAkZaFVyRXf9Hy3o3/5Ish3as603WqVlCJQvl14MUlMDb3GDB/a1PqTMX@cx@McgyGyzvbQuWkc2pMolwqSN6I0DA6D/2oHuA0zeECATz/ekVjkJk6ze@gMx5KMPT4ZWjpYoVWSvIZNS6nO/Epxk80vksF9XdnxpivzBWssn5Vc/wA "Python 3.8 (pre-release) – Try It Online")
## How it works :
We run the for loop twice.
* The first time we initialize the variable `n` to a power of 10 and
* The second time we print our quine dividing `n` by 10 and prepending a `0` in front of the code.
When `n` is equals to `1`, we set `n` to the initial power of 10 an we remove the prepending `0`
By adjusting the number of `0` in the original program, modifying `len(str(n))%10` by `len(str(n))%< x >` and `n//10 or 10**9` by `n//10 or 10**< x-1 >`, with x -> infinity, the asymptotic score is 1
] |
[Question]
[
You work at a beach. In the afternoon, the sun gets quite hot and beachgoers want to be shaded. So you put out umbrellas. When you put out umbrellas you want to shade the entire beach, with as few umbrellas as possible.
Umbrellas come in many sizes. However, larger umbrellas are susceptible to being pulled away by the wind, so in the morning you have to go to the beach and do a soil test. The soil test tells you, for each spot on the beach, the size of the largest umbrella that could be safely placed.
So after your soil test, you get back a list of positive integers. For example:
```
[2,1,3,1,3,1,1,2,1]
```
Each number represents the maximum radius of an umbrella that can be placed at that location. A radius \$r\$ umbrella covers itself, and \$r-1\$ spots to both its left and right.
For example a radius 3 umbrella covers:
* itself
* the two spaces directly adjacent to it,
* the two further spaces adjacent to those,
Your task is to write a computer program which takes the results of the soil test as a list of positive integers, and gives back the minimum number of umbrellas required to cover all the spots on the beach.
For example if the soil test gives back `[2,1,4,1,4,1,1,3,1]`, then you can cover the beach with 2 umbrellas:
```
X X X X X
X X X X X X X |
| |
[_,_,4,_,_,_,_,3,_]
```
So the output of the program should be 2.
This is code-golf so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
```
[9,2,1,3,2,4,2,1] -> 1
[9,9,9,9,9,9,9,9] -> 1
[1,1,1,1,1,1,1,1] -> 8
[2,1,4,1,4,1,1,3,1] -> 2
[5,1,3,1,3,1,1,1,6] -> 2
[4,1,1,3,1,1] -> 2
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~30~~ ~~27~~ 26 bytes
```
W‹↨υ⁰Lθ⊞υ⌈Eθ∧‹⁻λ↨υ⁰κ⁺λκILυ
```
[Try it online!](https://tio.run/##RY0xC8IwEIV3f8WNFzjBopuTujaQvXQ4ajChaWybRP33MaGCd7w3fMd7Nxhehye7nN/GOg3Y6hDwykFjIjgIglb7RzS4CCFApWAql/yxU5pQ8owLwcXft5y0PgV0BP@C0jAWKbcdRlHnvFOr9RFvHCL@HqTKc@66hk7UlD1W7/u8f7kv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Greedy algorithm.
```
W‹↨υ⁰Lθ
```
Until all of the beach has been covered, ...
```
⊞υ⌈Eθ∧‹⁻λ↨υ⁰κ⁺λκ
```
... filtering on those umbrellas whose left end is not to the right of the first uncovered index, pick the one that maximises the next uncovered index.
```
ILυ
```
Output the number of umbrellas used.
Edit: Saved 1 byte by porting @tsh's optimisation. Example: Take the input `[1,4,1,1,3,1,1]`. Initially, five umbrellas lie to the right of index `0`, the valid two being the `1` at index `0` itself, and the `4` at index `1`, which also covers indices `1` to `4`. The maximum next uncovered index is therefore `5`, obtained by choosing the `4`. The `1` at index `6` is the only umbrella to the right of index `5`, and the maximum next uncovered index is therefore `7`, obtained by choosing the `3`. This completes the coverage of the beach using two umbrellas.
A port of @Jonas' J solution was also 27 bytes:
```
UMθE謋↔⁻μκιW⌈⌊θ«→≧×⌊θθ»I⊕ⅈ
```
[Attempt this Online!](https://ato.pxeger.com/run?1=PU6xCsIwEJ3brwhOV0iHooPoJJ0EKyIOQukQa7TBJrG9VAXxS1wcFB31c_wb0yrewT3u3rt7d36kGStTzfLL5VaZld99PyO2DbWUTC2hoMR2NYy1gRFHhMECdV4ZDpFQFYKkZON5lAjPRt_dZyLnBCJ2ELKStabBwpLk6DqR3nHoTcU6M1bs2NsDRLFWzQRmQnK0jv8lSgorO7mTUigDIUMDQ5WWXHJl-BLm0JhecZHi7_t73PJ3eSt5xXFAOzSw2a5rknz5Dw "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
UMθE謋↔⁻μκι
```
Convert each umbrella into a list of `0`s and `1`s where the `0`s are the locations that are covered.
```
W⌈⌊θ«
```
Repeat until opening an umbrella will cover the beach.
```
‚Üí
```
Keep count of the number of umbrellas opened.
```
≧×⌊θθ
```
Zero out the locations covered by the largest remaining umbrella.
```
»I⊕ⅈ
```
Output the number of umbrellas required.
Previous 30-byte brute force solution:
```
I⌊EΦX²Lθ⬤θ⊙θ‹↔⁻μξ×ν﹪÷ιX²ξ²Σ⍘ι²
```
[Try it online!](https://tio.run/##PY7NCoMwEIRfJccVtgdtbz3ZlkJBQbA38ZBqsAv5qSax7dOnRqQDO3PYj2G6J586w2UI1UTawZlbByVpUl5ByV9wJenEBJV5L54hK4Qe3BPGJEGWSwnjEvoboxDWQv6wRnonYoe3oJB9InknJSxoZKXpvTRw0@5CM/UCCNm/e0WzZBWyellw4lbUblk2RHB7HUNomgxTPGyX4h7Ttg27Wf4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
² Literal integer `2`
X Raised to power
θ Input array
L Length
Φ Filter over implicit range
θ Input array
⬤ All indices satisfy
θ Input array
‚äô Any value satisfies
μ Inner index
ξ Innermost index
⁻ Difference
‚Üî Absolute value
‹ Is less than
ι Outer value
√∑ Integer divided by
² Literal integer `2`
X Raised to power
ξ Innermost index
Ôπ™ Modulo
² Literal integer `2`
√ó Multiplied by
ν Innermost value
E Map over implicit range
ι Current value
‚çò Convert to base
² Literal integer `2`
Σ Take the sum (i.e. popcount)
‚åä Take the minimum
I Cast to string
Implicitly print
```
[Answer]
## C89, 89 bytes
**-11 bytes thanks to @Martin Kealey**
```
int m,i,x;f(v,n)int*v;{for(i=n;i--;m=abs(m-i)<x?x+i:m)x=v[i];return m>=n?m=0,1:1+f(v,n);}
```
[Try it online!](https://tio.run/##dZLRToMwFIbveYoTvKGunbDpsq3rFm9MjCY@AFkMsjFPMoqBQoikry62dLpo9DSnPeV8@Qt/SVl6TOShv0CZHuvdHlaV2mExfl33KBXkFGnLs6Chkpj9ZcO7rCgDFJIjYzwXyUsV5AzJqt20I1zmpBVNjFte7lVdSsjXQm5yEdJoGY2cDNdOOUEZNAXuSOeBiUqVdao62yo52KWJp5OtKyXXoOItCHCwjS6i0C3ohEZ0auZrW2nqenNNz9ycWvbH@JObUJuRUXJpdU/k4jd347pD2jH7h/vWOZ9pY6YHTHPPfTu@758VIB92xmAwDtuHRQbq6quIQ@sGY@uQkwE8e/FWqyrIAmWcHzcUhlUSEMKVJWzAf3rwYQn@3e39o0/cSe4thul0XyH3tNd/pNkxOVQ9M/@CSOeLTw "C (clang) – Try It Online")
```
int m, i, x;
int f(int *v, int n)
{
for(i=n; i--;)
{
extern int abs();
x = v[i];
if (abs(m-i) < x) m = x+i;
}
if (m>=n){
m = 0;
return 1;
}
else {
return 1 + f(v, n);
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 13 bytes
-3 thanks to @KevinCruijssen
```
gDŒ¥Œ±‚Ä∫√¶ í√∏O√ü}√∏g
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/3eXclnMbHzXsOrzs1KTDO/wPz689vCP9//9oIx1DHRMoNtQx1jGMBQA "05AB1E – Try It Online")
## Explanation
```
g # push the length
D # twice
δα # create the 2D array a[i][j] = abs(i-j)
› # compare each value to the correct value in the input
æ # take the powerset
í # and keep sets such that:
√∏ # if transposed
O # and summed
ß # the minimum value
} # (is 1)
√∏ # transpose
g # and return the length
```
Requiring that the minimum is 1 is valid because in an optimal solution exactly one umbrella covers the leftmost position.
Transposing and then taking the length finds the minimum length, due to the way transposing works on different-sized arrays.
`δ›Å\` really feels like it can be shorter, but I can't find anything.
[Answer]
# [R](https://www.r-project.org), 61 bytes
```
f=\(b,p=l,l=sum(b|1))sum(if(p>0)1+f(b,min((1:l-b)[1:l+b>p])))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGq0tykotScnMRi26WlJWm6Fjdt02xjNJJ0CmxzdHJsi0tzNZJqDDU1QYzMNI0COwNNQ-00oHxuZp6GhqFVjm6SZjSQ0k6yK4jV1NSEGvIYbqxGsoaljpGOoY4xkDQBsTQ1FZQVdO0UDLmQFRnqoECYIgsURSBzTKAYZCJcmRGKMlOIJBiDoBl2ZSApI6gSY1RrTRRQVJog1CCMgnh1wQIIDQA)
**Ungolfed code**
```
f=function(b,p=1){ # begin at position p=1
l=length(b)
s=1:l-b+1 # start positions of umbrellas
e=1:l+b-1 # end positions of umbrellas
if(p>l)0
else 1+f(b,max(e[s<=p])+1)
# update position to
# furthest end of umbrella
# with start before current position
}
```
[Answer]
# [J](https://www.jsoftware.com), 36 34 33 31 33 bytes
```
{{1>.#}.(OR>./)^:a:#.y>|@-/~#\y}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZDBSsNAEIbxmqeYZLWb2M0ku2ppFhqWCp6kQvHWptCWBCuCYNJDie2LeIkHH6o-jZuskfQgw7Aw3_ezs_vx-VwdLyJb8mRgy4hSy0GawUgCBQYhSN0-wu30_u5rW2T-8GiXJY-R7NF9mMYYeAu5lAR38bvygwOZ7_Z7I36fTTxrMkbgRGm5j855WCZzucFe6PAmplyTUhtUpJUxLN1A8h5BT7mCyBouiOfOyGEmLwOH9zHQdtKJWpaVrp9eATIQjLPr3-bsinFD6GOaF7Be5mlOzYTDSOsRE40mdEC08rBBnJ2UQaJB_1xi4I0ZNV3XoAv_EjpTP3e8Xa1e0jeaQ9EueLJet8y3VpU5fwA)
*-1 thanks to Bubbler suggesting a conversion to explicit fn.*
*Also thanks to Bubbler for pointing out a bug when a single umbrella covers everything, which must be handled as a special case.*
Inspired by [Neil's idea](https://codegolf.stackexchange.com/a/266062/15469), but with an array implementation.
Consider the example `2 1 4 1 4 1 1 3 1`:
* `y>|@-/~#\y` For each entry in the list, this shows what the beach would look like with only that umbrella open, using a `1 0` list. The full phrase returns a binary matrix, with each row showing one "isolated umbrella" version of the beach:
```
1 1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
1 1 1 1 1 1 0 0 0
0 0 0 1 0 0 0 0 0
0 1 1 1 1 1 1 1 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 1
```
* `#.` Interpret those as binary numbers:
```
384 128 504 32 254 8 4 15 1
```
Conceptually, we'll still be working with `1 0` lists, but using integers will help us shorten the necessary computations.
* `(...^:a:)` Accumulate the results of `...` until a fixed point...
* `(...>./)` On each iteration, we find the row with the farthest rightward span of ones, provided that span starts at the left:
```
1 1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
1 1 1 1 1 1 0 0 0 <- farthest rightward span
0 0 0 1 0 0 0 0 0
0 1 1 1 1 1 1 1 0 <- doesn't count since it starts with 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 1
```
This row, however, is nothing but the largest integer in our list, because of how binary numbers work.
* `(OR...)` We then add that "farthest right" row elementwise to every row, essentially "blocking out" everything it covers from all rows. This is nothing but the bitwise `OR` operation. The transformation in this step corresponds to our chosen umbrella being deployed:
```
1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 0 0 0
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 1
```
Then we continue. Our process will reach a fixed point (a matix of all ones) in `n + 1` steps, where `n` is the minimum number of covering umbrellas.
* `#}.` So we kill one element and get the length.
* `1>.` Finally, we return the max of that length and 1. This is needed for the case where a single umbrella covers the entire beach, because otherwise the algorithm above will return 0 in this case.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
```
a=>(g=i=>a[i]&&-~g(a.reduce((m,r,j)=>j-i<r&r+j>m?r+j:m)))(0)
```
[Try it online!](https://tio.run/##dY1RC4IwFIXf@xV7kl2a2kyjoq0fIj4MnbKhLmb12F9fTkVI6B7O4cL9OFeLtxhKqx7PsDeVdDVzgnHcMMW4yFURBOGnwSKysnqVEuOOWKKBcR2qmw3sXvPuPua1AwB8AFeafjCtjFrT4BrnF5IQSo5jpn4rEAJAcYzobgNS8qMVPG9B35cu9s20mMFkC2bzebLX6R@4Nk1v/Syg@wI "JavaScript (Node.js) – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 73 bytes
```
f=lambda a,i=0:i<len(a)and-~f(a,max(r+j for j,r in enumerate(a)if j-i<r))
```
[Try it online!](https://tio.run/##ZY3RCsIwDEXf/YqALy1mYLcpU7YvkT1E1mLL1o0yQV/89bp2uiHmckMIJzfDc7z1NvNeVS1114aAUFf7sy5baRlxsk3yUoywowdzOwOqd2DQgbYg7b2TjkY5cVqBSXTpOPeD03Zkil1OmKLAbOp5mGoAzmELYrMQAn/0JYqVCAn5xyFL1JFIV@Iw76ODjn/Echs/hJoJ/wY "Python 3 – Try It Online")
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 13 bytes
```
Jᵐ{x:ᵒ≈>~}aş#
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Flu8Hm6dUF1h9XDrpEedHXZ1tYlH5ysvKU5KLoYqWHAzMtpSx0jHUMcYSJqAWLFc0YY6KBAoAlJhAsUgtSAxUwgLjEHQDCgGlweqgNgAAA)
```
Jᵐ{x:ᵒ≈>~}aş#
J Split the list into parts
ᵐ{x:ᵒ≈>~} Check that each part can be covered by an umbrella:
ᵐ{ } For each part:
x:ᵒ≈ Create a table a[i][j] = abs(i-j)
>~ Check that there is at least one row in the table
that is smaller than the corresponding item in the input
aş Find the shortest solution
# Take the length
```
This may output the same result multiple times. For example, the input `[2,1,4,1,4,1,1,3,1]` can be split into `[[2,1,4,1,4],[1,1,3,1]]` or `[[2,1,4,1,4,1],[1,3,1]]`, and the output is `2` in both cases.
[Answer]
# JavaScript (ES6), 87 bytes
Brute force.
```
a=>(g=(i,b=a,v=a[i++])=>v?Math.min(g(i,b),1+g(i,b.map(q=>--i*i<v*v?0:q))):b.join``*i)``
```
[Try it online!](https://tio.run/##dY3hCoIwFIX/9xT7uemczSxKmj5BTyCC09QmumnKXt@aipDQPdzLgfNxbs01H/K36EZHqmcxlWziLIQVgwJnjGPNeCxsO0Es1NGDjy/SCgkrkyJM7dmQlnewZ6HjCEvctaWjY9AjhIKM1ErINLUEStMpV3JQTUEaVcESxjfsYYpP3@sblwCAEHBdQA87kOIfbeB1D5o@f13TTJMF9PbgeYnnNbr8A7em@a2ZFZw@ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), 182 bytes
*-2 bytes, thanks to xigoi*
```
lambda l:(S:={*range(L:=len(l))})and[len(c)for n in S|{L}for c in combinations([range(i-k+1,i+k)for i,k in enumerate(l)],n)if{L}.union(*({*r}for r in c))>S][0]
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY6xTsMwEED3foUlFjt1KlIKaiOlX9AtY8jgpjZYsc-R6wyo9EtYIiEYGfkX_gY7qZIiodP5fPK753v7bF7cs4HuXWSPH60T8frnWzG9PzCkUpyn2SmyDJ443qWZ4oAVIWfC4FCEpiLCWARIAspfT7tz6KrQVUbvJTAnDRxxMQhkXM8TKud1PyRpHUAOreaWOe7FJQUihdcsWvCDOML-795peych27wsbsuZsEYj6bh1xqgjkrox1kWX7b8aK8FhgYsNXdKE3vlzFW4lIegGxVuUzEYkoX9iRNYTEhyrSwbbBC0n6H546jPEw3_QaLh2DFt33VB_AQ)
## ungolfed code:
```
import itertools
def f(l):
l=[range(i-k+1,i+k)for i,k in enumerate(l)]
S={*range(L:=len(l))}
for n in range(len(l)+1):
for c in itertools.combinations(l,n):
s=set()
for r in c:
s|={*r}
if s>S: # s=S not possible as L in s\S
return len(c)
```
Brute force solution, goes through all possible sets of umbrellas ordered by size and picks the first one that covers the whole range
[Answer]
# JavaScript, 62 bytes
```
f=(a,s=0)=>a[s]?1+f(a,Math.max(...a.map((v,i)=>i-v<s&&i+v))):0
```
[Try it online!](https://tio.run/##VYrRCsIgGIWv6ym8Gsr@yVYrKFo9QU8gXohpWdscU6Se3rS6icM5fHycuwjCydlMvnKTuah5sONDvWLUHRbgupp0R8EcPzWlTuIs/I0O4okppSLBhHEAkz6mCgdXFKYMhJB9HbWdEe6VR14iqxFjO1hBA@u0bSYOrIG/JJMf7a/5m93mS5/mbDkny4W0o7O9or29Yo29JCS@AQ "JavaScript (SpiderMonkey) – Try It Online")
Greedy algorithm: pick the umbrella that covers the most spaces while including the first uncovered space.
[Answer]
# [sed](https://www.gnu.org/software/sed/), 424 bytes
Thank you for restricting umbrella sizes to 9, otherwise `sed` stops to be the natural choice for solving this thing. (-; The maximum number of umbrellas is also limited to nine; you can upgrade to the big-beach-edition for a couple of extra bytes as an in-app-purchase.
I got distracted so often, that I decided to publish this initial version solving the problem, although I'm feeling that there are still ten to twenty bytes to golf away on a rainy day.
How it works:
* loop `1` creates all possible combinations of umbrellas used or not
* loop `2` sorts those combinations by their number of umbrellas used, which is awfully slow with this approach for 2^beachsize combinations!
* loop `3` takes one combination after the other to test whether they cover the beach with those sub-elements:
+ loop `4` makes a separate line for each umbrella
+ loop `5` opens the umbrellas by couting down there size and spreading `=`
+ loop `6` transposes the beaches from lines to columns (this will probably only work with wet sand)
+ if there is a line without umbrella, this means sun will hit the beach, so we have to start with the next combination of loop `3`
* loop `7` finally counts the number of umbrellas in the first shady combination
```
G
s/^/_/
:1
s/(\S*)_(\S)(\S*.)/\1-_\3\1\2_\3/
t1
:2
s/-(\S*_)/0\1#/
s/(\S*_(#*)\n)(\S*_\2#+\n)/\3\1/
t2
h
:3
s/\S*\n//
x
s/_.*/\n/
:4
s/^(-*)([0-9])(\S*.)/\1-\3\1\2_\3/
s/_\S/-_/
t4
s/-*/987654321#/
:5
s/((.)(.).*#.*)\2/\1x\3x/
s/(x=*)-/\1=/
s/-(=*)x/=\1/
s/x//g
t5
s/#./&!_/
s/\n//g
:6
s/!(.*_)([^x])/!\2\1x/
t6
s/_x*/_/g
s/!/!\n/
/__/!t6
s/!/!#/
/\n[-0]+(\n|_)/!b7
g
b3
:7
s/((.)(.).*!)\3(.*)1.*/\1\2\4/
t7
s/.*!(.).*/\1/
```
[Try it online!](https://tio.run/##TZDBasMwDIbvfosQGLaLrdpOm9XQ49gD9Fi1hrKR7ZIOkoEPe/Zlv8IOheDI@n9Jnzy9v7lh/F6WVzXRlQqpHBBpPllTcBqJvCEOrnDiwBE/UnNQOcLnRC6Gthxa@q8rurWGx7WycGw3iElqURbVh8oJRmg8EqmKuHhLuKjcCYN21ujz1h0uD7MfRsPPJ3IgncXvLB2e@/2uS1EQ8k4otDf4vG09SCIaVE515atHaxwSR1rpcat0FLSJKtGgZqlvPT01RXLCOKi8R9hoj031@VovhhqOaAoEUUq1eLhBPBCwCJVCzSohASi0ObvtZaN5/MFjNbdeDeqWVO4fYRvDCTNMkOfAttyhvzggrQYSzmXpQkghxPB7/5o/7@O0uJc/ "sed – Try It Online")
*Note that beaches of 8 parts or bigger will time out on TIO. Adding a `g` flag in the sorting part of the second loop drastically reduces execution time, but still not enough for hard cases.*
[Answer]
# Python3, 358 bytes
```
E=enumerate
F=lambda h,i,a:{*[i+j for j in range(1,a)if i+j<len(h)]+[i-j for j in range(1,a)if i-j>=0],i}
def f(h):
q,m=[(F(h,i,a),1)for i,a in sorted(E(h),key=lambda x:x[1])[::-1]],-1
while q:
a,b=q.pop(0)
if len(a)==len(h):m=b if m==-1 else min(m,b);continue
for x,y in E(h):
if x not in a and(m==-1or b+1<m):q=[({*a,*F(h,x,y)},b+1)]+q
return m
```
Non-greedy (where is the fun otherwise?) with a basic heuristic for the sake of speed.
[Try it online!](https://tio.run/##dVDBTsMwDL33K3xMNhctDBCEhdv2E1UPKU1pRpO2WSc6Tfv24nSAtAOKHDl@79nP6U5D3fr1cxemaauMPzoT9GCSnWq0K0oNNVrU8rzI7HIPVRtgD9ZD0P7DMIGa2woI2TTGs5rny8ym/9LS/Zta5WgvSWkqqIgvE@jRqYzt2DyHo@BRTGmUH9owmJJtiYmf5vRraZRjJnKeSZmKPMdUJPBV28ZAT/1AY6H6u67t2IrTkwZHb5ordfUonSpi1SmVCjDNwYCznjks@Ot76wfrj4Z00caIp2hje3U69xrBt0MsatC@ZHMTYhZLsXFc9rTKeaFxEfchNb8gIfQtfQLBDMfgwU1dsH5gFcte8B4Frul@iFnOefKHCbw5N1hUPfxE1N@ij9faHPE8ETp9Aw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
x<Ls-ƒÅ¬©+√¶ íÀú¬Æ√•P}√∏g
```
-1 byte thanks to *@CommandMaster*.
[Try it online](https://tio.run/##yy9OTMpM/f@/wsanWPdI46GV2oeXnZp0es6hdYeXBtQe3pH@/3@0kY6hjgkUG@oY6xjGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/ChufYt0jjYdWah9edmrS6TmH1h1eGlB7eEf6f53/0dGWOkY6hjrGQNIExIrViTbUQYFAEZAKEygGqQWJmUJYYAyCZrGxAA).
**Explanation:**
```
x< # Calculate the width of each umbrella:
x # Double each value in the (implicit) input-list (without popping)
< # Decrease each by 1
Ls-ā©+ # Convert each to 1-based ranges it can cover:
L # Convert each inner value to a [1,value]-ranged list
s- # Subtract the values of the input-list from each value of the lists
ā + # Add the 1-based indices
© # And also store the list of 1-based indices in variable `®`
√¶ íÀú¬Æ√•P} # Get all combinations of umbrellas that cover the entire beach:
æ # Get the powerset of this list of lists
í } # Filter it by:
Àú # Flatten the list of lists
®åP # Check whether it contains all 1-based indices of value `®`
√∏g # Output the least amount of umbrellas necessary to cover the beach:
√∏ # Zip/transpose; swapping rows/columns,
# discarding any trailing items of unequal length lists
g # Pop and push the length
# (which is output implicitly as result)
```
[Try it step-by-step.](https://tio.run/##VY6hTgNBEIY9TzE52624FkUgFRU1TVrfIGa3Q2@TvV2yMwtFIHgFNBYSDJKgryh4qOO216ZBjJr/@/4/MGpLbVtM0ZnkUAikIri3a6kg3AChqSDVOpJzeAGF2l5eNZ@Ts2Ia/B1F6QMSoBxqZFpDRL8hBitg0IMJXShjcx5@PzXvgx6ekQA6171rbT2KDZ5z27GIuxEoPb3fQ15sJNC5Let2bz/Pvy/Nx@51@dgrF0luk@zDjpA7fx2Sl/9WT4aYMT7kxSf7Sfu1mbTtaqRKdX64Uo1Vef0H)
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 76 bytes
```
f=(a,k=0,b=-1)=>a[k]?1+Math.min(...a.map((v,i)=>i>b&v+k>i?f(a,v+i,i):1/0)):0
```
[Try it online!](https://tio.run/##dY1RCoMwDIbfd4o@jRZrtc6NTVBPsBOID9Xp1lWtqBR2@q5VESYs4Q8h@fLnzRQby4H3kzv2/FENrexE9dG6jiHDIvZxEbsUxQnLRJ5S586mF2l5BwkhjLSsh1BhbvY8KY7KEQlPa3OoHG6mEfV8hCJfl7IbZVORRj5hDbMbDjDFJ1ND2@UAIAQ8D9DDDqT4JzfwugetX7jKOtN8AYM9eF7Ws2xe/oGb0/zWxgrqLw "JavaScript (SpiderMonkey) – Try It Online")
Try to fix m90's error
[Answer]
# APL (Dyalog Unicode), 78 bytes
```
⌊/b/⍨×b←{(+/⍵)×∧/(1@(∊{n(1⌈⌊)(⍳¯1+2×⍵⌷v)+⍵-⍵⌷v}¨⍵/⍳n))n⍴0}¨{⍵⊤⍨n⍴2}¨⍳¯1+2*n←⍴v
```
Another brute force attack. The index origin is set to 1 (‚éïIO‚Üê1). The variable v contains the integer vector to be evaluated.
I have some more work to do on this one. It is a bit convoluted as it is. I think I'm missing something obvious.
[Try it on TryAPL.org!](https://tryapl.org/?clear&q=%E2%8C%8A%2Fb%2F%E2%8D%A8%C3%97b%E2%86%90%7B(%2B%2F%E2%8D%B5)%C3%97%E2%88%A7%2F(1%40(%E2%88%8A%7Bn(1%E2%8C%88%E2%8C%8A)(%E2%8D%B3%C2%AF1%2B2%C3%97%E2%8D%B5%E2%8C%B7v)%2B%E2%8D%B5-%E2%8D%B5%E2%8C%B7v%7D%C2%A8%E2%8D%B5%2F%E2%8D%B3n))n%E2%8D%B40%7D%C2%A8%7B%E2%8D%B5%E2%8A%A4%E2%8D%A8n%E2%8D%B42%7D%C2%A8%E2%8D%B3%C2%AF1%2B2*n%E2%86%90%E2%8D%B4v%E2%86%902%201%204%201%204%201%201%203%201%0A2&run)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~102 100~~ 97 bytes
```
->l{(r=*1..l.size).find{|c|r.combination(c).any?{|x|r&x.flat_map{|a|[*a-l[-a]+1...a+l[-a]]}==r}}}
```
[Try it online!](https://tio.run/##VU7RisIwEHzvV@RJtLYrrVXuwOqL9@oPrOFYYwOBNC3RO/SafnttcxWUYZdhhhnG/pzuncy7eKubqc3DBEDDRf0VM5DKnBsnnAVRlSdl6KoqMxUzIHPfNe7m7OQGUtP1u6S6ceQwpFhjTHzetwDNPedtntu2bbuaScQsSnosh895ULPN5uuwB61McQHfIpzE4pc0E7g4IoRHvugrAvyMUh9Mo2xgnMVblgzyG55yEr3Byx8BDhXZeH6FN9IAV@Oo5ZhYP43Xvf9Sv7d7AA "Ruby – Try It Online")
Thanks value ink for some good ideas (-2/-3 bytes)
[Answer]
# [Desmos](https://desmos.com/calculator), ~~169~~ 168 bytes
```
L=l.count
I=[1...L]
B=mod(floor(2n/2^I),2)
k=i-l[i]
H=[1...k]0
A=[min(‚àë_{i=1}^Ljoin(H[k>H],[1...2l[i]-1+min(k,0)]0+1,I0)[I]B[i])B.totalforn=[1...2^L]]
f(l)=A[A>0].min
```
[Try It On Desmos!](https://www.desmos.com/calculator/jwxvjlvn20?nographpaper)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/hmmay3qe6m?nographpaper)
This brute forces every single umbrella combination, so expectedly this is very slow. In fact, this took about 40 or so seconds to finish running on my computer LOL.
Also, the code is absolutely horrendous and can definitely be golfed. I mean, just look at it....
[Answer]
**Raku 68 bytes**
```
map({$^a-$^b+1..^$^a+$^b},@_.kv).combinations.grep(^@_⊆*)>>.elems.min
```
simple brute force approch
[Try it online!](https://tio.run/##K0gtyjH7n1up4JCoYKugYaRjqGMCxYY6xjqGmtZc/6tzEws0qlXiEnVV4pK0DfX0gExtIFPXsFbHIV4vu0xTLzk/NykzL7EkMz@vWC@9KLVAI84h/lFXm5amnZ1eak5qbrFebmZerYZDoqZecWLl//8A "Perl 6 – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 113 bytes
Port of [@tsh's Python code](https://codegolf.stackexchange.com/a/266097/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##fY1BawIxEIXv/oo5zmBcN9aWdukWPArtSXoSD6lNtgkxanYOFvG3bxOrBWEpw8ybeXy8adfKq2774fSa4U3ZAMfuUxswqKqF3i/ngVfCVknqks5iDdpnVXgdGv4iOUykwBJ4C1dzJKkw1rOO6OoXN0o4OqJio3bZyMfQ5fNA2rcaym4AkJ9u0n9UsWkrmMWovpcLjjY0K6rgPViGGo6JBNgll31Ag6@2ZXwSEyHFXZrTvBERjMcg@1ApbuqCPvahOXN66Zx@hSd98P0vcu5cD//Bf4k3mafBqfsB)
```
def f(a:Seq[Int],i:Int=0):Int=if(i<a.length)1+f(a,(0 to a.length-1).filter(j=>j-i<a(j)).map(j=>a(j)+j).max)else 0
```
Ungolfed version. [Try it online!](https://tio.run/##fZBRS8MwFIXf@yvOY4Jxa@cULU7wUdEn8WnsIc6kpqSxpJlMpL@9Jmu6WShyueHm3o@Te9JsueZd9/lWiq3DM1cGPwnwLiQk4TmeVOPWD8ZtGFQOX2CFlA5VQAElQRRuwWdamMJ90NgHvrhGxfePu6r2NEmxM07pExgxYCaVdsKSEqs7lDjHQY@U9A9S8bqfhz7OUI5m@3jJ/MRvzoZ3e6iF0I047pX2zSRkdFt564Tboslxby3/Xr84q0yx8V5fjTqZrX3XaUMkCV9DbtiCZezCn8tQUUoxnyObQjM2ioheT6FBcxkzqA/wYgq@7JFDhrj6Dz4qjjTbpO26Xw)
```
object Main {
def f(a: List[Int], i: Int = 0): Int = {
if (i < a.length) {
val maxJump = (0 until a.length)
.filter(j => j - i < a(j))
.map(j => a(j) + j)
.max
1 + f(a, maxJump)
} else {
0
}
}
def main(args: Array[String]): Unit = {
println(f(List(9,2,1,3,2,4,2,1))) // 1
println(f(List(1,1,1,1,1,1,1,1))) // 8
println(f(List(2,1,4,1,4,1,1,3,1))) // 2
println(f(List(5,1,3,1,3,1,1,1,6))) // 2
println(f(List(4,1,1,3,1,1))) // 2
}
}
```
[Answer]
# [Python](https://www.python.org), 200 bytes
Not a very competitive answer, but it's the best I can do with the baseline python functions.
* l: is list of the beach spaces
* r: radius of already covered spaces
* p: amount of umbrellas and the final answer
Function goes through the beach from the left, finds the right most umbrella placing which covers all uncovered space to its left and reaches the farthest right.
The function then starts again with the spaces to the right of the last placed umbrella and now with info of which spaces on the left are already covered. When all spaces are covered prints out number of placed umbrellas.
Any tips for making this more streamlined are welcome, thank you.
```
def f(l,r=0,p=0):
m=r
for u in range(len(l)):
s=l[u]-1
if u-s-r<1 and u+s>=m:
m=u+s
t=u
if m>len(l)-2: return p+1
else: return f(l[t+1:],m, p+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZDBbsMgDIbvPIWPRDFSabtpi0ZfJMqhVWGLRGhE4LDX2HWXXrZn2Sv0bYoDzRRbBuvTb2P8_Tt-ho-Lu15_YjDi5fZ31gYMt-jVBke1qRoGyQbl59tcPEToHfije9fcasdtVTRkk7Jt7IRcQG8gikn4NwlHd4ZYTwc1_Otz70RXJKjISvFwyG-IbQNeh-gdjHVur-2kF5hGbkMtmw4HJEVV_vNlFbTtK25R4i6de8o6ZAmtnJDElROisn0JajDDp5zOQf5McFEkTccYLepEi7L5s6PvXeCGn6oy2WPjdw)
] |
[Question]
[
This is a somewhat [proof-golf](/questions/tagged/proof-golf "show questions tagged 'proof-golf'")-like [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. This is the cops' thread; [the robbers' thread is here.](https://codegolf.stackexchange.com/questions/157095/abstract-rewriting-challenge-robbers)
# Cops
Your task is to define an [abstract rewriting system](https://en.wikipedia.org/wiki/Abstract_rewriting_system) in which the reachability of one word from another is difficult to determine. You will prepare the following things:
1. A set of symbols, called the alphabet. (You may use any Unicode characters for these, but please don't use whitespace, or symbols that are hard to distinguish from each other.)
2. A *source string* composed of symbols from your alphabet.
3. A *target string* composed of symbols from your alphabet.
4. A set of rewrite rules using characters from your alphabet. (See below for the definition of a rewrite rule.)
5. A proof showing whether your source string can be converted into your target string by successive application of your rewrite rules. This proof might consist of an actual sequence of rewrite steps, or a mathematical proof that such a sequence must exist, or a mathematical proof that such a sequence does not exist.
You will post the first four of these, keeping the proof secret; the robbers will try to crack your answer by providing their own proof that your target string can or can not be reached from your source string. If your submission is not cracked within **two weeks**, you may mark it as safe and edit in your proof.
Submissions will be scored according to the number of characters in their rewrite rules and their source and target strings, as detailed below. The winner will be the uncracked submission with the lowest score.
**What is a rewrite rule?**
A rewrite rule is simply a pair of strings in your alphabet. (Either of these strings may be empty.) An application of a rewrite rule consists of finding a substring that is equal to the first string in the pair, and replacing it with the second.
An example should make this clear:
Suppose alphabet is `A`, `B` and `C`; the source string is "`A`"; the target string is "`C`" and the rewrite rules are
```
A:B
B:BB
B:A
AA:C
```
then the target string is reachable in the following way:
```
A
B (using rule 1)
BB (using rule 2)
AB (using rule 3)
AA (using rule 3)
C (using rule 4)
```
**Scoring**
Your score will be
* the length of your source string,
* plus the length of your target string,
* plus the length of all the strings included in your rewrite rules,
* plus one extra point for each rewrite rule.
If you write your rewrite rules with a colon separator as above, this is just the total length of all the rewrite rules (including the separator), plus the lengths of the source and target strings. A lower score is better. The number of distinct characters in your alphabet will be used to break ties, with fewer being better.
## Bounty
I'd like to see answers that really go for low scores. I will award **200 rep** to the first answer that scores less than 100 points in this challenge and doesn't get cracked.
[Answer]
## 326 points - [Cracked](https://codegolf.stackexchange.com/a/158452/21034) by jimmy23013
The level is Picokosmos #13 by Aymeric du Peloux (with a trivial modification). I tried to find a tasteful level that could be implemented with "boxes" and "walls" being the same character. For this level it was possible by making the central choke point two columns wide rather than one.
The rules/initial/target strings could be golfed a bit more, but this is just for fun.
Initial string:
```
___##___####_____##_#_#_##_#_!####______##_#####__####_#_######__###__
```
Target string:
```
___##___####_____##_#_#_##_#_#####____!__#_#####__####_#_######__###__
```
Rules:
```
_wW:!
_<:<_
Vv_:!
V_:_V
R:>>>>>>>>>>>>>
V#:#V
#w<:w#
>v_:_v
_wX:#
_!:!_
!:wLW_
L:<<<<<<<<<<<<<
#W:W#
!#_:_!#
_w<:w_
#<:<#
!:_VRv
>v#:#v
Uv_:#
_W:W_
_X:X_
>#:#>
#X:X#
U_:_U
Vv#:!URv
#wW:wLX!
>_:_>
!_:_!
_#!:#!_
U#:#U
```
[Answer]
# 171 points, [cracked by HyperNeutrino](https://codegolf.stackexchange.com/a/157170/68942)
Source: `YAAAT`
Target: `VW626206555675126212043640270477001760465526277571600601`
Rules:
```
T:AAAAAT
T:BBU
U:BU
U:ZW
AB:BCA
CB:BC
AZ:Z
CZ:ZC
YB:Y
YZ:V
V:VD
DCC:CD
DCW:W+
DW:W_
___:0
__+:1
_+_:2
_++:3
+__:4
+_+:5
++_:6
+++:7
```
Just something obvious to do. The actual sequence of rewrite steps probably won't fit in an SE answer.
[Answer]
## 33 points, [cracked by user71546](https://codegolf.stackexchange.com/a/157104/20260)
A simple one to start off.
Source: `xnor`
Target: `xor`
Rewrite rules:
```
x:xn
no:oon
nr:r
ooooooooooo:
```
The last rule takes 11 o's to the empty string.
[Answer]
# 139 points (safe-ish)
I intended this answer to be cracked, and user202729 basically solved it in the comments, but nobody posted an answer in the robbers' thread, so I'm marking it "safe-ish" and including my proof below.
(These things are evidently much easier to make than they are to crack. Nobody has tried to go for a really low score yet though, and there might be more fun to be had at that end of things, if this challenge ever takes off.)
---
Here's a self answer. It's potentially very hard, but should be easy if you work out where it came from.
alphabet: `ABCDE‚í∂‚í∑‚í∏‚íπ‚í∫‚íª‚¨õ‚ö™Ô∏èÔ∏èüéÇ‚Üê‚Üí`
source: `‚ÜêA‚Üí`
target: `‚ÜêüéÇ‚Üí`
Rules: (whitespace is not significant)
```
← : ←⬛
→ : ⬛→
A⬛ : ⚪B
A‚ö™ : ‚ö™‚í∑
⬛Ⓐ : E⚪
⚪Ⓐ : Ⓔ⚪
B⬛ : ⚪C
B‚ö™ : ‚ö™‚í∏
‚í∑‚¨õ : üéÇ
Ⓑ⚪ : ⚪Ⓕ
⬛C : D⚪
‚ö™C : ‚íπ‚ö™
Ⓒ⬛ : ⬛B
Ⓒ⚪ : ⬛Ⓑ
D⬛ : ⚪E
D‚ö™ : ‚ö™‚í∫
⬛Ⓓ : C⬛
⚪Ⓓ : Ⓒ⬛
⬛E : A⚪
⚪E : Ⓐ⚪
Ⓔ⬛ : ⬛D
Ⓔ⚪ : ⬛Ⓓ
Ⓕ⬛ : ⚪C
Ⓕ⚪ : ⚪Ⓒ
‚¨õüéÇ : üéÇ
‚ö™üéÇ : üéÇ
üéÇ‚¨õ : üéÇ
üéÇ‚ö™ : üéÇ
```
---
[Here is an ASCII version](https://gist.github.com/nathanielvirgo/7da0ea7b6f8405f169ec835d5fb29453), in case that unicode doesn't display well for everyone.
---
## Proof
This is equivalent to the current best contender for a six state [busy beaver](https://en.wikipedia.org/wiki/Busy_beaver). A busy beaver is a Turing machine that halts after a really long time. Because of this, the source string `‚ÜêA‚Üí` can indeed be transformed into the target string `‚ÜêüéÇ‚Üí`, but only after more than `7*10^36534` steps, which would take vastly longer than the age of the universe for any physical implementation.
The Turing machine's tape is represented by the symbols `⬛` (0) and `⚪` (1). The rules
```
← : ←⬛
→ : ⬛→
```
mean that the ends of the tape can always be extended with more zeros. If the head of the Turing machine ever gets near one end of the tape we can just apply one of these rules, which allows us to pretend that the tape is infinite, and starts out filled with all zeros. (The symbols `‚Üí` and `‚Üê` are never created or destroyed, so they're always at the ends of the tape.)
The Turing machine's head is represented with the symbols `ABCDE‚í∂‚í∑‚í∏‚íπ‚í∫‚íª` and `üéÇ`. `A` means the head is in state `A` and the symbol under the head is a `‚¨õ` (0), whereas ‚í∂ means it's in state `A` and the symbol under it is a `‚ö™` (1). This is continued for the other states, with the circled letter representing a 1 underneath the head and the uncircled version representing a 0. (There is no symbol `F` because it happens that the head never ends up in state `F` with a 1 underneath it.)
The state `üéÇ` is the halting state. It has the special rules
```
‚¨õüéÇ : üéÇ
‚ö™üéÇ : üéÇ
üéÇ‚¨õ : üéÇ
üéÇ‚ö™ : üéÇ
```
If the halting state is ever reached we can repeatedly apply these rules to "suck in" all of the tape (including any extra zeros that arose from extending the tape more than necessary), leaving us in the state `‚ÜêüéÇ‚Üí`. Therefore the reachability problem boils down to whether the state `üéÇ` will ever be reached.
The remaining rules are the transition rules for the Turing machine. For example, the rules
```
A⬛ : ⚪B
A‚ö™ : ‚ö™‚í∑
```
can be read as "if the machine is in state A and there is a zero under the head, then write a 1, change to state B and move right." Moving right takes two rules, because the tape cell to the right might contain a `⬛`, in which case the machine should go into state `B`, or the cell might contain a `⚪`, in which case it should go into state `Ⓑ`, since there is a `⚪` underneath it.
Similarly,
```
⬛Ⓓ : C⬛
⚪Ⓓ : Ⓒ⬛
```
means "if the machine is in state D and there is a 1 under the head, then write a 0, change to state C and move left."
The Turing machine used was discovered by Pavel Kropitz in 2010. Although it's often mentioned in the context of busy beavers, its actual transition table is a little tricky to track down, but it can be found for example [here](http://www.logique.jussieu.fr/~michel/bbc.html). It can be written as
```
0 1
A 1RB 1LE
B 1RC 1RF
C 1LD 0RB
D 1RE 0LC
E 1LA 0RD
F 1RH 1RC
```
which can be read as "if the machine is in state A and there is a zero under the head, then write a 1, change to state B and move right," and so on. It should be straightforward, if laborious, to check that each entry of this table corresponds to a pair of rules as described above.
The only exception is the rule `1RH` that occurs when the machine is in state F over a 0, because it seemed fairly pointless to make the machine write a 1 and move to the right when it could just halt immediately as soon as it ever enters state F over a 0. So I changed the rule that would have been
```
Ⓑ⬛ : ⚪F
```
into
```
‚í∑‚¨õ : üéÇ
```
This is why there is no symbol `F` in the alphabet. (There are some other 'golfs' I could have made, but I didn't want to obscure it too much.)
That's basically it. The target string is reachable from the source string, but only after a ridiculous number of steps.
One more fun fact: if I had used
`‚ÜêA‚ö™‚ö™‚Üí`
as the starting point instead, then it would take not `7*10^36534` steps to halt, but `10^10^10^10^18705352` steps, which is a very big number indeed.
[Answer]
# 287 points, safe
Source: `YAAT`
Target:
```
VW644507203420630255035757474755142053542246325217734264734527745236024300376212053464720055350477167345032015327021403167165534313137253235506613164473217702550435776242713
```
Rules:
```
T:AAAAAT
T:BBU
U:BU
U:ZW
AB:BCA
CB:BC
AZ:Z
CZ:ZC
YB:Y
YZ:V
V:VD
DCC:CD
DCW:W+
DW:W_
___:0
__+:1
_+_:2
_++:3
+__:4
+_+:5
++_:6
+++:7
```
I found that openssl is much easier to use than gpg for this purpose.
---
See [HyperNeutrino's crack](https://codegolf.stackexchange.com/a/157170/25180) to the weaker version. In this case, The number of `C`s is:
```
22030661124527021657244569669713986649562044939414344827127551659400215941242670121250289039666163853124410625741840610262419007778597078437731811349579211
```
And the prime factors are:
```
220040395270643587721928041668579651570457474080109642875632513424514300377757
100120985046540745657156603717368093083538096517411033964934953688222272684423
```
The first number mod 5 = 2, so it is possible to get the final string.
[Answer]
# 48 points, [cracked](https://codegolf.stackexchange.com/a/157114/60483) by [bb94](https://codegolf.stackexchange.com/users/14109/bb94)
Alphabet: `abc`
Source: `cbaabaabc`
Target: `cbacbcabc`
```
ab:ba
bc:cb
ca:ac
ab:cc
bc:aa
ca:bb
```
[Answer]
# 402 points
Alphabet: `abcdefghijklmnopqrstu`
Source: `abcdoi`
Target: `ioabcdnnnnnnnnnnnnnnnnnn`
Rewrite rules:
```
ab:ba
ba:ab
ac:ca
ca:ac
ad:da
da:ad
bc:cb
cb:bc
bd:db
db:bd
cd:dc
dc:cd
na:an
nb:bn
nc:cn
nd:dn
nm:mn
nj:jn
aoi:eag
boi:ebg
coi:ecg
doi:edg
ae:ha
be:hb
ce:hc
de:hd
ioa:kam
iob:kbm
ioc:kcm
iod:kdm
ma:aj
mb:bj
mc:cj
md:dj
dg:rdnnnnnnnnnn
cg:qcnnnnn
bg:pbnn
ag:fan
cr:fc
br:fb
ar:fa
bq:fb
aq:fa
ap:fa
er:io
eq:io
ep:io
ef:io
hf:io
kd:dunnnnnnnnnn
kc:ctnnnnn
kb:bsnn
ka:aln
uc:cl
ub:bl
ua:al
tb:bl
ta:al
sa:al
um:oi
tm:oi
sm:oi
lm:oi
lj:oi
:n
```
The last rule allows you to create as many `n`s as you need.
Ugly as it seems, it's actually quite nice, one way or another...
[Answer]
# 1337 Points
Definitely not competitive, and took way too long to create (I hope I made no mistake).
Hint:
>
> try to understand the source string before looking at the rules
>
>
>
Alphabet: `ABEILRSTabcdefijlr`
Source:
`SIbbbbbbbdbffacebbfadbdbeecddfaeebddcefaddbdbeeecddaaaaadfaeeebdddcefbbfadbdbdbeeecdddfaeeebdddcefaddbdbeeecddaaaadfaeeebdddcefbfadbdbdbeeecdddfaeeebdddcbdbffacebfadbdbeecddfaeebddceeefadddbdbeeeecddddfaeeeebddddceefaddbdbeeecdddfaeeebdddceefadadbefadfacdbeecddfaeebddcefaeeefaddbdbeeecdddfaeeebdddcceecdfaeeaddceecefaeadcbefadfacecdfaebdceeeeefadddddbdbeeeeeecddddddfaeeeeeebddddddceeefaddaeecdddbdbffacebfadbdbeecddfaeebddceeefadddbdbeeeecddddfaeeeebddddceefaddbdbeeecdddfaeeebdddceefadadbefadfacdbeecddfaeebddcefaeeefaddbdbeeecdddfaeeebdddcceecdfaeeaddceecefaeadcbefadfacecdfaebdcefaefaeeebdddcdcefaceeaaaceefacdffacebdceeeeefadddddbdbeeeeeecddddddfaeeeeeebddddddceeefaddaeecdddbdbffacebfadbdbeecddfaeebddceeefadddbdbeeeecddddfaeeeebddddceefaddbdbeeecdddfaeeebdddceefadadbefadfacdbeecddfaeebddcefaeeefaddbdbeeecdddfaeeebdddcceecdfaeeaddceecefaeadcbefadfacecdfaebdcefaefaeeebdddcdcefaceeaaaaceefacdffacebdcecefacE`
Target: `SE`
Rewrite rules:
```
Ab:bA
bA:Ab
Aa:aA
aA:Aa
Ad:dA
dA:Ad
Ae:eA
eA:Ae
Af:fA
fA:Af
Ac:cA
cA:Ac
IA:AI
AI:IA
Bb:bB
bB:Bb
Ba:aB
aB:Ba
Bd:dB
eB:Be
Be:eB
dB:Bd
Bf:fB
fB:Bf
Bc:cB
cB:Bc
E:BE
S:SB
Ib:AbI
AIa:aI
IdB:dBI
BIe:eIB
AIf:AfI
BIfB:BfiLB
Lb:bL
La:aL
Le:eL
Ld:dL
Lf:fL
Lc:cL
ib:bi
ia:ai
ie:ei
id:di
if:fil
lb:bl
la:al
le:el
ld:dl
lf:fl
lc:cl
icl:ci
icL:cI
Ic:jRc
bj:jb
aj:ja
dj:jd
ej:je
br:rb
ar:ra
dr:rd
er:re
fr:rf
cr:rc
bR:Rb
aR:Ra
dR:Rd
eR:Re
fR:Rf
cR:Rc
cj:jrc
fjr:jf
fjR:If
I:T
TB:T
BT:T
bT:T
aT:T
dT:T
eT:T
fT:T
cT:T
T:
```
[Answer]
>
> Note that I made some mistakes initially, so the score was changed. Nevertheless, the idea is the same. I hope there are no more mistakes now.
>
>
>
---
# 154 Points
Alphabet: `P.!xABC[{mD<`
Source: `[x!P.P...P..P.P....P..P.P.....P.P....P......P.P..P...P.P...Pm` (61 characters)
Target: `{CCCCC<` (there are 5 `C`s, so 7 characters)
Rules:
```
P. ‚Üí .PP
!. ‚Üí !
x ‚Üí AxB
x ‚Üí
AB ‚Üí BAC
CB ‚Üí BC
CA ‚Üí AC
[B ‚Üí [
[A ‚Üí {
{A ‚Üí {
! ‚Üí !m
mP ‚Üí PmD
Dm ‚Üí mD
DP ‚Üí PD
!P ‚Üí ?
?P ‚Üí ?
!m ‚Üí <
<m ‚Üí <
C<D ‚Üí <
```
There are 19 rules, total number of characters = 67.
[Answer]
# 106 points - cracked by [HyperNeutrino](https://codegolf.stackexchange.com/a/157534/68546)
Alphabet: `ABCDEFGHIJ`
Source: `FIABCJAGJDEHHID`
Target: `F`
Rewrite Rules:
```
B:DCIE
A:IFBA
D:EEFJ
C:GFIC
E:HBJG
F:FEBG
G:HFCJ
H:DIGB
I:FCAH
J:BHEA
EJGI:FF
FFF:J
FF:E
EE:D
DDEA:FI
I:F
```
---
Okay, HyperNeutrino has proved that this is unsolvable. However, there is another solution to this.
---
Take:
```
I E C D H G J A F B
1 2 3 4 5 6 7 8 9 10
```
The value of the source is even. The value of the target is odd. If we take each side, total the value, and take the value to mod 2, the values stay the same. Therefore, this cannot be achieved.
] |
[Question]
[
The challenge is to write the fastest code possible for computing the [permanent of a matrix](https://en.wikipedia.org/wiki/Permanent_(mathematics)).
The permanent of an `n`-by-`n` matrix `A` = (`a``i,j`) is defined as
[](https://i.stack.imgur.com/GOz7G.png)
Here `S_n` represents the set of all permutations of `[1, n]`.
As an example (from the wiki):
[](https://i.stack.imgur.com/Qr1OJ.png)
In this question matrices are all square and will only have the values `-1` and `1` in them.
**Examples**
Input:
```
[[ 1 -1 -1 1]
[-1 -1 -1 1]
[-1 1 -1 1]
[ 1 -1 -1 1]]
```
Permanent:
```
-4
```
Input:
```
[[-1 -1 -1 -1]
[-1 1 -1 -1]
[ 1 -1 -1 -1]
[ 1 -1 1 -1]]
```
Permanent:
```
0
```
Input:
```
[[ 1 -1 1 -1 -1 -1 -1 -1]
[-1 -1 1 1 -1 1 1 -1]
[ 1 -1 -1 -1 -1 1 1 1]
[-1 -1 -1 1 -1 1 1 1]
[ 1 -1 -1 1 1 1 1 -1]
[-1 1 -1 1 -1 1 1 -1]
[ 1 -1 1 -1 1 -1 1 -1]
[-1 -1 1 -1 1 1 1 1]]
```
Permanent:
```
192
```
Input:
```
[[1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1],
[1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, 1, 1, -1],
[-1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, 1, -1, -1],
[-1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1],
[-1, 1, 1, 1, -1, 1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1],
[1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1, -1],
[1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1],
[1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1],
[1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1],
[-1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1],
[-1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1],
[1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1],
[-1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, 1, -1, 1],
[1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1],
[1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1],
[1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1],
[-1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1],
[1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, 1],
[1, 1, 1, -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, 1, -1, -1, -1, -1, 1],
[-1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1]]
```
Permanent:
```
1021509632
```
**The task**
You should write code that, given an `n` by `n` matrix, outputs its permanent.
As I will need to test your code it would be helpful if you could give a simple way for me to give a matrix as input to your code, for example by reading from standard in.
Be warned that the permanent can be large (the all 1s matrix is the extreme case).
**Scores and ties**
I will test your code on random +-1 matrices of increasing size and stop the first time your code takes more than 1 minute on my computer. The scoring matrices will be consistent for all submissions in order to ensure fairness.
If two people get the same score then the winner is the one which is fastest for that value of `n`. If those are within 1 second of each other then it is the one posted first.
**Languages and libraries**
You can use any available language and libraries you like but no pre-existing function to compute the permanent. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible.`
**Reference implementations**
There is already a [codegolf question](https://codegolf.stackexchange.com/questions/96825/codegolf-the-permanent) question with lots of code in different languages for computing the permanent for small matrices. [Mathematica](https://reference.wolfram.com/language/ref/Permanent.html) and [Maple](https://www.maplesoft.com/support/help/Maple/view.aspx?path=LinearAlgebra%2FPermanent) also both have permanent implementations if you can access those.
**My Machine** The timings will be run on my 64-bit machine. This is a standard ubuntu install with 8GB RAM, AMD FX-8350 Eight-Core Processor and Radeon HD 4250. This also means I need to be able to run your code.
**Low level information about my machine**
`cat /proc/cpuinfo/|grep flags` gives
>
> flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov
> pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr\_opt
> pdpe1gb rdtscp lm constant\_tsc rep\_good nopl nonstop\_tsc extd\_apicid
> aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4\_1 sse4\_2 popcnt
> aes xsave avx f16c lahf\_lm cmp\_legacy svm extapic cr8\_legacy abm sse4a
> misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 tce
> nodeid\_msr tbm topoext perfctr\_core perfctr\_nb cpb hw\_pstate vmmcall
> bmi1 arat npt lbrv svm\_lock nrip\_save tsc\_scale vmcb\_clean flushbyasid
> decodeassists pausefilter pfthreshold
>
>
>
I will ask a closely related follow up multi-language question that doesn't suffer from the big Int problem so lovers of [Scala](https://en.wikipedia.org/wiki/Scala_(programming_language)), [Nim](https://en.wikipedia.org/wiki/Nim_(programming_language)), [Julia](https://en.wikipedia.org/wiki/Julia_(programming_language)), [Rust](https://en.wikipedia.org/wiki/Rust_(programming_language)), [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) can show off their languages too.
**Leader board**
* n = 33 (45 seconds. 64 seconds for n = 34). **Ton Hospel** in *C++* with g++ 5.4.0.
* n = 32 (32 seconds). **Dennis** in **C** with gcc 5.4.0 using Ton Hospel's gcc flags.
* n = 31 (54 seconds). **Christian Sievers** in **Haskell**
* n = 31 (60 seconds). **primo** in **rpython**
* n = 30 (26 seconds). **ezrast** in **Rust**
* n = 28 (49 seconds). **xnor** with **Python + pypy 5.4.1**
* n = 22 (25 seconds). **Shebang** with **Python + pypy 5.4.1**
*Note*. In practice the timings for Dennis and Ton Hospel's vary a lot for mysterious reasons. For example they seem to be faster after I have loaded a web browser! The timings quoted are the fastest in all the tests I have done.
[Answer]
# gcc C++ n ≈ 36 (57 seconds on my system)
Uses Glynn formula with a Gray code for updates if all column sums are even, otherwise uses Ryser's method. Threaded and vectorized. Optimized for AVX, so don't expect much on older processors. Don't bother with `n>=35` for a matrix with only +1's even if your system is fast enough since the signed 128 bit accumulator will overflow. For random matrices you will probably not hit the overflow. For `n>=37` the internal multipliers will start to overflow for an all `1/-1` matrix. So only use this program for `n<=36`.
Just give the matrix elements on STDIN separated by any kind of whitespace
```
permanent
1 2
3 4
^D
```
`permanent.cpp`:
```
/*
Compile using something like:
g++ -Wall -O3 -march=native -fstrict-aliasing -std=c++11 -pthread -s permanent.cpp -o permanent
*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstdint>
#include <climits>
#include <array>
#include <vector>
#include <thread>
#include <future>
#include <ctgmath>
#include <immintrin.h>
using namespace std;
bool const DEBUG = false;
int const CACHE = 64;
using Index = int_fast32_t;
Index glynn;
// Number of elements in our vectors
Index const POW = 3;
Index const ELEMS = 1 << POW;
// Over how many floats we distribute each row
Index const WIDTH = 9;
// Number of bits in the fraction part of a floating point number
int const FLOAT_MANTISSA = 23;
// Type to use for the first add/multiply phase
using Sum = float;
using SumN = __restrict__ Sum __attribute__((vector_size(ELEMS*sizeof(Sum))));
// Type to convert to between the first and second phase
using ProdN = __restrict__ int32_t __attribute__((vector_size(ELEMS*sizeof(int32_t))));
// Type to use for the third and last multiply phase.
// Also used for the final accumulator
using Value = __int128;
using UValue = unsigned __int128;
// Wrap Value so C++ doesn't really see it and we can put it in vectors etc.
// Needed since C++ doesn't fully support __int128
struct Number {
Number& operator+=(Number const& right) {
value += right.value;
return *this;
}
// Output the value
void print(ostream& os, bool dbl = false) const;
friend ostream& operator<<(ostream& os, Number const& number) {
number.print(os);
return os;
}
Value value;
};
using ms = chrono::milliseconds;
auto nr_threads = thread::hardware_concurrency();
vector<Sum> input;
// Allocate cache aligned datastructures
template<typename T>
T* alloc(size_t n) {
T* mem = static_cast<T*>(aligned_alloc(CACHE, sizeof(T) * n));
if (mem == nullptr) throw(bad_alloc());
return mem;
}
// Work assigned to thread k of nr_threads threads
Number permanent_part(Index n, Index k, SumN** more) {
uint64_t loops = (UINT64_C(1) << n) / nr_threads;
if (glynn) loops /= 2;
Index l = loops < ELEMS ? loops : ELEMS;
loops /= l;
auto from = loops * k;
auto to = loops * (k+1);
if (DEBUG) cout << "From=" << from << "\n";
uint64_t old_gray = from ^ from/2;
uint64_t bit = 1;
bool bits = (to-from) & 1;
Index nn = (n+WIDTH-1)/WIDTH;
Index ww = nn * WIDTH;
auto column = alloc<SumN>(ww);
for (Index i=0; i<n; ++i)
for (Index j=0; j<ELEMS; ++j) column[i][j] = 0;
for (Index i=n; i<ww; ++i)
for (Index j=0; j<ELEMS; ++j) column[i][j] = 1;
Index b;
if (glynn) {
b = n > POW+1 ? n - POW - 1: 0;
auto c = n-1-b;
for (Index k=0; k<l; k++) {
Index gray = k ^ k/2;
for (Index j=0; j< c; ++j)
if (gray & 1 << j)
for (Index i=0; i<n; ++i)
column[i][k] -= input[(b+j)*n+i];
else
for (Index i=0; i<n; ++i)
column[i][k] += input[(b+j)*n+i];
}
for (Index i=0; i<n; ++i)
for (Index k=0; k<l; k++)
column[i][k] += input[n*(n-1)+i];
for (Index k=1; k<l; k+=2)
column[0][k] = -column[0][k];
for (Index i=0; i<b; ++i, bit <<= 1) {
if (old_gray & bit) {
bits = bits ^ 1;
for (Index j=0; j<ww; ++j)
column[j] -= more[i][j];
} else {
for (Index j=0; j<ww; ++j)
column[j] += more[i][j];
}
}
for (Index i=0; i<n; ++i)
for (Index k=0; k<l; k++)
column[i][k] /= 2;
} else {
b = n > POW ? n - POW : 0;
auto c = n-b;
for (Index k=0; k<l; k++) {
Index gray = k ^ k/2;
for (Index j=0; j<c; ++j)
if (gray & 1 << j)
for (Index i=0; i<n; ++i)
column[i][k] -= input[(b+j)*n+i];
}
for (Index k=1; k<l; k+=2)
column[0][k] = -column[0][k];
for (Index i=0; i<b; ++i, bit <<= 1) {
if (old_gray & bit) {
bits = bits ^ 1;
for (Index j=0; j<ww; ++j)
column[j] -= more[i][j];
}
}
}
if (DEBUG) {
for (Index i=0; i<ww; ++i) {
cout << "Column[" << i << "]=";
for (Index j=0; j<ELEMS; ++j) cout << " " << column[i][j];
cout << "\n";
}
}
--more;
old_gray = (from ^ from/2) | UINT64_C(1) << b;
Value total = 0;
SumN accu[WIDTH];
for (auto p=from; p<to; ++p) {
uint64_t new_gray = p ^ p/2;
uint64_t bit = old_gray ^ new_gray;
Index i = __builtin_ffsl(bit);
auto diff = more[i];
auto c = column;
if (new_gray > old_gray) {
// Phase 1 add/multiply.
// Uses floats until just before loss of precision
for (Index i=0; i<WIDTH; ++i) accu[i] = *c++ -= *diff++;
for (Index j=1; j < nn; ++j)
for (Index i=0; i<WIDTH; ++i) accu[i] *= *c++ -= *diff++;
} else {
// Phase 1 add/multiply.
// Uses floats until just before loss of precision
for (Index i=0; i<WIDTH; ++i) accu[i] = *c++ += *diff++;
for (Index j=1; j < nn; ++j)
for (Index i=0; i<WIDTH; ++i) accu[i] *= *c++ += *diff++;
}
if (DEBUG) {
cout << "p=" << p << "\n";
for (Index i=0; i<ww; ++i) {
cout << "Column[" << i << "]=";
for (Index j=0; j<ELEMS; ++j) cout << " " << column[i][j];
cout << "\n";
}
}
// Convert floats to int32_t
ProdN prod32[WIDTH] __attribute__((aligned (32)));
for (Index i=0; i<WIDTH; ++i)
// Unfortunately gcc doesn't recognize the static_cast<int32_t>
// as a vector pattern, so force it with an intrinsic
#ifdef __AVX__
//prod32[i] = static_cast<ProdN>(accu[i]);
reinterpret_cast<__m256i&>(prod32[i]) = _mm256_cvttps_epi32(accu[i]);
#else // __AVX__
for (Index j=0; j<ELEMS; ++j)
prod32[i][j] = static_cast<int32_t>(accu[i][j]);
#endif // __AVX__
// Phase 2 multiply. Uses int64_t until just before overflow
int64_t prod64[3][ELEMS];
for (Index i=0; i<3; ++i) {
for (Index j=0; j<ELEMS; ++j)
prod64[i][j] = static_cast<int64_t>(prod32[i][j]) * prod32[i+3][j] * prod32[i+6][j];
}
// Phase 3 multiply. Collect into __int128. For large matrices this will
// actually overflow but that's ok as long as all 128 low bits are
// correct. Terms will cancel and the final sum can fit into 128 bits
// (This will start to fail at n=35 for the all 1 matrix)
// Strictly speaking this needs the -fwrapv gcc option
for (Index j=0; j<ELEMS; ++j) {
auto value = static_cast<Value>(prod64[0][j]) * prod64[1][j] * prod64[2][j];
if (DEBUG) cout << "value[" << j << "]=" << static_cast<double>(value) << "\n";
total += value;
}
total = -total;
old_gray = new_gray;
}
return bits ? Number{-total} : Number{total};
}
// Prepare datastructures, Assign work to threads
Number permanent(Index n) {
Index nn = (n+WIDTH-1)/WIDTH;
Index ww = nn*WIDTH;
Index rows = n > (POW+glynn) ? n-POW-glynn : 0;
auto data = alloc<SumN>(ww*(rows+1));
auto pointers = alloc<SumN *>(rows+1);
auto more = &pointers[0];
for (Index i=0; i<rows; ++i)
more[i] = &data[ww*i];
more[rows] = &data[ww*rows];
for (Index j=0; j<ww; ++j)
for (Index i=0; i<ELEMS; ++i)
more[rows][j][i] = 0;
Index loops = n >= POW+glynn ? ELEMS : 1 << (n-glynn);
auto a = &input[0];
for (Index r=0; r<rows; ++r) {
for (Index j=0; j<n; ++j) {
for (Index i=0; i<loops; ++i)
more[r][j][i] = j == 0 && i %2 ? -*a : *a;
for (Index i=loops; i<ELEMS; ++i)
more[r][j][i] = 0;
++a;
}
for (Index j=n; j<ww; ++j)
for (Index i=0; i<ELEMS; ++i)
more[r][j][i] = 0;
}
if (DEBUG)
for (Index r=0; r<=rows; ++r)
for (Index j=0; j<ww; ++j) {
cout << "more[" << r << "][" << j << "]=";
for (Index i=0; i<ELEMS; ++i)
cout << " " << more[r][j][i];
cout << "\n";
}
// Send work to threads...
vector<future<Number>> results;
for (auto i=1U; i < nr_threads; ++i)
results.emplace_back(async(DEBUG ? launch::deferred: launch::async, permanent_part, n, i, more));
// And collect results
auto r = permanent_part(n, 0, more);
for (auto& result: results)
r += result.get();
free(data);
free(pointers);
// For glynn we should double the result, but we will only do this during
// the final print. This allows n=34 for an all 1 matrix to work
// if (glynn) r *= 2;
return r;
}
// Print 128 bit number
void Number::print(ostream& os, bool dbl) const {
const UValue BILLION = 1000000000;
UValue val;
if (value < 0) {
os << "-";
val = -value;
} else
val = value;
if (dbl) val *= 2;
uint32_t output[5];
for (int i=0; i<5; ++i) {
output[i] = val % BILLION;
val /= BILLION;
}
bool print = false;
for (int i=4; i>=0; --i) {
if (print) {
os << setfill('0') << setw(9) << output[i];
} else if (output[i] || i == 0) {
print = true;
os << output[i];
}
}
}
// Read matrix, check for sanity
void my_main() {
Sum a;
while (cin >> a)
input.push_back(a);
size_t n = sqrt(input.size());
if (input.size() != n*n)
throw(logic_error("Read " + to_string(input.size()) +
" elements which does not make a square matrix"));
vector<double> columns_pos(n, 0);
vector<double> columns_neg(n, 0);
Sum *p = &input[0];
for (size_t i=0; i<n; ++i)
for (size_t j=0; j<n; ++j, ++p) {
if (*p >= 0) columns_pos[j] += *p;
else columns_neg[j] -= *p;
}
std::array<double,WIDTH> prod;
prod.fill(1);
int32_t odd = 0;
for (size_t j=0; j<n; ++j) {
prod[j%WIDTH] *= max(columns_pos[j], columns_neg[j]);
auto sum = static_cast<int32_t>(columns_pos[j] - columns_neg[j]);
odd |= sum;
}
glynn = (odd & 1) ^ 1;
for (Index i=0; i<WIDTH; ++i)
// A float has an implicit 1. in front of the fraction so it can
// represent 1 bit more than the mantissa size. And 1 << (mantissa+1)
// itself is in fact representable
if (prod[i] && log2(prod[i]) > FLOAT_MANTISSA+1)
throw(range_error("Values in matrix are too large. A subproduct reaches " + to_string(prod[i]) + " which doesn't fit in a float without loss of precision"));
for (Index i=0; i<3; ++i) {
auto prod3 = prod[i] * prod[i+3] * prod[i+6];
if (log2(prod3) >= CHAR_BIT*sizeof(int64_t)-1)
throw(range_error("Values in matrix are too large. A subproduct reaches " + to_string(prod3) + " which doesn't fit in an int64"));
}
nr_threads = pow(2, ceil(log2(static_cast<float>(nr_threads))));
uint64_t loops = UINT64_C(1) << n;
if (glynn) loops /= 2;
if (nr_threads * ELEMS > loops)
nr_threads = max(loops / ELEMS, UINT64_C(1));
// if (DEBUG) nr_threads = 1;
cout << n << " x " << n << " matrix, method " << (glynn ? "Glynn" : "Ryser") << ", " << nr_threads << " threads" << endl;
// Go for the actual calculation
auto start = chrono::steady_clock::now();
auto perm = permanent(n);
auto end = chrono::steady_clock::now();
auto elapsed = chrono::duration_cast<ms>(end-start).count();
cout << "Permanent=";
perm.print(cout, glynn);
cout << " (" << elapsed / 1000. << " s)" << endl;
}
// Wrapper to print any exceptions
int main() {
try {
my_main();
} catch(exception& e) {
cerr << "Error: " << e.what() << endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
```
[Answer]
# C99, n ≈ 33 (35 seconds)
```
#include <stdint.h>
#include <stdio.h>
#define CHUNK_SIZE 12
#define NUM_THREADS 8
#define popcnt __builtin_popcountll
#define BILLION (1000 * 1000 * 1000)
#define UPDATE_ROW_PPROD() \
update_row_pprod(row_pprod, row, rows, row_sums, mask, mask_popcnt)
typedef __int128 int128_t;
static inline int64_t update_row_pprod
(
int64_t* row_pprod, int64_t row, int64_t* rows,
int64_t* row_sums, int64_t mask, int64_t mask_popcnt
)
{
int64_t temp = 2 * popcnt(rows[row] & mask) - mask_popcnt;
row_pprod[0] *= temp;
temp -= 1;
row_pprod[1] *= temp;
temp -= row_sums[row];
row_pprod[2] *= temp;
temp += 1;
row_pprod[3] *= temp;
return row + 1;
}
int main(int argc, char* argv[])
{
int64_t size = argc - 1, rows[argc - 1];
int64_t row_sums[argc - 1];
int128_t permanent = 0, sign = size & 1 ? -1 : 1;
if (argc == 2)
{
printf("%d\n", argv[1][0] == '-' ? -1 : 1);
return 0;
}
for (int64_t row = 0; row < size; row++)
{
char positive = argv[row + 1][0] == '+' ? '-' : '+';
sign *= ',' - positive;
rows[row] = row_sums[row] = 0;
for (char* p = &argv[row + 1][1]; *p; p++)
{
rows[row] <<= 1;
rows[row] |= *p == positive;
row_sums[row] += *p == positive;
}
row_sums[row] = 2 * row_sums[row] - size;
}
#pragma omp parallel for reduction(+:permanent) num_threads(NUM_THREADS)
for (int64_t mask = 1; mask < 1LL << (size - 1); mask += 2)
{
int64_t mask_popcnt = popcnt(mask);
int64_t row = 0;
int128_t row_prod = 1 - 2 * (mask_popcnt & 1);
int128_t row_prod_high = -row_prod;
int128_t row_prod_inv = row_prod;
int128_t row_prod_inv_high = -row_prod;
for (int64_t chunk = 0; chunk < size / CHUNK_SIZE; chunk++)
{
int64_t row_pprod[4] = {1, 1, 1, 1};
for (int64_t i = 0; i < CHUNK_SIZE; i++)
row = UPDATE_ROW_PPROD();
row_prod *= row_pprod[0], row_prod_high *= row_pprod[1];
row_prod_inv *= row_pprod[3], row_prod_inv_high *= row_pprod[2];
}
int64_t row_pprod[4] = {1, 1, 1, 1};
while (row < size)
row = UPDATE_ROW_PPROD();
row_prod *= row_pprod[0], row_prod_high *= row_pprod[1];
row_prod_inv *= row_pprod[3], row_prod_inv_high *= row_pprod[2];
permanent += row_prod + row_prod_high + row_prod_inv + row_prod_inv_high;
}
permanent *= sign;
if (permanent < 0)
printf("-"), permanent *= -1;
int32_t output[5], print = 0;
output[0] = permanent % BILLION, permanent /= BILLION;
output[1] = permanent % BILLION, permanent /= BILLION;
output[2] = permanent % BILLION, permanent /= BILLION;
output[3] = permanent % BILLION, permanent /= BILLION;
output[4] = permanent % BILLION;
if (output[4])
printf("%u", output[4]), print = 1;
if (print)
printf("%09u", output[3]);
else if (output[3])
printf("%u", output[3]), print = 1;
if (print)
printf("%09u", output[2]);
else if (output[2])
printf("%u", output[2]), print = 1;
if (print)
printf("%09u", output[1]);
else if (output[1])
printf("%u", output[1]), print = 1;
if (print)
printf("%09u\n", output[0]);
else
printf("%u\n", output[0]);
}
```
Input is currently a bit cumbersome; it is taken with rows as command line arguments, where each entry is represented by its sign, i.e., **+** indicates a **1** and **-** indicates a **-1**.
### Test run
```
$ gcc -Wall -std=c99 -march=native -Ofast -fopenmp -fwrapv -o permanent permanent.c
$ ./permanent +--+ ---+ -+-+ +--+
-4
$ ./permanent ---- -+-- +--- +-+-
0
$ ./permanent +-+----- --++-++- +----+++ ---+-+++ +--++++- -+-+-++- +-+-+-+- --+-++++
192
$ ./permanent +-+--+++----++++-++- +-+++++-+--+++--+++- --+++----+-+++---+-- ---++-++++++------+- -+++-+++---+-+-+++++ +-++--+-++++-++-+--- +--+---+-++++---+++- +--+-++-+++-+-+++-++ +-----+++-----++-++- --+-+-++-+-++++++-++ -------+----++++---- ++---++--+-++-++++++ -++-----++++-----+-+ ++---+-+----+-++-+-+ +++++---+++-+-+++-++ +--+----+--++-+----- -+++-++--+++--++--++ ++--++-++-+++-++-+-+ +++---+--++---+----+ -+++-------++-++-+--
1021509632
$ time ./permanent +++++++++++++++++++++++++++++++{,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,} # 31
8222838654177922817725562880000000
real 0m8.365s
user 1m6.504s
sys 0m0.000s
$ time ./permanent ++++++++++++++++++++++++++++++++{,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,} # 32
263130836933693530167218012160000000
real 0m17.013s
user 2m15.226s
sys 0m0.001s
$ time ./permanent +++++++++++++++++++++++++++++++++{,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,} # 33
8683317618811886495518194401280000000
real 0m34.592s
user 4m35.354s
sys 0m0.001s
```
[Answer]
## Python 2, n ≈ 28
```
from operator import mul
def fast_glynn_perm(M):
row_comb = [sum(c) for c in zip(*M)]
n=len(M)
total = 0
old_grey = 0
sign = +1
binary_power_dict = {2**i:i for i in range(n)}
num_loops = 2**(n-1)
for bin_index in xrange(1, num_loops + 1):
total += sign * reduce(mul, row_comb)
new_grey = bin_index^(bin_index/2)
grey_diff = old_grey ^ new_grey
grey_diff_index = binary_power_dict[grey_diff]
new_vector = M[grey_diff_index]
direction = 2 * cmp(old_grey,new_grey)
for i in range(n):
row_comb[i] += new_vector[i] * direction
sign = -sign
old_grey = new_grey
return total/num_loops
```
Uses the [Glynn formula](https://en.wikipedia.org/wiki/Computing_the_permanent#CITEREFBalasubramanian1980) with a [Gray code](https://en.wikipedia.org/wiki/Gray_code) for updates. Runs up to `n=23` in a minute on my machine. One can surely do better implementing this in a faster language and with better data structures. This doesn't use that the matrix is ±1-valued.
A Ryser formula implementation is very similar, summing over all 0/1 vectors of coefficients rather than ±1-vectors. It takes about twice as long as Glynn's formula because adds over all 2^n such vectors, whereas Glynn's halves that using symmetry to only those starting with `+1`.
```
from operator import mul
def fast_ryser_perm(M):
n=len(M)
row_comb = [0] * n
total = 0
old_grey = 0
sign = +1
binary_power_dict = {2**i:i for i in range(n)}
num_loops = 2**n
for bin_index in range(1, num_loops) + [0]:
total += sign * reduce(mul, row_comb)
new_grey = bin_index^(bin_index/2)
grey_diff = old_grey ^ new_grey
grey_diff_index = binary_power_dict[grey_diff]
new_vector = M[grey_diff_index]
direction = cmp(old_grey, new_grey)
for i in range(n):
row_comb[i] += new_vector[i] * direction
sign = -sign
old_grey = new_grey
return total * (-1)**n
```
[Answer]
## Haskell, n=31 (54s)
With a lot of invaluable contributions by @Angs: use `Vector`, use short circuit products, look at odd n.
```
import Control.Parallel.Strategies
import qualified Data.Vector.Unboxed as V
import Data.Int
type Row = V.Vector Int8
x :: Row -> [Row] -> Integer -> Int -> Integer
x p (v:vs) m c = let c' = c - 1
r = if c>0 then parTuple2 rseq rseq else r0
(a,b) = ( x p vs m c' ,
x (V.zipWith(-) p v) vs (-m) c' )
`using` r
in a+b
x p _ m _ = prod m p
prod :: Integer -> Row -> Integer
prod m p = if 0 `V.elem` p then 0
else V.foldl' (\a b->a*fromIntegral b) m p
p, pt :: [Row] -> Integer
p (v:vs) = x (foldl (V.zipWith (+)) v vs) (map (V.map (2*)) vs) 1 11
`div` 2^(length vs)
p [] = 1 -- handle 0x0 matrices too :-)
pt (v:vs) | even (length vs) = p ((V.map (2*) v) : vs ) `div` 2
pt mat = p mat
main = getContents >>= print . pt . map V.fromList . read
```
My first attempts at parallelism in Haskell. You can see a lot of optimization steps through the revision history. Amazingly, it were mostly very small changes. The code is based on the formula in the section "Balasubramanian-Bax/Franklin-Glynn formula" in the Wikipedia article on [computing the permanent](https://en.wikipedia.org/wiki/Computing_the_permanent).
`p` computes the permanent. It is called via `pt` which transforms the matrix in a way that is always valid, but especially useful for the matrices that we get here.
Compile with `ghc -O2 -threaded -fllvm -feager-blackholing -o <name> <name>.hs`. To run with parallelisation, give it runtime parameters like this: `./<name> +RTS -N`. Input is from stdin with nested comma separated lists in brackets like `[[1,2],[3,4]]` as in the last example (newlines allowed everywhere).
[Answer]
# Python 2, n = 22 [Reference]
This is the 'reference' implementation I shared with Lembik yesterday, it misses making it to `n=23` by a few seconds on his machine, on my machine it does it in about 52 seconds. To achieve these speeds you need to run this through PyPy.
The first function calculates the permanent similar to how the determinant could be calculated, by going over each submatrix until you are left with a 2x2 which you can apply the basic rule to. It is *incredibly slow*.
The second function is the one implementing the Ryser function (the second equation listed in Wikipedia). The set `S` is essentially the powerset of the numbers `{1,...,n}` (variable `s_list` in the code).
```
from random import *
from time import time
from itertools import*
def perm(a): # naive method, recurses over submatrices, slow
if len(a) == 1:
return a[0][0]
elif len(a) == 2:
return a[0][0]*a[1][1]+a[1][0]*a[0][1]
else:
tsum = 0
for i in xrange(len(a)):
transposed = [zip(*a)[j] for j in xrange(len(a)) if j != i]
tsum += a[0][i] * perm(zip(*transposed)[1:])
return tsum
def perm_ryser(a): # Ryser's formula, using matrix entries
maxn = len(a)
n_list = range(1,maxn+1)
s_list = chain.from_iterable(combinations(n_list,i) for i in range(maxn+1))
total = 0
for st in s_list:
stotal = (-1)**len(st)
for i in xrange(maxn):
stotal *= sum(a[i][j-1] for j in st)
total += stotal
return total*((-1)**maxn)
def genmatrix(d):
mat = []
for x in xrange(d):
row = []
for y in xrange(d):
row.append([-1,1][randrange(0,2)])
mat.append(row)
return mat
def main():
for i in xrange(1,24):
k = genmatrix(i)
print 'Matrix: (%dx%d)'%(i,i)
print '\n'.join('['+', '.join(`j`.rjust(2) for j in a)+']' for a in k)
print 'Permanent:',
t = time()
p = perm_ryser(k)
print p,'(took',time()-t,'seconds)'
if __name__ == '__main__':
main()
```
[Answer]
# Rust + extprim
This straightforward Ryser with Gray code implementation takes about ~~65~~ 90 seconds to run n=31 on my laptop. ~~I imagine your machine will get there in well under 60s.~~ I'm using extprim 1.1.1 for `i128`.
I have never used Rust and have no idea what I'm doing. No compiler options other than whatever `cargo build --release` does. Comments/suggestions/optimizations are appreciated.
Invocation is identical to Dennis' program.
```
use std::env;
use std::thread;
use std::sync::Arc;
use std::sync::mpsc;
extern crate extprim;
use extprim::i128::i128;
static THREADS : i64 = 8; // keep this a power of 2.
fn main() {
// Read command line args for the matrix, specified like
// "++- --- -+-" for [[1, 1, -1], [-1, -1, -1], [-1, 1, -1]].
let mut args = env::args();
args.next();
let mat : Arc<Vec<Vec<i64>>> = Arc::new(args.map( |ss|
ss.trim().bytes().map( |cc| if cc == b'+' {1} else {-1}).collect()
).collect());
// Figure how many iterations each thread has to do.
let size = 2i64.pow(mat.len() as u32);
let slice_size = size / THREADS; // Assumes divisibility.
let mut accumulator : i128;
if slice_size >= 4 { // permanent() requires 4 divides slice_size
let (tx, rx) = mpsc::channel();
// Launch threads.
for ii in 0..THREADS {
let mat = mat.clone();
let tx = tx.clone();
thread::spawn(move ||
tx.send(permanent(&mat, ii * slice_size, (ii+1) * slice_size))
);
}
// Accumulate results.
accumulator = extprim::i128::ZERO;
for _ in 0..THREADS {
accumulator += rx.recv().unwrap();
}
}
else { // Small matrix, don't bother threading.
accumulator = permanent(&mat, 0, size);
}
println!("{}", accumulator);
}
fn permanent(mat: &Vec<Vec<i64>>, start: i64, end: i64) -> i128 {
let size = mat.len();
let sentinel = std::i64::MAX / size as i64;
let mut bits : Vec<bool> = Vec::with_capacity(size);
let mut sums : Vec<i64> = Vec::with_capacity(size);
// Initialize gray code bits.
let gray_number = start ^ (start / 2);
for row in 0..size {
bits.push((gray_number >> row) % 2 == 1);
sums.push(0);
}
// Initialize column sums
for row in 0..size {
if bits[row] {
for column in 0..size {
sums[column] += mat[row][column];
}
}
}
// Do first two iterations with initial sums
let mut total = product(&sums, sentinel);
for column in 0..size {
sums[column] += mat[0][column];
}
bits[0] = true;
total -= product(&sums, sentinel);
// Do rest of iterations updating gray code bits incrementally
let mut gray_bit : usize;
let mut idx = start + 2;
while idx < end {
gray_bit = idx.trailing_zeros() as usize;
if bits[gray_bit] {
for column in 0..size {
sums[column] -= mat[gray_bit][column];
}
bits[gray_bit] = false;
}
else {
for column in 0..size {
sums[column] += mat[gray_bit][column];
}
bits[gray_bit] = true;
}
total += product(&sums, sentinel);
if bits[0] {
for column in 0..size {
sums[column] -= mat[0][column];
}
bits[0] = false;
}
else {
for column in 0..size {
sums[column] += mat[0][column];
}
bits[0] = true;
}
total -= product(&sums, sentinel);
idx += 2;
}
return if size % 2 == 0 {total} else {-total};
}
#[inline]
fn product(sums : &Vec<i64>, sentinel : i64) -> i128 {
let mut ret : Option<i128> = None;
let mut tally = sums[0];
for ii in 1..sums.len() {
if tally.abs() >= sentinel {
ret = Some(ret.map_or(i128::new(tally), |n| n * i128::new(tally)));
tally = sums[ii];
}
else {
tally *= sums[ii];
}
}
if ret.is_none() {
return i128::new(tally);
}
return ret.unwrap() * i128::new(tally);
}
```
[Answer]
# Mathematica, n ≈ 20
```
p[m_] := Last[Fold[Take[ListConvolve[##, {1, -1}, 0], 2^Length[m]]&,
Table[If[IntegerQ[Log2[k]], m[[j, Log2[k] + 1]], 0], {j, n}, {k, 0, 2^Length[m] - 1}]]]
```
Using the `Timing` command, a 20x20 matrix requires about 48 seconds on my system. This is not exactly as efficient as the other since it relies on the fact that the permanent can be found as the coefficient of the product of polymomials from each row of the matrix. Efficient polynomial multiplication is performed by creating the coefficient lists and performing convolution using `ListConvolve`. This requires about *O*(2*n* *n*2) time assuming convolution is performed using a Fast Fourier transform or similar which requires *O*(*n* log *n*) time.
[Answer]
# RPython 5.4.1, n ≈ 32 (37 seconds)
```
from rpython.rlib.rtime import time
from rpython.rlib.rarithmetic import r_int, r_uint
from rpython.rlib.rrandom import Random
from rpython.rlib.rposix import pipe, close, read, write, fork, waitpid
from rpython.rlib.rbigint import rbigint
from math import log, ceil
from struct import pack
bitsize = len(pack('l', 1)) * 8 - 1
bitcounts = bytearray([0])
for i in range(16):
b = bytearray([j+1 for j in bitcounts])
bitcounts += b
def bitcount(n):
bits = 0
while n:
bits += bitcounts[n & 65535]
n >>= 16
return bits
def main(argv):
if len(argv) < 2:
write(2, 'Usage: %s NUM_THREADS [N]'%argv[0])
return 1
threads = int(argv[1])
if len(argv) > 2:
n = int(argv[2])
rnd = Random(r_uint(time()*1000))
m = []
for i in range(n):
row = []
for j in range(n):
row.append(1 - r_int(rnd.genrand32() & 2))
m.append(row)
else:
m = []
strm = ""
while True:
buf = read(0, 4096)
if len(buf) == 0:
break
strm += buf
rows = strm.split("\n")
for row in rows:
r = []
for val in row.split(' '):
r.append(int(val))
m.append(r)
n = len(m)
a = []
for row in m:
val = 0
for v in row:
val = (val << 1) | -(v >> 1)
a.append(val)
batches = int(ceil(n * log(n) / (bitsize * log(2))))
pids = []
handles = []
total = rbigint.fromint(0)
for i in range(threads):
r, w = pipe()
pid = fork()
if pid:
close(w)
pids.append(pid)
handles.append(r)
else:
close(r)
total = run(n, a, i, threads, batches)
write(w, total.str())
close(w)
return 0
for pid in pids:
waitpid(pid, 0)
for handle in handles:
strval = read(handle, 256)
total = total.add(rbigint.fromdecimalstr(strval))
close(handle)
print total.rshift(n-1).str()
return 0
def run(n, a, mynum, threads, batches):
start = (1 << n-1) * mynum / threads
end = (1 << n-1) * (mynum+1) / threads
dtotal = rbigint.fromint(0)
for delta in range(start, end):
pdelta = rbigint.fromint(1 - ((bitcount(delta) & 1) << 1))
for i in range(batches):
pbatch = 1
for j in range(i, n, batches):
pbatch *= n - (bitcount(delta ^ a[j]) << 1)
pdelta = pdelta.int_mul(pbatch)
dtotal = dtotal.add(pdelta)
return dtotal
def target(*args):
return main
```
To compile, [download](http://pypy.org/download.html) the most recent PyPy source, and execute the following:
```
pypy /path/to/pypy-src/rpython/bin/rpython matrix-permanent.py
```
The resulting executable will be named `matrix-permanent-c` or similiar in the current working directory.
As of PyPy 5.0, RPython's threading primitives are a lot less primitive than they used to be. Newly spawned threads require the GIL, which is more or less useless for parallel computations. I've used `fork` instead, so it may not work as expected on Windows, ~~although I haven't tested~~ fails to compile (`unresolved external symbol _fork`).
The executable accepts up to two command line parameters. The first is the number of threads, the second optional parameter is `n`. If it is provided, a random matrix will be generated, otherwise it will be read from stdin. Each row must be newline separated (without a trailing newline), and each value space separated. The third example input would be given as:
```
1 -1 1 -1 -1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 1 1 -1
1 -1 1 1 1 1 1 -1 1 -1 -1 1 1 1 -1 -1 1 1 1 -1
-1 -1 1 1 1 -1 -1 -1 -1 1 -1 1 1 1 -1 -1 -1 1 -1 -1
-1 -1 -1 1 1 -1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 1 -1
-1 1 1 1 -1 1 1 1 -1 -1 -1 1 -1 1 -1 1 1 1 1 1
1 -1 1 1 -1 -1 1 -1 1 1 1 1 -1 1 1 -1 1 -1 -1 -1
1 -1 -1 1 -1 -1 -1 1 -1 1 1 1 1 -1 -1 -1 1 1 1 -1
1 -1 -1 1 -1 1 1 -1 1 1 1 -1 1 -1 1 1 1 -1 1 1
1 -1 -1 -1 -1 -1 1 1 1 -1 -1 -1 -1 -1 1 1 -1 1 1 -1
-1 -1 1 -1 1 -1 1 1 -1 1 -1 1 1 1 1 1 1 -1 1 1
-1 -1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1
1 1 -1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 1 1 1 1 1 1
-1 1 1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 -1 1 -1 1
1 1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 1
1 1 1 1 1 -1 -1 -1 1 1 1 -1 1 -1 1 1 1 -1 1 1
1 -1 -1 1 -1 -1 -1 -1 1 -1 -1 1 1 -1 1 -1 -1 -1 -1 -1
-1 1 1 1 -1 1 1 -1 -1 1 1 1 -1 -1 1 1 -1 -1 1 1
1 1 -1 -1 1 1 -1 1 1 -1 1 1 1 -1 1 1 -1 1 -1 1
1 1 1 -1 -1 -1 1 -1 -1 1 1 -1 -1 -1 1 -1 -1 -1 -1 1
-1 1 1 1 -1 -1 -1 -1 -1 -1 -1 1 1 -1 1 1 -1 1 -1 -1
```
---
**Sample Usage**
```
$ time ./matrix-permanent-c 8 30
8395059644858368
real 0m8.582s
user 1m8.656s
sys 0m0.000s
```
---
**Method**
I've used the [Balasubramanian-Bax/Franklin-Glynn formula](https://en.wikipedia.org/wiki/Computing_the_permanent#Balasubramanian-Bax.2FFranklin-Glynn_formula), with a runtime complexity of *O(2nn)*. However, instead of iterating the *δ* in grey code order, I've instead replaced vector-row multiplication with a single xor operation (mapping (1, -1) → (0, 1)). The vector sum can likewise be found in a single operation, by taking n minus twice the popcount.
[Answer]
## Racket 84 bytes
Following simple function works for smaller matrices but hangs on my machine for larger matrices:
```
(for/sum((p(permutations(range(length l)))))(for/product((k l)(c p))(list-ref k c)))
```
Ungolfed:
```
(define (f ll)
(for/sum ((p (permutations (range (length ll)))))
(for/product ((l ll)(c p))
(list-ref l c))))
```
The code can easily be modified for unequal number of rows and columns.
Testing:
```
(f '[[ 1 -1 -1 1]
[-1 -1 -1 1]
[-1 1 -1 1]
[ 1 -1 -1 1]])
(f '[[ 1 -1 1 -1 -1 -1 -1 -1]
[-1 -1 1 1 -1 1 1 -1]
[ 1 -1 -1 -1 -1 1 1 1]
[-1 -1 -1 1 -1 1 1 1]
[ 1 -1 -1 1 1 1 1 -1]
[-1 1 -1 1 -1 1 1 -1]
[ 1 -1 1 -1 1 -1 1 -1]
[-1 -1 1 -1 1 1 1 1]])
```
Output:
```
-4
192
```
As I mentioned above, it hangs on testing following:
```
(f '[[1 -1 1 -1 -1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 1 1 -1]
[1 -1 1 1 1 1 1 -1 1 -1 -1 1 1 1 -1 -1 1 1 1 -1]
[-1 -1 1 1 1 -1 -1 -1 -1 1 -1 1 1 1 -1 -1 -1 1 -1 -1]
[-1 -1 -1 1 1 -1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 1 -1]
[-1 1 1 1 -1 1 1 1 -1 -1 -1 1 -1 1 -1 1 1 1 1 1]
[1 -1 1 1 -1 -1 1 -1 1 1 1 1 -1 1 1 -1 1 -1 -1 -1]
[1 -1 -1 1 -1 -1 -1 1 -1 1 1 1 1 -1 -1 -1 1 1 1 -1]
[1 -1 -1 1 -1 1 1 -1 1 1 1 -1 1 -1 1 1 1 -1 1 1]
[1 -1 -1 -1 -1 -1 1 1 1 -1 -1 -1 -1 -1 1 1 -1 1 1 -1]
[-1 -1 1 -1 1 -1 1 1 -1 1 -1 1 1 1 1 1 1 -1 1 1]
[-1 -1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1]
[1 1 -1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 1 1 1 1 1 1]
[-1 1 1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 -1 1 -1 1]
[1 1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 1]
[1 1 1 1 1 -1 -1 -1 1 1 1 -1 1 -1 1 1 1 -1 1 1]
[1 -1 -1 1 -1 -1 -1 -1 1 -1 -1 1 1 -1 1 -1 -1 -1 -1 -1]
[-1 1 1 1 -1 1 1 -1 -1 1 1 1 -1 -1 1 1 -1 -1 1 1]
[1 1 -1 -1 1 1 -1 1 1 -1 1 1 1 -1 1 1 -1 1 -1 1]
[1 1 1 -1 -1 -1 1 -1 -1 1 1 -1 -1 -1 1 -1 -1 -1 -1 1]
[-1 1 1 1 -1 -1 -1 -1 -1 -1 -1 1 1 -1 1 1 -1 1 -1 -1]])
```
] |
[Question]
[
You will be given a positive integer `N` as input. Your task is to build a Semi-Zigzag, of `N` sides, each of length `N`. Since it is relatively hard to clearly describe the task, here are some examples:
* `N = 1`:
```
O
```
* `N = 2`:
```
O
O O
```
* `N = 3`:
```
O O
O O
O O O
```
* `N = 4`:
```
O O O O O
O O
O O
O O O O
```
* `N = 5`:
```
O O O O O O
O O O
O O O
O O O
O O O O O O
```
* `N = 6`:
```
O O O O O O O
O O O
O O O
O O O
O O O
O O O O O O O O O O O O
```
* `N = 7`:
```
O O O O O O O O O
O O O O
O O O O
O O O O
O O O O
O O O O
O O O O O O O O O O O O O O
```
* [A larger test case with `N = 9`](https://pastebin.com/BHGM6p5y)
As you can see, a Semi-Zigzag is made of alternating diagonal and horizontal lines, and it always begins with a top-left to bottom right diagonal line. Take note that the characters on the horizontal lines are separated by a space.
# Rules
* You may choose any non-whitespace *character* instead of `O`, it may even be inconsistent.
* You may output / return the result as a String or as a list of Strings, each representing one *line*.
* You may have a trailing or leading newline.
* **[Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** apply.
* You can take input and provide output by **[any standard mean](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)**.
* If possible, please add a testing link to your submission. I will upvote any answer that shows golfing efforts and has an explanation.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes ***in every language*** wins!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
FN«↶§7117ι×⁺#× ﹪ι²⁻Iθ¹»#
```
[Try it online!](https://tio.run/##AT0Awv9jaGFyY29hbP//77ym77yuwqvihrbCpzcxMTfOucOX4oG6I8OXIO@5qs65wrLigbvvvKnOuMK5wrsj//85 "Charcoal – Try It Online")
-5 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil).
AST:
```
Program
├F: For
│├N: Input number
│└Program
│ ├↶: Pivot Left
│ │└§: At index
│ │ ├'7117': String '7117'
│ │ └ι: Identifier ι
│ └Print
│ └×: Product
│ ├⁺: Sum
│ │├'#': String '#'
│ │└×: Product
│ │ ├' ': String ' '
│ │ └﹪: Modulo
│ │ ├ι: Identifier ι
│ │ └2: Number 2
│ └⁻: Difference
│ ├I: Cast
│ │└θ: Identifier θ
│ └1: Number 1
└Print
└'#': String '#'
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~157~~ 153 bytes
```
n=input()
o,s=q='O '
def p(k,t=q*n+s*(4*n-6)):print(t*n)[k*~-n:][:n*3/2*~-n+1]
p(2)
for i in range(n-2):p(0,i*s+s+o+s*(4*n-7-2*i)+o+s*(2*n+i-2))
n>1>p(5)
```
[Try it online!](https://tio.run/##NY1NCsIwEEb3OUV2nZkkaONPoZBewQOULgRbDYVJ2sSFG68eK@Lywfe@F1/5EdiWws5zfGZAEXRyi6sushK3cZIRZp3dQqwSwZHYnBHbuHrOkImxn@ltuB36lumws19Q9SAiWBRTWKWXnuV65fsIbOxmwl57Siqp8D9sjCWPP7Zbx287FNzVXYQTltJ8AA "Python 2 – Try It Online")
* `n*3/2*~-n+1` is the width of each line: ⌊3n/2⌋ · (n−1) + 1 characters.
* The string `q*n+s*(4*n-6)` represents the top and bottom rows. If we repeat it and slice `[2*(n-1):]` we get the top row; if we slice `[5*(n-1):]` we get the bottom row. Hence the definition of `p` and the calls to `p(2)` and `p(5)`. But since we need the repetition and line-length slicing for all other lines anyway, we reuse `p` in the loop.
* The `i*s+s+o+…` is just a boring expression for the middle rows.
* `n>1>p(5)` will short-circuit if `n≯1`, causing `p(5)` to not get evaluated. Hence, it’s shorthand for `if n>1:p(5)`.
[Answer]
# Mathematica, ~~126~~ ~~125~~ ~~121~~ ~~112~~ ~~104~~ ~~89~~ 86 bytes
```
(m=" "&~Array~{#,#^2-#+1};Do[m[[1[i,#,-i][[j~Mod~4]],j#-#+i+1-j]]="X",{j,#},{i,#}];m)&
```
* `#` is the input number for an anonymous function (ended by the final `&`).
* `m=" "&~Array~{#,#^2-#+1};` makes a matrix of space characters of the right size by filling an array of given dimensions `#,#^2-#+1` with the outputs of the constant anonymous function "output a space" `" "&`.
* `Do[foo,{j,#},{i,#}]` is a pair of nested do loops, where `j` ranges from `1` to `#` and inside of that `i` ranges from `1` to `#`.
* `m[[1[i,#,-i][[j~Mod~4]],j#-#+i+1-j]]="X"` sets the the corresponding part of the matrix to be the character `X` based on `j` and `i`. The `-i` uses negative indexing to save bytes from `#-i+1`. (I forgot to write `Mod[j,4]` as `j~Mod~4` in the original version of this code.) Jenny\_mathy pointed out that we can use the modular residue to index into the list directly (rather than using `Switch`) to save 9 bytes, and JungHwan Min pointed out that we didn't need to use `ReplacePart` since we can set a part of an array and that `1[i,#,-i][[j~Mod~4]]` uses the odd behavior and generality of `[[foo]]` to save bytes over `{1,i,#,-i}[[j~Mod~4+1]]`
* Since [meta established that a list of characters is a string](https://codegolf.meta.stackexchange.com/questions/2214/whats-a-string) (as [JungHwan Min pointed out](https://codegolf.stackexchange.com/questions/136660/build-a-semi-zigzag/136689#comment334433_136696)) we don't need to map any function across the rows of the matrix of characters since it's already a list of "string"s.
You can test this out in the [Wolfram Cloud sandbox](http://sandbox.open.wolframcloud.com) by pasting code like the following and hitting Shift+Enter or the numpad Enter:
```
(m=" "&~Array~{#,#^2-#+1};Do[m[[1[i,#,-i][[j~Mod~4]],j#-#+i+1-j]]="X",{j,#},{i,#}];m)&@9//MatrixForm
```
[Answer]
## C++, ~~321~~ 234 bytes
-87 bytes thanks to Zacharý
```
#include<vector>
#include<string>
auto z(int n){std::vector<std::string>l;l.resize(n,std::string(n*n+n/2*(n-1),32));l[0][0]=79;int i=0,j,o=0;for(;i<n;++i)for(j=1;j<n;++j)l[i%4?i%4-1?i%4-2?0:n-j-1:n-1:j][i*n+j-i+(o+=i%2)]=79;return l;}
```
Returns a vector of strings
[Answer]
# Mathematica, 179 bytes
```
Rotate[(c=Column)@(t=Table)[{c@(a=Array)[" "~t~#<>(v="o")&,z,0],c@t[t[" ",z-1]<>v,z-1],c@a[t[" ",z-2-#]<>v&,z-1,0],c@t[v,z-Boole[!#~Mod~4<1]-1]}[[i~Mod~4+1]],{i,0,(z=#)-1}],Pi/2]&
```
edit for @JungHwanMin
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ ~~20~~ 19 bytes
### Code
Uses the new canvas mode:
```
Fx<)Nè'ONÉúR3212NèΛ
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/frcJG0@/wCnV/v8Odh3cFGRsZGgG552b//28GAA "05AB1E – Try It Online")
### Explanation:
```
F # For N in range(0, input)
x<) # Push the array [input, 2 × input - 1]
Nè # Retrieve the Nth element
'ONÉúR # Push "O" if N is odd, else "O "
3212Nè # Retrieve the Nth element of 3212
Λ # Write to canvas
```
For input **6**, this gives the following arguments (in the same order) for the canvas:
```
[<num>, <fill>, <patt>]
[6, 'O', 3]
[11, 'O ', 2]
[6, 'O', 1]
[11, 'O ', 2]
[6, 'O', 3]
[11, 'O ', 2]
```
To explain what the canvas does, we pick the first set of arguments from the list above.
The number **6** determines the *length* of the string that will be written into the canvas. The filler is used to write on the canvas, which in this case is `O`. It cyclically runs through the filler string. The direction of the string is determined by the final argument, the direction. The directions are:
```
7 0 1
\ | /
6- X -2
/ | \
5 4 3
```
This means that the **3** sets the direction to *south-east*, which can also be [tried online](https://tio.run/##MzBNTDJM/f/fTEHJX0nBWOHc7P//AQ).
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 36 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
╝.H∫2\?.╝}F2%?№@.┌Ο};1w⁄Hh1ž}.4%1>?№
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTVELkgldTIyMkIyJTVDJTNGLiV1MjU1RCU3REYyJTI1JTNGJXUyMTE2QC4ldTI1MEMldTAzOUYlN0QlM0IxdyV1MjA0NEhoMSV1MDE3RSU3RC40JTI1MSUzRSUzRiV1MjExNg__,inputs=NQ__)
The basic idea is to for each number of the input range choose either adding a diagonal or the horizontal dotted part, in which case it will turn the array around for easier adding on.
Explanation:
```
╝ get a diagonal from the bottom-left corner with the length of the input - the starting canvas
.H∫ } for each number in the range [1,inp-1] do, pushing counter
2\? } if it divides by 2, then
.╝ create another diagonal of the input
F2% push counter % 2
? } if that [is not 0]
№ reverse the current canvas upside down
@.┌Ο get an alternation of spaces and dashes with the dash amount of the input length
; get the canvas on top of the stack
1w⁄ get its 1st element length
H decrease it
h swap the bottom 2 items - the canvas is now at the bottom and the current addition ontop
1 push 1
ž at 1-indexed coordinates [canvasWidth-1, 1] in the canvas insert the current part made by the Ifs
.4%1>? if input%4 > 1
№ reverse the array vertically
```
If the input of 1 wasn't allowed, then `ο.∫2%?.╝}F2\?№@.┌Ο};1w⁄Hh1ž}.4%1>?№` would work too. If random numbers floating around were allowed `.∫2%?.╝}F2\?№@.┌Ο};1w⁄Hh1ž}.4%1>?№` would work too. If I were not lazy and implemented [`‼`](https://github.com/dzaima/SOGL/blob/master/P5ParserV0_12/data/charDefs.txt#L702), `}F2%?` could be replaced with `‼` for -4 bytes
[Answer]
# Mathematica, ~~106~~ 87 bytes
```
SparseArray[j=i=1;k=#-1;Array[{j+=Im@i;k∣#&&(i*=I);j,#+1}->"o"&,l=k#+1,0],{#,l}," "]&
```
Returns a `SparseArray` object of `String`s. To visualize the output, you can append `Grid@`. Throws an error for case `1`, but it's safe to ignore.
### Explanation
```
j=i=1
```
Set `i` and `j` to 1.
```
k=#-1
```
Set `k` to input - 1.
```
l=k#+1
```
Set `l` to `k*input + 1`
```
Array[ ..., l= ...,0]
```
Iterate `l` times, starting from `0`, incrementing by `1` each time...
---
```
j+=Im@i
```
Add the imaginary component of `i` to `j`...
```
k∣#&&(i*=I)
```
If the current iteration is divisible by `k`, multiply `i` by the imaginary unit...
```
{... j,#+1}->"o"
```
Create a `Rule` object that changes element at position `{j, current iteration + 1}` to `"o"`
---
```
SparseArray[ ...,{#,l}," "]
```
Create a `SparseArray` object using the generated `Rule` objects, with dimension `{input, l}`, using `" "` as blank.
[Try it on Wolfram Sandbox!](https://sandbox.open.wolframcloud.com/)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~228 226 224 215 197~~ 195 bytes
***-11 bytes Thanks to @Mr. Xcoder***
-2 bytes Thanks to @Mr. Xcoder
```
def f(n,s=range):
x=y=t=c=0;z=[]
for i in s(n*n-n+2):c+=i%(n-(2<=n))<1;z+=[[x,y]];t=max(t,x);x+=2-c%2;y+=[-1,1][c%4<3]*(c%2)
return'\n'.join(''.join(' O'[[k,j]in z]for k in s(t))for j in s(n))
```
[Try it online!](https://tio.run/##PY9NboMwEIX3nGI2iJlgqphkFTNn6AFcLyIKrYk6RI4rGS5PTf9WT/Nm8X3vvsT3WU7b9jqMMKKoB4ervA10KSDxwpF7PpqVrStgnAN48AIPlIM0Urd06Wv2JUqDbcdC1Gmz1mxtUotzJvLHNWFUiUyquW36sjVLfjdaaWf78tyd3AFzSwWEIX4GqV6keppmL1j9JTxX1t7U5DJ4dbvD7cchEu3X9GtEtP0Lfk9ArUAf9yH34CXiiJ5UBmQEbV8 "Python 3 – Try It Online")
## Explanation and less-golfed code:
```
def f(n):
x=y=t=c=0;z=[] #initialize everything
for i in range(n*n-n+2): #loop n*n-n+2 times which is the numberr of 'o's expected
c+=i%[~-n,n]<n-1 #if one cycle has been completed, increase c by 1, if n>1.
z+=[[x,y]] #add [x,y] to z(record the positions of 'o')
t=max(t,x) #trap maximum value of x-coordinate(to be used later while calculatng whole string)
r=[[2,0],[1,1],[2,0],[1,-1]][c%4] #r gives direction for x and y to move, adjust it as per c i.e. cycles
x+=r[0];y+=r[1] #yield newer values of x and y
return '\n'.join(''.join(' o'[[k,j]in z]for k in range(t))for j in range(n)) #place space or 'o' accordingly as per the recorded posititons in z
```
[Answer]
# [Haskell](https://www.haskell.org/), 197 bytes
```
a n c=take(2*n)$cycle$c:" "
r i n x y=take(div(3*n)2*(n-1)+1)$(' '<$[1..i])++(cycle$"O "++(a(2*n-i-3)y)++"O "++(a(n+i-2)x))
z n=take n$(r 0 n 'O' ' '):[r i n ' ' ' '|i<-[1..n-2]]++[r(n-1)n ' ' 'O']
```
[Try it online!](https://tio.run/##RY7BbsIwDIbP5CmsKFJioqC1HCYh@ghb76tyiEoFFsWggjaK9u6d27JNPtlf/v/LIV2PTdsOQwKGurilY@PyJaOp@7ptTL3RoFUHJPQO/cx39OnW8iZfOg4Z@gyNs2C3pspWK4rovZvTugQtSxobA4U19sL@juwp5HhHVA/gqRnYuA5exGVLKQSLm2p223m@aRtGCYc8Ru@rbvrAE5c2DpeO@PZB@0faS6qA3VktppvR74Vor4fzF7BanNLlDSYATuyo1CnRb@AfPptG5WscfgA "Haskell – Try It Online")
*Thanks to @Lynn : fixed the spaces between `O`s on horizontal segments of the zigzag, but it costed a lot of bytes!*
Some explanations:
* `r` is a row of the output: it has the `0 y y y y y 0 x x x 0 y ...` format, the number of `x`and `y` depending on the row and the initial `n`
* for the top row, `x='0'`and `y=' '`
* for the middle rows, `x=' '`and `y=' '`
* for the bottom row, `x=' '`and `y='0'`
* `take(div(3*n)2*(n-1)+1)` cuts an infinite row at the right place
* every output has one top row and one bottom row except when `n=1`: `take n` handles this case.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~155~~ ~~151~~ ~~146~~ 137 bytes
```
m=input()
n=m-1
r=range(n+2)
for L in zip(*[' '*i+'O'+n*' 'for i in(r+[n,m]*~-n+r[-2::-1]+([m,0]*n)[:-1])*m][:1+3*m/2*n]):print''.join(L)
```
[Try it online!](https://tio.run/##NY4xCgIxEEX7nCJgkcxkoyYWSmBvsOABQgoLV0fIbAhroYVXj7uI3X88ePzymu8T@9ZyT1yeswbBfbZO1L5e@HbVbDyIcapykMTyTUVjVFIhGXVWhnHZq6XF6moidznhx7Kp0foQrEtGx9ztEzLEFQFzisGZA@adR04QSiWeldo@piUxQNv8e/L3wHUnCGIjR03Qjl8 "Python 2 – Try It Online")
] |
[Question]
[
I didn't check [the sandbox](http://meta.codegolf.stackexchange.com/a/7435/20634) before posting this challenge - it looks like this challenge was proposed by [Cᴏɴᴏʀ O'Bʀɪᴇɴ](http://meta.codegolf.stackexchange.com/u/31957).
Given an integer input, write a program that prints the "four is a magic number" riddle
* Four is the magic number
* Five is four and four is the magic number
* Six is three and three is five and five is four and four is the magic number
* Eleven is six and six is three and three is five and five is four and four is the magic number
* Five Hundred is eleven and eleven is six and six is three and three is five and five is four and four is the magic number
If you already know the riddle, or are too ~~lazy to solve it~~ anxious to find out what the riddle is, here's an explanation
>
> The next number is the number of letters in the previous number. So, for example, **five** has **four** letters, so the next number is **four**.
>
>
>
> **six** has **three** letters, so the next number is **3**, and **three** has **five** letters, so the next number is **5**, and **five** has **four** letters, so the next number is **4**
>
>
>
> The reason the riddle ends at four is because four has four letters, and four is four and four is four and four is four... (four is the magic number)
>
>
>
## Test Cases
```
0 =>
Zero is four and four is the magic number
1 =>
One is three and three is five and five is four and four is the magic number
2 =>
Two is three and three is five and five is four and four is the magic number
3 =>
Three is five and five is four and four is the magic number
4 =>
Four is the magic number
5 =>
Five is four and four is the magic number
6 =>
Six is three and three is five and five is four and four is the magic number
7 =>
Seven is five and five is four and four is the magic number
8 =>
Eight is five and five is four and four is the magic number
9 =>
Nine is four and four is the magic number
10 =>
Ten is three and three is five and five is four and four is the magic number
17 =>
Seventeen is nine and nine is four and four is the magic number
100 =>
One Hundred is ten and ten is three and three is five and five is four and four is the magic number
142 =>
One Hundred Forty Two is eighteen and eighteen is eight and eight is five and five is four and four is the magic number
1,000 =>
One Thousand is eleven and eleven is six and six is three and three is five and five is four and four is the magic number
1,642 =>
One Thousand Six Hundred Forty Two is twenty nine and twenty nine is ten and ten is three and three is five and five is four and four is the magic number
70,000 =>
Seventy Thousand is fifteen and fifteen is seven and seven is five and five is four and four is the magic number
131,072 =>
One Hundred Thirty One Thousand Seventy Two is thirty seven and thirty seven is eleven and eleven is six and six is three and three is five and five is four and four is the magic number
999,999 =>
Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine is fifty and fifty is five and five is four and four is the magic number
```
## Rules
* The input may either be taken from `STDIN` or as an argument to a function
* The input will be a positive number between 0 and 999,999
* The input will *only* contain numbers (it will follow the regex `^[0-9]+$`)
* The input can either be taken as an integer or a string
* When converted to a word string, spaces and hyphens should not be included in the count (100 [One Hundred] is 10 characters, not 11. 1,742 [One thousand Seven hundred Forty-Two] is 31 characters, not 36)
* When converted to a string, 100 should be One Hundred, not A Hundred or Hundred, 1000 should be One Thousand, not A Thousand or Thousand.
* When converted to a string 142 should be One Hundred Forty Two, not One Hundred *and* Forty Two
* The output is **case-insensitive**, and should follow the format "**N** is **K** and **K** is **M** and **M** is ... and four is the magic number" (unless the input is 4, in which case the output should simply be "four is the magic number")
* The output *can* use numbers instead of letters ("5 is 4 and 4 is the magic number" instead of "five is four and four is the magic number") as long as your program is always consistent
* The output can either be the return value of a function, or printed to `STDOUT`
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/20634) apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. Good luck!
## Bonus
**-30 bytes** if the program works when the input is between -999,999 and 999,999.
Negative numbers, when converted to words, just have "negative" in front of them. For example `-4` is "Negative Four", *Negative Four is twelve and twelve is six and six is three and three is five and five is four and four is the magic number*
**-150 bytes** if the program does not use any built-in functions for generating the string representation of the number
## Leaderboard
This is a Stack Snippet that generates both a leaderboard and an overview of winners by language.
To ensure 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, in bytes, of your submission
If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the *last* number in your header
```
## Language Name, <s>K</s> X + 2 = N bytes
```
```
var QUESTION_ID=67344;var OVERRIDE_USER=20634;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
## Bash + common utilities (including bsd-games), 123 - 30 = 93 bytes
```
for((n=$1;n-4;n=m)){
m=`number -l -- $n|sed 's/nus/&&/;s/\W//g'`
s+="$n is $[m=${#m}] and "
}
echo $s 4 is the magic number
```
Luckily the output from the [bsd-games `number` utility](http://wiki.linuxquestions.org/wiki/BSD_games) is almost exactly what we need. Output numbers are all written numerically and not in words as per the 8th bullet point:
```
$ ./4magic.sh 131072
131072 is 37 and 37 is 11 and 11 is 6 and 6 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
$ ./4magic.sh -4
-4 is 12 and 12 is 6 and 6 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
$
```
[Answer]
# C, 263 261 bytes - 180 = 81
```
char*i="jmmonnmoonmpprrqqsrrjjddeeecdd",x;f(n,c){return!n?n:n<0?f(-n,8):n<100?c+i[n<20?n:n%10]-i[20+n/10]:f(n/1000,8)+f(n/100%10,7)+f(n/100%10,0)+c;}main(int c,char**v){for(c=atoi(*++v);c-4;c=x)printf("%d is %d and ",c,x=c?f(c,0)):4;puts("4 is the magic number");}
```
Inspired by [the answer from Cole Cameron](/a/74627/39490). I thought I might be able to do better without the macro definition. Although I eventually managed, it did take some squeezing to achieve!
It requires a host character set with consecutive letters (so ASCII is okay, but EBCDIC won't work). That's for the pair of lookup tables. I chose `j` as the zero character, and took advantage of needing two lookups, so I could subtract one from the other rather than having to subtract my zero from both.
## Commented version:
```
char*i=
"jmmonnmoon" /* 0 to 9 */
"mpprrqqsrr" /* 10 to 19 */
"jjddeeecdd"; /* tens */
char x; /* current letter count */
f(n,c){
return
!n?n /* zero - return 0 (ignore c) */
:n<0?f(-n,8) /* negative n (only reached if c==0) */
:n<100?c+i[n<20?n:n%10]-i[20+n/10] /* lookup tables */
:
f(n/1000,8) /* thousand */
+ f(n/100%10,7) /* hundred */
+ f(n%100,0) /* rest */
+ c; /* carry-in */
}
main(int c, char**v)
{
for(c=atoi(*++v);c-4;c=x)
printf("%d is %d and ",c,x=c?f(c,0):4);
puts("4 is the magic number");
}
```
There's an obvious extension to support millions, by replacing `f(n/1000,8)` with `f(n/1000000,7)+f(n/1000%1000,8)`.
## Test output
```
0 is 4 and 4 is the magic number
1 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
2 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
3 is 5 and 5 is 4 and 4 is the magic number
4 is the magic number
5 is 4 and 4 is the magic number
6 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
7 is 5 and 5 is 4 and 4 is the magic number
8 is 5 and 5 is 4 and 4 is the magic number
9 is 4 and 4 is the magic number
10 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
17 is 9 and 9 is 4 and 4 is the magic number
100 is 10 and 10 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
142 is 18 and 18 is 8 and 8 is 5 and 5 is 4 and 4 is the magic number
1000 is 11 and 11 is 6 and 6 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
1642 is 29 and 29 is 10 and 10 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
70000 is 15 and 15 is 7 and 7 is 5 and 5 is 4 and 4 is the magic number
131072 is 37 and 37 is 11 and 11 is 6 and 6 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
999999 is 50 and 50 is 5 and 5 is 4 and 4 is the magic number
```
[Answer]
## Mathematica, 156 - 30 = 126 bytes
```
a=ToString;({a@#," is ",a@#2," and "}&@@@Partition[NestWhileList[#~IntegerName~"Words"~StringCount~LetterCharacter&,#,#!=4&],2,1])<>"4 is the magic number"&
```
I'm simply surprised that this uses strings and *isn't* ridiculously long.
[Answer]
## [Swift 2](https://swift.org/), ~~408~~ 419 - 30 = 389 Bytes
I would be able to get rid of 176 bytes if it Swift wasn't so verbose with regular expressions (removing hyphens and spaces) \*glares at Apple\*
```
func c(var s:Int)->String{var r="";while(s != 4){r+="\(s)";let f=NSNumberFormatter();f.numberStyle=NSNumberFormatterStyle.SpellOutStyle;let v=f.stringFromNumber(s)!;s=v.stringByReplacingOccurrencesOfString("[- ]",withString:"",options:NSStringCompareOptions.RegularExpressionSearch,range:Range<String.Index>(start:v.startIndex,end:v.endIndex)).utf8.count+(s<0 ?3:0);r+=" is \(s) and "};return r+"4 is the magic number"}
```
This can be tested [on swiftstub.com, here](http://swiftstub.com/843107568/)
I ran a little for loop, and it turns out that `100003` is the number between 0 and 999999 has the longest string result, which has 6 iterations, and is
>
> **100003** is **23** and **23** is **11** and **11** is **6** and **6** is **3** and **3** is **5** and **5** is **4** and **4** is the magic number
>
>
>
### Ungolfed
```
func a(var s: Int) -> String{
var r = ""
while(s != 4){
r+="\(s)"
let f = NSNumberFormatter()
f.numberStyle = NSNumberFormatterStyle.SpellOutStyle
let v = f.stringFromNumber(s)!
s = v.stringByReplacingOccurrencesOfString(
"[- ]",
withString: "",
options: NSStringCompareOptions.RegularExpressionSearch,
range: Range<String.Index>(start: v.startIndex, end: v.endIndex)
).utf8.count + (s < 0 ? 3 : 0)
r+=" is \(s) and "
}
return r+"4 is the magic number"
}
```
[Answer]
# Haskell, 285 - 180 = 105 Bytes
In fact, there is no built-in at all for displaying number. I still dissatisfied with the score. Feel free to comment. I will experiment further, though. Still the score is better than Swift's score
```
c n|n<0=8+c(-n)|n>999=r 1000+8|n>99=7+r 100|n>19=r 10+2-g[30..59]+g[20..29]|n>15=r 10-1|2>1=[0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7]!!n where{g=fromEnum.elem n;r k=c(mod n k)+c(div n k)}
m 4="4 is the magic number"
m 0="0 is 4 and "++m 4
m n=show n++" is "++show(c n)++" and "++m(c n)
```
usage
```
m 7
"7 is 5 and 5 is 4 and 4 is the magic number"
m 999999
"999999 is 50 and 50 is 5 and 5 is 4 and 4 is the magic number"
```
Explanation.
`m` is trivial enough, however, the `c` is not. `c` is the function to count the number of character the english name of number.
```
c n |n<0=8+c(-n) -- Add word "negative" in front of it, the length is 8
|n>999=r 1000+8 -- the english name for number with form xxx,yyy is xxx thousand yyy
|n>99=7+r 100 -- the english name for number with form xyy is x hundred yy
|n>19=r 10+2-g[30..59]+g[20..29] -- the english name for number with form xy with x more
-- than 1 is x-ty. However *twoty>twenty,
-- *threety>thirty, *fourty>forty, *fivety>fifty.
|n>10=r 10-1-g(15:18:[11..13]) -- the english name for number with form 1x is x-teen.
-- However, *oneteen>eleven, *twoteen>twelve,
-- *threeteen>thirteen, *fiveteen>fifteen,
-- *eightteen>eighteen
|2>1=[0,3,3,5,4,4,3,5,5,4,3]!!n -- for number 0-10, the length is memorized. 0 is 0
-- because it is omitted. Input zero is handled
-- separately. If we defined 0 to be 4, then
-- 20 => twenty zero.
where g =fromEnum.elem n -- Check if n is element of argument array, if true, 1 else 0
r k=c(mod n k)+c(div n k) -- Obvious.
```
[Answer]
# C, 268 - 180 = 88 bytes
```
#define t(x,o)n<x?o:f(n/x)+(n%x?f(n%x):0)
char*i="4335443554366887798866555766";f(n){return t(1000,t(100,n<20?n<0?8+f(-n):i[n]-48:i[n/10+18]-48+(n%10?f(n%10):0))+7)+8;}main(n){for(scanf("%d",&n);n^4;n=f(n))printf("%d is %d and ",n,f(n));puts("4 is the magic number");}
```
Try it [here](http://ideone.com/GZfBjy).
## Ungolfed
```
/* Encode number length in string (shorter representation than array) */
char*i="4335443554366887798866555766";
f(n)
{
return n < 1000
? n < 100
? n < 20
? n < 0
? 8 + f(-n) /* "Negative x" */
: i[n] - 48 /* "x" */
: i[n/10+18] + (n%10 ? f(n%10) : 0) /* 20-99 */
: f(n/100) + (n%100 ? f(n%100) : 0) + 7 /* x hundred y */
: f(n/1000) + (n%1000 ? f(n%1000) : 0) + 8; /* x thousand y */
}
main(n)
{
/* Keep printing until you get to the magic number */
for(scanf("%d",&n);n^4;n=f(n))
printf("%d is %d and ",n,f(n));
puts("4 is the magic number");
}
```
[Answer]
## Java, 800 - 150 = 650 bytes
```
class G{static String e="",i="teen",j="ty",k="eigh",y="thir",d="zero",l="one",n="two",m="three",h="four",s="five",c="six",t="seven",b=k+"t",g="nine",D="ten",L="eleven",N="twelve",M=y+i,H=h+i,S="fif"+i,C=c+i,T=t+i,B=k+i,G=g+i,o="twen"+j,p=y+j,q="for"+j,r="fif"+j,u=c+j,v=t+j,w=k+j,x=g+j,A=" ",O=" hundred ",z,E;public static void main(String a[]){z=e;int l=new Integer(a[0]);do{E=a(l,1,e);l=E.replace(A,e).length();z=z+E+" is "+a(l,1,e)+" and ";}while(l!=4);System.out.print(z+h+" is the magic number");}static String a(int P,int _,String Q){String[]f={e,l,n,m,h,s,c,t,b,g,D,L,N,M,H,S,C,T,B,G,e,D,o,p,q,r,u,v,w,x};int R=20,X=10,Y=100,Z=1000;return P==0?(_>0?d:e):(P<R?f[P]+Q:(P<Y?(f[R+(P/X)]+" "+a(P%X,0,e)).trim()+Q:(P<Z?a(P/Y,0,O)+a(P%Y,0,e)+Q:a(P/Z,0," thousand ")+a((P/Y)%X,0,O)+a(P%Y,0,e)+Q)));}}
```
### De-golfed
```
class G {
static String e="",i="teen",j="ty",k="eigh",y="thir",d="zero",l="one",n="two",m="three",h="four",s="five",c="six",t="seven",b=k+"t",g="nine",D="ten",L="eleven",N="twelve",M=y+i,H=h+i,S="fif"+i,C=c+i,T=t+i,B=k+i,G=g+i,o="twen"+j,p=y+j,q="for"+j,r="fif"+j,u=c+j,v=t+j,w=k+j,x=g+j,A=" ",O=" hundred ",z,E;
public static void main(String a[]){
z = e;
int l = new Integer(a[0]);
do {
E = a(l,1,e);
l = E.replace(A,e).length();
z = z+E+" is "+a(l,1,e)+" and ";
} while(l!=4);
System.out.println(z+h+" is the magic number");
}
static String a(int P,int _,String Q) {
String[] f = {e,l,n,m,h,s,c,t,b,g,D,L,N,M,H,S,C,T,B,G,e,D,o,p,q,r,u,v,w,x};
int R=20,X=10,Y=100,Z=1000;
return P==0?(_>0?d:e):(P<R?f[P]+Q:(P<Y?(f[R+(P/X)]+" "+a(P%X,0,e)).trim()+Q:(P<Z?a(P/Y,0,O)+a(P%Y,0,e)+Q:a(P/Z,0," thousand ")+ a((P/Y)%X,0,O)+a(P%Y,0,e)+Q)));
}
}
```
[Answer]
## QC, 265 - 30 - 150 = 85 bytes
```
(✵1:oaT%=ta100%=ha100/⌋T%=X[0 3 3 5 4 4 3 5 5 4 3 6 6 8 8 7 7 9 8 8]=Y[6 6 5 5 5 7 6 6]=a0≟4a20<Xt☌YtT/⌋2-☌Xo☌+▲▲hXh☌7+0▲+)(❆1:na0<8*=ba‖1000/⌋=ca1000%=nbb✵8+0▲a✵++){I4≠:EEI" is "++=II❆=EEI" and "++=E!}E"4 is the magic number"+
```
**[Test suite](http://qc.avris.it/try/xktTljXn)**
Ungolfed:
```
(✵1:
oaT%= # ones
ta100%= # tens
ha100/⌋T%= # hundreds
X[0 3 3 5 4 4 3 5 5 4 3 6 6 8 8 7 7 9 8 8]= # length of "zero", "one", "two", ..., "nineteen"
Y[6 6 5 5 5 7 6 6]= # length of "twenty", ..., "ninety"
a0≟
4
a20<
Xt☌
YtT/⌋2-☌ Xo☌ +
▲
▲
hXh☌7+0▲+)
(❆1:
na0<8*= # if negative, add 8
ba‖1000/⌋= # split aaaaaa into bbbccc
ca1000%=
n bb✵8+0▲ a✵ ++)
{I4≠:EEI" is "++=II❆=EEI" and "++=E!}E"4 is the magic number"+
```
[Answer]
## JavaScript, 382 - 150 - 30 = 202 bytes
```
var o=[0,3,3,5,4,4,3,5,5,4],f=s=>(s[1]==1?[3,6,6,8,8,7,7,9,8,8][s[0]]:o[s[0]]+(s.length>1?[0,3,6,6,5,5,5,7,6,6][s[1]]:0))+(s.length==3?(7+o[s[2]]-(o[s[2]]==0?7:0)):0),l=n=>{var s=(""+n).split("").reverse();return f(s.slice(0,3))+(s.length>3?(f(s.slice(3,6))+8):0)};(n=>{var s="";while(n!=4){s+=n+" is ";n=n>=0?l(n):(l(-n)+8);s+=n+" and ";}console.log(s+"4 is the magic number");})()
```
The input is given as the parameter to the Immediately-Invoked Function Expression.
Test input:
```
999999 ->
999999 is 50 and 50 is 5 and 5 is 4 and 4 is the magic number
17 ->
17 is 9 and 9 is 4 and 4 is the magic number
-404 ->
-404 is 23 and 23 is 11 and 11 is 6 and 6 is 3 and 3 is 5 and 5 is 4 and 4 is the magic number
```
De-golfed:
```
// array of the lengths of digits in ones place:
// one is 3, two is 3, three is 5, etc... zero is a special case
// and is assigned zero length because zero is never written out in a number name
var o=[0,3,3,5,4,4,3,5,5,4],
// function that computes the length of a substring of the input
// because the input is 6 digits, it can be broken into two 3 digit subsections
// each of which can have it's length calculated separately
f=s=>
(
s[1]==1? // check for if the tens digit is a one
// when the tens is a one, pull the string length from an array that represents
// ten, eleven, twelve, thirteen, etc...
[3,6,6,8,8,7,7,9,8,8][s[0]]
:
// when the tens digit is not a one, add the ones digit normally and...
o[s[0]]
+
// add the tens digit length from the array that represents
// zero, ten, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety
(s.length>1?[0,3,6,6,5,5,5,7,6,6][s[1]]:0)
)
+
(
s.length==3? // check if the length is 3 and weren't not accidentally trying to do something wierd with a minus sign
// if so, then we have to add a hundred (7 characters) to the length and the
// length of the ones digit that is in the hundreds place like
// 'one' hundred or 'two' hundred
(7+o[s[2]]-
(
// also, if the hundreds place was a zero, subtract out those 7 characters
// that were added because 'hundred' isn't added if there's a zero in its
// place
o[s[2]]==0?
7
:
0
)
)
:
// if the length wasn't 3, then don't add anything for the hundred
0
),
// function that computes the length of the whole six digit number
l=n=>{
// coerce the number into a string and then reverse the string so that the
// ones digit is the zeroth element instead of last element
var s=(""+n).split("").reverse();
return
// calculate the character length of the first 3 characters
// like in the number 999888, this does the '888'
f(s.slice(0,3))
+
// then if there actually are any characters after the first 3
(s.length>3?
// parse the character length of the second 3 characters
(f(s.slice(3,6))+8)
:
0
)
};
// lastly is the Immediately-Invoked Function Expression
(n=>{
var s="";
// as long as we haven't reached four, just keep going through the loop
while(n!=4){
s+=n+" is ";
n=n>=0?l(n):(l(-n)+8) // this handles negatives by only passing positive values to l and then just adding 8 onto the length for negatives
s+=n+" and ";
}
// finally just say that '4 is the magic number'
console.log(s+"4 is the magic number");
})(999999)
```
[Answer]
# Python 641-150 = 501 bytes
At least it isn't longer than Java! It is based on [this](https://codereview.stackexchange.com/a/39201/77246) except using strings.
**EDIT**: I forgot about 0 and that I need to say "5 is 4", not skip to "4 is the magic number" - that added a bit to the score.
```
w={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",10:"ten",11:"eleven",12:"twelve",13:"thirteen",14:"fourteen",15:"fifteen",16:"sixteen",17:"seventeen",18:"eighteen",19:"nineteen",20:"twenty",30:"thirty",40:"forty",50:"fifty",60:"sixty",70:"seventy",80:"eighty",90:"ninety"}
s=""
def i(n):
global s
e=""
o=n%10
t=n%100
h=n/100%10
th=n/1000
if th:
e+=i(th)
e+='thousand'
if h:
e+=w[h]
e+='hundred'
if t:
if t<20 or o==0:
e+=w[t]
else:
e+=w[t-o]
e+=w[o]
if len(e)==4:s+="4 is the magic number";print s
else: s+="%d is %d and "%(n,len(e));i(len(e))
In=input()
i(In)
```
[Try it here!](http://ideone.com/T9WpiG)
[Answer]
## PHP, 168 - 30 = 138 bytes
```
function m($i){$e=strlen(preg_replace('/[^a-z-]/','',(new NumberFormatter("en",5))->format($i)));echo($i==$e?"":"$i is $e and "),($e==4?"4 is the magic number":m($e));}
```
[Answer]
# Moo, ~~182~~ 176/~~192~~ 188 bytes - 30 = 146/158
188 byte version:
```
u=$string_utils;s="";i=args[1];while(i-4)j=u:english_number(i);s=s+j+(s?" and "+j|"")+" is ";i=length(u:strip_chars(j,"- "}));endwhile;return s+(s?"four and "|"")+"four is the magic number"
```
176 byte **implementation-dependent** version:
```
s="";i=args[1];while(i-4)j=#20:english_number(i);s=s+j+(s?" and "+j|"")+" is ";i=length(#20:strip_chars(j," -"));endwhile;return s+(s?"four and "|"")+"four is the magic number"
```
Both are functions.
] |
[Question]
[
This is a rock:
```
*
```
Rocks can be stacked. Apart from the bottom-most layer, each rock must rest on two other rocks, like this:
```
*
* *
```
You have a pile of rocks, and your boss wants you to pile them *symmetrically*, taking up the least horizontal space possible.
Your challenge is to take a number of rocks as input, and output that many rocks stacked *symmetrically*, on *as small* a base as possible.
For example, with input `4`:
You can't fit a pile of 4 rocks on a base of 2. With a base of 3, you can, but you can't make it symmetrical - you end up with something like
```
*
* * *
```
So you need a base size of 4, which uses up all your rocks, so the result is:
```
* * * *
```
Any trailing or leading whitespace is allowed in the output, and you may use any two distinct characters instead of `*` and . If there are multiple ways to stack the inputted number of rocks symmetrically with the same base, any of them are valid.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
# Testcases
```
4 =>
* * * *
7 =>
* * *
* * * *
8 =>
*
* *
* * * * *
9 =>
* *
* * *
* * * *
12 =>
* * *
* * * *
* * * * *
13 =>
* *
* * * * *
* * * * * *
or
* *
* * * * *
* * * * * *
17 =>
* *
* * * *
* * * * *
* * * * * *
19 =>
* *
* * * *
* * * * * *
* * * * * * *
Or
*
* *
* * *
* * * * * *
* * * * * * *
20 =>
* *
* * *
* * * *
* * * * *
* * * * * *
56 =>
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
or
* *
* * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~124 117 112~~ 110 bytes
```
->n{b=0
a=*a,"* "*b+=1while(n-=b)>0||n==-2
~n%2*n<0&&a[2][2]=' '
a.map{|j|q=n<0?2:0;n+=2;j[q..~q].center b*2}}
```
[Try it online!](https://tio.run/##Tc/NCoJAEMDxu08hQVlbys70nY09iHjYDaWkFq0kIvPVTah2gjn8hjn8mUulH21GrR@ZpybpKBJq0hNuT@gxwf1wPKVD45MeRbKuDZGPTmP6KMxWDgYqxqQb8lzPUcFZFc86r0vqbjvcyNCMCcM8LoOgKZNgn5pbenG1wNerLarb1c1iSJyv8KPfOrWHmdXcamG1tFpZra1AMjkFyOQOcAi4BJwCbgHHgGvINfx7DJP2DQ "Ruby – Try It Online")
Incorporated ideas from dingus and G B, and also removed the deletion loop completely by using the output loop to perform its function (it truncates the first and last `*` rather than overwriting them).
# [Ruby](https://www.ruby-lang.org/), ~~163~~ 137 bytes
```
->n{a=[];b=x=0
(a<<"* "*b+=1)while(x+=b)<n||2==c=x-n
(-~c/2).times{|i|a[i][0]=a[i][-2]=' '}
~c%2*c>0&&a[2][2]=' '
a.map{|j|j.center b*2}}
```
[Try it online!](https://tio.run/##Tc9LboMwEIDhvU@BIiU8IigzbfNQmFzE8sK2iAIqKEqIQoTh6lRqWk9X/mZm8cvXu3nOJ5rTYztokupgqKdcRLooFkmwSMyaIH6cq68y6tdk4qJ1Doks9WkronSybxhnXdWUt8FVTstKyVzRz5uiojAIRzHZJSb2mK9WWqKSr7XQWaMvg6tdndmy7cprYBIcx/ly727BSYISv8KX/sZ3f/jw@vTaeG29dl57L8iZnAJkcgc4BFwCTgG3gGPANeQa/vsYqvkb "Ruby – Try It Online")
This is a fast algorithm with no searching.
**Explanation**
Where `T` is a triangular number greater than the input, the only solution for `T-1` is to delete the top `*` and the only solution for `T-4` is to delete the top two rows and the `*` from the middle of the next row, forming a diamond shape.
For `T-1-2n` or `T-4-2n` a possible solution is to also delete the `*` at the beginning and the end of each row. In practice there are always enough asterisks to delete; If you run out it means that there is a triangular number smaller than `T` which would give a smaller base (This is fairly easy to prove so I'll not explain here.)
For `T-2` there is no solution and we are forced to use a triangle with the next larger base.
See examples below for odd and even numbers of deletions (numbers represent the number of deletions `O` not the number of `*`).
```
1 3 7
O O O
* * O O O O
* * * * * * O * O
* * * * * * * * O * * O
* * * * * * * * * * * * * * *
4 6 8
O O O
O O O O O O
* O * O O O O O O
* * * * * * * * O * * O
* * * * * * * * * * * * * * *
```
**Commented code**
```
->n{a=[];b=x=0 #a[] = empty array for solution;b = base size; x = asterisk count
(a<<"* "*b+=1)while(x+=b)<n||2==c=x-n #Add rows to a while asterisk count is below n, or the count is exactly 2 above n. Save the difference between the count and the required in c
(-~c/2).times{|i|a[i][0]=a[i][-2]=' '} #Overwrite the excess asterisks with spaces by looping (c+1)/2 times. An odd number of asterisks is deleted because there is only one on the 1st row.
~c%2*c>0&&a[2][2]=' ' #If there was a positive even number of excess asterisks, we still need to delete the middle asterisk on row 2.
a.map{|j|j.center b*2}} #Return an array of strings, each centred to width b*2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~53~~ 43 bytes
```
ŒṗQƑƇḂ⁹ƤḄ_’ʋⱮ3Ȧ$ƇṀÞḢµạṀIḂ’+Ʋ⁶ẋ;"b1KḣƊ€z⁶ZŒB
```
[Try it online!](https://tio.run/##AYQAe/9qZWxsef//xZLhuZdRxpHGh@G4guKBucak4biEX@KAmcqL4rGuM8imJMaH4bmAw57huKLCteG6oeG5gEnhuILigJkrxrLigbbhuos7ImIxS@G4o8aK4oKseuKBtlrFkkL/O@KAnCAtPsK24oCdO8OHWSQKw4figqxq4oG@wrbCtv//NTA "Jelly – Try It Online")
A monadic link taking an integer and returning a list of lists. >50% of the code is focused on the ASCII art aspect. If a list of integers indicating row sizes were permissible, [this would be 20 bytes](https://tio.run/##AVEArv9qZWxsef//xZLhuZdRxpHGh@G4guKBucak4biEX@KAmcqL4rGuM8imJMaH4bmAw57huKL/O@KAnCAtPiDigJ07w4fhub4kCsOH4oKsWf//NTA).
In brief, this is the algorithm:
1. Generate all integer partitions of n
2. Keep only those made of distinct integers
3. Keep only those where there is no length 2 subsequence of odd numbers and no length 3 subsequence that is odd, even, even.
4. Keep one of the lists with the smallest maximum integer
5. Left pad the list of integers with spaces; in general, this is max integer minus current integer, but where there are two even numbers in a row, there is one less space.
6. Half the integer, rounding up, convert to unary and separate with spaces, with an extra space if the integer is even
7. Right pad with spaces to make each line the same length.
8. Palindromise each line
Full explanation to follow.
---
As an alternative, here’s a translation of [@LevelRiverSts clever Ruby solution](https://codegolf.stackexchange.com/a/233492/42248):
# [Jelly](https://github.com/DennisMitchell/jelly), 49 bytes
```
ŻÄ_=2o<ʋ0Tðb1K€a3¦€3¦S_Ḃo¬Ɗɗ^Ø.¦"S_HĊʋb1ɗŻṛ¡"U{o⁶
```
[Try it online!](https://tio.run/##AXYAif9qZWxsef//xbvDhF89Mm88yoswVMOwYjFL4oKsYTPCpuKCrDPCplNf4biCb8KsxorJl17DmC7CpiJTX0jEisqLYjHJl8W74bmbwqEiVXtv4oG2/zvigJwtPsK24oCdO8OHWSQKw4figqxq4oG@wrbCtv//MTAw "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~69~~ ~~60~~ 56 bytes
~~Very~~ slow bruteforcing approach. Generates all triangles of with the right number of stars in increasing size.
```
[N>L©ODULI.ÆεXLå}vy®£0δ.ýJ.c0ð:D.BÐíQs…1 1ƵA:€Sø€ü@PP*iq
```
[Try it online!](https://tio.run/##AWIAnf9vc2FiaWX//1tOPkzCqU9EVUxJLsOGzrVYTMOlfXZ5wq7CozDOtC7DvUouYzDDsDpELkLDkMOtUXPigKYxIDHGtUE64oKsU8O44oKsw7xAUFAqaXH//zE3/y0tbm8tbGF6eQ "05AB1E – Try It Online")
If we sacrifice the performance, two more bytes can be saved: [Try it online!](https://tio.run/##AV4Aof9vc2FiaWX//1swTE4@TMKpT8OjdnlPSVF5wq7CozDOtC7DvUouYzDDsDpExaAuQsOQw61Rc@KApjEgMca1QTrigqxTw7jigqzDvEBQUCoqaXH//zT/LS1uby1sYXp5 "05AB1E – Try It Online")
Some high-level comments:
```
[ # for N in 0, 1, ...
N>L©O # K = (N+1-th triangular number)
DULI.ÆεXLå} # all length K lists of 0's and 1's that sum to the input
vy # for each list y
®£0δ.ýJ.c0ð:D.B # format as a pyramid with 1's and spaces
ÐíQ # is it symmetric?
…1 1ƵA: # make the pyramid "dense", fill the gaps between 1's
€Sø€ü@PP* # check if each column is supported
iq # if so, exit and implicitly print
```
[Answer]
# JavaScript (ES7), 186 bytes
A rather naive search, but reasonably fast.
```
f=(n,W)=>(g=(w,x=2**w-1,o='',t=n,p=o,X=x)=>x?(i=t,s='',h=k=>k--&&(q=(x&X)>>k&1)|2*h(k,i-=q,s+=' X'[q]+' '))(w)==x&&g(w-1,x&x/2,p+s+`
`+o,i,p+' ')||o&&g(w,x-1,o,t,p,X):!t&&o)(W)||f(n,-~W)
```
[Try it online!](https://tio.run/##HY5Lb4MwEITv@RWuFNlrWKeFPtNq6anXXkFKI4FoeJTIhoCKpZD@dWJ6GGl3v9HO/GS/WZ@f6nZQ2nwf5rkg0BhLiqAkGNFS6HmjCtCQEDiQxpYMJmSdw75DTQP2C6mooahRinPoCCxPZBQ1PJBT6FXQYK2ow94nwRKx6/a@YEJKGCWR5byEJcByexti6/d@ukp9g7WbF9s0mX8L2qUFDthiIl9vBs6NhNjhwhVWf7Gc33YPyJ6RvSDbIgtCp3sndwncHt4he3xydLtfbQpz@sjyCjSjiOVG9@Z42BxNCeknI7Y@68uXXp/dZ3lJpZyv "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes
```
NθW∨›θ⁰⁼θ±²≧⁻L⊞Oυωθ↘Eυ⭆⁻Lυκ§ *⎇∧κλ∨﹪責∧θ⁼²⁺κλ›⊕⊗⁺κλ±θ
```
[Try it online!](https://tio.run/##TU/bSsQwEH33K8I@TSSC9k33qbAiBdst6g9k2yEtm03aXKx@fZx0LzgQwsy5zJxukK6zUqdUmSmGJp4O6GDm27tlGDUy2Dt4cyhDngr2yAV7naPUPncNKgKg4FSsllPp/ajMx6iGAPVoohfsHY0KA7TRD/sJnQzWQRRs4WSUt7RuNAFednY560T2yYzPQIjKzeoEF6NIuiO9MlSmxx/YsPuNYF/ojHS/UJoejoJpItDdte2jtvnQggaNDSs@3xIUgrWarFcFzxddk1amc3hCE7CHnY0HTf9/6i36zM@1TenpOT186z8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @LevelRiverSt's observations.
```
Nθ
```
Input `n`.
```
W∨›θ⁰⁼θ±²≧⁻L⊞Oυωθ
```
Subtract increasing number of rocks from `n` until the result is no longer positive, but subtract the next number if the result is exactly `-2`.
```
↘Eυ⭆⁻Lυκ§ *⎇∧κλ∨﹪責∧θ⁼²⁺κλ›⊕⊗⁺κλ±θ
```
Print a triangle of rocks, but remove rocks symmetrically from both sides as necessary, and also the rock directly below the topmost rock if necessary.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 176 170 bytes
```
g:{r:,1+&b:1+#**|x
s:(,'/2#,:)'x@&b>2*#'*:'x
s:x@&2!b+#'*:'x:s,x
?x,((,!0),0^@\:[;!b]'{(&-2!x-#*y),/:y}[b]'s),\:r}
f:{*(x=+//')#({~(x=#**|:y)||/x=+//'y}[x])g/(,,,1)}
```
[Try it online!](https://ngn.codeberg.page/k#eJwljsFuwyAQRO/+isVIZhc2wtCkaTZq6/+IU1U+JD3HFyxwv700vs280WjmLvkhHFw3SXDa2pIagFmQjY+ahUwauukjWm2smC2rJKrJbURmrvQzMSKrnrj/Gka5nNV0NRm7XVRpp+1C7GVZLxXOxKM81uYm2WJ6d94b0ph/q/5fl4VK8RuvhXSlu0dmDrQ2zfwj+bsXrMfalrgF2w71ZwnYmaK00OjYu+qeMj0b5mb2cIQ3OEGIEF4gHCGcIPZweD3/AZT5PCI=)
-6 bytes : @Adám
Recursively build up structures by placing either one or two smaller such structures on top of a base wide enough to accommodate them.
Could probably use a better heuristic for impossible answers. Currently just iterates until the base is as wide as the target.
] |
[Question]
[
The 16-color CGA palette (also known as the [HTML colors](https://en.wikipedia.org/wiki/Web_colors#HTML_color_names)) is a set of 16 colors used by early graphics adapters. The goal of this challenge is to output all 16 of them, in hex format (`RRGGBB`), in ascending order by hex value, separated by newlines. Thus, the output should be exactly this:
```
000000
000080
0000FF
008000
008080
00FF00
00FFFF
800000
800080
808000
808080
C0C0C0
FF0000
FF00FF
FFFF00
FFFFFF
```
A single trailing newline is allowed, but not required.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ ~~29~~ 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“×Ɗ¡‘ŒP»Ṫ¦209ṗ€3Fd⁴ịØHs3ṢQY
```
[Try it online!](https://tio.run/nexus/jelly#ATUAyv//4oCcw5fGisKh4oCYxZJQwrvhuarCpjIwOeG5l@KCrDNGZOKBtOG7i8OYSHMz4bmiUVn//w "Jelly – TIO Nexus")
### How it works
`“×Ɗ¡‘` yield the code points of the characters between the quotes in Jelly's [SBCS](https://github.com/DennisMitchell/jelly/wiki/Code-page), which are **0x11 = 17**, **0x91 = 145**, and **0x00 = 0**.
`ŒP` constructs the powerset of the array of code points, yielding
```
[[], [17], [145], [0], [17, 145], [17, 0], [145, 0], [17, 145, 0]]
```
The last two entries correspond to combinations that contain both **80** and **FF**, so we have to discard them.
`»Ṫ¦209` consists of three parts:
* `Ṫ` (tail) removes the last array of code points, i.e., **[17, 145, 0]**.
* `»209` takes the maximum of each integer in the remainder of the powerset and **0xD1 = 209**, replacing all of them with **209**.
* `¦` (sparse) iterates over the elements of the remainder of the powerset. If the corresponding index is found in **[17, 145, 0]**, the element is replaced with all **209**'s. If not, it is left untouched.
`¦` isn't modular, so this modifies only the last array (index **0**) in the remainder of the powerset. The indices **17** and **145** are too large and have no effect.
The result is as follows.
```
[[], [17], [145], [0], [17, 145], [17, 0], [209, 209]]
```
`ṗ€3` computes the third Cartesian power of each array, i.e., the array of all 3-tuples of elements of each array.
`Fd⁴` flattens the result and computes quotient and remainder of each integer divided by **16**.
`ịØH` indexes (1-based) into **"0123456789ABCDEF**, so **0x11**, **0x91**, **0x00**, and **0xD1** get mapped to **"00"**, **"80"**, **"FF"**, and **"C0"** (resp.).
`s3ṢQ` splits the character pairs into 3-tuples, sorts the tuples, and deduplicates.
Finally, `Y` joins the unique tuples, separating by linefeeds.
[Answer]
# Bash + GNU Utilities, 67
* 2 bytes saved thanks to @manatwork
* 2 bytes saved thanks to @zeppelin
```
a={00,80,FF}
eval echo $a$a$a|fmt -w9|sed '16iC0C0C0
/F0*8\|80*F/d'
```
* The [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) `{00,80,FF}{00,80,FF}{00,80,FF}` gives all need combinations in the right order (excluding `C0C0C0`), along some extras. The extras are the ones that contain both `F` and `8` characters.
* The result of the brace expansion is a single space-separated line. `fmt` puts each entry on its own line
* The 1st line of the `sed` expression inserts `C0C0C0` in the appropriate line
* The 2nd line of the `sed` expression filters out the "extras" described above.
[Ideone](https://ideone.com/kXRDqI).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“mạ9ṣṃwɠƁ,¡ẓw’b4µża1$ị“08CF”s3Y
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=4oCcbeG6oTnhuaPhuYN3yaDGgSzCoeG6k3figJliNMK1xbxhMSThu4vigJwwOENG4oCdczNZ&input=)**
Base 250 compression of a number (`“...’`),
converted to base 4 (`b4`),
zipped (`ż`) with a copy of itself after a vectorised logical-and with 1 (`a1$`)\*,
indexed (`ị`) into the four characters used (`“08CF”`),
split into chunks of length 3 (`s3`),
and joined with line feeds (`Y`).
\* Thus pairing each zero digit with another zero and each of any other digits with a one. Along with the following indexed fetch this means `'F'` becomes paired with another `'F'` while `'0'`,`'8'`, and `'C'` each pair with a `'0'`.
[Answer]
# Python 3, ~~134~~ ~~129~~ ~~125~~ ~~108~~ ~~91~~ 90 bytes
I think there is still a lot of golfing to do here. Golfing suggestions welcome!
**Edit:** -9 bytes and many thanks to Mego for helping with the string formatting. -17 bytes from figuring out a better way to print the string in the first place. -17 bytes from figuring out a better way to write the for loop in the first place. -1 byte thanks to xnor's tip to use `i%3//2*"\n"` instead of `"\n"*(i%3<2)`.
```
for i in range(48):print(end="F0C8F000"[0x10114abf7f75c147d745d55//4**i%4::4]+i%3//2*"\n")
```
**Ungolfing**
```
z = 0
a = [0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 2, 2, 2, 3, 3, 3, 1, 3, 3, 3, 1, 3, 1, 1, 3, 0, 0, 1, 1, 0, 1, 3, 3, 1, 1, 3, 1, 0, 1, 1, 3, 1, 1, 1, 1, 1]
for i in range(len(a)):
z = (z + a[i]) * 4
z //= 4 # we multiplied by 4 one too many times
for i in range(48):
m = z // 4**j % 4
s = "F0C8F000"[c::4]
if i % 3 == 2:
s += "\n"
print(s, end="")
```
[Answer]
## JavaScript (ES6), ~~109~~ 107 bytes
*Saved 2 bytes, thanks to Neil*
This is ~~7~~ 9 bytes shorter than just returning the raw string in backticks.
```
_=>[...'1121173113106393'].map(v=>[4,2,0].map(x=>'08CF'[x=n>>x&3]+'000F'[x],n+=+v||21).join``,n=-1).join`
`
```
### Test
```
let f =
_=>[...'1121173113106393'].map(v=>[4,2,0].map(x=>'08CF'[x=n>>x&3]+'000F'[x],n+=+v||21).join``,n=-1).join`
`
console.log(f())
```
[Answer]
## PowerShell, ~~113~~ 106 bytes
```
'777
7780
77FF
7807
78080
7FF7
7FFFF
8077
80780
80807
808080
C0C0C0
FF77
FF7FF
FFFF7
FFFFFF'-replace7,'00'
```
~~Yeah, I haven't found anything shorter than just printing the literal string...~~ Thanks to @[Martin Smith](https://codegolf.stackexchange.com/users/47524/martin-smith) for shaving down 7 bytes using a simple replacement (which I completely overlooked). So, we're at least 7 bytes shorter than simply hardcoding it. Yay!
***But that's boring!***
So instead ...
## PowerShell v4, 128 bytes
```
[consolecolor[]](0,7+9..15)+-split'Lime Maroon Navy Olive Purple Silver Teal'|%{-join"$([windows.media.colors]::$_)"[3..8]}|sort
```
The `[system.consolecolor]` namespace defines the console colors (natively) [available](https://codegolf.stackexchange.com/a/98984/42963) to the PowerShell console. If we reference them via an integer array like this, the default value is the name (e.g., `Black` or `White` or the like). We combine that with a string that has been `-split` on spaces, so now we have an array of strings of color names.
We loop through those `|%{...}` and each iteration pull out the corresponding `[system.windows.media.colors]` value. The default stringification for those objects is the color in `#AARRGGBB` format as a hex value, so we leverage that by encapsulating that call in a string with a script block `"$(...)"`. But, since we don't want the alpha values or the hash, we take the back end `[3..8]` of the string, and need to `-join` that resulting `char`-array back into a string. Then, a simple `Sort-Object` to put them in the right order.
[Answer]
# Pyth - ~~64~~ ~~48~~ 44 bytes
Super simple base compression.
```
jcs@L"FC80"jC"ÿÿûÿ¿û¿ðÿ¿»¿»·wðð\0ð\0"4 6
```
[Try it online here](http://pyth.herokuapp.com/?code=jcs%40L%22FC80%22jC%22%C3%BF%C3%BF%C3%BB%C3%BF%0F%C2%BF%C3%BB%C2%BF%0F%C3%B0%0B%C3%BF%C2%BF%C2%BB%C2%BF%C2%BB%C2%B7w%0F%C3%B0%C3%B0%5C0%C3%B0%5C0%224+6&debug=0).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 39 bytes
```
'80FFC000'2e'3na:1Fswv1=`uIn'F4:ZaZ)6e!
```
[Try it online!](https://tio.run/nexus/matl#@69uYeDm5mxgYKBulKpunJdoZehWXF5maJtQ6pmn7mZiFZUYpWmWqvj/PwA "MATL – TIO Nexus")
```
'80FFC000' % Push this string
2e % Reshape with 2 rows. So 1st column contains '80', 2nd 'FF' etc
'3na:1Fswv1=`uIn' % Push this string
F4:Za % Convert from base 95 to alphabet [1 2 3 4]
Z) % Use as column indices into the first string
6e! % Reshape with 6 rows and transpose.
% Implicitly display
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 57 bytes
```
•P{Ætg7«r¨ëÅ,…}ù¢Ý%Vt®£8ãøÚ$0óDÛY²Zþ…ð7ê‘Ó{òìàYëØU¥•hR6ô»
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCiUHvDhnRnN8KrcsKow6vDhSzigKZ9w7nCosOdJVZ0wq7CozjDo8O4w5okMMOzRMObWcKyWsO-4oCmw7A3w6rigJjDk3vDssOsw6BZw6vDmFXCpeKAomhSNsO0wrs&input=Mzk0MDIwMDM4NTcwMjU4OTAzNTc3MjEwNjA1MjQ3NTU5OTIyNjE2NjEwNjIwOTk0MzI5NDE0NzUyNzI0NDgxMDMyOTY2NDQ2OTY2ODM3MDkwMjY3OTMwNDMxNTA0MzA5NDUyMDg5MTAwMDc4Njk4OTg3NTI)
What we need to output is basically (reversed and split):
```
FFFFFF00FFFFFF00FF0000FF0C0C0C080808000808080008000008FFFF0000FF00080800000800FF0000080000000000
```
Which, in decimal is:
```
39402003857025890357721060524755992261661062099432941475272448103296644696683709026793043150430945208910007869898752
```
Which in Base-214 is:
```
P{Ætg7«r¨ëÅ,…}ù¢Ý%Vt®£8ãøÚ$0óDÛY²Zþ…ð7ê‘Ó{òìàYëØU¥
```
This is the simplest solution I could come up with, because there's no way in hell I'm beating Dennis. Spent an hour trying and nothing beat his idea.
[Answer]
# PHP, 92 Bytes
```
<?=strtr("000
001
002
010
011
020
022
100
101
110
111
333
200
202
220
222",["00",80,FF,CO]);
```
[Try it online!](https://tio.run/nexus/php#DYwxCoAwFEP3f4xOCn9I0kVQcRC6egDxEtX71wwh4SVkbMf@fv3rUwEQAC0F6Exn2aWgO7qjOc1rrSEzeStvJJW8fVFyQbaW5/XM6xg/ "PHP – TIO Nexus")
simply replacement from the digits as key in the array with the values [strtr](http://php.net/manual/en/function.strtr.php)
[Answer]
## Batch, 137 bytes
```
@for %%c in (000000 000080 0000FF 008000 008080 00FF00 00FFFF 800000 800080 808000 808080 C0C0C0 FF0000 FF00FF FFFF00 FFFFFF)do @echo %%c
```
Yes, it's that boring. Previous 148-byte attempt:
```
@if "%2"=="" (call %0 000000 80&call %0 C0C0C0 FF)|sort&exit/b
@echo %1
@for %%c in (0000%2 00%200 00%2%2 %20000 %200%2 %2%200 %2%2%2)do @echo %%c
```
Unfortunately you can't pipe the output of a `for` or a `call:` command, so I have to invoke myself recursively.
[Answer]
## Pyke, 42 bytes
```
"80FF"2c8DF3"00"]F3+b2tRT`_R.:(s}"C0"3*+SJ
```
[Try it here!](http://pyke.catbus.co.uk/?code=%2280FF%222c8DF3%2200%22%5DF3%2Bb2tRT%60_R.%3A%28s%7D%22C0%223%2a%2BSJ&input=000000%0A000080%0A0000FF%0A008000%0A008080%0A00FF00%0A00FFFF%0A800000%0A800080%0A808000%0A808080%0AC0C0C0%0AFF0000%0AFF00FF%0AFFFF00%0AFFFFFF)
[Answer]
# Befunge, ~~83~~ 69 bytes
```
<v"UVTYZQPefij?EDA@"
v>>9\:4/:\4/>4%:3g,0`
<^_@#:,+55$_^#!-9:,g3
F08C
```
[Try it online!](http://befunge.tryitonline.net/#code=PHYiVVZUWVpRUGVmaWo_RURBQCIKdj4-OVw6NC86XDQvPjQlOjNnLDBgCjxeX0AjOiwrNTUkX14jIS05OixnMwpGMDhD&input=)
The colours are encoded in the string you see on the first line, two bits per colour component, with an additional high bit set to force each value into the ASCII range (except in the case of 63, which would be out of range as 127).
The list of colours on the stack is then processed as follows:
```
9\ 9 is pushed behind the current colour to serve as a marker.
:4/:\4/ The colour is repeatedly divided by 4, splitting it into 3 component parts.
> The inner loop deals with each of the 3 components.
4% Modulo 4 masks out the 2 bits of the colour component that we care about.
:3g, That is used as an index into the table on line 4 to get the character to output.
0`3g, For component values greater than 0 the second char is a '0', otherwise an 'F'.
:9-! Check if the next component is our end marker.
^ If not, repeat the inner loop.
55+, Output a newline.
:_ Repeat the outer loop until there are no more colours on the stack.
```
[Answer]
# C#, 195 bytes
```
void n(){string a="000000\r\n000080\r\n0000FF\r\n008000\r\n008080\r\m00FF00\r\n00FFFF\r\n800000\r\n800080\r\n808000\r\n808080\r\nC0C0C0\r\nFF0000\r\nFF00FF\r\nFFFF00\r\nFFFFFF";Console.Write(a);}
```
Sadly this beats, by a huge margin, the more interesting albeit incredibly convoluted (I had tons more fun writing it) **C#, 270 bytes**
```
void n(){string a,b,c,d;a="00";b="80";c="C0";d="FF";for(int i=0;i<16;i++){Console.WriteLine((i<7?a:i<11?b:i>11?d:c)+(i<3?a:i<5?b:i<7?d:i<9?a:i<11?b:i==11?c:i<14?a:d)+(i==0||i==3||i==5|i==7||i==9||i==12||i==14?a:i==1||i==4||i==8||i==10?b:i==2||i==6||i==13||i==15?d:c));}}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 99 bytes
```
f(i){for(i=48;i--;)printf("%.2s%s","FFC08000"+("#&/28MNQRSV]^_ab"[i/3]-35>>i%3*2&3)*2,"\n\0"+i%3);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOi2/SCPT1sTCOlNX11qzoCgzryRNQ0lVz6hYtVhJR8nNzdnAwsDAQElbQ0lZTd/IwtcvMCg4LDYuPjFJKTpT3zhW19jUzi5T1VjLSM1YU8tIRykmLwaoHCiiaV37H2icQm5iZp6GJlc1F2eahqY1V@1/AA "C (gcc) – Try It Online")
After having made an attempt involving creating a list of numbers and outputting them while sorting, I compared to the naïve solution, which was sobering:
```
f(){puts("000000\n000080\n0000FF\n008000\n008080\n00FF00\n00FFFF\n800000\n800080\n808000\n808080\nC0C0C0\nFF0000\nFF00FF\nFFFF00\nFFFFFF");}
```
That one clocks in at 140 bytes compared to my try at 200 and change.
The solution was to think of it as text like any other, albeit with a small alphabet. Each colour could be thought of as a triplet of 2-bit indices into the alphabet {0xff, 0xc0, 0x80, 00}. The process of colour -> triplet -> number -> character (with offset +35 to make them all printable and avoid any need for escapes) can be illustrated as such:
```
000000 333 63 b
000080 332 62 a
0000FF 330 60 _
008000 323 59 ^
008080 322 58 ]
00FF00 303 51 V
00FFFF 300 48 S
800000 233 47 R
800080 232 46 Q
808000 223 43 N
808080 222 42 M
C0C0C0 111 21 8
FF0000 033 15 2
FF00FF 030 12 /
FFFF00 003 3 &
FFFFFF 000 0 #
```
Then it's just a matter of iterating over the resulting string and cutting out the appropriate parts of the alphabet string.
] |
[Question]
[
This is a mirror: `|`. I just found out that you can stick a mirror in the middle of a string if the string can be mirrored on itself! For example, the string `abccba`. If you cut it in half the two halves are mirror images of each other:
```
abc <--> cba
```
So, we can stick a mirror in the middle of the string, and our new string is `abc|cba`. Sometimes, only part of the string can be mirrored on itself. For example, the string "mirror". The two r's are mirrored, but the rest of the string isn't. That's OK, we'll just remove the parts of the string that don't mirror each other, and we get the following string:
```
r|r
```
Some strings could be mirrored in multiple places. For example, "Hello World, xyzzyx". I like having a lot of text reflected in my mirror, so you need to find the best place to put my mirror. In this case, you should output the longer mirrored string and just like our last example, remove everything else. This string becomes:
```
xyz|zyx
```
Some strings *look* like they can be mirrored, but actually can not. If a string cannot be mirrored anywhere, you should output nothing.
# The challenge:
Given a string containing only printable-ascii, find the best place to put my mirror. In other words,
>
> Find the largest even-length palindromic substring, then output it with a pipe character '|' in the middle of it.
>
>
>
The input will be 1-50 characters long.
You can assume that the input will not contain mirrors `|` or newlines. Beyond that, all printable-ascii characters are fair game. If the longest mirrored substring is tied between two substrings, you can choose which one to output. For example, for the string "abba ollo", you must output "ab|ba" or "ol|lo", but it doesn't matter which one you output. Strings are case-sensitive, e.g. "ABba" should *not* output "AB|ba", it should output the empty string.
# Sample IO:
```
"Hello World" --> "l|l"
"Programming Puzzles and Code-Golf" --> Either "m|m" or "z|z"
"abcba" --> ""
"Hulluh" --> "ul|lu"
"abcdefggfedcba" --> "abcdefg|gfedcba"
"abcdefggfabc" --> "fg|gf"
"AbbA" --> "Ab|bA"
"This input is a lot like the last one, but with more characters that don't change the output. AbbA" --> "Ab|bA"
```
As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!
[Answer]
# Pyth - ~~19~~ ~~17~~ ~~15~~ 13 bytes
*Thanks to @FryAmTheEggman for saving me two bytes.*
~~ARRGH the special case for no answer.~~ Solved that!
```
e_I#jL\|cL2.:
```
[Test Suite](http://pyth.herokuapp.com/?code=e_I%23jL%5C%7CcL2.%3A&test_suite=1&test_suite_input=%22Hello+World%22+++++%0A%22Programming+Puzzles+and+Code-Golf%22+++++%0A%22abcba%22+++++++++++%0A%22Hulluh%22++++++++++%0A%22abcdefggfedcba%22++%0A%22abcdefggfabc%22++++%0A%22AbbA%22++++++++++++%0A%22This+input+is+a+lot+like+the+last+one%2C+but+with+more+characters+that+don%27t+change+the+output.+AbbA%22+&debug=0).
```
e Last element in list, this works out to longest one
_I Invariance under reverse, this detect palindrome
# Filter
jL Map join
\| By "|"
cL2 Map chop in two pieces
.:Q) Substrings. Implicit Q). ) makes it do all substrings.
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~19~~ ~~17~~ 14 bytes
Code:
```
Œévy2ä'|ý©ÂQi®
```
Explanation:
```
Œ # Get all substrings of the input
é # Sort by length (shortest first)
vy # For each element...
2ä # Split into two pieces
'|ý # Join by "|"
© # Copy this into the register
 # Bifurcate, pushing a and reversed a
Q # Check if it's a palindrome
i® # If so, push that string again
# Implicit, the top element is outputted
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=xZLDqXZ5MsOkJ3zDvcKpw4JRacKu&input=YWJjZGVmZ2dmZWRjYmE).
[Answer]
# Python 2, ~~102~~ 97 bytes
```
def f(s):h=len(s)/2;r=s[:h]+'|'+s[h:];return s and max(r*(r==r[::-1]),f(s[1:]),f(s[:-1]),key=len)
```
Rather slow and inefficient... Verify the smaller test cases on [Ideone](http://ideone.com/NckMlB).
[Answer]
# JavaScript, ~~100~~ 99 bytes
```
s=>eval('for(O=i=0;s[i++];O=O[j+j]?O:o)for(o="|",j=0;(S=s[i-1-j])&&S==s[i+j++];o=S+o+S);O[1]?O:""')
```
**or**
```
s=>eval('for(O="",i=0;s[i++];O=O[j+j]||j<2?O:o)for(o="|",j=0;(S=s[i-1-j])&&S==s[i+j++];o=S+o+S);O')
```
[Answer]
# Lua, 133 bytes
```
s=...for i=#s,1,-1 do for j=1,#s-i do m=j+i/2-i%2/2t=s:sub(j,m).."|"..s:sub(m+1,i+j)if t==t.reverse(t)then print(t)return end end end
```
[Verify all testcases on Ideone.com](http://ideone.com/OmmYrR).
[Answer]
## [Retina](https://github.com/m-ender/retina), 66 bytes
Byte count assumes ISO 8859-1 encoding.
```
M!&`(.)+(?<-1>\1)+(?(1)¶)
O$#`.+
$.&
A-2`
^(.)+?(?=(?<-1>.)+$)
$&|
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYApNISZgKC4pKyg_PC0xPlwxKSsoPygxKcK2KQpPJCNgLisKJC4mCkEtMmAKXiguKSs_KD89KD88LTE-LikrJCkKJCZ8&input=SGVsbG8gV29ybGQKUHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZS1Hb2xmCmFiY2JhCkh1bGx1aAphYmNkZWZnZ2ZlZGNiYQphYmNkZWZnZ2ZhYmMKQWJiQQpUaGlzIGlucHV0IGlzIGEgbG90IGxpa2UgdGhlIGxhc3Qgb25lLCBidXQgd2l0aCBtb3JlIGNoYXJhY3RlcnMgdGhhdCBkb24ndCBjaGFuZ2UgdGhlIG91dHB1dC4gQWJiQQ) (The first line enables testing of several linefeed-separated test cases at once.)
Hmmm, much longer than I would like...
[Answer]
# JavaScript (ES6), 91
```
s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r
```
*Less golfed*
```
f=s=>
[...s].map(
(d,i) => {
for(a='|', j=0; d=s[i-j], d&&d==s[i-~j]; r = r[j++ +j]? r : a)
a = d+a+d
}, r=''
) && r
```
**Test**
```
F=
s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r
;[["Hello World", "l|l"]
,["Programming Puzzles and Code-Golf", "m|m"]
,["abcba", ""]
,["Hulluh", "ul|lu"]
,["abcdefggfedcba", "abcdefg|gfedcba"]
,["abcdefggfabc", "fg|gf"]
,["AbbA", "Ab|bA"]
,["This input is a lot like the last one, but with more characters that don't change the output. AbbA", "Ab|bA"]]
.forEach(t=>{
var i=t[0],k=t[1],r=F(i)
console.log(k==r?'OK ':'KO ',i+' -> '+r,k!=r?'(check '+k+')':'')
})
```
[Answer]
## Perl 5, ~~105~~ ~~100~~ 98 + 1 = ~~106~~ ~~101~~ 99 bytes
```
/(?=((.)(?1)?\2)(?{[push@_,$1})(?!))/;($_)=sort{length$b<=>length$a}@_;substr($_,length>>1,0)='|'if$_
```
I just wanted to give recursive regexes a go. Needs the `-p` option. Edit: Saved (crossed out 4) 7 bytes thanks to @msh210. (The missing byte is due to a saving that was superseded by @msh210's latest saving.)
[Answer]
## Python 2, 91 bytes
```
f=lambda s,p='':s and max((''<p<=s<p+'\x7f')*(p[::-1]+'|'+p),f(s[1:]),f(s[1:],s[0]+p),key=len)
```
Replace `\x7f` with the actual character DEL, which is ASCII 127 (credit to Dennis).
This follows a similar strategy to [Dennis's answer](https://codegolf.stackexchange.com/a/84402/20260) of using `max` and recursively branching to find the longest palindrome interval. But, instead, it finds the left half, checking that the corresponding mirrored right half comes right after it with a [self-made startswith](https://codegolf.stackexchange.com/a/51783/20260).
The function guesses whether the first character is in the mirrored left half. If not, it just drops it and recurses on the remainder. If it is, it's added to to the stack `p` of reversed characters. If the string ever starts with the stack, the mirror string is generated and considered as a possible longest mirror. To avoid `|` as an output, only non-empty stacks are considered.
[Answer]
# Haskell, ~~126~~ 111 bytes
```
(!)=drop
f s|n<-length s=last$"":[a++'|':b|k<-[1..n],t<-map(!s)[1..n-k],let[a,b]=take k<$>[t,k!t],a==reverse b]
```
[Answer]
# TSQL ~~227~~ 223 bytes
I hardcoded the length to max 99 bytes, this saved bytes but made it slower. It still have a decent performance though.
**Golfed:**
```
DECLARE @t varchar(99)='AbccbA'
,@z char(99)='',@a INT=0,@ INT=0WHILE @a<LEN(@t)SELECT
@z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE
Thai_bin,x+'|'+REVERSE(x),@z),@=IIF(@=50,1,@+1),@a+=IIF(@=1,1,0)FROM(SELECT
SUBSTRING(@t,@a,@)x)x PRINT @z
```
**Ungolfed:**
```
DECLARE @t varchar(99)='AbccbA'
,@z char(99)='',
@a INT=0,
@ INT=0
WHILE @a<LEN(@t)
SELECT
@z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE Thai_bin,x+'|'
+REVERSE(x),@z),
@=IIF(@=99,1,@+1),
@a+=IIF(@=1,1,0)
FROM
(SELECT SUBSTRING(@t,@a,@)x)x
PRINT @z
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/edit/507690)**
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
►S=↔ΘmoJ'|½Q
```
[Try it online!](https://tio.run/##PY09TgQxDIWvYk2zzcINKFYUrKgWsRIFonAmniRaJ0b5EdKKBgpOgBBnQaLhABxiLhIMI1G95@89276VQ4/z81Of3z6uz@aX1@/3KJerx6/Pq9777bAlZoEbyWyH9bDL4jLGGJKDXTsemQpgsnAulk4uhCftoBkNqm4bc/MLsDQ5N5Fdkn@gRseNMRuVvQ8FQrpvFdQgsFTgcCConoCxVJBEazCaP4TqIUomGD1mHCvlojWsYCWt6i9NblmUVvXiKfw9ufsB "Husk – Try It Online")
-1 from Leo.
[Answer]
## Python 2, 149 bytes
```
R,L,s=range,len,input()
t=max([s[i:j/2+i/2]for i in R(L(s))for j in R(L(s)+1)if s[i:j]==s[i:j][::-1]and(j-i)%2<1],key=L)
print t+'|'*(L(t)>0)+t[::-1]
```
[Try it online](http://ideone.com/fork/jxoIbM)
This program finds the first half of the largest palindromic substring of even length, and prints that string, followed by a `|`, followed by that string reversed. If there is no suitable string, `t` will be the empty string, and `'|'*(L(t)>0)` will evaluate to the empty string.
[Answer]
# Java 8, ~~294~~ ~~283~~ 232 bytes
```
s->{int l=s.length(),i=0,j,z,y=0;String a,b="";for(;i<l;i++)for(j=0;j<=l-i;)if((a=s.substring(i,i+j++)).equals(new StringBuffer(a).reverse()+"")&(z=a.length())%2<1&z>y){y=z;b=a;}return y>0?b.substring(0,y/=2)+"|"+b.substring(y):"";}
```
**Explanation:**
[Try it here.](https://tio.run/##jVJNb9swDL33V3AG1kmw42U9znGGbof1sqLABuww9EDbtC1XljJJTmFn@e0Z0xpFLkUKSAA/Hh/JB3a4xYXdkOmqh0Op0Xv4gcrsLgCUCeRqLAlujy7Az@CUaaAUs@FlxvE9f34@YFAl3IKBHA5@sd5xPejcp5pME1ohE5Uvky6ZkjFfZjMFJkUeRVltncjUSmcqjuXR6RjSrXK9UJlUtRDIPH4o/FOVUImKO0bKlP4OqL0w9DhP93Woa3ICZepoS86TkHEUyUsx5fgyiXx/tfp0Oa1HuRvzKStyzPaOwuAMjOvll@Kk1TIZP@ZXzPEvik/jo/zMc@8P2fP2m6HQvP0swtaqCnqWcVbqzz2gnDUcfaA@tUNIN5wK2giTliK6Ia1tAr@t09W7SD4p@zr6ztnGYd8fJbwbpkmTBzQVfLMVLb5bXZ9lwKIs8CzqZtB6aN9CVlHdNDVVb2F9gbNxFnxdFNdnQb9a5fleN0MANhC05dNTDwShJeCjDmANJVBw/lGFFnrrCMoWHZZ8455hGKCy5kM4Rk3zXMhtmDGFkxH2F/vDfw)
```
s->{ // Method with String as both parameter and return-type
int l=s.length(), // Length of the input-String
i=0,j, // Index-integers
z,y=0; // Temp-integers
String a,b=""; // Temp-Strings
for(;i<l;i++) // Loop (1) from 0 to `l` (exclusive)
for(j=0;j<=l-i; // Inner loop (2) from 0 to `l-i` (inclusive)
if((a=s.substring(i,i+j++)) // Set the current substring to `a`
.equals(new StringBuffer(a).reverse()+"")
// If `a` is a palindrome
&(z=a.length())%2<1 // And the length of `a` is even
&z>y){ // And the length of `a` is larger than `y`
y=z; // Change `y` to `z`
b=a;} // Change `b` to `a`
// End of inner loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
return y>0? // If the result-length is not 0:
b.substring(0,y/=2)+"|"+b.substring(y)
// Return the result
: // Else:
""; // Return an empty String
} // End of method
```
] |
[Question]
[
In this challenge your goal will be to output the lyrics to Daft Punk's [Harder, Better, Faster, Stronger.](https://www.youtube.com/watch?v=gAjR4_CbPpQ) Specifically, output this text:
```
Work It
Make It
Do It
Makes Us
Harder
Better
Faster
Stronger
More Than
Hour
Our
Never
Ever
After
Work Is
Over
Work It
Make It
Do It
Makes Us
Harder
Better
Faster
Stronger
More Than
Hour
Our
Never
Ever
After
Work Is
Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over
Work It Harder, Make It
Do It Faster, Makes Us
More Than Ever, Hour
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour Af-
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour Af-
Our Work Is Never Over
Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour Af-
Our Work Is Never Over
Work It Harder
Make It Better
Do It Faster Makes Us Stronger
More Than Ever Hour
Our Work Is Never Over
Work It Harder
Do It Faster
More Than Ever
Our Work Is Never Over
Work It Harder
Make It Better
Do It Faster
Makes Us Stronger
More Than Ever
Hour After
Our Work Is Never Over
```
Your output may have a trailing newline or trailing whitespace.
**Built in compression methods are not allowed.**
This is code golf, so shortest code wins!
[Answer]
# Ruby, ~~308~~ 303
```
puts a='Work It|Make It|Do It|Makes Us|Harder|Better|Faster|Stronger|More Than|Hour|Our|Never|Ever|After|Work Is|Over
'.split(?|),a
56.times{|i|puts a[j=i%4/2*4+i%4*2]+' '+a[j+4]+[[' ',', ','
']["l4yq62lhgnizb0kfu".to_i(36)/3**i%3]+a[j+1]+' ',''][i%51/48]+[a[j+5],['','Af-'][i%44/32]][7619655>>i-28&1]}
```
**Algorithm**
Song intro: Take 16 tokens, and print them twice (last one bears an extra newline)
Verses: Riffle the tokens together to make the verses, 4 tokens per line, in the following order:
```
0 4 1 5
2 6 3 7
8 12 9 13
10 14 11 15
```
In some lines, the last token is omitted, or exchanged for `Af-`. These lines are noted with a 1 bit in the magic number 0x744447=7619655.
In three lines, the penultimate token is also omitted, those where `i%51/48==1`
The punctuation in the middle of the line can be one of `' '` `', '` `'\n'`. These are encoded in the number 02220010000200100010001001110010001000100010001000100010 (base 3) = "l4yq62lhgnizb0kfu" (base 36.)
**With comments**
```
puts a='Work It|Make It|Do It|Makes Us|Harder|Better|Faster|Stronger|More Than|Hour|Our|Never|Ever|After|Work Is|Over
'.split(?|),a #Set up array containing all 16 tokens, print it, and print it again (note newlines at end of last token.)
56.times{|i| #14 verses, 4 lines each
puts a[j=i%4/2*4+i%4*2]+ #expression cycles through 0,2,8,10. Print the first token on the line.
' '+a[j+4]+ #print a space, and the second token on the line.
[[' ',', ','
']["l4yq62lhgnizb0kfu".to_i(36)/3**i%3]+a[j+1]+' ',''][i%51/48]+ #if i%51/48==1,print nothing. Otherwise print the 3rd token, followed by a space, and preceded by one of ' ' or ', ' or '\n'
[a[j+5],['','Af-'][i%44/32]][7619655>>i-28&1] #if 7619655>>i-28&1==0 print the fourth token. Otherwise print either nothing or Af- depending on the value of i%44/32
}
```
[Answer]
# Perl, ~~316~~ ~~309~~ ~~308~~ 307 bytes
The source must be encoded as Latin-1.
```
@c=split b,'
Â×
Ô
ÚáÐÙáÒ
ÅOÆÖáEváAftáØ
bÑÏábÝà
bÑÈ-
bÈÇÈÇbHoÆbur
btáÑbÏßËÌÊßÉbHoÜAfbÔ ÒÍbÝà ÐÎber, b Evb× ÙbÓ ÚbBettábOÜØ ÖßbStrongáÛbÕ
ÞàbÝs UsbOvábNevbDoàbÞ IsbFastbHardbMore Thanbur bMakebWorkber b Itber
';$e='ÞàÀÓÀÄÄÄÈÇÏÌÂÎÌÔ
ÛÍÌÅÃÃÃÁËßÊßÅÁÎáÛÍáÁËáÊáÉÇÕ';$f=chr$_+192,$e=~s/$f/$c[$_]/g for 0..34;print$e
```
# Explanation
We start out with the original lyrics. For brevity, let’s assume they are
```
lyrics = "Work Work Harder Harder"
```
Now we find short substrings (≥ 3 characters) that occur often. In this case, `"Work "` occurs twice. We replace each occurrence with character 0xE1. We also remember the replaced string in an array:
```
lyrics = "ááHarder Harder"
substs = ["Work "]
```
The next substring, `"Harder"`, is replaced with 0xE0. The `substs` array grows towards the front:
```
lyrics = "ááà à"
substs = ["Harder", "Work "]
```
This continues for a total of 34 iterations until we get to character 0xC0.
Now we concatenate the `substs` using the character `b` (which doesn’t occur in the lyrics) as a separator. In the Perl code, the `substs` array is stored in `@c` (using the bareword `b` to tell `split` where to split), the new jumbled lyrics are in `$e`, and the code simply reverses the 34 substitutions.
[Answer]
# [Sprects](http://dinod123.neocities.org/interpreter.html), 302 bytes
```
:xxnnnnnnnmW12603 27428 3s59qp wb12604280qpb12603 2742803s59qp0wjb:ncvb:mcQb:WcEb:x1203 204203s50607809q0w0y0i0p0j01l0z00:c1263 27428, 3s59:vqp wj:Qqp, w:Eqp wAf-:b0y1liz00:0\n:1Work :2It :3Make:4Do :5 Us :6Harder :7Better\n:8Faster:9Stronger\n:qMore Than :wHour :yOur :iNever :pEver:jAfter :lIs :zOver
```
I just recently made this language and I decided to test it out with this challenge. It outputs `\n`s instead of new lines because it outputs into HTML, but the interpreter is written in JavaScript. Because of this, here's a version with `<br>`s instead of `\n`s:
```
:xxnnnnnnnmW12603 27428 3s59qp wb12604280qpb12603 2742803s59qp0wjb:ncvb:mcQb:WcEb:x1203 204203s50607809q0w0y0i0p0j01l0z00:c1263 27428, 3s59:vqp wj:Qqp, w:Eqp wAf-:b0y1liz00:0<br>:1Work :2It :3Make:4Do :5 Us :6Harder :7Better<br>:8Faster:9Stronger<br>:qMore Than :wHour :yOur :iNever :pEver:jAfter :lIs :zOver
```
[Answer]
## GolfScript (275 bytes)
This contains non-printable ASCII characters, so here's a hexdump:
```
0000000: 3a6b 2757 6f72 6b20 4974 0a4d 616b 6586 :k'Work It.Make.
0000010: 0444 6f8c 0873 2055 730a 4861 7264 6572 .Do..s Us.Harder
0000020: 0a42 6574 7485 0346 6173 8504 5374 726f .Bett..Fas..Stro
0000030: 6e67 9503 4d6f 7265 2054 6861 6e0a 486f ng..More Than.Ho
0000040: 7572 0a4f 8203 4e65 76ae 0345 8304 4166 ur.O..Nev..E..Af
0000050: b204 df06 730a 4f96 048c 07ed 7020 d606 ....s.O.....p ..
0000060: 20f4 0720 de07 fb05 20e4 062c 9b05 7320 .. .... ..,..s
0000070: 5573 20ee 1220 df04 20f3 0420 e406 f903 Us .. .. .. ....
0000080: 20e8 0720 4e65 9b04 eeff eeff eeb6 d206 .. Ne..........
0000090: fe03 e817 df0f 2ce0 05da 5c27 d908 2042 ......,...\'.. B
00000a0: 6574 d303 e017 2053 7472 6f6e 67bd 03e9 et.... Strong...
00000b0: 0ee8 0520 4166 2dec ffec 040a ec1b eb26 ... Af-........&
00000c0: e728 d80c c60f c128 4d61 6b65 d004 4265 .(.....(Make..Be
00000d0: 74c3 04d0 0e9a 0373 2055 7320 5374 726f t......s Us Stro
00000e0: 6e67 e212 486f e303 4166 fc04 ed16 277b ng..Ho..Af....'{
00000f0: 6b7b 7b6b 247d 2a30 3a6b 3b7d 7b31 3237 k{{k$}*0:k;}{127
0000100: 2e32 243c 7b2d 3a6b 7d2a 3b7d 6966 7d2f .2$<{-:k}*;}if}/
0000110: 5d28 2b ](+
```
[Answer]
# Ruby - 643 bytes
Edit: Golfed down from 899 to 830.
Edit2: 830 -> 755.
Edit3: 755 -> 684.
Edit4: 684 -> 670.
Edit5: 670 -> 643.
I haven't really used ruby, so I'm sure this could be golfed down, this is just an attempt:
```
l=%w[Work Make Do Harder Better Faster Stronger More Than Hour Our Never Ever After Over Faster,]
i,j,f,u,d=->x{l[x]+' It'},->x,y{l[x]+' It '+l[y]+' '},->a,b,c,d,e{a+' '+b+' '+c+' '+d+' '+e},'s Us ',l[6]
s,q,w,e,r,y,k=f[l[10],l[0],'Is',l[11],l[14]],j[0,3],j[1,4],j[2,15],j[2,5],->d,e{f[l[7],l[8],l[12],d,e]},l[1]+u
t,z,m=e+k,->a{puts q+w,t+d,y[l[9],a],s,''},y['','']
2.times{puts i[0],i[1],i[2],k,l[3],l[4],l[5],d,l[7]+' '+l[8],l[9],l[10],l[11],l[12],l[13],l[0]+' Is',l[14],''}
7.times{z[l[13]]}
puts q+i[1],t,f[l[7],l[8],l[12]+',',l[9],''],s,''
3.times{z['Af-']}
puts q,w,r+k+d,y[l[9],''],s,'',q,r,m,s,'',q,w,r,k+d,m,l[9]+' '+l[13],s
```
[Answer]
## JAVA 518/490Bytes
Edit: unneeded 7 Bytes and added a Java 6 version with the static{} trick
Edit2: Explanation expand
```
class E{public static void main(String[]_){String l="\n#, #Work#Make#Do#Makes Us#Hard#Bett#Fast#Strong#More#Than#Hour#Our#Nev#Ev#Aft#Af-#Work Is#Ov# #er# It",a="cwadwaewafagvahvaivajvakulamanaovapvaqvasatvaa",z="anusuovutvaa",y="kulupvu",x="cwugv",w="fujva",b=x+"udwuhvuaewuivb"+w,c=b+y+"muqvu"+z,d=x+"bdwaewuivbfakulupvbm"+z,e=b+y+"mur"+z,f=x+"adwuhvaewuivu"+w+y+z+x+"aewuivakulupv"+z+x+"adwuhvaewuiva"+w+"kulupvamuqv"+z,r=a+a+c+c+c+c+c+c+c+d+e+e+e+f;for(char o:r.toCharArray())System.out.print(l.split("#")[o-97]);}}
```
java6:
```
class E{static{String l="\n#, #Work#Make#Do#Makes Us#Hard#Bett#Fast#Strong#More#Than#Hour#Our#Nev#Ev#Aft#Af-#Work Is#Ov# #er# It",a="cwadwaewafagvahvaivajvakulamanaovapvaqvasatvaa",z="anusuovutvaa",y="kulupvu",x="cwugv",w="fujva",b=x+"udwuhvuaewuivb"+w,c=b+y+"muqvu"+z,d=x+"bdwaewuivbfakulupvbm"+z,e=b+y+"mur"+z,f=x+"adwuhvaewuivu"+w+y+z+x+"aewuivakulupv"+z+x+"adwuhvaewuiva"+w+"kulupvamuqv"+z,r=a+a+c+c+c+c+c+c+c+d+e+e+e+f;for(char o:r.toCharArray())System.out.print(l.split("#")[o-97]);}}
```
Thanks to @Chris Drost for the hint with the many "ER"s in the text.
First String is a lookup table, second part uses the lowercase letters (which are a sequential block in ascii) as a index into the table by subtracting the magic value of a from the value.
Second part consists of multiple Strings of different length (short ones are common parts shared between multiple verses) which get assembled to a long one before the looping through the chars happens
[Answer]
# JavaScript ES6, ~~440 bytes~~ 438 bytes
This is a bunch of simple compression optimizations. As a one-liner:
```
eval("a='w_m_d_u_h_b_f_s_M_H_O_N_E_A_W_VX';b='w hTm b_d f,Tu s_M ETH A_O W N VX';c=bRA/,'Y');o={};'wWork It|mMake It|dDo It|uMakes Us|hHard&bBett&fFast&sStrong&MMore Than|HHour|OOur|NNev&EEv&AAft&WWork Is|VOv&X\\n\\n|YAf-|_\\n|T 'R&/g,'er|').split('|').map(x=>o[x[0]]=x.slice(1));console.log((a+a+b.repeat(7)+bR._/g,'_')R,?T/g,',T')+c+c+c+bRT/,'_')R,/,'')+bR,?T. ._/g,'_')+bR,?T/g,'_'))R\\w/g,x=>o[x]).trim())".replace(/R/g,'.replace(/'))
```
This was written to be an executable script via `iojs --harmony_arrow_functions file.js`; you can shave off the `console.log()` overhead depending on the meaning of "output the lyrics".
## Explanation
After performing the outer `.replace()`, the code fed to `eval` is:
```
// The first three lines, with each phrase compressed to a single character, newlines
// compressed to _, and block-endings compressed to X. Call this compressed-format.
a = 'w_m_d_u_h_b_f_s_M_H_O_N_E_A_W_VX';
// The compressed-format main block: this is repeated seven times literally but
// every other stanza, besides `a` above, ultimately uses some simple variant
// of this block.
b = 'w hTm b_d f,Tu s_M ETH A_O W N VX';
// The new character T above is a new character we're adding to compressed-format, it is
// a space in the main block but also a hook for some regular expressions later.
// We need one more entry in compressed-format: some blocks, here assigned to
// the variable `c`, shorten "After" to Y = "Af-".
c = b.replace(/A/, 'Y');
// Now we want to build a lookup table for this compressed format above. That is done by
// these lines, which have also been compressed:
o={};
'wWork It|mMake It|dDo It|uMakes Us|hHard&bBett&fFast&sStrong&MMore Than|HHour|OOur|NNev&EEv&AAft&WWork Is|VOv&X\n\n|YAf-|_\n|T '
.replace(/&/g, 'er|')
.split('|')
.map(x => o[x[0]] = x.slice(1));
// The fact that so many fragments end in 'er' allows us to actually shave a couple
// bytes above, but the compression scheme is fundamentally creating a dict like
// {a: "Phrase 1", b: "Phrase 2", c: "Phrase 3", d: "Phrase 4"}
// from the string "aPhrase 1|bPhrase 2|cPhrase 3|dPhrase4".
// Now we have the part that actually does the work:
console.log(
( // build-string phase
// first two opening blocks `a`
a + a +
// seven repetitions of `b`
b.repeat(7) +
// a version of `b` without final words and with commas before each T.
b.replace(/._/g, '_').replace(/,?T/g, ',T') +
// three repetitions with the 'Af-' suffix.
c + c + c +
// one with the first T converted into a newline and no commas
b.replace(/T/, '_').replace(/,/, '') +
// one with only the first halfs of the three lines
b.replace(/,?T. ._/g, '_') +
// one with no commas and all T's converted to newlines.
b.replace(/,?T/g, '_')
) // end build-string phase
// Now we convert from compressed-format to actual format
.replace(/\w/g, x => o[x])
// We are only told that one trailing newline is allowed; we have two extra:
.trim()
)
```
# Kudos
* @vihan, who reminded me that ES6 also has this shiny new `.repeat` function for strings, saving 2 bytes.
[Answer]
# PowerShell, 659 Bytes
```
$a=@(" ","`n",",","Stronger","Make It","Do It","Makes Us","Harder","Better","Faster","Work It","More Than","Hour","Our","Never","Ever","After","Work Is","Over","Af-")
$z="1000070"
$y="01130017001400180101"
$x="010500090200060"
$v="00301110015001200"
$b="100104010501060107010801090103011101120113011401150116011701180101"
$c=$z+"0040008$x$v"+"16$y"
$d=$z+"20004$x"+"1110015020012$y"
$e=$z+"0040008$x$v"+"19$y"
$f=$z+"10400080105000900060003011100150012$y"
$g=$z+"105000901110015$y"+"10000701040008010500090106000301110015011200160113001700140018"
$($b,$b,$c,$c,$c,$c,$c,$c,$c,$d,$e,$e,$e,$f,$g|%{for($i=0;$i-lt$_.length;$i+=2){$a[$_.Substring($i,2)]}})-join''
```
Creates an array of keywords `$a`, then encodes the lyrics using a series of numerical strings which are sent into a `for` loop. The loop takes two-digit substrings, pulls the corresponding keyword from the `$a` array, and finally the `-join''` concatenates it all together.
I think this is about as good as this method can be done, as every time I tried to golf further (e.g., replacing `040008` with a new variable), it turned out to be a couple bytes longer because the substring length wasn't enough to account for all the extra quotes needed. Though there have been some new answers posted since I started that have slightly different methods that look like they might be shorter in PowerShell (like using ASCII characters to encode, rather than two-digits, maybe?), I'm going to stick with this one.
Edit - forgot the replacement encoding I used:
```
00 <space>
01 `n
02 ,
10 Work It
04 Make It
05 Do It
06 Makes Us
07 Harder
08 Better
09 Faster
03 Stronger
11 More Than
12 Hour
13 Our
14 Never
15 Ever
16 After
17 Work Is
18 Over
19 Af-
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 251 bytes golfed
```
'Work It
Make It
Do It
Makes Us
Harder
Better
Faster
Stronger
More Than
Hour
Our
Never
Ever
After
Work Is
Over
'2*.n/:a;56,{:@4%.2&+2*:^a=' ':|4^+a='jSRSSS]SSSSSST'81base 3@?/3%[|', 'n]=^)a=+@ 51%48/!*|237118176 2 55@-?/1&@44%32/'Af-'*5^+a=if^9/n*n}/
```
[Try it online!](https://tio.run/##NY1RT8IwEMff@ynqw2jcgKZdC3NmoRgl@AAkFuODYUnVDhHTmnb44vzss9V4yd3vf/e/3O3te@Of3eGj7Xv0YN0R3rZgpY468tr@dx7ee7BU7kU7cKXbNmChfIRsnTX7IFbWabh9VQYs7cmBTci1/gzGTSzzJi7/PfBgE0cA0XRscKku@WT4VQqWjOkgo2lZqwpBVHaszoJ6k3dSyp38jS0qyJPyGuZihvPksUNDiMyuqs9VlQnIScIKfJZ2NJ8SUpDpBFLIuRjNMBkIxpKcYjRvRijl8fahqS@wSc037vsf "GolfScript – Try It Online")
Eliminated unnecessary `[]` and simplified code accordingly. Changed `i` and `j` to `@` and `^` to permit removal of whitespace. Assigned first occurence of `' '` to variable `|` to avoid repeating the same three characters.
# [GolfScript](http://www.golfscript.com/golfscript/), First working version 262 bytes
```
'Work It
Make It
Do It
Makes Us
Harder
Better
Faster
Stronger
More Than
Hour
Our
Never
Ever
After
Work Is
Over
'2*.n/:a;56,{:i;[i 4%.2&+2*:j a=' '4j+a='jSRSSS]SSSSSST'81base 3i?/3%[' '', 'n]=j)a=+i 51%48/!*' '237118176 2 55i-?/1&i 44%32/'Af-'*5j+a=if j 9/n*n]}/
```
[Try it online!](https://tio.run/##NY1BT8MwDIXv@RXm0EW026Kk7VY6VdMQoHEYk5YhDlMPAdKRDCUoKVwQv70koFmyP9vvSe9o3zv/4tRHPwz4yboT3PdoI04y8saeLw@PHq2Fe5UOXcu@D7gTPoL3zppjWDbWSdi/CYPW9tOhbegH@RWE2zhWXTT/B3i0jS@EWTo1pBaLcjb@rtXioKBIpmyUsbTWIBoMuNBZoOY7znnL/2qPK/osvIRcLUmeHIILjwGbttGXoskUlDQpKnKRBoHlc0orOp8Bg7JUkyWhoxBSJDkjeNVNcFrGANWBhitiUtP@kGH4BQ "GolfScript – Try It Online")
This is a port of my Ruby answer into golfscript using the same basic algorithm: output the list of tokens twice, then riffle them into the verses and build the verses line by line, adjusting for the peculiarities of each.
There are a couple of differences. The number for the correct mid-line punctuation is in base 81 (conveniently this makes one printable ascii character per verse); and the number encoding whether or not to print the last token is modified because the index is `55-i`instead of `i-28` (the latter was found to cause problems with negative powers generating fractional numbers instead of truncating to integer.)
**Commented**
```
'Work It
Make It
Do It
Makes Us
Harder
Better
Faster
Stronger
More Than
Hour
Our
Never
Ever
After
Work Is
Over
'2* #make a string of all the tokens twice and push on the stack
.n/:a; #duplicate the string, split into tokens at newline to form array. Assign to a
56,{:i; #iterate through i= (0..55)
[i 4%.2&+2*:j #calculate j=(i%4+(i%4&2))*2 to cycle through 0 2 8 10.
a=' ' #leave a[j] on stack followed by space (token A)
4j+a= #leave a[j+4] on stack (token B))
'jSRSSS]SSSSSST'81base 3i?/3%[' '', 'n]=j)a=+ #leave ' ' ', ' or newline on stack as appropriate followed by a[j+1] (token C)
i 51%48/!* #multiply the data described in the previous line by !(i%51/48) (1 or 0)
' ' #leave a space on the stack
237118176 2 55i-?/1& #leave 237118176/2**55-i & 1 on stack (true or false indicates token D required)
i 44%32/'Af-'*5j+a= #leave i%44/32= 0 or 1 copies of 'Af-' on the stack. Leave a[j+5] on the stack.
if #depending on value of last but one line, select an option from the previous line.
j 9/n*n] #leave a newline on the stack. if 9/n is 1 or more (last line of verse) leave an additional newline
}/ #close the loop
#printing done by implied stack dump on program exit.
```
[Answer]
## Python - 1056 Charaters
```
a,b,d,s,w,i,t,e,f,h,H,mi,mu,mt,ad,n,o,O="After","Better","Do It ","Stronger","Work ","Is ","It ","Ever ","Faster ","Harder ","Hour ","Make It ","Makes Us ","More Than ","Af-","Never ","Our ","Over"
owinO=o+w+i+n+O
mus=mu+s
df=d+f
dfmu=df[0:-1]+", "+mu
dfmus=df+mus
dfcmus=df[0:-1]+", "+mus
ha=h+a
Ha=H+a
mib=mi+b
mte=mt+e
mteh=mte+H
mtech=mte[0:-1]+", "+H
mtehad=mteh+ad
mteha=mteh+a
wi=w+i
wt=w+t
wth=wt+h
wthmt=wth[0:-1]+", "+mi
wthmib=wth+mi+b
E = ""
l =[wt,mi,d,mu,h,b,f,s,mt,H,o,n,e,a,wi,O,E,wt,mi,d,mu,h,b,f,s,mt,H,o,n,e,a,wi,O,E,wthmib,dfcmus,mteha,owinO,E,wthmib,dfcmus,mteha,owinO,E,wthmib,dfcmus,mteha,owin
O,E,wthmib,dfcmus,mteha,owinO,E,wthmib,dfcmus,mteha,owinO,E,wthmib,dfcmus,mteha,owinO,E,wthmib,dfcmus,mteha,owinO,E,wthmt,dfmu,mtech,owinO,E,wthmib,dfcmus,mteha
d,owinO,E,wthmib,dfcmus,mtehad,owinO,E,wthmib,dfcmus,mtehad,owinO,E,wth,mib,dfmus,mteh,owinO,E,wth,df,mte,owinO,E,wth,mib,df,mus,mte,Ha,owinO]
for ln in l:
print ln
```
Still room for improvement with variable names, but its a start.
[Answer]
# Ruby, 486 Bytes
```
i=%w(Work\ It Make\ It Do\ It Makes\ Us Harder Better Faster Stronger More\ Than Hour Our Never Ever After Work\ Is Over)
z=i[1]+p+i[5]
y=i[2]+p+i[6]
x=z+n+y
w=i[3]+p+i[7]
v=i[8]+p+i[12]
u=w+n+v
t="Our "+i[14]+" Never Over"
s=i[0]+p+i[4]
r=i[9]+p+i[13]
n="\n"
p=' '
m=', '
a=i.join n
q=n+t
l=s+n
b=s+p+x+m+u+p+r+q
c=s+m+i[1]+n+y+m+i[3]+n+v+m+i[9]+q
d=b.gsub("After","Af-")
e=l+x+p+u+p+i[9]+q
f=l+y+n+v+q
g=l+x+n+u+n+r+q
def o s
s+"
"
end
puts o(a)*2+o(b)*7+o(c)+o(d)*2+o(d)+o(e)+o(f)+g
```
[Answer]
## Ruby, 483 bytes
```
puts "#{'a buc bud bucs eufuguhuiuj kulumuoupuqua rutuu'*2}#{'a b f c b gud b h, cs e iuj k p l qum a r o tuu'*7}a b f, c bud b h, cs euj k p, lum a r o tuu#{'a b f c b gud b h, cs e iuj k p l num a r o tuu'*3}a b fuc b gud b h cs e iuj k p lum a r o tuua b fud b huj k pum a r o tuua b fuc b gud b hucs e iuj k pul qum a r o tu".gsub /./,Hash[[*?a..?u,' ',','].zip %w{Work It Make Do Us Harder Better Faster Stronger More Than Hour Our Af- Never Ever After Is s Over}+[?\n,' ',',']]
```
Works by encoding every word used in the song to a single letter, multiplying some stanzas, then substituting the encoded letters with the actual lyrics. Commas, spaces are left as is. `u` is a newline.
[Answer]
# PHP, 434 Bytes
```
$m="Make It";$b="$m Better";$o="Our Work Is Never Over
";$u="Makes Us";$s="$u Stronger";$d="Do It";$f="$d Faster";$e="More Than Ever";$h="Hour";$w="Work It Harder";echo strtr("001111111$w, $m
$f, $u
$e, $h
$o
222$w
$b
$f $s
$e $h
$o
$w
$f
$e
$o
$w
$b
$f
$s
$e
$h After
$o",["Work It
$m
$d
$u
Harder
Better
Faster
Stronger
More Than
$h
Our
Never
Ever
After
Work Is
Over
","$w $b
$f, $s
$e $h After
$o
","$w $b
$f, $s
$e $h Af-
$o
"]);
```
[Try it online!](https://tio.run/nexus/php#dVA9T8MwEN3vV5xON4AUpJK1WKgIUDtAB0AMiCEhDpaq1JU/mp8fznaTDQ@@j6f37u7d3Z/MaeJB0Utz0LgLtOZWEQ/4oEPQTkqraB8dflp3wJ3HV33WDvfygYCxED1@eKm8MCO@BWePv5nbKXq0RbUXrMPnxhdVLUTrNL6b5ohP59wzirY2pmxUVOYF3DauS6j@MRZ9cMFd0Wp1Wx6PFfIA3EuIwFqCAbZQ1zWPwK0gyF6ASz81eynnvM2lzx2Dm152E4iqr3k8JPUORLzsAcUWKHfAfCost4gOiF2QbYJ0GBTZi3@QnQOqiEfM86tlw2WBf@GbDH5fr6fpDw "PHP – TIO Nexus")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~489~~ 431 bytes
```
$d='8t11 4our Aft93t93t93t93t93t93t96Harder, Make It
Do It Faster, 0
More Than Ever, Hour
3-
3-
3-
6Hard95er 0 7n Ever Hour
6Hard9Do It Fast9More Than Ev96Hard9590 7n Ev9Hour Aft9Our 8s Never Over';'Makes Us~
Make2r
Our
Nev9Ev9Aft98s
Ov9
8t~ It
Do It
Makes Us
Hard9Bett9Fast97n
Hou~64our Af~Harder 5er, Makes Us 7n Ever H~Make It Bett9Do It Fast~Our 8s Never Ov9
8t ~Strong9More Tha~Work I~er
'-split'~'|%{$d=$d-replace+$i++,$_}
$d
```
[Try it online!](https://tio.run/##ZVFNT8MwDL37V/hQlENXaWNsa4Q4gAB1h9EDII4oooZNq5rKCeMA5K@XpB8rAslyIsfv@T2n1h/EZktl2TRRcSFSO5vhmX5nvHy1cv4vlpnigniCG7UnXFu41j7jrTI2VKew0Uz4sFUV3hxCJfNcME/6aOFyQYxTXHUtXUf3MJLJ3zyyh8keJLNBYO7P1OAdBaLcJ3EugjKDj8ZBuJ0y@CbwHdIDAyY1kB8kpNYd9cOAgXbQFVkrWxWrCvwst@w34jr3uBg2EDCjEdcvBVuC0Yz7IzMMR3dvWVdvR6PuSfMe144YRGLqcmeFE18nn/5XoiJhqkv1QnG0i@NJ9PwNUdE0Pw "PowerShell – Try It Online")
] |
[Question]
[
**Goal:** Write a program or function which prints an input string in a sinusoidal shape.
### The ASCII sinusoid
Here is one period of the sinusoid:
```
.......
... ...
.. ..
. .
. .
. .
. . .
. .
. .
. .
.. ..
... ...
.......
```
Note that there is exactly one dot on each column.
* Each character in the input string will replace a dot in the shape above, from left to right.
* Spaces in the input have to be outputted like normal characters, in place of a dot.
* The starting character corresponds to the leftmost dot in the figure above.
* This is only one period, inputs can be longer than the number of dots above.
### Input
* Inputs are ASCII strings that contain only characters between ASCII decimal 32 (space) and ASCII decimal 126 (Tilde ~).
* Inputs will always be one line only (no linebreaks).
* Inputs can be taken via STDIN, function parameters, command line arguments, or anything similar.
### Output
* Output must be printed exactly like they are in the test cases given.
* Trailing spaces on lines are allowed as long as the length of the line with those trailing spaces does not exceed the length of the longest line (the one with the last character on it).
* No leading/trailing line allowed.
### Test cases
* Input: `.................................................`
Output:
```
.......
... ...
.. ..
. .
. .
. .
. . .
. .
. .
. .
.. ..
... ...
.......
```
* Input: `Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.`
Output:
```
ng Puzz ion and siasts stratio
mmi les est an thu and egi n r
ra & qu sw en c r eq
g e o o u
o C a r e d n i
r o l e r
P d s s z , e
e i i z g e d
t u o e .
G e e p l r
ol ng f g fe f
f S cha or min rs. 00%
tack Ex program It's 1
```
* Input: `Short text.`
Output:
```
t.
tex
t
r
o
h
S
```
* Input: `The quick brown fox jumps over the lazy dog`
Output:
```
brown
ick fox
qu j
u
e m
h p
T s
o
v
er
th dog
e lazy
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program or function in bytes wins.
[Answer]
## Python 2, 156 bytes
```
l=map(int,"654322111%08d1122345"%1);l+=[12-c for c in l]
def f(t):
h=len(t);o=bytearray(' '*h+'\n')*13;i=0
for c in t:o[i-~h*l[i%48]]=c;i+=1
print o[:-1]
```
## Explanation
* The whole code simply makes a block of spaces (`o`) and replaces the right spaces with the letters of the input `t`.
* The variable `l` stores a list of offsets from the top. So that the `n`th character of `t` should be on line `l[n]`.
* The bytearray `o` serves as a mutable string, since strings are immutable in python.
* `-~h` is the same as `h+1` but saves space because I don't need parentheses.
[Answer]
# Pyth, 59 bytes (57 characters)
```
Xjb.sC.>V+R*12\ Xz\ C9*+-L12K+JsM._+6jC\2tP_JKlz]*dlzC9d
```
[Demonstration.](https://pyth.herokuapp.com/?code=Xjb.sC.%3EV%2BR*12%5C+Xz%5C+C9*%2B-L12K%2BJsM._%2B6jC%5C%E0%BD%882tP_JKlz%5D*dlzC9d&input=Short.+++++++++++++d&debug=0)
A binary lookup table is encoded inside ``, which has value 3912. This is converted to binary, giving `[1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0]`. This is treated as the differences between consecutive heights. By prepending a 6, forming all prefixes and mapping each to its sum, the first quarter of the wave is generated.
`sM._+6jC\2` evaluates to `[6, 7, 8, 9, 10, 10, 11, 11, 11, 12, 12, 12, 12]` as described above. Then, the code concatenates on the reverse of this string to form the first half of the wave, and then subtracts it from 12 to give the entire wave.
Then, we form lines of each input character followed by 12 spaces. This line is rotated to the right by the wave height parameter corresponding to that location, and then the lines are transposed and joined on newlines.
Then, we strip off leading and trailing blank lines. However, we can't strip off leading or trailing blank lines that have spaces from the input. This is implemented by replacing spaces in the input with tabs (`C9`), which can't be in the input, stripping blank lines, and turning the tabs back into spaces.
[Answer]
## Java, 219 209 199 bytes
```
void p(char[]s){int r=6,c;String t="";for(;r>-7;r--,t+='\n')for(c=0;c<s.length;c++)t+=(s(c%48)==r?s[c]:' ');System.out.println(t);}int s(int a){return a<4?a:a<6?4:a<9?5:a<15?6:a<24?s(24-a):-s(a-24);}
```
I'm still a newbie here, and hope that it is compliant to the rules to introduce a sub-function (when the bytes of this function are counted, of course). If not, I'll try to convert the `sin` function into some clever array lookup...
```
public class SinusText
{
public static void main(String[] args)
{
SinusText s = new SinusText();
s.p(".................................................".toCharArray());
s.p("Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.".toCharArray());
s.p("Short text.".toCharArray());
s.p("The quick brown fox jumps over the lazy dog".toCharArray());
}
void p(char[]s){int r=6,c;String t="";for(;r>-7;r--,t+='\n')for(c=0;c<s.length;c++)t+=(s(c%48)==r?s[c]:' ');System.out.println(t);}int s(int a){return a<4?a:a<6?4:a<9?5:a<15?6:a<24?s(24-a):-s(a-24);}
}
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-lF -Mbigint -M5.10.0`, 97 bytes
Coming back to this after a while it's nice to see how much my approach to this kind of thing has improved, -123 bytes!
```
eval's!.!(@l=654322111000000011122345=~/./g,map{12-$_}@l)[pos()%48]-$-?$":$F[pos]!ge;$-+=say;'x13
```
[Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHvVhRT1HDIcfWzNTE2MjI0NDQAAKALCMjYxNT2zp9Pf10ndzEgmpDI12V@FqHHM3ogvxiDU1VE4tYXRVdexUlKxU3kFCsYnqqtYqutm1xYqW1eoWhMR2s@JdfUJKZn1f8X9ftv66vqZ6hgZ4BkJGUmZ6ZVwIA "Perl 5 – Try It Online")
## Explanation
Input is implicitly placed in `$_` (due to `-n`, and `-a`, being implicitly set by `-F` being set) and is split into chars in `@F`. Then the code in `'`s is `eval`ed 13 times. This code `s`ubstitues every char (`s!.!...!`) in the input (`s///` works on `$_` by default) with either the char at the current position from `@F` (`$F[pos]`) or a space (`$"`) depending on whether or not the current value of `$-` (which starts as `0`) is equal to the value in the in the list of values, modulo `48`. This list is constructed from the 24-digit integer (`654322111000000011122345`), which represents the first set of rows in which the char should be displayed for the waveform, which is split into digits (`=~/./g`) and the second part is created in the immediately following `map` which subtracts the values from `12`, resulting in a list of 48 values that indicate where chars should be displayed. `$-` is incremented using the return from `say` (which outputs the current value of `$_` with a trailing newline) which is `1`.
[Answer]
## JavaScript, ~~251~~ ~~243~~ ~~224~~ ~~220~~ 217
Really simple implementation: it uses a string of characters to represent the y-position of each character on the wave (offset by `a`, which is ASCII code 97). It then iterates through all possible rows; if the y-value of the current row is the same as the y-position on the wave, it writes a character from the string. There's also a cleanup at the end to remove the row if it turned out to be completely blank.
Note that the output will appear wonky in the `alert()` window if it's not using a monospaced font, you can change it to `console.log()` to verify the output is correct.
```
s=prompt(o=[])
for(y=i=0;y<13;++y){o[i]=""
for(x=0;x<s.length;++x)o[i]+=y=="gfedccbbbaaaaaaabbbccdefghijkklllmmmmmmmlllkkjih".charCodeAt(x%48)-97?s[x]:" "
if(o[i++].trim().length<1)o.splice(--i,1)}
alert(o.join("\n"))
```
EDIT1: `++` and `--` exist.
EDIT2: Blank line removal is now done in the same loop as the rest, saving 17 characters. Didn't need those brackets either, for an extra 2 characters.
EDIT3: No need to declare the waveform as a variable, saving 4 characters.
EDIT4: As pointed out by Dom Hastings in the comments, the byte count included the carriage return as well as the newline character, updated the byte counts for all revisions to exclude the carriage return.
EDIT5: Saved 3 bytes courtesy of Dom Hastings. I haven't implemented the `o.splice` fix as this fails to remove the blank lines (on my end, at least).
[Answer]
## Matlab, 133, 130 bytes
The one liner:
```
s=input('');y=ceil(5.6*sin(0:pi/24:pi-.1).^.9);l=[-y y]+7;n=numel(s);t=repmat(' ',13,n);for k=1:n;t(l(mod(k-1,48)+1),k)=s(k);end;t
```
And the expanded version:
```
function f(s)
y=ceil(5.6*sin(0:pi/24:pi-.1).^.9);l=[-y y]+7; %// calculate the line number for each column position
n=numel(s); %// number of character in input
t=repmat(' ',13,n); %// Create a blank canvas of whitespace characters
for k=1:n
t(l(mod(k-1,48)+1),k)=s(k); %// place each input character where it should be
end
t %// force the output display
```
---
The one liner takes input from the console (`stdin`) and is 130 bytes. The expanded version replace the console input by a function definition (+1 byte) but is much more comfortable to use for the test case in a loop:
---
**Description:**
The line index of each character is calculated for a half period, then mirrored and concatenated to have a full period.
We create a blank background of whitespace character (same length as the input string.
We place each character according to its position in the relevant line. If the input string is longer than one period, the `mod` (modulo) operator wraps that so we don't get out of bound when requesting the line number.
---
**Test case:**
Save the function version under `textsine.m` in your path, then run:
```
s = {'.................................................';...
'Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It''s 100% free, no registration required.';...
'Short text.';...
'The quick brown fox jumps over the lazy dog'};
for txtcase=1:4
textsine(s{txtcase,1})
end
```
will output:
```
t =
.......
... ...
.. ..
. .
. .
. .
. . .
. .
. .
. .
.. ..
... ...
.......
t =
ng Puzz ion and siasts stratio
mmi les est an thu and egi n r
ra & qu sw en c r eq
g e o o u
o C a r e d n i
r o l e r
P d s s z , e
e i i z g e d
t u o e .
G e e p l r
ol ng f g fe f
f S cha or min rs. 00%
tack Ex program It's 1
t =
t.
tex
t
r
o
h
S
t =
brown
ick fox
qu j
u
e m
h p
T s
o
v
er
th dog
e lazy
```
---
if you want to test the one liner version with input from `stdin`, your input has to be entered as **one** single `string`, so you'd have to enclose your input between `'` characters.
Example:
```
'Short text.' %// valid input
Short text. %// INVALID input
```
---
*Thanks `Luis Mendo` for shaving up 3 bytes ;-)*
[Answer]
# Scala 377 characters
first cut. probably can get a better formula to translate `x` to `y`
```
(s:String)⇒s.zipWithIndex.map(t⇒(t._1,t._2,t._2%48 match{
case i if i<5⇒6-i
case 5|19⇒2
case 6|7|8|16|17|18⇒1
case i if i<16⇒0
case i if i<29⇒i%20+2
case 29|43⇒10
case 30|31|32|40|41|42⇒11
case i if i<40⇒12
case i if i>43⇒10-i%44
})).groupBy(_._3).toSeq.map{case(y,xs)⇒(""→0/:xs.sortBy(_._2)){case((p,l),(c,x,_))⇒(p+" "*(x-l-1)+c)→x}._1→y}.sortBy(_._2).map(_._1).mkString("\n")
```
[Answer]
# Common Lisp, 205 bytes
```
(lambda(s &aux p v o)(dotimes(r 13)(setf o 0 p v v(round(*(/ 24 pi)(+(asin(-(/ r 6)1))pi))))(when p(map()(lambda(c)(princ(if(some(lambda(k)(<= p(mod k 48)(1- v)))`(,o,(- 23 o)))c" "))(incf o))s)(terpri))))
```
## Tests
See <http://pastebin.com/raw.php?i=zZ520FTU>
## Remarks
Print the output line by line, computing the indices in the strings that should be printed using the inverse sine function `asin`. The output do not match exactly the expected inputs in the question, but since OP acknowledges that the example outputs are not real sine, I guess this is ok. At least, there is always only one character written for each column.
[Answer]
# Python 2, 172 bytes
This isn't as good as [Alex L's answer](https://codegolf.stackexchange.com/a/53850/19349), but it's pretty close. Takes input from standard input and works best in a `.py` file.
```
l=map(int,bin(9960000)[2:]);l+=[-c for c in l];s=6;o=[];i=9
for c in raw_input():b=[' ']*13;b[s]=c;o+=[b];s+=l[i%48];i+=1
print''.join(sum(zip(*o+['\n'*13])[::-1],())[:-1])
```
I decided to build the output transposed (each column is a row) and then transpose the result, since in python the transpose of a matrix is `map(*m)`.
* `l`: The binary representation of `9960000` (after chopping off the `"0b"` from `bin`) is `100101111111101001000000`. This is the "step" of the sine wave each column, starting at the very last character of the very lowest point. I copy this list, negate each number, and tack it onto the end of itself to form what is effectively a derivative of the function.
* `s`: This is the variable that keeps track of which row (column in the transpose) the next character gets inserted into.
* `o`: End output, transposed
* `i`: Keeps track of sine wave period. Starts at 9 since `l` is shifted slightly.
In the `for` loop, I create a list of 13 spaces (I was using bytearrays but lists of characters turn out to have a shorter print statement), then replace the `s`th character with the input character. Append `b` to the end of `o`, add the appropriate step to `s`, and increment `i`.
I had hoped the `print` statement would be as simple as `\n'.join(*zip(o))`, but no such luck. `zip(*o+['\n'*13])[::-1]` appends a column of newlines and then reverses and transposes the whole thing (without the reversing, the sine wave is upside down), `sum(...,())` concatenates the tuples together into one tuple of characters, and then `''.join(...)` concatenates the characters and prints it.
Other things I tried were making a 12-character array of spaces and inserting the new character into the appropriate place, and replacing `l+=[-c for c in l];` with some sort of math with some sort of multiplication of `1` and `-1` with the result of indexing into `l`, but nothing I could come up with ended up being shorter.
[Answer]
# Mathematica, 131 bytes
```
i=[input string];c=Characters@i;l=Length@c;StringJoin@Riffle[StringJoin@@@SparseArray[Table[{7-Round[6 Sin[.13(x-1)]],x},{x,l}]->c,{13,l}," "],"\n"]
```
That's 131 characters, including the three for `i=foo;`. That seemed a reasonable way to take the input; I could have put it straight into the definition of `c` and saved a few strokes, but that feels unfair.
It's pretty straightforward -- almost even readable. It splits the string into a list of characters, and then puts those characters into a sparse array at the positions determined from the `Table` (any spot in the array not given a character defaults to a space). The lines are assembled separately, then newlines sprinkled between them. The final StringJoin stitches it all up.
**NB:** Like some other solutions, this may not actually be valid because it produces a real sinusoid rather than the (beautiful) handcrafted example.
## Tests:
```
(*i=Programming Puzzles...*)
ng Puzz on and iasts tration
mi le sti a us and is r
am s e ns th c eg eq
r & qu we en o r u
og C r d o ir
r o a e e n e
P d s si l g d
e i t zz o , .
G e u lf ee
o ge f p e r
lf an or g rs f
St ch p min . 0%
ack Ex rogram It's 10
(*i=.... ...*)
.......
.. ..
.. ..
. .
.. ..
. .
. . .
.. .
. .
. ..
.. ..
... ..
......
(*i= Short text.*)
t.
ex
t
t
or
h
S
(*i=The quick...*)
brown
ck fo
ui x
q j
e um
h p
T s
o
v
e
r g
the do
lazy
```
] |
[Question]
[
The look-say sequence is a sequence of lists of numbers where each element is the previous element with run length encoding. Run length encoding is the process of grouping together like elements and then giving the element and the size of the group for each group. So for example:
```
1 1 1 2 2 1
```
To run length encode this we group like elements together
```
1 1 1 | 2 2 | 1
```
And then replace each group with its size and the element:
```
3 1 | 2 2 | 1 1
```
Then we concatenate these back together:
```
3 1 2 2 1 1
```
The look-say sequence starting from just `1` goes:
```
1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 2 2 1 1
1 3 1 1 2 2 2 1
1 1 1 3 2 1 3 2 1 1
3 1 1 3 1 2 1 1 1 3 1 2 2 1
1 3 2 1 1 3 1 1 1 2 3 1 1 3 1 1 2 2 1 1
...
```
But we can start with different values. For example we could start with `2`
```
2
1 2
1 1 1 2
3 1 1 2
1 3 2 1 1 2
1 1 1 3 1 2 2 1 1 2
3 1 1 3 1 1 2 2 2 1 1 2
1 3 2 1 1 3 2 1 3 2 2 1 1 2
1 1 1 3 1 2 2 1 1 3 1 2 1 1 1 3 2 2 2 1 1 2
```
Or we could even start it with `3 3 3`:
```
3 3 3
3 3
2 3
1 2 1 3
1 1 1 2 1 1 1 3
3 1 1 2 3 1 1 3
1 3 2 1 1 2 1 3 2 1 1 3
1 1 1 3 1 2 2 1 1 2 1 1 1 3 1 2 2 1 1 3
```
In this task you are going to be given a sequence and your job will be to trace it back as far as you can to get a starting point. That is you are going to undo operations until you get a list of numbers that could not have been produced by run length encoding another list.
As some examples:
* `3 3 3` is not a possible run length encoding since it has an odd number of terms.
* `1 2 2 2` is not a possible run length encoding since expanding it out gives `2 2 2` which would be encoded as `3 2` instead.
As input you will receive a list of positive integers less than 4. You should output all the terms of the look-say sequence up to and including the input. Your output may be in forwards or backwards order.
There is one case where the input can be traced back indefinitely `2 2`. What your program does on this input is undefined behavior.
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
```
1:
1
1 1 1 2 1 1 1 3:
3 3 3
3 3
2 3
1 2 1 3
1 1 1 2 1 1 1 3
1 2 2 1 1 3 1 1 1 2:
1 2 2 2
1 1 3 2
2 1 1 3 1 2
1 2 2 1 1 3 1 1 1 2
1 2 1 3 1 2 1 1:
3 3 3 1 1 1
3 3 3 1
3 3 1 1
2 3 2 1
1 2 1 3 1 2 1 1
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~19~~ 16 bytes
-3 bytes thanks to Mukundan314
```
W.A.+%2t
Q=r9cQ2
```
[Try it online!](https://tio.run/##K6gsyfj/P1DZU19PW9WoJDDKicu2yDI50Oj//2hDHQUjHQUgaQwmIWzDWAA "Pyth – Try It Online")
Prints in reverse order.
### Explanation
```
W while:
.A zero is not in
.+ the deltas of
%2tQ every second element of implicitly printed Q
=r9cQ2 set Q to the length decoding of itself
```
[Answer]
# Excel (ms365), 374 bytes
[](https://i.stack.imgur.com/4VYDf.png)
[](https://i.stack.imgur.com/kEMJd.png)
[](https://i.stack.imgur.com/yFw70.png)
Formula in `A3`:
```
=LET(x,CONCAT(1:1),y,TOCOL(SCAN(x,SEQUENCE(1048575),LAMBDA(a,b,LET(c,SEQUENCE(LEN(a)/2,,,2),IF(ISODD(LEN(a)),NA(),CONCAT(REPT(MID(a,c+1,1),MID(a,c,1))))))),3),z,MAP(y,LAMBDA(d,LET(e,SEQUENCE(LEN(d)),f,MID(d,e,1),g,TEXTSPLIT(CONCAT(f&IF(f<>MID(d,e+1,1),"|","")),"|",,1),CONCAT(LEN(g)&LEFT(g))))),MID(FILTER(VSTACK(x,y),VSTACK(1,z=VSTACK(x,DROP(y,-1)))),SEQUENCE(1,LEN(x)),1))
```
All one has to do is change the input in 1st row.
* 'x-varibale' - `CONCAT(1:1)` - Concatenate all values from row 1 into a string;
* 'y-variable' - `TOCOL(SCAN(x,SEQUENCE(1048575),LAMBDA(a,b,LET(c,SEQUENCE(LEN(a)/2,,,2),IF(ISODD(LEN(a)),NA(),CONCAT(REPT(MID(a,c+1,1),MID(a,c,1))))))),3)` - Will go over 1048575 possibilities (max rows in ms365 if one include the input at the end) and will get each number from every even position and repeat it n-times where n == its neighboring digit on the left;
* 'z-variable' - `MAP(y,LAMBDA(d,LET(e,SEQUENCE(LEN(d)),f,MID(d,e,1),g,TEXTSPLIT(CONCAT(f&IF(f<>MID(d,e+1,1),"|","")),"|",,1),CONCAT(LEN(g)&LEFT(g)))))` - Loop over elements from y and reverse it's value into it's logical predecessor;
* `MID(FILTER(VSTACK(x,y),VSTACK(1,z=VSTACK(x,DROP(y,-1)))),SEQUENCE(1,LEN(x)),1)` - Finally we can check each value against the elements in y and filter what is not a possible run length encoding string. All strings are then cut into seperate integers again.
No doubt other Excel-fanatics can beat this, but my brain is fried! I'm not even sure an answer like this length belongs on CG...
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-p`, 33 bytes
```
T$|_=BMPDQUWg|%#gg:_@1RL@_MF<>Pgg
```
Takes the initial sequence as separate command-line arguments; prints the sequences from there on back as far as possible to stdout as lists. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJUJHxfPUJNUERRVVdnfCUjZ2c6X0AxUkxAX01GPD5QZ2ciLCIiLCIiLCItcCAxIDIgMSAzIDEgMiAxIDEiXQ==)
### Explanation
The basic structure of the program is
```
T <cond> <body> g
```
that is, loop until `<cond>` becomes true, executing `<body>` each time, and at the end of the loop, output the final value of `g`. (The original value of `g` is a list of the command-line arguments.)
The condition is:
```
$|_=BMPDQUWg|%#g
UWg Unweave g into two lists, each containing every other value
DQ Get the latter of the two (the values at odd indices)
MP Map this function to each adjacent pair of values in that list:
_=B The first equals the second
$| Fold on logical OR: true if any of the equality checks are true
| OR:
#g The length of g
% Is odd
```
The loop body is:
```
g:_@1RL@_MF<>Pg
Pg Print the current value of g
<> Group into chunks of length 2
MF Map this function to each chunk and flatten the resulting list:
@_ The first number in the chunk
RL Create a list containing that many copies of
_@1 The second number in the chunk
g: Assign the resulting list back to g
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~18~~ 17 bytes
*This uses [CursorCoercer](https://codegolf.stackexchange.com/users/73054/cursorcoercer)'s [idea](https://codegolf.stackexchange.com/a/253834/36398) of testing if increments are zero.*
The output is in backwards order.
```
`t0h2L&)Y"6Mdyh]x
```
Verify test cases: [1](https://tio.run/##y00syfn/P6HEIMPIR00zUsnMN6UyI7bi//9ow1gA), [2](https://tio.run/##y00syfn/P6HEIMPIR00zUsnMN6UyI7bi//9oQwUQNFKA0MaxAA), [3](https://tio.run/##y00syfn/P6HEIMPIR00zUsnMN6UyI7bi//9oQwUjIDQEQmMwCeTHAgA), [4](https://tio.run/##y00syfn/P6HEIMPIR00zUsnMN6UyI7bi//9oQwUjBUMFYwUIbRgLAA).
### Explanation
```
` % Do... while
t % Duplicate current list of numbers (*). This takes input implicitly in
% the first iteration
0h % Append a 0
2L&) % Push the subarray of entries at (1-based) even positions (**), then
% the subarray of entries at odd positions (***)
Y" % Run-length decoding using those two subarrays as inputs, cyclically
% reusing the shorter of the two if needed. The result will contain
% zeros if and only if (*) had odd length
6M % Push (**) again
d % Consecutive differences
y % Duplicate from below: pushes again the result of run-length decoding
h % Concatenate horizontally
] % End. A new iteration is run of the top of the stack contains no zeros
x % Delete. This removes the last array, which is not valid. Implicit display
```
[Answer]
# JavaScript (ES10), 91 bytes
Inspired by [CursorCoercer's answer](https://codegolf.stackexchange.com/a/253834/58563).
```
f=a=>[...a.every((v,i)=>a[i%2-~i]^i%2*v)?f(a.flatMap((v,i)=>Array(i&1&&p).fill(p=v))):[],a]
```
[Try it online!](https://tio.run/##dctBCsIwEAXQvadwY5mRNtB0J6TiATxBiDDURCKhCWkJdOPVY0ErRRQ@zGd4/06Jhi7aMFa9v@qcjSDRSsYYMZ10nABSaVG0JO2OVw@rLvPdJzwaIGYcjWcKiznFSBPYoi6KgMxY5yCIhIgHqUpSufP94J1mzt/AgKwV4ub7V25f4UuZ0/yGfKWaFed/@Qe@dzPMTw "JavaScript (Node.js) – Try It Online")
### Commented
Testing if `a[]` is still valid:
```
a.every((v, i) => // for each value v at position i in a[]:
a[i % 2 - ~i] // get a[i + 1] if i is even, or a[i + 2] if i is odd
^ // and make sure it's different from
i % 2 * v // 0 (or undefined) if i is even, or v if i is odd
) // end of every()
```
Run-length decoding of `a[]`:
```
a.flatMap((v, i) => // for each value v at position i in a[]:
Array(i & 1 && p) // build an array of p entries if i is odd,
// or an empty array if i is even
.fill(p = v) // fill it with v and copy v to p
) // end of flatMap()
```
---
# JavaScript (ES6), 91 bytes
A version without `.flatMap()`.
```
f=a=>[...a.every((v,i)=>a[j=i%2,b.push(...Array(j&&p).fill(p=v)),j-~i]^j*v,b=[])?f(b):[],a]
```
[Try it online!](https://tio.run/##dcvfCsIgGAXw@56im8b3hROyu8BFzyEGbmkpMsWVsJte3Qb9YUTBuTgcfseprIYu2Xit@3DSpRiueCMopYrqrNMIkIlF3ijhuF0x0tJ4Gy4wgUNKagRXVRGpsd5D5BmRuPpu5dGtM2m5kLg30OJOSKJk6UI/BK@pD2cwIDYScfG9keUz7F2mbH9DNlPbGWd/@Qe@fhMsDw "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~70~~ 69 bytes
*Edit: -1 byte thanks to pajonk*
```
f=function(v)if(all(w<-c(print(v),0)[!1:0],diff(w)))f(rep(w,v[!0:1]))
```
[Try it online!](https://tio.run/##hYxBCoMwEEX33kJXM5BCEne2OYl1IWkHQkMiaUzs6dNWha6KzOLD/@9NKNb7x3N8GZdUIUWz09F4BwkNwWgt5MtJwxSMi5@Ocexr0fGB3QwRZEQkCPcJMkt9zTsxIJZFaRBY/R7Dgmc9RmiursFqndn3JNuyPYLljra7II@FDV61/3B5Aw "R – Try It Online")
```
f=function(v, # f is recursive function with arg vector v;
print(v) # first print v
w=c( )[!1:0]) # and set w to every second element of v,
,0 # followed by a zero if length is odd.
if( ) # now, check if v is valid:
all(w, ) # there shouldn't be a final zero
diff(w) # and every second element should be different to its neighbour
f( ) # if so, recurse
rep(w,v[!0:1]) # with even numbered elemnts of v
# repeated odd numbered elements of v times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[=ιÂ`ÅΓ©Åγ‚RÊ#®
```
Outputs in 'reversed' order compared to the challenge description.
[Try it online](https://tio.run/##yy9OTMpM/f8/2vbczsNNCYdbz00@tBJIbn7UMCvocJfyoXVAOUMdEDTSgdDGsQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLkFQO5OpX/o23P7TzclHC49dzkQyuB5OZHDbOCDncpH1r3v/bQNvv/0dGGsTrRhjogaKQDoY3BIkZQvjFU1AgqChEBy8XGAgA).
**Explanation:**
I basically run-length decode and then encode it again, and see if it's unchanged.
```
[ # Start an infinite loop:
= # Print the current list with trailing newline (without popping)
# (which will be the implicit input-list in the first iteration)
ι # Uninterleave the copy into 2 parts: [lengths,values]
 # Bifurcate (short for Duplicate & Reverse copy) this pair of lists
` # Pop and push the reversed pair of lists to the stack
ÅΓ # Pop both the values & length lists, and run-length decode them
© # Store this list in variable `®` (without popping)
Åγ # Run-length encode it again, pushing the list of values and lengths
# separated to the stack
‚R # Pair them together in reversed order: [lengths,values]
Ê # If the two pairs of lists are NOT the same:
# # Stop the infinite loop
® # (else) Push the list of variable `®` for the next iteration
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
Wq
Qsr8=r9cQ2
```
[Try it online!](https://tio.run/##K6gsyfj/P7yQK7C4yMK2yDI50Oj//2hDHQUjHQUgaQwmIWzD2H/5BSWZ@XnF/3VTAA "Pyth – Try It Online")
### Explanation
```
Q is initialized to input
Wq\nQsr8=r9cQ2
W # while
\nQ # print(Q)
q # ==
sr8=r9cQ2 # run_length_encode(Q = run_length_decode(Q)):
# pass
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 28 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
OpU;Êv ©Uó Ìän e ©ßUò crÈo{Y
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=T3BVO8p2IKlV8yDM5G4gZSCp31XyIGNyyG97WQ&input=WzEgMSAxIDIgMSAxIDEgM10)
I imagine there's room for improvement. Outputs in "reverse" order.
Explanation:
```
OpU;Êv ©Uó Ìän e ©ßUò crÈo{Y
OpU; # Print the input followed by a newline
Ê # The length of the input
v # Is divisible by 2
© # Break if false
Uó # Separate the input into "sizes" and "elements"
Ì # Take just the array of elements
än # Calculate the consecutive differences
e # Check that they are all non-zero
© # Break if false
ß # Otherwise repeat the program with new input:
Uò # Split the current input into size,element pairs
cr # Run the following on each pair, then flatten:
Èo # An array with length equal to the first number
{Y # Where each element is the second number
```
I've made an [alternative](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ynYgqVXzIMzkbiBlIKnfTnBV8iBjcshve1l9fSnMCk4&input=WzEgMSAxIDIgMSAxIDEgM10tUg) which builds an array instead of printing in each loop, but it's currently longer.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
W∧⊞Oυθ¬∨﹪Lθ²⊙✂θ³Lθ²⁼κ§θ⊕⊗λ≔ΣE⪪θ²⁺⊟κE⊟κ⁰θIυ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU-xTsMwEN35CqvTRXKlhi5InSLKUKmlkTJGGVzHbaxe7cT2FfgWlg4g-Ab-hIVvwQbagZNO907vvdO753fZCSetwNPplcJ2fPP59dBpVAwK00JJvlv3yolgHRBnQ8bZvQ2wdrCyLaGFpTK70EEirmMX5gkq1FLBwNmUs3_03UACPeyjMCxMqx6TbGGkUwdlgmphbmmDcWJ2LlZ4r3cGKjrASvRQ9ahDsqV7JZKH0vawj0tiz3iSrCnv7Kp02gS4FT4AZdnsxW-k__v1rR6NjzhqPuo6jwc5y39CX3DeNL_Cbw) Link is to verbose version of code. Outputs the lists in reverse order; each element is printed on its own line and lists are double-spaced from each other. Explanation:
```
W∧⊞Oυθ¬∨
```
Push the current list to the predefined empty list, and while neither...
```
﹪Lθ²
```
... the length of the list is odd, nor...
```
⊙✂θ³Lθ²⁼κ§θ⊕⊗λ
```
... any of the third, fifth, seventh etc. entries equals the entry two previous, then...
```
≔ΣE⪪θ²⁺⊟κE⊟κ⁰θ
```
... run-length decode the list.
```
Iυ
```
Output all of the collected lists.
[Answer]
# [Haskell](https://www.haskell.org/), 86 bytes
```
r!(a:b:t)|r==b=[0]|k<-b<$[1..a]=k++b!t
r![]=[]
r!x=[0]
g l|0`elem`0!l=[l]|1>0=l:g(0!l)
```
[Try it online!](https://tio.run/##fY7PCsIwDMbveYpMPCj@YU1vxfoE3jyWghuOKeum1Aoe9u6ztR2iiIQ2yff9kvZU3JrKmGGw2awQpXDz3kpZSpXrvtmsys1UsfW60LJZLMrMgc2Ulkr7/AgM1Gj6/FCZqj3kmZHK6J5tc2lEPfP9fGiLc4cSjxcEvNpz53CKtWLad3e3d3bX4WTyYS1D0DJm/g@khPEE0384gq8RPTABDIBhCMKYuQCOPsIN5E@0@DcGLyO2PIkkkkgQZYI3QL8GYFw/rk6vR3@sISnhPwH7HoIn "Haskell – Try It Online")
r!list compares *r* with element to replicate, if they are equal inserts a 0 in the resulting list, same does if it matches an odd list.
Function *g* repeatedly apply *0!* and stops if there is a *0* in the result.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 73 bytes
-15 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)
```
F=->a,y=0{a.all?&&(p a)&&F[a.each_slice(2).flat_map{y!=_2&&[y=_2]*_1},y]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWNz3dbHXtEnUqbQ2qE_USc3Ls1dQ0ChQSNdXU3KIT9VITkzPii3Myk1M1jDT10nISS-JzEwuqKxVt443U1KIrgVSsVrxhrU5lbC3UQCO36GhDHRA00oHQxrGxXAWlJcVcYBkjqLgxVNYoNhaiE-YkAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṅṭ2/Ḋm2IẠƲ¡Œṙß
```
A full program that accepts a list of integers from \$[1,4]\$ and prints the results in Jelly's list format separated by newlines.
**[Try it online!](https://tio.run/##y0rNyan8///hzpaHO9ca6T/c0ZVr5Plw14Jjmw4tPDrp4c6Zh@f////fUEfBSEcBSBqDSQjbEAA "Jelly – Try It Online")**
### How?
Inspired by [CursorCoercer](https://codegolf.stackexchange.com/users/73054/cursorcoercer)'s [Pyth answer](https://codegolf.stackexchange.com/a/253834/53748).
`Œṙ`, run-length decode, will error if given a list of integers or a list containing a singleton list. The code ensures that if the current list identifies the same value to be repeated twice in a row then the former will be true and, otherwise, if the current list is of odd length when the latter will be true.
```
Ṅṭ2/Ḋm2IẠƲ¡Œṙß - Main Link: list of integers, S
Ṅ - print S
¡ - repeat...
Ʋ - ...number of times: last four links as a monad:
Ḋ - dequeue
m2 - modulo-two slice
I - deltas
Ạ - all non-zero?
2/ - ...action: pairwise reduce by:
ṭ - tack
Œṙ - run-length decode
ß - call this link again with that as S
```
[Answer]
# [Python](https://www.python.org), ~~126~~ ~~124~~ ~~120~~ ~~113~~ 110 bytes
```
i=lambda t,x,a,b,*c:b and i(t&(b!=c[1]),x+(b,)*a,*c)or(x,a*t)
j=lambda l,t=1:t*[0]and j(*i(1,(),*l,1,0,0))+[l]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZA7jsJADIb7nMKbAtmDs8qjWUXKSUKKGR7aicIkCl4JzkJDA-eh5TY7EIKCsP7C0v_5ebx0B_lt3el0_pNN9HNztmj01qw0CO9Zs2G1zA1otwKLMkPzVSzLpCLez9EwKe19anv0rBIK6rG6YSmSXFQZV_faGpXFhJFYNZxwzDHRvGyq59SrrHcCBZQB-PAgEL_SQemYeGUTN51Y2YRJ35mX-4Q_-g9ARkEVbNoeBKyD-1b5g-t66wTDhQu_69Y63OoOd9JzjUI-pkwURSENd41f_Qc)
The recursive function `i` simultaneously undoes the look-and-say sequence and also determines whether it's a valid sequence -- the last element of the return value is `1` if the sequence is valid and `0` if it's not.
This is then used in the main function `j` to undo the calculation until hitting a stopping point.
[Answer]
# [Raku](https://raku.org/), 60 bytes
```
{$_,*.flatmap(*Rxx*)...{$_%2|{any $_ Z==.skip}(.[1,3...*])}}
```
[Try it online!](https://tio.run/##NcxNCsIwEIbhq3yUKEkIA03BhTU9hEtFQhcGxLaGWqGl5uyxfzKLGZ4Xxt/b6hDrAXsHE0dmlSRXlV1dei7PfS8FEU2809@xbAYwi4sx9H4@fOB0TVU2dXkTIUT3asFTJRROKebRWHdWLKQ3yDbWf15piQVG@E@HhNljkoPme/7rOLMiX1OCEH8 "Perl 6 – Try It Online")
This is a lazily generated sequence of the form `first-element, generator ... termination-condition`.
* The first element is `$_`, the list argument to the function.
* `*.flatmap(* Rxx *)` takes the previous element and `flatmap`s over it two elements at a time using the anonymous function `* Rxx *`. `Rxx` is the `R`eversed version of the replication operator `xx`; it produces a number of copies of its right-hand side given by its left-hand side.
* The termination condition is an anonymous function that returns true if `$_ % 2`--that is, if the number of elements in the last list is odd--or if `.[1, 3 ... *]`, the odd-indexed elements of the last list, satisfies the condition `any $_ Z== .skip`--that is, if any two adjacent elements are equal.
[Answer]
# Rust, 146 bytes
```
|a|while dbg!(&a).len()%2<1{let(c,mut r,mut p)=(a.chunks_exact(2),vec![],9);for
t in c{if p==t[1]{return}p=t[1];r.extend([p].repeat(t[0]));}*a=r;}
```
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b6756f974d65fb5fb8840ac7bc2146c0)
This is a `fn(&mut Vec<usize>)`.
[Answer]
# [Python](https://www.python.org), 93 bytes
```
f=lambda a:(a,*(eval("0"+(l:=len(b:=a[1::2]))*"!=%d"%b)*a[~l:l]and f(eval(l*"+%d*(%d,)"%a))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY5BCsIwEEX3PcUYCExiBdtuJJCT1C6mpMFCTEWj4MZLuHRTEL2Tt7FaW-rnwwz8N_y5PXfnsGl8e7d6_TgGu1i9CqsdbUtDQAopllidyCFbsjk6pV3lsVSa8kSptBBCspnmhvFSSMovTrmCvAHbHznJ5txI5CYWjJPo9Cu5huoQQEMeQSdMYhDxuPZOh6VzNknTSZRNmPSfGdMfLKIiss0eaqg9fNrVl97tax_QYj281rb9fAM)
Returns the history newest to oldest.
# [Python](https://www.python.org), 80 bytes
```
def f(a):print(a);f(eval(eval((l:=len(b:=a[1::2]))*".0!=%d"%b)*l*"+%d*(%d,)"%a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FGMgkIlVbLuRSO7gvnSR2gQLJS01ij2Lm4LonbyNtT_q8Bje8B7ze7yrxp1L27avqzOb_eeYaQOGKRRVnVvXkYNh-qaKIbFCyEJblgqp4kCIMEHkZLtbSZoRmiIvOFnTjDOa-UioQhz7Pp2-OJAQe9AFC3xAf6YDwol0iBZquJCihSf898zqaEYv8UxZQw65hd900btd3QjDcuwLfT_pyo2njqtOr_gC)
Prints the history line-by-line newest to oldest. Exits with an error.
#### How?
Nothing clever here. Using `eval` because control structures in general and in particular concatenation of a list of strings or pairwise iteration over a list or chained comparisons are all rather verbose when done "the proper way" in Python.
The second, semi-legal version does away with a few stop conditions (like odd number of terms) because the function crashes at the right time anyway when any of these conditions are met.
] |
[Question]
[
**This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. The robbers' thread is [here](https://codegolf.stackexchange.com/questions/167597/hardcoding-the-cops-and-robbers-robbers).**
An interesting question to think about is the following:
>
> If I have a sequence of numbers how many of them do I have to provide before it is clear what sequence I am talking about?
>
>
>
For example if I want to talk about the positive integers in order starting from \$1\$, I could say \$1,2,3, \dots\$, but is that really enough?
I have one way of answering this question, and being a code-golfer it involves code-golf. You have provided enough terms of a sequence if the shortest code that produces those terms produces all the terms of the sequence. If we think about this in terms of code-golf, this would mean you have provided enough test cases such that the shortest code that passes the test-cases does the desired task.
## Challenge
This challenge is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. In which cops will be presenting test-cases and robbers will have to find a shorter way to spoof the test-cases other than the intended sequence. Cops will present the following things:
* A piece of code that takes a non-negative integer as input and produces an integer as output. This code will define your sequence. Your code does not need to support 0 as an input, opting to instead take 1 as the smallest input. It should be clear if this is the case in your answer.
* Any relevant platform or language requirements that might affect the output, for example the size of longint.
* A number \$n\$, along with the first \$n\$ terms of the sequence as calculated by the code. These will act as "test-cases".
You are encouraged to explain what your sequence does and link OEIS if it exists, however it is your code that defines the sequence not the description.
Robbers will be finding a program in the same language that is shorter than the one presented and passes all the test cases (produces the same output for the first \$n\$ inputs as the cop's code). The robber's code must also differ in output from the cop's program for some number larger than \$n\$.
Cops must be able to crack their own answers before submitting them.
After one week a cop *may* reveal their crack and mark their answer as Safe. Answers marked as such can no longer be cracked.
## Scoring
Cops answers will be scored by the number of bytes with fewer bytes being better. Cracked answers score an infinite score.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents/tree/cquents-0), 4 bytes ([Cracked](https://codegolf.stackexchange.com/a/167643/78410))
```
"::$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X8nKSuX/f0sA "cQuents 0 – Try It Online")
Here are eight (`n=8`) cases:
```
1 1
2 12
3 123
4 1234
5 12345
6 123456
7 1234567
8 12345678
```
Code explanation:
```
" Stringify sequence (join on "", remove it and see what happens)
:: Given input n, output all items in the sequence up to and including n
$ Each item in the sequence equals the index
```
So the sequence is `1,2,3,4,5 ...`, it is joined on `""` so it becomes `12345 ...`, and `::` means that it prints up to the input.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~66~~ 57 bytes ([Cracked](https://codegolf.stackexchange.com/a/167642/20260))
*cracked by [xnor](https://codegolf.stackexchange.com/users/20260/xnor)*
*also cracked by [Cat Wizard](https://codegolf.stackexchange.com/users/56656/cat-wizard) before an edit*
```
def f(n):x=n/10-2;return int(x*60-x**3*10+x**5/2-x**7/84)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI0/TqsI2T9/QQNfIuii1pLQoTyEzr0SjQsvMQLdCS8tYy9BAG0ib6huBuOb6Fiaa/wuKQEqi0zQyNRXS8osUMoFaFIoS89JTNQx0TAw0YzX/AwA "Python 3 – Try It Online")
Hello! Here is a sequence to crack for \$n=40\$.
It gives these first 40 elements with 0-indexing, it's not an OEIS sequence
```
[-54, -56, -58, -59, -59, -59, -59, -57, -55, -53, -50, -46, -43, -38, -33, -28, -23, -17, -11, -5, 0, 5, 11, 17, 23, 28, 33, 38, 43, 46, 50, 53, 55, 57, 59, 59, 59, 59, 58, 56]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes ([cracked](https://codegolf.stackexchange.com/a/167972/20260))
```
f=lambda n,i=1,p=1:n and-~f(n-p%i,i+1,p*i*i)
```
[Try it online!](https://tio.run/##DYyxDsIgGAb3PsW3kAJSIzVdmuC7oLT6J@0PARy6@OqV4ZbL5dJRP5HHk/YUc0U5Ste4lqXm5fXNhSJvtFOV9qb1pM7VbX5/Bg825KxJzs4Mz2H4rZKHJMjQpWlNmlocMxjEyJ7fi7RmsmrukDJxRS/GgOEBcQ89BCQbtIVS5x8 "Python 2 – Try It Online")
The prime numbers. What sequence could be purer? Or more [overdone](https://codegolf.meta.stackexchange.com/a/14580/20260)? Your goal is to produce the first 50 primes for `n=1` to `n=50`.
The code is a [Wilson's Theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) generator copied exactly from [this tip](https://codegolf.stackexchange.com/a/152433/20260).
The different values for the alternative sequence are not due to machine limitations like overflows and precision. No 3rd party libraries.
---
[Cracked](https://codegolf.stackexchange.com/a/167972/20260) by Arnauld, @PoonLevi, and Mr. Xcoder.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~39~~ 34 bytes (Safe)
```
Check[{1,9,7}[[#]],18+Boole[#>9]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d85IzU5O7raUMdSx7w2Olo5NlbH0ELbKT8/JzVa2c4yNlbtv6Y1V2BpZmqJQ0BRZl6Jg2NRUWJldJqOgqVl7H8A "Wolfram Language (Mathematica) – Try It Online")
Looks simple, solution should be hard.
1-indexed and \$n = 99\$. This sequence is not available on the OEIS.
```
{1, 9, 7, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19}
```
This above list is equal to:
```
Join[{1, 9, 7}, Table[18, 6], Table[19, 90]]
```
Here's a template for checking your solution: [Try it online!](https://tio.run/##HczBasMwDIDhu55CS2FsxIXmtBXXobSnXcYGgx2MDyaRZ9GmblznMEqfPVN3kNDh@zX4EmnwhTs/B/M0/6YpY5d6wkiZ5mcNbBoN3nzliTR8TkzFfkc@kvUK4IwGw5Y1jHLsI3UHe23UWr3crF04p5rXepeS4EW7du7xLr1IyYzBUcNH5lOxjMsWr2eF403hW5DPWFUyuFlizyFUzgHXtQZwTtZ/tBXH2GKzWoncZ98dqH@4V@@pIJ3S9BOxUB4ulZv/AA "Wolfram Language (Mathematica) – Try It Online")
## Intended Crack
>
> The catch here is that the output increases by 1 when the number of digit increases by 1, with the exception for the first three terms; the intended solution has something to do with string conversion.
>
>
>
> Hence, reading the documentation on [Converting between Expressions & String](http://reference.wolfram.com/language/guide/ConvertingBetweenExpressionsAndStrings.html), one could find the function [`SpokenString`](http://reference.wolfram.com/language/ref/SpokenString.html).
>
>
>
> The solution is simply the length of the spoken-string version of the expression `x^n` for various inputs: [`StringLength@SpokenString[x^#]&`](https://tio.run/##JY1Na8MwDIbv/hVaAmUjLjSnrXgOoT0NxtjoYAejgkntWKT5nAOD0t@eqdtB4kU8z6vWxuBaG6myi9f3yyFO1NWvrqtjKA9D37ju/2R@jimulgclSOdKWP05zU6Jj5lcNF@Bzs5YKcQAGnxJSowc9sFVjbnkcisfr8akiDJ/ynZ9z3BabBFXN9IyyZrWMCrxzr@iIVgXcBkkjFcJL56bIUl44HkNJ/I@QRSUZUoIRF5/UskcQQH5ZsPkfrJV4053N@utj@C6fq4DRDe13wkuvw "Wolfram Language (Mathematica) – Try It Online")
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), 29 bytes (Cracked: [1](https://codegolf.stackexchange.com/a/167654/56433),[2](https://codegolf.stackexchange.com/a/167709/))
```
a n=n*ceiling(realToFrac n/2)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1EhzzZPKzk1MyczL12jKDUxJyTfrSgxWSFP30jzf25iZp6CrUJBUWZeiYKKQm5igUKiQrSBnp6RQex/AA "Haskell – Try It Online")
This is [A093005](https://oeis.org/A093005): \$ a(n)=n\lceil \frac{n}{2} \rceil\$.
Test cases for \$0 \leq n \leq 20 \$, that is `map a [0..20]`:
```
[0,1,2,6,8,15,18,28,32,45,50,66,72,91,98,120,128,153,162,190,200]
```
## Intended solution (20 bytes)
```
b n=sum$n<$show(3^n)
```
[Try it online!](https://tio.run/##VcmxDkAwFAXQ3VfcoQMGhJXVF9iE5KGh0b5KS3x@WQzWczbyu9Q6ELjhdJZKK15jJ0l3tnU0g/MyCdO7/jKCa@E3e8fVyEkwpBgNFhvhcIpPCBg6QOiLLCur4c/Tx@EB "Haskell – Try It Online") Differs at \$ n=23 \$, with \$ a(23) = 276 \$ and \$ b(23) = 253\$.
This function is equivalent to \$b(n) = n\ len(3^n) = n \lceil log\_{10}(1+3^n)\rceil\$. Thanks to the ceiling, both functions overlap for integer arguments in the range from \$0\$ to \$22\$:
[source](http://www.wolframalpha.com/input/?i=Plot%5B%7Bn+Ceiling%5BLog_10%5B1+%2B+3%5En%5D%5D,+n+Ceiling%5Bn%2F2%5D%7D,+%7Bn,+0,+25%7D%5D)
[Answer]
# JavaScript (ES6), 12 bytes ([Cracked](https://codegolf.stackexchange.com/a/167656/58563))
This one is rather easy.
```
n=>n*(8*n+1)
```
[Try it online!](https://tio.run/##FcpBCoMwEEbhvaf4yWrGQWldCTbeJVhTFJkpKm5Kzx6T1ePBt4YrHNO@fM9G7T2n6JP6UWvqa5Unp2g7KTweAxQvdKUijF8FTKaHbXO72YdcIAfJRuA4@zKRlHmo/ukG "JavaScript (Node.js) – Try It Online")
This is [A139275](https://oeis.org/A139275):
$$a(n) = n(8n+1)$$
Your code must support \$0\le n<9\$:
$$0, 9, 34, 75, 132, 205, 294, 399, 520$$
And as per the challenge rules, it must diverge beyond.
[Answer]
# Malbolge, 10 bytes
```
ub&;$9]J6
```
Note that the code ends with an 0x14 (device control 4) byte.
[Try it online!](https://tio.run/##y03MScrPSU/9/780Sc1axTLWy0zk/39DAwA)
The 0-indexed sequence to crack is `[9, 19, 29]`.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 276 bytes ([Cracked](https://codegolf.stackexchange.com/a/167677/76162))
```
1$1-:?!v$: 1[0$ >:?!va2[$:{:@%:{$-{,]v
>$n; v < ^ >~{]02.1+1+ffr+1r<
:}[r]{ [01>:{*@@+$a*l2=?!^~]+ff+9+1g"3"=?v"3"ff+9+1pf0.
:}[l01-$> $:0(?v$@$:@@:@)?v@@1-$}v >"2"ff+9+1p00.
>. ^-1l v!?} < .4a}$@@$< .4a<
^26{]r0[}:{]~{<
```
[Try it online!](https://tio.run/##VY7BasQwDETv@QolqNCu62B7l0LVrK3/CA7kkm0hlJKCL8b5ddfe7RY6BzHiadAsH9/vOWvUklwbkOAqPSqEP9mKZjMiReIHiijjsw/NneLnGwT4pwFgqmiPXpleCy2WZRN6GxqgNG4@AoxKW4oHZoHzYTVn1067L2fiVehLd@zOLpR5278W1V@Tq9ISbf2ApB5dQEZiJn5ygbmgdOthO3NPqpK0/W@tSeoVQutSLdif5oTMWGz1QzOZl@g3NSaKfo9DzlkGOJ5@AA "><> – Try It Online") Call this one with `-v n` to get the n-th element (1-indexed)
```
1$1-:?!;$::n84*o1[0$ >:?!va2[$:{:@%:{$-{,]v
v < ^ >~{]02.1+1+ffr+1r<
:}[r]{ [01>:{*@@+$a*l2=?!^~]+ff+9+1g"3"=?v"3"ff+9+1pf0.
:}[l01-$> $:0(?v$@$:@@:@)?v@@1-$}v >"2"ff+9+1p00.
>. ^-1l v!?} < .4a}$@@$< .4a<
^26{]r0[}:{]~{<
```
[Try it online!](https://tio.run/##VY7BSsUwEEX3/YppGUEbU5K8Ijr2JfMfJYVuqkJRqZBNSH89pj4VvYvhDncOc5eXj@ecNWpJrn5Eotf7vn3To0L4lS1RmM2IFImvKKKMtz5U8EcB/mkAmA5wj16ZTgstlmUTehsqoDRuPgKMSluKLbPAuV3N2dXT7suZeBD6qTk1ZxfKvOzvi@q@yFVpifb4gKSuXUBGYia@cYG5ROnSwzbmh1SFtN13rUnqFULt0lGw6@eEzFjs4YdqMnfRb2pMFP0eh5yzDHDqPwE "><> – Try It Online") Call with `-v n` to get a list of n-1 elements starting at 1
[Online Fish Interpreter](https://fishlanguage.com/)
A long and complex one, this is [OEIS A004000](http://oeis.org/A004000).
>
> Let a(n) = k, form m by Reversing the digits of k, Add m to k Then
> Sort the digits of the sum into increasing order to get a(n+1).
>
>
> Example: 668 -> 668 + 866 = 1534 -> 1345.
>
>
>
Because the code in ><> is quite long, the challenge is to crack it for \$n = 34\$.
These 34 elements make a total of 290 bytes, just a bit too much to hardcode the result ;)
Here are the 34 first elements 1-indexed
```
1 2 4 8 16 77 145 668 1345 6677 13444 55778 133345 666677 1333444 5567777 12333445 66666677 133333444 556667777 1233334444 5566667777 12333334444 55666667777 123333334444 556666667777 1233333334444 5566666667777 12333333334444 55666666667777 123333333334444 556666666667777 1233333333334444 5566666666667777
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), Safe!
```
<4+ạ2ȯ
```
This defines a **zero-indexed** sequence where:
$$ a(n) =
\begin{cases}
1 & n<3 \\
2 & n=3 \\
n-2 & n>3
\end{cases}$$
As such the first sixteen values \$a(0)\cdots a(15)\$ are `1,1,1,2,2,3,4,5,6,7,8,9,10,11,12,13`
**[Try it online!](https://tio.run/##y0rNyan8/9/GRPvhroVGJ9b/P9z@qGnN///RBjoKhjoKRjoKxjoKJjoKpjoKZjoK5joKFjoKlkApkDRQ3hCowBCowhCoxNA0FgA "Jelly – Try It Online")** ([here](https://tio.run/##y0rNyan8/9/GRPvhroVGJ9b////f0BQA) is a single value version)
This is not currently in the OEIS (although [A34138](https://oeis.org/A034138 "Number of partitions of n into distinct parts from [1,8]") will work as a crack if short enough)
### Intended Crack
>
> The sequence above agrees with the count of decimal digits of the first \$16\$ terms of [A062569](https://oeis.org/A062569 "a(n) = sigma(n!)"), the sum of the divisors of the factorial of \$n\$ (also zero-indexed).
>
> The \$17^{\text{th}}\$ term of [A062569](https://oeis.org/A062569 "a(n) = sigma(n!)"), however, is \$107004539285280\$ which has \$15\$ digits, not \$14=a(16)\$.
>
>
>
> The required code is **five** bytes in Jelly, [`!ÆsDL`](https://tio.run/##y0rNyan8/1/xcFuxi89/GxPth7sWGp1Yz3W4XefwRE33//@jDXQUDHUUjHQUjHUUTHQUTHUUzHQUzHUULHQULIFSIGmgvCFQgSFQhSFQiSFQjaFZLAA "Jelly – Try It Online").
>
>
>
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~17~~ 15 [bytes](https://github.com/abrudz/SBCS), safe
```
⌈∊∘1 5+.633*5-⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P/1R24RHPR2POroedcwwVDDV1jMzNtYy1X3UtQgoeWjFo97NhsYA "APL (Dyalog Unicode) – Try It Online")
The first 13 terms (1-based) are:
```
2 1 1 1 2 2 3 4 7 10 16 25 39
```
Hint: The intended solution uses one of the least used built-in functions.
---
The intended code is the following:
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [bytes](https://github.com/abrudz/SBCS)
```
⌊(2*⍳)⌹⌽∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P/1R24RHPV0aRlqPejdrPurZ@ahn76OOGUAOUO7QCiBtaAwA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# JavaScript, 26 bytes ([Cracked](https://codegolf.stackexchange.com/a/167609/64505))
```
let f=x=>x>1?f(x-1)*f(x-2)+1:1
for (x of [0,1,2,3,4,5,6,7]) {
console.log(x + ' -> ' + f(x))
}
```
[OEIS A007660](https://oeis.org/A007660)
Output is the first 6 elements with 0 indexing (1,1,2,3,7,22)
(somewhat shifted from what OEIS has it listed as)
Just creating a simple to solve answer to kick things off
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbC1q7CztA@TaNC11BTC0QZaWobWhn@L8ktsI020DHUMdIx1jHRMY3lSs7PK87PSdXLyU/XAMrq5SYWaKRpav4HAA "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript, 16 bytes ([Cracked](https://codegolf.stackexchange.com/a/167623/64505))
```
g=
x=>Math.exp(x)|0
tmp=[0,1,2,3,4]
console.log(tmp.map(g).join(','))
```
First 5 elements of [OEIS149](https://oeis.org/A000149) (\$\lfloor e^n\rfloor\$)
Required inputs to match are 0,1,2,3,4.
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1s43sSRDL7WiQKNCs8bgf0lugW20gY6hjpGOsY6JjmksV3J@XnF@TqpeTn66BlBWLzexQCNNU/M/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes ([cracked](https://codegolf.stackexchange.com/a/167660/48198) by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan?tab=profile))
This one is [A000030](https://oeis.org/A000030) shifted by \$16\$:
```
←d+16
```
[Try it online!](https://tio.run/##yygtzv7//1HbhBRtQ7P///8bAAA "Husk – Try It Online")
The sequence is 0-indexed, [output](https://tio.run/##yygtzv7/qG1ibn5xsM6jpsZzM/yA3Akp2oZm////NzIGAA "Husk – Try It Online") for \$ 0 \leq n < 23 \$:
$$ 1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3 $$
### Explanation
```
←d+16 -- example input: 23
+16 -- add 16: 39
d -- digits: [3,9]
← -- extract first: 3
```
### Solution
>
> [`LdΣ`](https://tio.run/##yygtzv7/3yfl3OL///8bAAA)
>
>
>
[Answer]
# JavaScript, 25 bytes ([Cracked](https://codegolf.stackexchange.com/a/167666/64505) 21 bytes)
```
f=
x=>[7,11,12,13,13][x]||14
for(i=0;i<15;i++)
console.log(i+"->"+f(i))
```
Sequence of 7,11,12,13,13 followed by infinite 14s.
Intended solution 22 bytes:
>
> x=Math.atan(x+1)\*10|0
>
>
>
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1i7aXMfQUMfQSMfQGIhioytia2oMTf6n5RdpZNoaWGfaGJpZZ2pra3Il5@cV5@ek6uXkp2tkKmgr6dopaadpZGpq/gcA "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript, 22 bytes ([Cracked](https://codegolf.stackexchange.com/a/167627/64505))
```
f=
x=>(3-(5/63)**.5)**x|1
for(y=0;y<16;y++)
console.log(y +"->"+f(y))
```
This is 0 indexed and accuracy is required up to an input of 15. It can not be found on OEIS
My solution 20 bytes
>
> x=>163\*\*(32\*x/163)|1
>
>
>
[Try it online!](https://tio.run/##DcuxDoIwFEbh3cdguiU/xUtpkaG@iHFoEAwE2kaIYfDda5czfMlZ3Nftw2eOR@XDa0yTTae9k6pI10aJspQ65/xxOrZoH1cwGii00DDocEMPzsjgBqzALViDzfMyBL@HdZRreFNe5eYiTUIuYfZUoBAi/QE "JavaScript (Node.js) – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 42 bytes, [cracked](https://codegolf.stackexchange.com/questions/167597/hardcoding-the-cops-and-robbers-robbers/167923#167923)
```
i3%0v
642 .
840
789
159
a 1
v<<
n
l
?
\/
;
```
[Try it online!](https://tio.run/##S8sszvj/P9NY1aCMy8zESEGPy8LEgMvcwpLL0NSSK1HBkKvMxoYrjyuHy54rRp/L@v9/AwA "><> – Try It Online")
Sequence to crack (0-indexed): `101786, 5844, 19902` (not on OEIS).
[Intended solution](https://tio.run/##S8sszvj/X9/eSkshL8aayy5H2ypJVZ8rk0uJy@D/fwMA), for reference.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 53 bytes
```
{(1,2,2,{$!=++$;prepend(@,2-$!%2 xx$_).pop}...*)[$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNQxwgIq1UUbbW1VawLilILUvNSNBx0jHRVFFWNFCoqVOI19QryC2r19PS0NKNV4mNr/xeUlgC1a8QZGhtoWv8HAA "Perl 6 – Try It Online")
Anonymous code-block that returns the 0-indexed Kolakoski sequence ([OEIS A000002](http://oeis.org/A000002)). Solutions are required to match the first 130 elements, so that for some `n > 129` it differs from the Kolakoski sequence.
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), 86 bytes ([cracked](https://codegolf.stackexchange.com/a/170843))
```
var n:word;begin read(n);write(n div 2+n div 4+n div 8+n div 16+n div 32+n div 64)end.
```
[Try it online!](https://tio.run/##K0gsTk7M0U0rSP7/vyyxSCHPqjy/KMU6KTU9M0@hKDUxRSNP07q8KLMkVSNPISWzTMFIG0KbQGkLKG1oBmUYw1SYmWim5qXo/f9vCAA "Pascal (FPC) – Try It Online")
The sequence must be equal up to \$n=120\$. The sequence from input 0 to input 120 is
```
0 0 1 1 3 3 4 4 7 7 8 8 10 10 11 11 15 15 16 16 18 18 19 19 22 22 23 23 25 25 26 26 31 31 32 32 34 34 35 35 38 38 39 39 41 41 42 42 46 46 47 47 49 49 50 50 53 53 54 54 56 56 57 57 63 63 64 64 66 66 67 67 70 70 71 71 73 73 74 74 78 78 79 79 81 81 82 82 85 85 86 86 88 88 89 89 94 94 95 95 97 97 98 98 101 101 102 102 104 104 105 105 109 109 110 110 112 112 113 113 116
```
---
My original solution was
>
> `var n,i,s:word;begin read(n);i:=2;repeat s:=s+n div i;i:=i*2until i>n;write(s)end.`
>
>
>
but r\_64 [made it even better](https://codegolf.stackexchange.com/a/170843)!
] |
[Question]
[
A list of numbers is called [monotonically increasing](https://en.wikipedia.org/wiki/Monotonic_function) (or nondecreasing) is every element is greater than or equal to the element before it.
For example, `1, 1, 2, 4, 5, 5, 5, 8, 10, 11, 14, 14` is monotonically increasing.
Given a monotonically increasing list of positive integers that has an arbitrary number of empty spots denoted by `?`, fill in the empty spots with positive integers such that as many unique integers as possible are present in the list, yet it remains monotonically increasing.
There may be multiple ways to accomplish this. Any is valid.
Output the resulting list.
>
> **For example**, if the input is
>
>
>
> ```
> ?, 1, ?, 1, 2, ?, 4, 5, 5, 5, ?, ?, ?, ?, 8, 10, 11, ?, 14, 14, ?, ?
>
> ```
>
> it is guaranteed that without the empty spots the list will be
> monotonically increasing
>
>
>
> ```
> 1, 1, 2, 4, 5, 5, 5, 8, 10, 11, 14, 14
>
> ```
>
> and your task is to assign positive integers to each `?` to maximize
> the number of distinct integers in the list while keeping it
> nondecreasing.
>
>
> One assignment that is ***not valid*** is
>
>
>
> ```
> 1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 8, 10, 11, 14, 14, 14, 14, 14
>
> ```
>
> because, while it is nondecreasing, it only has one more unique
> integer than the input, namely `3`.
>
>
> In this example it is possible to insert six unique positive integers and
> keep the list nondecreasing.
>
> A couple possible ways are:
>
>
>
> ```
> 1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 8, 10, 11, 12, 14, 14, 15, 16
>
> 1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 5, 6, 6, 7, 8, 10, 11, 13, 14, 14, 20, 200
>
> ```
>
> Either of these (and many others) would be valid output.
>
>
>
All empty spots must be filled in.
There is no upper limit on integers that can be inserted. It's ok if very large integers are printed in scientific notation.
Zero is not a positive integer and should never be inserted.
In place of `?` you may use any consistent value that is not a positive integer, such as `0`, `-1`, `null`, `False`, or `""`.
**The shortest code in bytes wins.**
# More Examples
```
[input]
[one possible output] (a "*" means it is the only possible output)
2, 4, 10
2, 4, 10 *
1, ?, 3
1, 2, 3 *
1, ?, 4
1, 2, 4
{empty list}
{empty list} *
8
8 *
?
42
?, ?, ?
271, 828, 1729
?, 1
1, 1 *
?, 2
1, 2 *
?, 3
1, 3
45, ?
45, 314159265359
1, ?, ?, ?, 1
1, 1, 1, 1, 1 *
3, ?, ?, ?, ?, 30
3, 7, 10, 23, 29, 30
1, ?, 2, ?, 3, ?, 4
1, 1, 2, 3, 3, 3, 4
1, ?, 3, ?, 5, ?, 7
1, 2, 3, 4, 5, 6, 7 *
1, ?, 3, ?, 5, ?, ?, 7
1, 2, 3, 4, 5, 6, 7, 7
1, ?, ?, ?, ?, 2, ?, ?, ?, ?, 4, ?, 4, ?, ?, 6
1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 6
98, ?, ?, ?, 102, ?, 104
98, 99, 100, 101, 102, 103, 104 *
```
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
`f` takes a list and returns a list, with 0 representing `?`s.
```
f=scanr1 min.tail.scanl(#)0
m#0=m+1
_#n=n
```
Basically, first scan list from left, replacing 0s by one more than the previous element (or 0 at the start); then scan from right reducing too large elements to equal the one on their right.
[Try it online!](https://tio.run/nexus/haskell#bY7hCsIgFIX/36eQLXBjQ9SsViF7kIiQtUiYFm7R4690KwyCwzl8h8PlGqWt1HZonWqGxcN22rY9Meqe9dfbk1yIa9XZM3Ikwwe8y0lWFMkxyXMStuAQrrHEFO8damQzXmTfKOsYMtqSQemOeO6yNKdgUipNweCUWmnHkZdIlIhRYCWqS7ScUwBUUEMdICTzxiFsxMqX03ISg2VEfvS5yCecr7KIVsE3f7qo/or/ooj8rTVsq/gdyucU8AI "Haskell – TIO Nexus") (with wrapper to convert `?`s.)
[Answer]
# Mathematica, 84 bytes
```
Rest[{0,##}&@@#//.{a___,b_,,c___}:>{a,b,b+1,c}//.{a___,b_,c_,d___}/;b>c:>{a,c,c,d}]&
```
Pure function taking a list as argument, where the empty spots are denoted by `Null` (as in `{1, Null, Null, 2, Null}`) or deleted altogether (as in `{1, , , 2, }`), and returning a suitable list (in this case, `{1, 2, 2, 2, 3}`).
Turns out I'm using the same algorithm as in [Ørjan Johansen's Haskell answer](https://codegolf.stackexchange.com/a/113013/56178): first replace every `Null` by one more than the number on its left (`//.{a___,b_,,c___}:>{a,b,b+1,c}`), then replace any too-large number by the number on its right (`//.{a___,b_,c_,d___}/;b>c:>{a,c,c,d}`). To deal with possible `Null`s at the beginning of the list, we start by prepending a `0` (`{0,##}&@@#`), doing the algorithm, then deleting the initial `0` (`Rest`).
Yes, I chose `Null` instead of `X` or something like that to save literally one byte in the code (the one that would otherwise be between the commas of `b_,,c___`).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~25~~ ~~23~~ 21 bytes
```
Y{Y+a|y+1}MgW PMNyPOy
```
Takes input as multiple space-separated command-line arguments. Outputs the result list one number per line. [Try it online!](https://tio.run/nexus/pip#S7dKjCv@H1kdqZ1YU6ltWOubHq4Q4OtXGeBf@f//f3sFQwUQNgKSJgqmYGgPhRYKhgYKhmB5ExACigEA "Pip – TIO Nexus") (I've fudged the multiple command-line args thing because it would be a pain to add 25 arguments on TIO, but it does work as advertised too.)
### Explanation
We proceed in two passes. First, we replace every run of `?`s in the input with a sequence starting from the previous number in the list and increasing by one each time:
```
? 1 ? 1 2 ? 4 5 5 5 ? ? ? ? 8 10 11 ? 14 14 ? ?
1 1 2 1 2 3 4 5 5 5 6 7 8 9 8 10 11 12 14 14 15 16
```
Then we loop through again; for each number, we print the minimum of it and all numbers to its right. This brings the too-high numbers down to keep monotonicity.
```
y is initially "", which is 0 in numeric contexts
Stage 1:
{ }Mg Map this function to list of cmdline args g:
+a Convert item to number: 0 (falsey) if ?, else nonzero (truthy)
| Logical OR
y+1 Previous number +1
Y Yank that value into y (it is also returned for the map operation)
Y After the map operation, yank the whole result list into y
Stage 2:
W While loop, with the condition:
MNy min(y)
P printed (when y is empty, MN returns nil, which produces no output)
POy Inside the loop, pop the leftmost item from y
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~31~~ ~~23~~ 13 bytes
Saved 10 bytes thanks to *Grimy*
```
ε®X:D>U].sR€ß
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3NZD6yKsXOxCY/WKgx41rTk8////aF1DHQUgglJGEJaJjoIpDOkaomILoEIDIIZpMoFgiHQsAA "05AB1E – Try It Online")
**Explanation**
```
ε ] # apply to each number in input
®X: # replace -1 with X (initially 1)
D>U # store current_number+1 in X
.s # get a list of suffixes
R # reverse
ۧ # take the minimum of each
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~43~~ ~~27~~ ~~24~~ 22 bytes
*-2 bytes thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334)*
```
Ė|a₀ᶠ⟨{a₁+0}ᶜ+⌉⟩ᵐa₁ᶠ⌋ᵐ
```
Uses 0 as the blank value. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/Pzq2JvFRU8PDbQsezV9RDWQ22mYY1D7cNkf7UU/no/krH26dABIEyfd0AzlAHQY6CoY6ChDSCMww0VEwhSEDJGQBVANSB1VuAsEgudj/jgA "Brachylog – Try It Online")
### How?
Lots of prefixes and suffixes.
We want to perform a two-step process that goes like this:
```
[0, 1, 0, 0, 0, 3, 0, 0]
[1, 1, 2, 3, 4, 3, 4, 5]
[1, 1, 2, 3, 3, 3, 4, 5]
```
For the first step, we look at each prefix of the list:
```
[0]
[0, 1]
[0, 1, 0]
...
[0, 1, 0, 0, 0, 3, 0, 0]
```
We're going to map each prefix to what its last number *would* be if we had already completed step 1:
```
[1] -> 1
[1, 1] -> 1
[1, 1, 2] -> 2
...
[1, 1, 2, 3, 4, 3, 4, 5] -> 5
```
Observe that nonzero final numbers stay the same, while final zeros are replaced with the result of counting up from the last previous nonzero number (or from 1, if there is no previous nonzero number). Since the list is nondecreasing, the last previous nonzero number is simply the max of the prefix, so our calculation boils down to (max value) + (number of trailing 0s). We collect all the results in a list, and step 1 is completed.
For step 2, we simply take each suffix of the step 1 result and replace it with its minimum.
### Code with explanation
```
Ė|a₀ᶠ⟨{a₁+0}ᶜ+⌉⟩ᵐa₁ᶠ⌋ᵐ
Ė If input is empty list, output is empty list
| Otherwise
a₀ᶠ Find all (nonempty) prefixes of input list
ᵐ For each prefix:
Find how many 0s it ends with:
{ }ᶜ Count the number of ways to satisfy this predicate:
a₁ Get a suffix
+ whose sum
0 is 0
The numbers are nonnegative, so this means they are all 0
⌉ Get the maximum number in the prefix
⟨ + ⟩ Add that to the number of trailing 0s
a₁ᶠ Find all (nonempty) suffixes of the resulting list
⌋ᵐ Take the minimum of each
```
[Answer]
# C 127
**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**
```
#define p;printf("%d ",l
l,m,n;main(c,v)char**v;{for(;--c;m++)if(**++v-63){for(n=atoi(*v);m--p<n?++l:n))p=n);}for(;m--p+++1));}
```
[Try it online!](https://tio.run/##HctBCsIwEEDRvacoFSGTSRZVceFYepaQNhpIpiGUbMSzj9rtf3xvn96LHOclRF66QqVG3oLqT3PXm3RIJhum7CIrbxr4l6taN3qHtSqy1lNGhBiU1ojN3i6wC49uW6PSDShbWx48IaY7A5SRgT77/AdEHOAXRGSQSa7nLw "C (gcc) – Try It Online")
[Answer]
# PHP, ~~95~~ ~~77~~ ~~71~~ ~~69~~ 68 bytes
```
for($p=1;$n=$argv[++$i];)echo$p=$n>0?$n:++$p-in_array($p,$argv)," ";
```
takes input from command line arguments, prints space separated list. Run with `-nr`.
**breakdown**
```
for($p=1;$n=$argv[++$i];) # loop through arguments
echo$p= # print and copy to $p:
$n>0 # if positive number
?$n # then argument
:++$p # else $p+1 ...
-in_array($p,$argv) # ... -1 if $p+1 is in input values
," "; # print space
```
`$n` is truthy for any string but the empty string and `"0"`.
`$n>0` is truthy for positive numbers - and strings containing them.
[Answer]
## Python 2 with NumPy, 163 bytes
Saved 8 bytes thanks to @wythagoras
Zeros used to mark empty spots
```
import numpy
l=[1]+input()
z=numpy.nonzero(l)[0]
def f(a,b):
while b-a-1:a+=1;l[a]=l[a-1]+1;l[a]=min(l[a],l[b])
i=1
while len(z)-i:f(z[i-1],z[i]);i+=1
print l[1:]
```
More readable with comments:
```
import numpy
l=[1]+input() # add 1 to the begining of list to handle leading zeros
z=numpy.nonzero(l)[0] # get indices of all non-zero values
def f(a,b): # function to fill gap, between indices a and b
while b-a-1:
a+=1
l[a]=l[a-1]+1 # set each element value 1 larger than previous element
l[a]=min(l[a],l[b]) # caps it by value at index b
i=1
while len(z)-i:
f(z[i-1],z[i]) # call function for every gap
i+=1
print l[1:] # print result, excluding first element, added at the begining
```
[Answer]
# [Perl 6](https://perl6.org), 97 bytes
```
{my $p;~S:g/(\d+' ')?<(('?')+%%' ')>(\d*)/{flat(+($0||$p)^..(+$2||*),(+$2 xx*,($p=$2)))[^+@1]} /}
```
Input is either a list of values, or a space separated string, where `?` is used to stand in for the values to be replaced.
Output is a space separated string with a trailing space.
[Try it](https://tio.run/nexus/perl6#bU/bboJAEH3fr5hY7O4K5bJQa6WK/9DHtiZU0ZiIEkEjAfx1OwsLwaTJ7FzPOTN7TiO4jM2VT@IcnlfHdQSze4G5lvi3z@nWYt9rnQLlwQdjNKBcHw5lOcf@iFvFZh9mTGeaXZZawpemyXRNlOWIGzKB63VkMC2ZaYJz/rXUF85PBVZ1xwWL3SE5ZzCD/e4QpYybcZhMoSAAcngJ9@coxam5Osa/zAI8A0rAC8DiPoIUglRkczy1Yi/zjimF0jCHW9sokc04PEEUJ1mOW9OM@gok/806KpfYAaUdNs1Ou8N20KIp8qp7YIBjQONFnXgGvLYW9GyCGBufgnvNkzMiapZjk2bmqugRxsmEBERpyOhIJ0iN8uQGhW3MIe7jUrfVbG5zla7Tq5oz3/7p9dqdicfS63m0MXmf9M@xhYreHw "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
my $p; # holds the previous value of 「$2」 in cases where
# a number is sandwiched between two replacements
~ # stringify (may not be necessary)
S # replace
:global
/
( \d+ ' ' )? # a number followed by a space optionally ($0)
<( # start of replacement
( '?' )+ # a list of question marks
%% # separated by (with optional trailing)
' ' # a space
)> # end of replacement
(\d*) # an optional number ($2)
/{ # replace with the result of:
flat(
+( $0 || $p ) # previous value or 0
^.. # a range that excludes the first value
( +$2 || * ), # the next value, or a Whatever star
(
+$2 xx *, # the next value repeated endlessly
( $p = $2 ) # store the next value in 「$p」
)
)[ ^ +@1 ] # get as many values as there are replacement chars
} / # add a space afterwards
}
```
[Answer]
## JavaScript (ES6), 65 bytes
```
a=>a.map(e=>a=e||-~a).reduceRight((r,l)=>[r[0]<l?r[0]:l,...r],[])
```
Because I wanted to use `reduceRight`. Explanation: The `map` replaces each falsy value with one more than the previous value, then the `reduceRight` works back from the end ensuring that no value exceeds the following value.
[Answer]
## Q, 63 bytes
`{1_(|){if[y>min x;y-:1];x,y}/[(|){if[y=0;y:1+-1#x];x,y}/[0,x]]}`
Essentially the same algorithm as [Ørjan Johansen's Haskell answer](https://codegolf.stackexchange.com/questions/113011/fill-in-an-increasing-sequence-with-as-many-numbers-as-possible/113013#113013).
* Assumes ? = 0.
* Inserts a 0 at the start of the array in case of ? at start.
* Scans the array replacing 0 with 1+previous element.
* Reverses the array and scans again, replacing elements greater than
previous element with previous element.
* Reverses and cuts the first element out (the added 0 from the
beginning).
Use of min vs last was used to save one byte, since can assume the last element will be the min element given the descending sort of the array.
[Answer]
# TI-Basic (TI-84 Plus CE), 81 bytes
```
not(L1(1))+L1(1→L1(1
For(X,2,dim(L1
If not(L1(X
1+L1(X-1→L1(X
End
For(X,dim(L1)-1,1,-1
If L1(X)>L1(X+1
L1(X+1→L1(X
End
L1
```
A simple port of [Ørjan Johansen's Haskell answer](https://codegolf.stackexchange.com/a/113013/44694) to TI-Basic. Uses 0 as null value. Takes input from L1.
Explanation:
```
not(L1(1))+L1(1→L1(1 # if it starts with 0, change it to a 1
For(X,2,dim(L1 # starting at element 2:
If not(L1(X # if the element is zero
1+L1(X-1→L1(X # change the element to one plus the previous element
End
For(X,dim(L1)-1,1,-1 # starting at the second-last element and working backwards
If L1(X)>L1(X+1 # if the element is greater than the next
L1(X+1→L1(X # set it equal to the next
End
L1 # implicitly return
```
[Answer]
# Java 8, ~~199~~ 164 bytes
```
a->{for(int l=a.length,n,j,x,i=0;i<l;)if(a[i++]<1){for(n=j=i;j<l;j++)if(a[j]>0){n=j;j=l;}for(j=i-3;++j<n-1;)if(j<l)a[j+1]=j<0?1:a[j]+(l==n||a[n]>a[j]|a[n]<1?1:0);}}
```
Modifies the input-array instead of returning a new one to save bytes.
Uses `0` instead of `?`.
[Try it online.](https://tio.run/##hVJLbtswEN3nFERWEkgTpKy0bim66AGaTZaGFowip2QZypDooIGjbQ/QI/Yi7pBiCytOEFAkNO@9@WHGqEe16HatM3c/jo1Vw4C@Ke0OFwhp59t@q5oWXQcTocdO36EmA3xTI5ULAMcLeAavvG7QNXJIHtVifdh2fVAhKxW1rbv334kjhvwkWjKhKytyvc3URmNcVzyPcieN1MIAZzCeaFOvWX4AQhhpxRhUoFksBcamcgseo4BHDlLMa2kq9oV/Dn44s1K652e1cfU6APGv4kCzXIzjUYSyd/tbC2Wn6mNzD9B6duN77e5ji1Pfvh18VpCScBabTggnjCxPgdWpMZMykL4A@Nws5uYsbnlFzhKHMwuxTCD4nomLgMItz8qHC8HJx7eIV6jpFP//ynQZ@XAq/bT6VyUr4lu@6D@AMUwJma5StnBWICY88mX4YrqU7zTG2QLGEUYKlo9SChu82/s0xJunwbcPtNt7uoP5@szA5tO915Z@7Xv1NFDfTZPPJjd8if78@o0uU0pHm0SIV@NZ927EVPB4/As)
**Explanation:**
```
a->{ // Method with integer-array parameter and no return-type
for(int l=a.length, // Length of the input-array
n,j,x, // Temp integers
i=0;i<l;) // Loop `i` over the input-array, in the range [0, length):
if(a[i++]<1){ // If the `i`'th number of the array is 0:
// (And increase `i` to the next cell with `i++`)
for(n=j=i; // Set both `n` and `j` to (the new) `i`
j<l;j++) // Loop `j` in the range [`i`, length):
if(a[j]>0){ // If the `j`'th number of the array is not 0:
n=j; // Set `n` to `j`
j=l;} // And set `j` to the length to stop the loop
// (`n` is now set to the index of the first non-0 number
// after the `i-1`'th number 0)
for(j=i-3;++j<n-1;) // Loop `j` in the range (`i`-3, `n-1`):
if(j<l) // If `j` is still within bounds (smaller than the length)
a[j+1]= // Set the `j+1`'th position to:
j<0? // If `j` is a 'position' before the first number
1 // Set the first cell of the array to 1
: // Else:
a[j]+ // Set it to the `j`'th number, plus:
(l==n // If `n` is out of bounds bounds (length or larger)
||a[n]>a[j]// Or the `n`'th number is larger than the `j`'th number
|a[n]<1? // Or the `n`'th number is a 0
1 // Add 1
: // Else:
0);}} // Leave it unchanged by adding 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~144~~ ~~124~~ 119 bytes
```
l=input()
for n in range(len(l)):a=max(l[:n]+[0]);b=filter(abs,l[n:]);b=len(b)and b[0]or-~a;l[n]=l[n]or a+(b>a)
print l
```
[Try it online!](https://tio.run/nexus/python2#TYzBCsMgEETv@QqPu8SCh/RisD8iHlZiirDdBGugp/66Ne2lDMzAzGMauyz7UQGHdStKVBZVSO4JOAkwoiX3oBewtxJGbwLO0a2ZaypA8anZi/12Jx6RZFGxU1u5vGnuY3Cn9WcaId4Ih71kqYpb80YbPWnzp@svwwc "Python 2 – TIO Nexus")
---
Uses `0` instead of `?`
[Answer]
# JavaScript (ES6), 59
A function with an integer array as input. The empty spots are marked with `0`
```
a=>a.map((v,i)=>v?w=v:(a.slice(i).find(x=>x)<=w?w:++w),w=0)
```
**Test**
```
var F=
a=>a.map((v,i)=>v?w=v:(a.slice(i).find(x=>x)<=w?w:++w),w=0)
;[[2, 4, 10]
,[1, 0, 3]
,[1, 0, 4]
,[]
,[8]
,[0]
,[0, 0, 0]
,[0, 1]
,[0, 2]
,[0, 3]
,[45, 0]
,[1, 0, 0, 0, 1]
,[3, 0, 0, 0, 0, 30]
,[1, 0, 2, 0, 3, 0, 4]
,[1, 0, 3, 0, 5, 0, 7]
,[1, 0, 3, 0, 5, 0, 0, 7]
,[1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 0, 4, 0, 0, 6]
,[98, 0, 0, 0, 102, 0, 104]]
.forEach(a=>{
console.log(a+'\n'+F(a))
})
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 182 bytes
Using the same strategy as Ørjan Johansen.
Uses 0 in the input list to mark the unknown var.
```
l=>{if(l[0]<1)l[0]=1;int j;for(j=0;j<l.Length;j++)l[j]=l[j]==0?l[j-1]+1:l[j];for(j=l.Length-2;j>=0;j--)l[j]=l[j]>l[j+1]?l[j+1]:l[j];foreach(var m in l) System.Console.Write(m+" ");};
```
[Try it online!](https://tio.run/##XZA9a8MwEIZ3/4ojSyT8gdxOrWyH0DWF0AwdggdVkRMJWQqSagjBv92V26aBDncv3L0P98F9zq0TU8I18x62zh4d668JwPnzQ0sOPrAQZbDyAK9MGoTnJsDu4oPoizUP0ppKmrBvG@ignnTdXGWH9J60VYlnqUsa@6BoZx1SNaGq0sVGmGM4UZWm0aPa@jvVZBU1L9u0fJ4Lv8TNnT9Q1cx8nt@hJqa0bFc/8ocJxk9oYA56kAY0vi38Yo23WhTvTgaB@nQBC0xHOiUdup3kHLvMvkG4sNYa/SPfBDtspBEIF7uzlgEtsyXO4pRQbJnzAmMaPzQm40Syx4xkTzHIFw "C# (.NET Core) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 99 bytes
```
s,(\d+ )?\K((\? )+)(?=(\d+)),$d=$1;$l=$4;$2=~s/\?/$d<$l?++$d:$l/rge,ge;($d)=/.*( \d+)/;s/\?/++$d/ge
```
[Try it online!](https://tio.run/##LUtLCsMgEL3KLGahNYkxKIRamQOU3sClEgrSSOy6R6@NUt5n8T45HsnUWgbmgwBO/s6YJ@CCM3It43zA4FBZTA61xcV9ivQkMdwwkRAYrpjkscVhi5Zh4E5OFwbtKW1fto3cYq0ECpqW0zWYDvpjBTWD6r1uPLPvnt/P/VXq@DDTrOY65h8 "Perl 5 – Try It Online")
] |
[Question]
[
This task is about compressing and processing a sequence of conditionals.
---
In the game [Keep Talking and Nobody Explodes](http://www.keeptalkinggame.com/), a bomb defuser must disarm a bomb with the help of instructions relayed by experts consulting a convoluted [Bomb Defusal Manual](http://www.bombmanual.com/manual/1/pdf/Bomb-Defusal-Manual_1.pdf). This challenge deals with the module "On the Subject of Wires", explained on page 5 of the manual. The defuser is presented with an array of colored wires. Only one of them is safe to cut -- the rest detonate the bomb.
Your code acts as the expert to determine which wire to cut based on the number and colors of the wires, as per the instructions in the manual reproduced under "Wire cutting rules".
**Input:** An ordered list or string of 3, 4, 5, or 6 wire colors, represented by uppercase letters:
* `B`: Black
* `U`: Blue
* `R`: Red
* `W`: White
* `Y`: Yellow
Note that blue is `U`, not `B`.
The input also includes a bit (True/False or 0/1) for whether the last digit of the bomb's serial number is odd, a condition used in some rules.
You should not take the number of wires as a separate input, but derive it from the list or string of colors. You may have your list or string have a terminator element after the colors, perhaps if your language cannot tell how long it is. This terminator should be a fixed value that doesn't encode additional information.
**Output:** A number 1 through 6, indicating which wire to cut. This may not be zero-indexed.
**Wire cutting rules:** These rules are reproduced from page 5 of [the defusal manual](http://www.bombmanual.com/manual/1/pdf/Bomb-Defusal-Manual_1.pdf)
```
3 wires:
If there are no red wires, cut the second wire.
Otherwise, if the last wire is white, cut the last wire.
Otherwise, if there is more than one blue wire, cut the last blue wire.
Otherwise, cut the last wire.
4 wires:
If there is more than one red wire and the last digit of the serial number is odd, cut the last red wire.
Otherwise, if the last wire is yellow and there are no red wires, cut the first wire.
Otherwise, if there is exactly one blue wire, cut the first wire.
Otherwise, if there is more than one yellow wire, cut the last wire.
Otherwise, cut the second wire.
5 wires:
If the last wire is black and the last digit of the serial number is odd, cut the fourth wire.
Otherwise, if there is exactly one red wire and there is more than one yellow wire, cut the first wire.
Otherwise, if there are no black wires, cut the second wire.
Otherwise, cut the first wire.
6 wires:
If there are no yellow wires and the last digit of the serial number is odd, cut the third wire.
Otherwise, if there is exactly one yellow wire and there is more than one white wire, cut the fourth wire.
Otherwise, if there are no red wires, cut the last wire.
Otherwise, cut the fourth wire.
```
**Reference solution ([TIO](https://tio.run/##pVtRb@M2En7e/ApeDos4PTeoY9UPC2SBU9E@FShAlDcYLBaBGyuxD44VKHK3@@u3lCw7IvXNUEaDRTaxPg6HM@TMN0Pl5Wu9Lne3376tikfzZVMV93V5/7CvJ83Pr1PzWlSb5fa@XK2uP1wY/3V5eWmLel/tTL0uzGa3Kv4y5WP7SzPE1KXxw6em3BXft0@L1Y35fb15Nf7f0uz2z38UlZk1uMVNK7Gd6YP5r9luXutG1txLq8r909oszEO5LSvzsF5Wy4e6qF7NY1U@m9xZ4nbwm36NhLwst8VyZx79mC/rwitVtZptl17yavO0qY@6HsY1OvmhXsFqX5hnP/Tw@0Ur@@PHj4FJPl3Zq6m5yptv7U909XnaDu1sMz9aqP3fL/W@XZu5M9tid7Dodfuo0ad95h@1H3/6fvb5MOnmsT/wzswPortH7cc3D@V@V0@8DtcN4oc3RPNVHbxze/qw2PqBvRnvGsXhmNPE4dhgUucn/Whm4fh/m18bC/@x3R92ARJ@dXXz/3JzNMNN1W6Og7z/mFlvxtciodzFSbPAUpluKa@0We5W/R2D1lAVq3OXYAdLGBicr9q5x7tvlnCBHzg7eyAj3ym@FzxxK3ngx8ADoQXyK9X6nehM0b6z12xoSW1dmj3ysQdIMMRMMsRC3orczTnGGvOEL7E1SLHGCPv@8E@3R3a0Sv95tdy8FuZ/Sx8hfq6qsppcUlXuno75oDzqcnl9cbF5fimr2mx8vK99QPcHvklOT8WuqJZ1cb/cbu83u5d9/Trp4m6bJJow@@kQnF0vQk@bw9fF1iYtvPlpszOf5lOTTc2PU7P4/KZrmz2OkJMWNy9Vudo/1JPDbFO/3JdiWd@dBF6H1mikvPm3ne2XpbfJIWN8DsHN19dNsV2ZSZMFuwgTpN9vdfX1w8W7L@vNtmi8@@5dXfgD9rBsRNbL6qmovQVaw0yu/VMvYL@tuwRzTGHfncY0EL8DOtS/7joRjdx3Lz6y1abzULmvvch2Oe9fb8xP/uf3DTFYl3uv7nr5Z9EkfP/ZpXlvJj2dDqKPul1fFH89FC@1@fm3X9od4Gfq5vmpfH7ZFrUPvM1o04z2G@HbZNK5s/vmc21rQG@W2@uL8CmfMnH40B6@9YbOe0/psFkGQ104q/SQgUqut//wUHeaFA218dB57yFLs77xEgfWarHG/aduYOL@U6tKHlixe0inaQmoTJrvKJwVyCXBO6T5lU5GpOFDDu0gPURrYdVIfJo1l8ayMG3e8yteUi4xUgkhnRTXg/W0nMUQOzDCAELxHsYI1hCsamKhr2bDgx8h5jGCNaPZ8Mx1iCwOIIN9OosRrAYwYffMIMRKgSNXneN6ZzGOA7NhXIuMMhvGNmw2F3o4VwOkrokQ0gaxkrUYHvlYnIdVVai3KzUIqRMxTmUYIlmfk@mF1X0QFbBWyiU4A85iBEnLsaEL7fD82JCjpRFgu1nFgZkMAUIojO9gvVFiQeslvNv68@hnva9nLCWL06aTImQEYQkiEJkBxAnWp3ROIBAkEUSPbxSaRZfCQmrpHz98fDiMkWiaCCJyARemWyTF4nwLGAU@HRxmObT3OTxATlVlmKMyGQJUIUwjZzHEaushGA9uIULyMakbhUEoBoqwpmoebyWNEUVsRGdOuCrBvMZpLAvFTpFIcZpwUahdruJcmLolVmS1mBvBRsxKaRpFZ3A2GjktQ2Y9IG9pzzLIqmDfcUiRdbJnRzI@Usk/wo0imUl5uObKZNgI4qpzYBeeXZdkuS5JdXlcya@XkBHn5TQ31tO3iwOAxjs13jFguXnSZxF1UGE2dC0wHoXxzI6DiTamZO3n4jyTYtsj6ioeVzpxHOKFRTCoFsRpGZbCGYSJZ9aG50Ynwnl6f1qQG1mg3rlMDRSYWP64ZI6KYFZtu0UnV5/WajvKxnWvop2V@z4zWD7lmoVtvKm0CselyxwK96e0CB63VpY7WBimbpOIWju1VGMtHyMYcASBrW7TFZfIpQnsTh1n1fROIfGQ6DfFvTmlKrRxNsNGoZj4pmCklogjeBvCkSqPkw1lSkdPiuOwph4DpgWswkntOO4VKAXPiM7r4Bhq5W0OakJpWlaPBYNj4dKFN6mlKOrrSR1/VuMdxwdbyBWDej1Z@Qsdp0E1nGsFDQNCRlptrccUHsfIGDAtqy6CtGTBI083xwWZVgyiKt6B/gfCSbd0A3GQGGZye0C9sUAVdmCGRQLskoIJNsjmw@vWIPZYaXUuxRoXMdjJTZ4MYoXAm8F7K5ySMng9lY9TgpXEroDFdlsOCjyXvMeyySYdagupjkbUi1SFGZBNBKZUTZzJraKR13FjBRMo4EWw1rfFYKEXuYDdIfW6ZNAuGSfYxqZWBCv3LQMsJdM7Ovrqyw2oz4gWh7tHgj@cFIVYkox0yQWVHQiIumAH7mY6wQp2rGDG2XGhNbYUjzjobuxp1JYQHWIBkzwLzIIWqILWBVNMBZJghvVqJtxLK/nGwfm1XU9SY1ftrlkt1DvQZ@dk145i7p7CkppCRDBrDSut5ZvJvTcn5SYE5rRkGzPsJFi4ysy0Bp8SLBhEcBa6FYMXioTlRWBWGTI6oeq1fw42c64KJmDkcCNboCyry3Pg6JEg2KWu/DLYOXTq/awF0dulJVvQqhkLHiF5hK9dqheIwaTF70HBpJVONu65Ji2HtxJ2tpUuikTBURTNk4L1qsWCuELa9rQgMlP6bRh3Dpgha8nirm@evHKwsDLF6clK9YK4K1BjUVVYu8LBYKeWOBa2DrUtxNIlhwjW7hwweMSp5sT7BbjrrRMtC2lhUmVO8gsL7q3E80Rqv0d6azlPv11GIE2O0MKCKwhJCwsYkSiY5Tp5AbFW3RYEahErxCF0K0GqKdBVtip4kC8HuwJh7RlydRM76YCIYDpDY0pyJ3QDkwulOsWXDVqGFMGcFMxpP1tYVmN/oAypKmHT0ZtAl8xJlJNgJySlBSVZJEmZN9fkstxxzoZ/DJGqAFDpJhWy@OIt9QcZLllDEkjoA@wCvj1qk6cZKyI4mSGHTILxm8IYq9IgTBFSWPRGB3phM4cJRANb@Q8rMvkCcITgdGBjEE6kkpdha1zomiCwOwcsdt4YBDXp3LGaRpHd3Mi9ydLNAmsvDOdp3sZq@kgLtum3ifM0h2WQ9UeorHAKjKVzsS6tcRRnc00wpckjg/aK/so2opCkgt05YKtcQ2CwU4s3hi/xpV44R00IEC8GjdsokWGsVdvCgzfJUUZfyFjSgiGnXuHFYOEVrgW8Hs/V3g2@Sx8ckb8B))**
This code is in Python.
```
def wire_to_cut(wires, serial_odd):
"""Return the index of the wire to cut, one-indexed. This is a number 1 to 6.
wires: A list of 3 through 6 color characters from BURWY
serial_odd: A Boolean for whether the last digit of the serial is odd.
>>> wire_to_cut(['R', 'B', 'R', 'W'], True):
3
"""
num_wires = len(wires)
last_wire = wires[-1]
if num_wires == 3:
if wires.count('R') == 0:
return 2
elif last_wire == 'W':
return num_wires
elif wires.count('U') > 1:
# Last blue wire
return ''.join(wires).rindex('U') + 1
else:
return num_wires
elif num_wires == 4:
if wires.count('R') > 1 and serial_odd:
# Last red wire
return ''.join(wires).rindex('R') + 1
elif last_wire == 'Y' and wires.count('R') == 0:
return 1
elif wires.count('U') == 1:
return 1
elif wires.count('Y') > 1:
return num_wires
else:
return 2
elif num_wires == 5:
if last_wire == 'B' and serial_odd:
return 4
elif wires.count('R') == 1 and wires.count('Y') > 1:
return 1
elif wires.count('B') == 0:
return 2
else:
return 1
elif num_wires == 6:
if wires.count('Y') == 0 and serial_odd:
return 3
elif wires.count('Y') == 1 and wires.count('W') > 1:
return 4
elif wires.count('R') == 0:
return num_wires
else:
return 4
else:
raise ValueError("Wrong number of wires.")
```
**Test cases**
As `(input, output)` where `input = (wires, odd_serial)`.
```
((['B', 'B', 'B'], False), 2)
((['B', 'B', 'Y'], True), 2)
((['B', 'R', 'R'], False), 3)
((['B', 'W', 'U'], True), 2)
((['U', 'B', 'B'], True), 2)
((['U', 'B', 'Y'], False), 2)
((['U', 'U', 'R'], True), 2)
((['U', 'U', 'U'], False), 2)
((['U', 'R', 'R'], True), 3)
((['U', 'Y', 'Y'], False), 2)
((['R', 'B', 'U'], False), 3)
((['R', 'B', 'Y'], False), 3)
((['R', 'U', 'B'], False), 3)
((['R', 'R', 'U'], False), 3)
((['R', 'W', 'U'], True), 3)
((['W', 'B', 'W'], False), 2)
((['W', 'B', 'Y'], True), 2)
((['W', 'R', 'U'], True), 3)
((['W', 'W', 'B'], True), 2)
((['W', 'W', 'U'], True), 2)
((['W', 'Y', 'W'], True), 2)
((['Y', 'U', 'B'], True), 2)
((['Y', 'U', 'W'], False), 2)
((['Y', 'R', 'U'], False), 3)
((['Y', 'Y', 'B'], False), 2)
((['Y', 'Y', 'B'], True), 2)
((['B', 'B', 'U', 'U'], True), 2)
((['B', 'B', 'R', 'W'], True), 2)
((['B', 'B', 'R', 'Y'], True), 2)
((['B', 'U', 'B', 'R'], False), 1)
((['B', 'U', 'R', 'W'], False), 1)
((['B', 'U', 'W', 'R'], True), 1)
((['B', 'U', 'W', 'Y'], True), 1)
((['B', 'U', 'Y', 'R'], False), 1)
((['B', 'R', 'U', 'B'], True), 1)
((['B', 'R', 'R', 'B'], True), 3)
((['B', 'R', 'Y', 'W'], True), 2)
((['B', 'R', 'Y', 'Y'], True), 4)
((['B', 'W', 'R', 'U'], True), 1)
((['B', 'W', 'Y', 'B'], False), 2)
((['B', 'Y', 'R', 'U'], False), 1)
((['B', 'Y', 'R', 'R'], False), 2)
((['U', 'B', 'R', 'W'], False), 1)
((['U', 'B', 'W', 'Y'], False), 1)
((['U', 'B', 'Y', 'W'], True), 1)
((['U', 'U', 'R', 'W'], True), 2)
((['U', 'U', 'W', 'B'], False), 2)
((['U', 'U', 'W', 'Y'], False), 1)
((['U', 'R', 'B', 'U'], False), 2)
((['U', 'R', 'Y', 'U'], True), 2)
((['U', 'R', 'Y', 'W'], False), 1)
((['U', 'R', 'Y', 'Y'], False), 1)
((['U', 'W', 'U', 'Y'], False), 1)
((['U', 'W', 'W', 'W'], False), 1)
((['U', 'Y', 'B', 'B'], False), 1)
((['U', 'Y', 'B', 'W'], True), 1)
((['U', 'Y', 'U', 'R'], True), 2)
((['U', 'Y', 'R', 'W'], False), 1)
((['R', 'B', 'R', 'R'], False), 2)
((['R', 'U', 'B', 'B'], True), 1)
((['R', 'U', 'W', 'B'], False), 1)
((['R', 'R', 'B', 'R'], True), 4)
((['R', 'R', 'W', 'R'], True), 4)
((['R', 'R', 'W', 'W'], True), 2)
((['R', 'R', 'Y', 'Y'], False), 4)
((['R', 'R', 'Y', 'Y'], True), 2)
((['R', 'W', 'U', 'W'], True), 1)
((['R', 'W', 'W', 'U'], False), 1)
((['R', 'W', 'Y', 'W'], False), 2)
((['R', 'Y', 'R', 'U'], False), 1)
((['R', 'Y', 'Y', 'W'], False), 4)
((['W', 'B', 'U', 'R'], False), 1)
((['W', 'B', 'U', 'Y'], False), 1)
((['W', 'U', 'B', 'Y'], False), 1)
((['W', 'U', 'U', 'W'], True), 2)
((['W', 'U', 'R', 'W'], False), 1)
((['W', 'W', 'R', 'U'], False), 1)
((['W', 'Y', 'R', 'R'], False), 2)
((['W', 'Y', 'Y', 'U'], False), 1)
((['W', 'Y', 'Y', 'Y'], True), 1)
((['Y', 'B', 'B', 'R'], True), 2)
((['Y', 'B', 'W', 'U'], False), 1)
((['Y', 'B', 'W', 'W'], False), 2)
((['Y', 'U', 'R', 'Y'], False), 1)
((['Y', 'R', 'B', 'R'], False), 2)
((['Y', 'R', 'U', 'R'], True), 4)
((['Y', 'R', 'R', 'Y'], False), 4)
((['Y', 'R', 'W', 'U'], False), 1)
((['Y', 'R', 'Y', 'B'], False), 4)
((['Y', 'R', 'Y', 'B'], True), 4)
((['Y', 'W', 'U', 'B'], False), 1)
((['Y', 'W', 'R', 'R'], True), 4)
((['Y', 'W', 'W', 'R'], True), 2)
((['Y', 'W', 'W', 'Y'], True), 1)
((['Y', 'W', 'Y', 'U'], False), 1)
((['Y', 'Y', 'B', 'B'], True), 4)
((['Y', 'Y', 'R', 'R'], True), 4)
((['B', 'B', 'B', 'R', 'W'], False), 1)
((['B', 'B', 'R', 'R', 'W'], False), 1)
((['B', 'U', 'B', 'W', 'U'], True), 1)
((['B', 'R', 'R', 'U', 'R'], True), 1)
((['B', 'R', 'R', 'W', 'W'], False), 1)
((['B', 'R', 'Y', 'Y', 'R'], False), 1)
((['B', 'W', 'B', 'W', 'B'], False), 1)
((['B', 'W', 'U', 'B', 'U'], True), 1)
((['B', 'W', 'R', 'U', 'W'], True), 1)
((['B', 'W', 'R', 'W', 'B'], False), 1)
((['B', 'W', 'W', 'R', 'U'], False), 1)
((['B', 'W', 'W', 'R', 'U'], True), 1)
((['B', 'W', 'W', 'W', 'B'], False), 1)
((['B', 'W', 'Y', 'R', 'Y'], True), 1)
((['B', 'Y', 'B', 'W', 'U'], True), 1)
((['B', 'Y', 'U', 'W', 'B'], True), 4)
((['B', 'Y', 'U', 'Y', 'W'], False), 1)
((['U', 'B', 'R', 'W', 'Y'], False), 1)
((['U', 'B', 'W', 'B', 'R'], False), 1)
((['U', 'B', 'W', 'B', 'W'], False), 1)
((['U', 'B', 'W', 'Y', 'R'], False), 1)
((['U', 'B', 'Y', 'U', 'B'], True), 4)
((['U', 'B', 'Y', 'U', 'Y'], False), 1)
((['U', 'B', 'Y', 'R', 'W'], False), 1)
((['U', 'U', 'B', 'B', 'U'], True), 1)
((['U', 'U', 'R', 'U', 'W'], True), 2)
((['U', 'U', 'Y', 'U', 'R'], True), 2)
((['U', 'U', 'Y', 'U', 'W'], False), 2)
((['U', 'R', 'B', 'Y', 'Y'], False), 1)
((['U', 'R', 'U', 'B', 'Y'], False), 1)
((['U', 'R', 'W', 'W', 'B'], False), 1)
((['U', 'R', 'Y', 'Y', 'W'], False), 1)
((['U', 'W', 'B', 'U', 'B'], True), 4)
((['U', 'W', 'U', 'U', 'B'], True), 4)
((['U', 'W', 'R', 'U', 'Y'], True), 2)
((['U', 'W', 'R', 'R', 'R'], True), 2)
((['U', 'W', 'R', 'R', 'W'], False), 2)
((['U', 'W', 'R', 'Y', 'W'], True), 2)
((['U', 'W', 'W', 'Y', 'R'], True), 2)
((['U', 'Y', 'B', 'W', 'Y'], False), 1)
((['U', 'Y', 'U', 'R', 'W'], True), 2)
((['U', 'Y', 'R', 'R', 'U'], False), 2)
((['U', 'Y', 'Y', 'B', 'W'], False), 1)
((['U', 'Y', 'Y', 'R', 'B'], True), 4)
((['U', 'Y', 'Y', 'Y', 'R'], False), 1)
((['R', 'B', 'B', 'W', 'U'], False), 1)
((['R', 'B', 'U', 'B', 'Y'], False), 1)
((['R', 'B', 'R', 'R', 'Y'], True), 1)
((['R', 'B', 'W', 'W', 'R'], True), 1)
((['R', 'B', 'W', 'W', 'W'], False), 1)
((['R', 'U', 'U', 'B', 'U'], True), 1)
((['R', 'U', 'U', 'R', 'Y'], False), 2)
((['R', 'U', 'R', 'B', 'W'], False), 1)
((['R', 'U', 'R', 'Y', 'R'], True), 2)
((['R', 'R', 'B', 'U', 'U'], True), 1)
((['R', 'R', 'B', 'R', 'W'], True), 1)
((['R', 'R', 'W', 'B', 'Y'], True), 1)
((['R', 'R', 'Y', 'Y', 'B'], False), 1)
((['R', 'W', 'U', 'Y', 'W'], False), 2)
((['R', 'W', 'Y', 'B', 'U'], True), 1)
((['R', 'Y', 'B', 'U', 'U'], True), 1)
((['R', 'Y', 'B', 'R', 'Y'], True), 1)
((['R', 'Y', 'B', 'W', 'R'], True), 1)
((['R', 'Y', 'R', 'U', 'U'], False), 2)
((['R', 'Y', 'Y', 'W', 'B'], True), 4)
((['R', 'Y', 'Y', 'W', 'W'], True), 1)
((['W', 'B', 'R', 'R', 'R'], False), 1)
((['W', 'U', 'U', 'U', 'B'], False), 1)
((['W', 'U', 'U', 'R', 'B'], False), 1)
((['W', 'U', 'R', 'B', 'R'], False), 1)
((['W', 'U', 'W', 'W', 'R'], True), 2)
((['W', 'U', 'Y', 'R', 'W'], True), 2)
((['W', 'R', 'R', 'B', 'Y'], True), 1)
((['W', 'W', 'U', 'B', 'W'], True), 1)
((['W', 'W', 'U', 'W', 'R'], False), 2)
((['W', 'W', 'W', 'W', 'B'], False), 1)
((['W', 'W', 'W', 'W', 'W'], False), 2)
((['W', 'W', 'Y', 'W', 'U'], True), 2)
((['W', 'W', 'Y', 'Y', 'R'], False), 1)
((['W', 'Y', 'R', 'B', 'B'], False), 1)
((['W', 'Y', 'W', 'B', 'W'], True), 1)
((['W', 'Y', 'Y', 'W', 'U'], True), 2)
((['Y', 'B', 'U', 'R', 'B'], True), 4)
((['Y', 'B', 'U', 'Y', 'R'], False), 1)
((['Y', 'B', 'R', 'Y', 'Y'], False), 1)
((['Y', 'B', 'W', 'U', 'B'], True), 4)
((['Y', 'B', 'Y', 'R', 'R'], False), 1)
((['Y', 'U', 'U', 'U', 'U'], False), 2)
((['Y', 'U', 'R', 'W', 'B'], False), 1)
((['Y', 'U', 'W', 'U', 'Y'], True), 2)
((['Y', 'U', 'Y', 'Y', 'W'], False), 2)
((['Y', 'R', 'R', 'R', 'Y'], False), 2)
((['Y', 'R', 'R', 'Y', 'R'], False), 2)
((['Y', 'R', 'W', 'W', 'U'], False), 2)
((['Y', 'W', 'B', 'R', 'U'], True), 1)
((['Y', 'W', 'U', 'U', 'W'], True), 2)
((['Y', 'W', 'U', 'R', 'B'], False), 1)
((['Y', 'W', 'R', 'R', 'R'], True), 2)
((['Y', 'W', 'R', 'Y', 'R'], False), 2)
((['Y', 'W', 'W', 'B', 'U'], True), 1)
((['Y', 'W', 'W', 'W', 'B'], False), 1)
((['Y', 'Y', 'R', 'Y', 'U'], False), 1)
((['B', 'B', 'B', 'B', 'R', 'U'], False), 4)
((['B', 'B', 'B', 'R', 'R', 'R'], True), 3)
((['B', 'B', 'R', 'U', 'W', 'Y'], False), 4)
((['B', 'B', 'R', 'R', 'R', 'B'], True), 3)
((['B', 'B', 'W', 'U', 'B', 'B'], False), 6)
((['B', 'B', 'W', 'U', 'B', 'U'], True), 3)
((['B', 'B', 'W', 'W', 'B', 'R'], True), 3)
((['B', 'B', 'Y', 'Y', 'W', 'R'], False), 4)
((['B', 'U', 'B', 'B', 'W', 'U'], False), 6)
((['B', 'U', 'U', 'W', 'W', 'Y'], True), 4)
((['B', 'U', 'U', 'Y', 'Y', 'R'], False), 4)
((['B', 'U', 'R', 'R', 'B', 'Y'], True), 4)
((['B', 'U', 'W', 'B', 'W', 'Y'], True), 4)
((['B', 'U', 'Y', 'R', 'R', 'R'], False), 4)
((['B', 'U', 'Y', 'R', 'Y', 'B'], False), 4)
((['B', 'R', 'U', 'B', 'U', 'B'], True), 3)
((['B', 'R', 'R', 'R', 'Y', 'B'], True), 4)
((['B', 'R', 'R', 'W', 'B', 'R'], True), 3)
((['B', 'R', 'Y', 'B', 'R', 'W'], False), 4)
((['B', 'R', 'Y', 'W', 'B', 'Y'], False), 4)
((['B', 'W', 'U', 'Y', 'U', 'W'], False), 4)
((['B', 'W', 'R', 'U', 'Y', 'Y'], True), 4)
((['B', 'W', 'R', 'Y', 'U', 'W'], False), 4)
((['B', 'W', 'W', 'Y', 'U', 'R'], False), 4)
((['B', 'W', 'Y', 'R', 'B', 'R'], False), 4)
((['B', 'W', 'Y', 'W', 'Y', 'U'], False), 6)
((['B', 'Y', 'B', 'R', 'B', 'R'], True), 4)
((['B', 'Y', 'U', 'B', 'Y', 'U'], False), 6)
((['B', 'Y', 'R', 'U', 'Y', 'U'], True), 4)
((['B', 'Y', 'R', 'R', 'W', 'W'], True), 4)
((['B', 'Y', 'W', 'W', 'U', 'B'], True), 4)
((['U', 'B', 'B', 'W', 'R', 'R'], True), 3)
((['U', 'B', 'W', 'B', 'W', 'U'], False), 6)
((['U', 'B', 'Y', 'U', 'B', 'R'], False), 4)
((['U', 'U', 'B', 'B', 'W', 'Y'], False), 6)
((['U', 'U', 'B', 'W', 'B', 'B'], True), 3)
((['U', 'U', 'B', 'Y', 'Y', 'Y'], False), 6)
((['U', 'U', 'U', 'B', 'U', 'Y'], True), 6)
((['U', 'U', 'U', 'B', 'Y', 'Y'], False), 6)
((['U', 'U', 'U', 'Y', 'W', 'B'], False), 6)
((['U', 'U', 'R', 'U', 'W', 'R'], True), 3)
((['U', 'U', 'Y', 'W', 'W', 'U'], True), 4)
((['U', 'U', 'Y', 'Y', 'B', 'R'], False), 4)
((['U', 'R', 'B', 'R', 'Y', 'R'], False), 4)
((['U', 'R', 'B', 'R', 'Y', 'Y'], True), 4)
((['U', 'R', 'R', 'B', 'U', 'R'], False), 4)
((['U', 'R', 'W', 'B', 'B', 'B'], False), 4)
((['U', 'R', 'W', 'Y', 'U', 'U'], True), 4)
((['U', 'R', 'Y', 'U', 'B', 'Y'], True), 4)
((['U', 'W', 'B', 'B', 'B', 'U'], False), 6)
((['U', 'W', 'B', 'R', 'W', 'Y'], True), 4)
((['U', 'W', 'R', 'R', 'B', 'R'], True), 3)
((['U', 'W', 'R', 'W', 'Y', 'B'], True), 4)
((['U', 'W', 'W', 'B', 'Y', 'R'], True), 4)
((['U', 'W', 'W', 'W', 'R', 'W'], False), 4)
((['U', 'W', 'W', 'W', 'R', 'Y'], True), 4)
((['U', 'Y', 'B', 'Y', 'R', 'W'], False), 4)
((['U', 'Y', 'U', 'R', 'U', 'Y'], False), 4)
((['U', 'Y', 'U', 'R', 'Y', 'W'], False), 4)
((['U', 'Y', 'R', 'W', 'U', 'U'], False), 4)
((['U', 'Y', 'R', 'Y', 'Y', 'U'], False), 4)
((['U', 'Y', 'Y', 'B', 'W', 'Y'], True), 6)
((['U', 'Y', 'Y', 'R', 'R', 'Y'], True), 4)
((['R', 'B', 'B', 'U', 'U', 'W'], False), 4)
((['R', 'B', 'B', 'Y', 'R', 'U'], False), 4)
((['R', 'B', 'R', 'Y', 'B', 'R'], True), 4)
((['R', 'B', 'W', 'B', 'R', 'B'], False), 4)
((['R', 'B', 'W', 'W', 'U', 'U'], True), 3)
((['R', 'B', 'Y', 'R', 'Y', 'W'], False), 4)
((['R', 'U', 'B', 'B', 'B', 'W'], True), 3)
((['R', 'U', 'B', 'B', 'R', 'W'], False), 4)
((['R', 'U', 'U', 'U', 'R', 'Y'], False), 4)
((['R', 'U', 'U', 'Y', 'U', 'W'], False), 4)
((['R', 'U', 'R', 'W', 'W', 'R'], False), 4)
((['R', 'U', 'R', 'W', 'W', 'W'], False), 4)
((['R', 'U', 'R', 'Y', 'R', 'U'], False), 4)
((['R', 'U', 'W', 'U', 'Y', 'W'], False), 4)
((['R', 'U', 'W', 'W', 'Y', 'Y'], True), 4)
((['R', 'U', 'W', 'Y', 'W', 'Y'], False), 4)
((['R', 'R', 'B', 'W', 'U', 'W'], False), 4)
((['R', 'R', 'B', 'W', 'W', 'U'], True), 3)
((['R', 'R', 'U', 'B', 'B', 'U'], False), 4)
((['R', 'R', 'U', 'W', 'R', 'B'], True), 3)
((['R', 'R', 'U', 'Y', 'Y', 'R'], False), 4)
((['R', 'R', 'W', 'U', 'W', 'W'], True), 3)
((['R', 'R', 'W', 'W', 'B', 'W'], False), 4)
((['R', 'R', 'Y', 'U', 'B', 'W'], False), 4)
((['R', 'R', 'Y', 'Y', 'U', 'Y'], True), 4)
((['R', 'W', 'B', 'Y', 'R', 'B'], True), 4)
((['R', 'W', 'U', 'B', 'U', 'R'], True), 3)
((['R', 'W', 'U', 'Y', 'U', 'Y'], False), 4)
((['R', 'W', 'W', 'U', 'B', 'Y'], True), 4)
((['R', 'W', 'Y', 'B', 'W', 'Y'], False), 4)
((['R', 'W', 'Y', 'U', 'B', 'Y'], False), 4)
((['R', 'W', 'Y', 'W', 'U', 'U'], False), 4)
((['R', 'Y', 'B', 'W', 'W', 'R'], False), 4)
((['R', 'Y', 'U', 'R', 'B', 'W'], False), 4)
((['R', 'Y', 'U', 'Y', 'R', 'U'], False), 4)
((['R', 'Y', 'R', 'R', 'U', 'R'], True), 4)
((['R', 'Y', 'Y', 'B', 'U', 'R'], False), 4)
((['R', 'Y', 'Y', 'B', 'R', 'W'], False), 4)
((['R', 'Y', 'Y', 'B', 'Y', 'R'], True), 4)
((['R', 'Y', 'Y', 'Y', 'Y', 'R'], False), 4)
((['W', 'B', 'B', 'B', 'R', 'U'], True), 3)
((['W', 'B', 'B', 'R', 'Y', 'Y'], False), 4)
((['W', 'B', 'B', 'Y', 'Y', 'R'], False), 4)
((['W', 'B', 'R', 'R', 'U', 'U'], True), 3)
((['W', 'B', 'R', 'W', 'R', 'Y'], False), 4)
((['W', 'B', 'Y', 'U', 'Y', 'Y'], True), 6)
((['W', 'B', 'Y', 'R', 'R', 'U'], False), 4)
((['W', 'U', 'U', 'B', 'R', 'W'], True), 3)
((['W', 'U', 'U', 'R', 'W', 'R'], False), 4)
((['W', 'U', 'R', 'U', 'B', 'W'], True), 3)
((['W', 'U', 'R', 'U', 'U', 'Y'], True), 4)
((['W', 'U', 'R', 'U', 'R', 'W'], True), 3)
((['W', 'U', 'R', 'U', 'R', 'Y'], False), 4)
((['W', 'U', 'R', 'R', 'U', 'R'], False), 4)
((['W', 'U', 'W', 'U', 'U', 'Y'], True), 4)
((['W', 'U', 'W', 'Y', 'B', 'R'], True), 4)
((['W', 'U', 'Y', 'R', 'B', 'W'], True), 4)
((['W', 'R', 'B', 'B', 'U', 'W'], False), 4)
((['W', 'R', 'B', 'B', 'U', 'Y'], True), 4)
((['W', 'R', 'B', 'Y', 'W', 'R'], False), 4)
((['W', 'R', 'U', 'B', 'W', 'B'], True), 3)
((['W', 'R', 'U', 'Y', 'Y', 'Y'], True), 4)
((['W', 'R', 'R', 'B', 'W', 'Y'], False), 4)
((['W', 'R', 'R', 'R', 'U', 'B'], False), 4)
((['W', 'R', 'R', 'W', 'W', 'Y'], True), 4)
((['W', 'R', 'W', 'B', 'B', 'W'], True), 3)
((['W', 'R', 'Y', 'U', 'B', 'B'], True), 4)
((['W', 'R', 'Y', 'R', 'R', 'R'], True), 4)
((['W', 'W', 'B', 'R', 'R', 'Y'], True), 4)
((['W', 'W', 'B', 'Y', 'U', 'U'], True), 4)
((['W', 'W', 'U', 'W', 'R', 'U'], True), 3)
((['W', 'W', 'U', 'W', 'Y', 'B'], True), 4)
((['W', 'W', 'U', 'Y', 'Y', 'B'], True), 6)
((['W', 'W', 'R', 'R', 'R', 'W'], True), 3)
((['W', 'W', 'W', 'U', 'W', 'Y'], False), 4)
((['W', 'Y', 'R', 'B', 'W', 'U'], False), 4)
((['W', 'Y', 'R', 'W', 'U', 'W'], True), 4)
((['W', 'Y', 'R', 'Y', 'R', 'B'], True), 4)
((['W', 'Y', 'W', 'U', 'U', 'B'], True), 4)
((['W', 'Y', 'Y', 'Y', 'R', 'B'], False), 4)
((['Y', 'B', 'B', 'R', 'W', 'R'], False), 4)
((['Y', 'B', 'R', 'R', 'U', 'B'], True), 4)
((['Y', 'B', 'R', 'Y', 'W', 'R'], False), 4)
((['Y', 'B', 'W', 'Y', 'B', 'R'], True), 4)
((['Y', 'B', 'Y', 'W', 'W', 'Y'], True), 6)
((['Y', 'U', 'B', 'U', 'B', 'U'], False), 6)
((['Y', 'U', 'B', 'U', 'U', 'U'], False), 6)
((['Y', 'U', 'B', 'U', 'Y', 'Y'], False), 6)
((['Y', 'U', 'B', 'W', 'R', 'Y'], True), 4)
((['Y', 'U', 'U', 'B', 'R', 'W'], False), 4)
((['Y', 'U', 'R', 'B', 'W', 'U'], False), 4)
((['Y', 'U', 'Y', 'R', 'Y', 'Y'], True), 4)
((['Y', 'R', 'B', 'B', 'U', 'R'], False), 4)
((['Y', 'R', 'B', 'B', 'U', 'W'], True), 4)
((['Y', 'R', 'B', 'B', 'R', 'B'], False), 4)
((['Y', 'R', 'B', 'R', 'B', 'W'], False), 4)
((['Y', 'R', 'U', 'U', 'U', 'R'], False), 4)
((['Y', 'R', 'R', 'U', 'B', 'W'], True), 4)
((['Y', 'R', 'R', 'W', 'B', 'W'], True), 4)
((['Y', 'R', 'R', 'W', 'U', 'W'], False), 4)
((['Y', 'R', 'W', 'B', 'Y', 'B'], True), 4)
((['Y', 'R', 'W', 'Y', 'Y', 'R'], False), 4)
((['Y', 'R', 'Y', 'B', 'Y', 'B'], False), 4)
((['Y', 'W', 'B', 'R', 'W', 'W'], False), 4)
((['Y', 'W', 'U', 'R', 'W', 'W'], False), 4)
((['Y', 'W', 'R', 'B', 'Y', 'U'], False), 4)
((['Y', 'W', 'R', 'U', 'U', 'Y'], False), 4)
((['Y', 'W', 'R', 'R', 'W', 'B'], True), 4)
((['Y', 'W', 'W', 'U', 'Y', 'W'], True), 6)
((['Y', 'W', 'Y', 'U', 'U', 'U'], True), 6)
((['Y', 'W', 'Y', 'R', 'B', 'B'], False), 4)
((['Y', 'Y', 'B', 'B', 'B', 'B'], True), 6)
((['Y', 'Y', 'B', 'B', 'W', 'R'], True), 4)
((['Y', 'Y', 'B', 'R', 'W', 'Y'], False), 4)
((['Y', 'Y', 'B', 'Y', 'Y', 'B'], False), 6)
((['Y', 'Y', 'R', 'B', 'Y', 'W'], False), 4)
((['Y', 'Y', 'R', 'Y', 'U', 'W'], True), 4)
```
This Python code generates all 39000 possible inputs ([TIO](https://tio.run/##pVtRb@M2En7e/ApeDos4PTeoY9UPC2SBU9E@FShAlDcYLBaBGyuxD44VKHK3@@u3lCw7IvXNUEaDRTaxPg6HM@TMN0Pl5Wu9Lne3376tikfzZVMV93V5/7CvJ83Pr1PzWlSb5fa@XK2uP1wY/3V5eWmLel/tTL0uzGa3Kv4y5WP7SzPE1KXxw6em3BXft0@L1Y35fb15Nf7f0uz2z38UlZk1uMVNK7Gd6YP5r9luXutG1txLq8r909oszEO5LSvzsF5Wy4e6qF7NY1U@m9xZ4nbwm36NhLwst8VyZx79mC/rwitVtZptl17yavO0qY@6HsY1OvmhXsFqX5hnP/Tw@0Ur@@PHj4FJPl3Zq6m5yptv7U909XnaDu1sMz9aqP3fL/W@XZu5M9tid7Dodfuo0ad95h@1H3/6fvb5MOnmsT/wzswPortH7cc3D@V@V0@8DtcN4oc3RPNVHbxze/qw2PqBvRnvGsXhmNPE4dhgUucn/Whm4fh/m18bC/@x3R92ARJ@dXXz/3JzNMNN1W6Og7z/mFlvxtciodzFSbPAUpluKa@0We5W/R2D1lAVq3OXYAdLGBicr9q5x7tvlnCBHzg7eyAj3ym@FzxxK3ngx8ADoQXyK9X6nehM0b6z12xoSW1dmj3ysQdIMMRMMsRC3orczTnGGvOEL7E1SLHGCPv@8E@3R3a0Sv95tdy8FuZ/Sx8hfq6qsppcUlXuno75oDzqcnl9cbF5fimr2mx8vK99QPcHvklOT8WuqJZ1cb/cbu83u5d9/Trp4m6bJJow@@kQnF0vQk@bw9fF1iYtvPlpszOf5lOTTc2PU7P4/KZrmz2OkJMWNy9Vudo/1JPDbFO/3JdiWd@dBF6H1mikvPm3ne2XpbfJIWN8DsHN19dNsV2ZSZMFuwgTpN9vdfX1w8W7L@vNtmi8@@5dXfgD9rBsRNbL6qmovQVaw0yu/VMvYL@tuwRzTGHfncY0EL8DOtS/7joRjdx3Lz6y1abzULmvvch2Oe9fb8xP/uf3DTFYl3uv7nr5Z9EkfP/ZpXlvJj2dDqKPul1fFH89FC@1@fm3X9od4Gfq5vmpfH7ZFrUPvM1o04z2G@HbZNK5s/vmc21rQG@W2@uL8CmfMnH40B6@9YbOe0/psFkGQ104q/SQgUqut//wUHeaFA218dB57yFLs77xEgfWarHG/aduYOL@U6tKHlixe0inaQmoTJrvKJwVyCXBO6T5lU5GpOFDDu0gPURrYdVIfJo1l8ayMG3e8yteUi4xUgkhnRTXg/W0nMUQOzDCAELxHsYI1hCsamKhr2bDgx8h5jGCNaPZ8Mx1iCwOIIN9OosRrAYwYffMIMRKgSNXneN6ZzGOA7NhXIuMMhvGNmw2F3o4VwOkrokQ0gaxkrUYHvlYnIdVVai3KzUIqRMxTmUYIlmfk@mF1X0QFbBWyiU4A85iBEnLsaEL7fD82JCjpRFgu1nFgZkMAUIojO9gvVFiQeslvNv68@hnva9nLCWL06aTImQEYQkiEJkBxAnWp3ROIBAkEUSPbxSaRZfCQmrpHz98fDiMkWiaCCJyARemWyTF4nwLGAU@HRxmObT3OTxATlVlmKMyGQJUIUwjZzHEaushGA9uIULyMakbhUEoBoqwpmoebyWNEUVsRGdOuCrBvMZpLAvFTpFIcZpwUahdruJcmLolVmS1mBvBRsxKaRpFZ3A2GjktQ2Y9IG9pzzLIqmDfcUiRdbJnRzI@Usk/wo0imUl5uObKZNgI4qpzYBeeXZdkuS5JdXlcya@XkBHn5TQ31tO3iwOAxjs13jFguXnSZxF1UGE2dC0wHoXxzI6DiTamZO3n4jyTYtsj6ioeVzpxHOKFRTCoFsRpGZbCGYSJZ9aG50Ynwnl6f1qQG1mg3rlMDRSYWP64ZI6KYFZtu0UnV5/WajvKxnWvop2V@z4zWD7lmoVtvKm0CselyxwK96e0CB63VpY7WBimbpOIWju1VGMtHyMYcASBrW7TFZfIpQnsTh1n1fROIfGQ6DfFvTmlKrRxNsNGoZj4pmCklogjeBvCkSqPkw1lSkdPiuOwph4DpgWswkntOO4VKAXPiM7r4Bhq5W0OakJpWlaPBYNj4dKFN6mlKOrrSR1/VuMdxwdbyBWDej1Z@Qsdp0E1nGsFDQNCRlptrccUHsfIGDAtqy6CtGTBI083xwWZVgyiKt6B/gfCSbd0A3GQGGZye0C9sUAVdmCGRQLskoIJNsjmw@vWIPZYaXUuxRoXMdjJTZ4MYoXAm8F7K5ySMng9lY9TgpXEroDFdlsOCjyXvMeyySYdagupjkbUi1SFGZBNBKZUTZzJraKR13FjBRMo4EWw1rfFYKEXuYDdIfW6ZNAuGSfYxqZWBCv3LQMsJdM7Ovrqyw2oz4gWh7tHgj@cFIVYkox0yQWVHQiIumAH7mY6wQp2rGDG2XGhNbYUjzjobuxp1JYQHWIBkzwLzIIWqILWBVNMBZJghvVqJtxLK/nGwfm1XU9SY1ftrlkt1DvQZ@dk145i7p7CkppCRDBrDSut5ZvJvTcn5SYE5rRkGzPsJFi4ysy0Bp8SLBhEcBa6FYMXioTlRWBWGTI6oeq1fw42c64KJmDkcCNboCyry3Pg6JEg2KWu/DLYOXTq/awF0dulJVvQqhkLHiF5hK9dqheIwaTF70HBpJVONu65Ji2HtxJ2tpUuikTBURTNk4L1qsWCuELa9rQgMlP6bRh3Dpgha8nirm@evHKwsDLF6clK9YK4K1BjUVVYu8LBYKeWOBa2DrUtxNIlhwjW7hwweMSp5sT7BbjrrRMtC2lhUmVO8gsL7q3E80Rqv0d6azlPv11GIE2O0MKCKwhJCwsYkSiY5Tp5AbFW3RYEahErxCF0K0GqKdBVtip4kC8HuwJh7RlydRM76YCIYDpDY0pyJ3QDkwulOsWXDVqGFMGcFMxpP1tYVmN/oAypKmHT0ZtAl8xJlJNgJySlBSVZJEmZN9fkstxxzoZ/DJGqAFDpJhWy@OIt9QcZLllDEkjoA@wCvj1qk6cZKyI4mSGHTILxm8IYq9IgTBFSWPRGB3phM4cJRANb@Q8rMvkCcITgdGBjEE6kkpdha1zomiCwOwcsdt4YBDXp3LGaRpHd3Mi9ydLNAmsvDOdp3sZq@kgLtum3ifM0h2WQ9UeorHAKjKVzsS6tcRRnc00wpckjg/aK/so2opCkgt05YKtcQ2CwU4s3hi/xpV44R00IEC8GjdsokWGsVdvCgzfJUUZfyFjSgiGnXuHFYOEVrgW8Hs/V3g2@Sx8ckb8B)).
```
import itertools
def generate_all_inputs():
colors = ['B', 'U', 'R', 'W', 'Y']
for num_wires in [3, 4, 5, 6]:
for wires in itertools.product(colors, repeat=num_wires):
for serial_odd in [False, True]:
yield (list(wires), serial_odd)
```
**Leaderboard**
```
var QUESTION_ID=125665,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/125665/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), ~~210~~ ~~203~~ ~~199~~ ~~187~~ 180 bytes
*Saved 7 bytes [thanks to nore](https://codegolf.stackexchange.com/questions/125665/which-wire-to-cut/125819#comment310352_125665).*
---
Takes the list of wires `w` and the flag `o` in currying syntax `(w)(o)`.
```
w=>o=>(([,,C,D,E,F]=w).map(c=>eval(c+`=${++i}+`+c),i=B=U=R=W=Y=''),F?!Y&o?3:7/Y&7&&W>7||R?4:6:E?E<'C'&o?4:7/R&7&&Y>7||B?1:2:D?R>7&o?+R[0]:D>'X'&!R|7/U&7?1:Y>7?4:2:!R?2:U<7?3:+U[0])
```
### How?
For each color, we build a string representing the list of 1-based indices at which this color is found, from last to first position.
For instance, the last test case `['Y', 'Y', 'R', 'Y', 'U', 'W']` will be translated as:
* **B = ''**
* **U = '5'**
* **R = '3'**
* **W = '6'**
* **Y = '421'**
These variables provide enough information to process all rules in a rather short format, except tests on specific wires which are performed on the destructured input list `[, , C, D, E, F]`.
```
Rule | Code
----------------------------------+---------------------------------------------------
no X wires | !X
more than one X wire | X>7
exactly one X wire | 7/X&7
position of last X wire (1-based) | +X[0]
(N+1)th wire is X (1-based) | w[N]=='X' (where w[N] is replaced by C, D, E or F)
```
### Test cases
```
let f =
w=>o=>(([,,C,D,E,F]=w).map(c=>eval(c+`=${++i}+`+c),i=B=U=R=W=Y=''),F?!Y&o?3:7/Y&7&&W>7||R?4:6:E?E<'C'&o?4:7/R&7&&Y>7||B?1:2:D?R>7&o?+R[0]:D>'X'&!R|7/U&7?1:Y>7?4:2:!R?2:U<7?3:+U[0])
let passed = 0
let test = (a, r) => passed += (f(a[0])(a[1]) === r)
test([['B', 'B', 'B'], false], 2)
test([['B', 'B', 'Y'], true ], 2)
test([['B', 'R', 'R'], false], 3)
test([['B', 'W', 'U'], true ], 2)
test([['U', 'B', 'B'], true ], 2)
test([['U', 'B', 'Y'], false], 2)
test([['U', 'U', 'R'], true ], 2)
test([['U', 'U', 'U'], false], 2)
test([['U', 'R', 'R'], true ], 3)
test([['U', 'Y', 'Y'], false], 2)
test([['R', 'B', 'U'], false], 3)
test([['R', 'B', 'Y'], false], 3)
test([['R', 'U', 'B'], false], 3)
test([['R', 'R', 'U'], false], 3)
test([['R', 'W', 'U'], true ], 3)
test([['W', 'B', 'W'], false], 2)
test([['W', 'B', 'Y'], true ], 2)
test([['W', 'R', 'U'], true ], 3)
test([['W', 'W', 'B'], true ], 2)
test([['W', 'W', 'U'], true ], 2)
test([['W', 'Y', 'W'], true ], 2)
test([['Y', 'U', 'B'], true ], 2)
test([['Y', 'U', 'W'], false], 2)
test([['Y', 'R', 'U'], false], 3)
test([['Y', 'Y', 'B'], false], 2)
test([['Y', 'Y', 'B'], true ], 2)
test([['B', 'B', 'U', 'U'], true ], 2)
test([['B', 'B', 'R', 'W'], true ], 2)
test([['B', 'B', 'R', 'Y'], true ], 2)
test([['B', 'U', 'B', 'R'], false], 1)
test([['B', 'U', 'R', 'W'], false], 1)
test([['B', 'U', 'W', 'R'], true ], 1)
test([['B', 'U', 'W', 'Y'], true ], 1)
test([['B', 'U', 'Y', 'R'], false], 1)
test([['B', 'R', 'U', 'B'], true ], 1)
test([['B', 'R', 'R', 'B'], true ], 3)
test([['B', 'R', 'Y', 'W'], true ], 2)
test([['B', 'R', 'Y', 'Y'], true ], 4)
test([['B', 'W', 'R', 'U'], true ], 1)
test([['B', 'W', 'Y', 'B'], false], 2)
test([['B', 'Y', 'R', 'U'], false], 1)
test([['B', 'Y', 'R', 'R'], false], 2)
test([['U', 'B', 'R', 'W'], false], 1)
test([['U', 'B', 'W', 'Y'], false], 1)
test([['U', 'B', 'Y', 'W'], true ], 1)
test([['U', 'U', 'R', 'W'], true ], 2)
test([['U', 'U', 'W', 'B'], false], 2)
test([['U', 'U', 'W', 'Y'], false], 1)
test([['U', 'R', 'B', 'U'], false], 2)
test([['U', 'R', 'Y', 'U'], true ], 2)
test([['U', 'R', 'Y', 'W'], false], 1)
test([['U', 'R', 'Y', 'Y'], false], 1)
test([['U', 'W', 'U', 'Y'], false], 1)
test([['U', 'W', 'W', 'W'], false], 1)
test([['U', 'Y', 'B', 'B'], false], 1)
test([['U', 'Y', 'B', 'W'], true ], 1)
test([['U', 'Y', 'U', 'R'], true ], 2)
test([['U', 'Y', 'R', 'W'], false], 1)
test([['R', 'B', 'R', 'R'], false], 2)
test([['R', 'U', 'B', 'B'], true ], 1)
test([['R', 'U', 'W', 'B'], false], 1)
test([['R', 'R', 'B', 'R'], true ], 4)
test([['R', 'R', 'W', 'R'], true ], 4)
test([['R', 'R', 'W', 'W'], true ], 2)
test([['R', 'R', 'Y', 'Y'], false], 4)
test([['R', 'R', 'Y', 'Y'], true ], 2)
test([['R', 'W', 'U', 'W'], true ], 1)
test([['R', 'W', 'W', 'U'], false], 1)
test([['R', 'W', 'Y', 'W'], false], 2)
test([['R', 'Y', 'R', 'U'], false], 1)
test([['R', 'Y', 'Y', 'W'], false], 4)
test([['W', 'B', 'U', 'R'], false], 1)
test([['W', 'B', 'U', 'Y'], false], 1)
test([['W', 'U', 'B', 'Y'], false], 1)
test([['W', 'U', 'U', 'W'], true ], 2)
test([['W', 'U', 'R', 'W'], false], 1)
test([['W', 'W', 'R', 'U'], false], 1)
test([['W', 'Y', 'R', 'R'], false], 2)
test([['W', 'Y', 'Y', 'U'], false], 1)
test([['W', 'Y', 'Y', 'Y'], true ], 1)
test([['Y', 'B', 'B', 'R'], true ], 2)
test([['Y', 'B', 'W', 'U'], false], 1)
test([['Y', 'B', 'W', 'W'], false], 2)
test([['Y', 'U', 'R', 'Y'], false], 1)
test([['Y', 'R', 'B', 'R'], false], 2)
test([['Y', 'R', 'U', 'R'], true ], 4)
test([['Y', 'R', 'R', 'Y'], false], 4)
test([['Y', 'R', 'W', 'U'], false], 1)
test([['Y', 'R', 'Y', 'B'], false], 4)
test([['Y', 'R', 'Y', 'B'], true ], 4)
test([['Y', 'W', 'U', 'B'], false], 1)
test([['Y', 'W', 'R', 'R'], true ], 4)
test([['Y', 'W', 'W', 'R'], true ], 2)
test([['Y', 'W', 'W', 'Y'], true ], 1)
test([['Y', 'W', 'Y', 'U'], false], 1)
test([['Y', 'Y', 'B', 'B'], true ], 4)
test([['Y', 'Y', 'R', 'R'], true ], 4)
test([['B', 'B', 'B', 'R', 'W'], false], 1)
test([['B', 'B', 'R', 'R', 'W'], false], 1)
test([['B', 'U', 'B', 'W', 'U'], true ], 1)
test([['B', 'R', 'R', 'U', 'R'], true ], 1)
test([['B', 'R', 'R', 'W', 'W'], false], 1)
test([['B', 'R', 'Y', 'Y', 'R'], false], 1)
test([['B', 'W', 'B', 'W', 'B'], false], 1)
test([['B', 'W', 'U', 'B', 'U'], true ], 1)
test([['B', 'W', 'R', 'U', 'W'], true ], 1)
test([['B', 'W', 'R', 'W', 'B'], false], 1)
test([['B', 'W', 'W', 'R', 'U'], false], 1)
test([['B', 'W', 'W', 'R', 'U'], true ], 1)
test([['B', 'W', 'W', 'W', 'B'], false], 1)
test([['B', 'W', 'Y', 'R', 'Y'], true ], 1)
test([['B', 'Y', 'B', 'W', 'U'], true ], 1)
test([['B', 'Y', 'U', 'W', 'B'], true ], 4)
test([['B', 'Y', 'U', 'Y', 'W'], false], 1)
test([['U', 'B', 'R', 'W', 'Y'], false], 1)
test([['U', 'B', 'W', 'B', 'R'], false], 1)
test([['U', 'B', 'W', 'B', 'W'], false], 1)
test([['U', 'B', 'W', 'Y', 'R'], false], 1)
test([['U', 'B', 'Y', 'U', 'B'], true ], 4)
test([['U', 'B', 'Y', 'U', 'Y'], false], 1)
test([['U', 'B', 'Y', 'R', 'W'], false], 1)
test([['U', 'U', 'B', 'B', 'U'], true ], 1)
test([['U', 'U', 'R', 'U', 'W'], true ], 2)
test([['U', 'U', 'Y', 'U', 'R'], true ], 2)
test([['U', 'U', 'Y', 'U', 'W'], false], 2)
test([['U', 'R', 'B', 'Y', 'Y'], false], 1)
test([['U', 'R', 'U', 'B', 'Y'], false], 1)
test([['U', 'R', 'W', 'W', 'B'], false], 1)
test([['U', 'R', 'Y', 'Y', 'W'], false], 1)
test([['U', 'W', 'B', 'U', 'B'], true ], 4)
test([['U', 'W', 'U', 'U', 'B'], true ], 4)
test([['U', 'W', 'R', 'U', 'Y'], true ], 2)
test([['U', 'W', 'R', 'R', 'R'], true ], 2)
test([['U', 'W', 'R', 'R', 'W'], false], 2)
test([['U', 'W', 'R', 'Y', 'W'], true ], 2)
test([['U', 'W', 'W', 'Y', 'R'], true ], 2)
test([['U', 'Y', 'B', 'W', 'Y'], false], 1)
test([['U', 'Y', 'U', 'R', 'W'], true ], 2)
test([['U', 'Y', 'R', 'R', 'U'], false], 2)
test([['U', 'Y', 'Y', 'B', 'W'], false], 1)
test([['U', 'Y', 'Y', 'R', 'B'], true ], 4)
test([['U', 'Y', 'Y', 'Y', 'R'], false], 1)
test([['R', 'B', 'B', 'W', 'U'], false], 1)
test([['R', 'B', 'U', 'B', 'Y'], false], 1)
test([['R', 'B', 'R', 'R', 'Y'], true ], 1)
test([['R', 'B', 'W', 'W', 'R'], true ], 1)
test([['R', 'B', 'W', 'W', 'W'], false], 1)
test([['R', 'U', 'U', 'B', 'U'], true ], 1)
test([['R', 'U', 'U', 'R', 'Y'], false], 2)
test([['R', 'U', 'R', 'B', 'W'], false], 1)
test([['R', 'U', 'R', 'Y', 'R'], true ], 2)
test([['R', 'R', 'B', 'U', 'U'], true ], 1)
test([['R', 'R', 'B', 'R', 'W'], true ], 1)
test([['R', 'R', 'W', 'B', 'Y'], true ], 1)
test([['R', 'R', 'Y', 'Y', 'B'], false], 1)
test([['R', 'W', 'U', 'Y', 'W'], false], 2)
test([['R', 'W', 'Y', 'B', 'U'], true ], 1)
test([['R', 'Y', 'B', 'U', 'U'], true ], 1)
test([['R', 'Y', 'B', 'R', 'Y'], true ], 1)
test([['R', 'Y', 'B', 'W', 'R'], true ], 1)
test([['R', 'Y', 'R', 'U', 'U'], false], 2)
test([['R', 'Y', 'Y', 'W', 'B'], true ], 4)
test([['R', 'Y', 'Y', 'W', 'W'], true ], 1)
test([['W', 'B', 'R', 'R', 'R'], false], 1)
test([['W', 'U', 'U', 'U', 'B'], false], 1)
test([['W', 'U', 'U', 'R', 'B'], false], 1)
test([['W', 'U', 'R', 'B', 'R'], false], 1)
test([['W', 'U', 'W', 'W', 'R'], true ], 2)
test([['W', 'U', 'Y', 'R', 'W'], true ], 2)
test([['W', 'R', 'R', 'B', 'Y'], true ], 1)
test([['W', 'W', 'U', 'B', 'W'], true ], 1)
test([['W', 'W', 'U', 'W', 'R'], false], 2)
test([['W', 'W', 'W', 'W', 'B'], false], 1)
test([['W', 'W', 'W', 'W', 'W'], false], 2)
test([['W', 'W', 'Y', 'W', 'U'], true ], 2)
test([['W', 'W', 'Y', 'Y', 'R'], false], 1)
test([['W', 'Y', 'R', 'B', 'B'], false], 1)
test([['W', 'Y', 'W', 'B', 'W'], true ], 1)
test([['W', 'Y', 'Y', 'W', 'U'], true ], 2)
test([['Y', 'B', 'U', 'R', 'B'], true ], 4)
test([['Y', 'B', 'U', 'Y', 'R'], false], 1)
test([['Y', 'B', 'R', 'Y', 'Y'], false], 1)
test([['Y', 'B', 'W', 'U', 'B'], true ], 4)
test([['Y', 'B', 'Y', 'R', 'R'], false], 1)
test([['Y', 'U', 'U', 'U', 'U'], false], 2)
test([['Y', 'U', 'R', 'W', 'B'], false], 1)
test([['Y', 'U', 'W', 'U', 'Y'], true ], 2)
test([['Y', 'U', 'Y', 'Y', 'W'], false], 2)
test([['Y', 'R', 'R', 'R', 'Y'], false], 2)
test([['Y', 'R', 'R', 'Y', 'R'], false], 2)
test([['Y', 'R', 'W', 'W', 'U'], false], 2)
test([['Y', 'W', 'B', 'R', 'U'], true ], 1)
test([['Y', 'W', 'U', 'U', 'W'], true ], 2)
test([['Y', 'W', 'U', 'R', 'B'], false], 1)
test([['Y', 'W', 'R', 'R', 'R'], true ], 2)
test([['Y', 'W', 'R', 'Y', 'R'], false], 2)
test([['Y', 'W', 'W', 'B', 'U'], true ], 1)
test([['Y', 'W', 'W', 'W', 'B'], false], 1)
test([['Y', 'Y', 'R', 'Y', 'U'], false], 1)
test([['B', 'B', 'B', 'B', 'R', 'U'], false], 4)
test([['B', 'B', 'B', 'R', 'R', 'R'], true ], 3)
test([['B', 'B', 'R', 'U', 'W', 'Y'], false], 4)
test([['B', 'B', 'R', 'R', 'R', 'B'], true ], 3)
test([['B', 'B', 'W', 'U', 'B', 'B'], false], 6)
test([['B', 'B', 'W', 'U', 'B', 'U'], true ], 3)
test([['B', 'B', 'W', 'W', 'B', 'R'], true ], 3)
test([['B', 'B', 'Y', 'Y', 'W', 'R'], false], 4)
test([['B', 'U', 'B', 'B', 'W', 'U'], false], 6)
test([['B', 'U', 'U', 'W', 'W', 'Y'], true ], 4)
test([['B', 'U', 'U', 'Y', 'Y', 'R'], false], 4)
test([['B', 'U', 'R', 'R', 'B', 'Y'], true ], 4)
test([['B', 'U', 'W', 'B', 'W', 'Y'], true ], 4)
test([['B', 'U', 'Y', 'R', 'R', 'R'], false], 4)
test([['B', 'U', 'Y', 'R', 'Y', 'B'], false], 4)
test([['B', 'R', 'U', 'B', 'U', 'B'], true ], 3)
test([['B', 'R', 'R', 'R', 'Y', 'B'], true ], 4)
test([['B', 'R', 'R', 'W', 'B', 'R'], true ], 3)
test([['B', 'R', 'Y', 'B', 'R', 'W'], false], 4)
test([['B', 'R', 'Y', 'W', 'B', 'Y'], false], 4)
test([['B', 'W', 'U', 'Y', 'U', 'W'], false], 4)
test([['B', 'W', 'R', 'U', 'Y', 'Y'], true ], 4)
test([['B', 'W', 'R', 'Y', 'U', 'W'], false], 4)
test([['B', 'W', 'W', 'Y', 'U', 'R'], false], 4)
test([['B', 'W', 'Y', 'R', 'B', 'R'], false], 4)
test([['B', 'W', 'Y', 'W', 'Y', 'U'], false], 6)
test([['B', 'Y', 'B', 'R', 'B', 'R'], true ], 4)
test([['B', 'Y', 'U', 'B', 'Y', 'U'], false], 6)
test([['B', 'Y', 'R', 'U', 'Y', 'U'], true ], 4)
test([['B', 'Y', 'R', 'R', 'W', 'W'], true ], 4)
test([['B', 'Y', 'W', 'W', 'U', 'B'], true ], 4)
test([['U', 'B', 'B', 'W', 'R', 'R'], true ], 3)
test([['U', 'B', 'W', 'B', 'W', 'U'], false], 6)
test([['U', 'B', 'Y', 'U', 'B', 'R'], false], 4)
test([['U', 'U', 'B', 'B', 'W', 'Y'], false], 6)
test([['U', 'U', 'B', 'W', 'B', 'B'], true ], 3)
test([['U', 'U', 'B', 'Y', 'Y', 'Y'], false], 6)
test([['U', 'U', 'U', 'B', 'U', 'Y'], true ], 6)
test([['U', 'U', 'U', 'B', 'Y', 'Y'], false], 6)
test([['U', 'U', 'U', 'Y', 'W', 'B'], false], 6)
test([['U', 'U', 'R', 'U', 'W', 'R'], true ], 3)
test([['U', 'U', 'Y', 'W', 'W', 'U'], true ], 4)
test([['U', 'U', 'Y', 'Y', 'B', 'R'], false], 4)
test([['U', 'R', 'B', 'R', 'Y', 'R'], false], 4)
test([['U', 'R', 'B', 'R', 'Y', 'Y'], true ], 4)
test([['U', 'R', 'R', 'B', 'U', 'R'], false], 4)
test([['U', 'R', 'W', 'B', 'B', 'B'], false], 4)
test([['U', 'R', 'W', 'Y', 'U', 'U'], true ], 4)
test([['U', 'R', 'Y', 'U', 'B', 'Y'], true ], 4)
test([['U', 'W', 'B', 'B', 'B', 'U'], false], 6)
test([['U', 'W', 'B', 'R', 'W', 'Y'], true ], 4)
test([['U', 'W', 'R', 'R', 'B', 'R'], true ], 3)
test([['U', 'W', 'R', 'W', 'Y', 'B'], true ], 4)
test([['U', 'W', 'W', 'B', 'Y', 'R'], true ], 4)
test([['U', 'W', 'W', 'W', 'R', 'W'], false], 4)
test([['U', 'W', 'W', 'W', 'R', 'Y'], true ], 4)
test([['U', 'Y', 'B', 'Y', 'R', 'W'], false], 4)
test([['U', 'Y', 'U', 'R', 'U', 'Y'], false], 4)
test([['U', 'Y', 'U', 'R', 'Y', 'W'], false], 4)
test([['U', 'Y', 'R', 'W', 'U', 'U'], false], 4)
test([['U', 'Y', 'R', 'Y', 'Y', 'U'], false], 4)
test([['U', 'Y', 'Y', 'B', 'W', 'Y'], true ], 6)
test([['U', 'Y', 'Y', 'R', 'R', 'Y'], true ], 4)
test([['R', 'B', 'B', 'U', 'U', 'W'], false], 4)
test([['R', 'B', 'B', 'Y', 'R', 'U'], false], 4)
test([['R', 'B', 'R', 'Y', 'B', 'R'], true ], 4)
test([['R', 'B', 'W', 'B', 'R', 'B'], false], 4)
test([['R', 'B', 'W', 'W', 'U', 'U'], true ], 3)
test([['R', 'B', 'Y', 'R', 'Y', 'W'], false], 4)
test([['R', 'U', 'B', 'B', 'B', 'W'], true ], 3)
test([['R', 'U', 'B', 'B', 'R', 'W'], false], 4)
test([['R', 'U', 'U', 'U', 'R', 'Y'], false], 4)
test([['R', 'U', 'U', 'Y', 'U', 'W'], false], 4)
test([['R', 'U', 'R', 'W', 'W', 'R'], false], 4)
test([['R', 'U', 'R', 'W', 'W', 'W'], false], 4)
test([['R', 'U', 'R', 'Y', 'R', 'U'], false], 4)
test([['R', 'U', 'W', 'U', 'Y', 'W'], false], 4)
test([['R', 'U', 'W', 'W', 'Y', 'Y'], true ], 4)
test([['R', 'U', 'W', 'Y', 'W', 'Y'], false], 4)
test([['R', 'R', 'B', 'W', 'U', 'W'], false], 4)
test([['R', 'R', 'B', 'W', 'W', 'U'], true ], 3)
test([['R', 'R', 'U', 'B', 'B', 'U'], false], 4)
test([['R', 'R', 'U', 'W', 'R', 'B'], true ], 3)
test([['R', 'R', 'U', 'Y', 'Y', 'R'], false], 4)
test([['R', 'R', 'W', 'U', 'W', 'W'], true ], 3)
test([['R', 'R', 'W', 'W', 'B', 'W'], false], 4)
test([['R', 'R', 'Y', 'U', 'B', 'W'], false], 4)
test([['R', 'R', 'Y', 'Y', 'U', 'Y'], true ], 4)
test([['R', 'W', 'B', 'Y', 'R', 'B'], true ], 4)
test([['R', 'W', 'U', 'B', 'U', 'R'], true ], 3)
test([['R', 'W', 'U', 'Y', 'U', 'Y'], false], 4)
test([['R', 'W', 'W', 'U', 'B', 'Y'], true ], 4)
test([['R', 'W', 'Y', 'B', 'W', 'Y'], false], 4)
test([['R', 'W', 'Y', 'U', 'B', 'Y'], false], 4)
test([['R', 'W', 'Y', 'W', 'U', 'U'], false], 4)
test([['R', 'Y', 'B', 'W', 'W', 'R'], false], 4)
test([['R', 'Y', 'U', 'R', 'B', 'W'], false], 4)
test([['R', 'Y', 'U', 'Y', 'R', 'U'], false], 4)
test([['R', 'Y', 'R', 'R', 'U', 'R'], true ], 4)
test([['R', 'Y', 'Y', 'B', 'U', 'R'], false], 4)
test([['R', 'Y', 'Y', 'B', 'R', 'W'], false], 4)
test([['R', 'Y', 'Y', 'B', 'Y', 'R'], true ], 4)
test([['R', 'Y', 'Y', 'Y', 'Y', 'R'], false], 4)
test([['W', 'B', 'B', 'B', 'R', 'U'], true ], 3)
test([['W', 'B', 'B', 'R', 'Y', 'Y'], false], 4)
test([['W', 'B', 'B', 'Y', 'Y', 'R'], false], 4)
test([['W', 'B', 'R', 'R', 'U', 'U'], true ], 3)
test([['W', 'B', 'R', 'W', 'R', 'Y'], false], 4)
test([['W', 'B', 'Y', 'U', 'Y', 'Y'], true ], 6)
test([['W', 'B', 'Y', 'R', 'R', 'U'], false], 4)
test([['W', 'U', 'U', 'B', 'R', 'W'], true ], 3)
test([['W', 'U', 'U', 'R', 'W', 'R'], false], 4)
test([['W', 'U', 'R', 'U', 'B', 'W'], true ], 3)
test([['W', 'U', 'R', 'U', 'U', 'Y'], true ], 4)
test([['W', 'U', 'R', 'U', 'R', 'W'], true ], 3)
test([['W', 'U', 'R', 'U', 'R', 'Y'], false], 4)
test([['W', 'U', 'R', 'R', 'U', 'R'], false], 4)
test([['W', 'U', 'W', 'U', 'U', 'Y'], true ], 4)
test([['W', 'U', 'W', 'Y', 'B', 'R'], true ], 4)
test([['W', 'U', 'Y', 'R', 'B', 'W'], true ], 4)
test([['W', 'R', 'B', 'B', 'U', 'W'], false], 4)
test([['W', 'R', 'B', 'B', 'U', 'Y'], true ], 4)
test([['W', 'R', 'B', 'Y', 'W', 'R'], false], 4)
test([['W', 'R', 'U', 'B', 'W', 'B'], true ], 3)
test([['W', 'R', 'U', 'Y', 'Y', 'Y'], true ], 4)
test([['W', 'R', 'R', 'B', 'W', 'Y'], false], 4)
test([['W', 'R', 'R', 'R', 'U', 'B'], false], 4)
test([['W', 'R', 'R', 'W', 'W', 'Y'], true ], 4)
test([['W', 'R', 'W', 'B', 'B', 'W'], true ], 3)
test([['W', 'R', 'Y', 'U', 'B', 'B'], true ], 4)
test([['W', 'R', 'Y', 'R', 'R', 'R'], true ], 4)
test([['W', 'W', 'B', 'R', 'R', 'Y'], true ], 4)
test([['W', 'W', 'B', 'Y', 'U', 'U'], true ], 4)
test([['W', 'W', 'U', 'W', 'R', 'U'], true ], 3)
test([['W', 'W', 'U', 'W', 'Y', 'B'], true ], 4)
test([['W', 'W', 'U', 'Y', 'Y', 'B'], true ], 6)
test([['W', 'W', 'R', 'R', 'R', 'W'], true ], 3)
test([['W', 'W', 'W', 'U', 'W', 'Y'], false], 4)
test([['W', 'Y', 'R', 'B', 'W', 'U'], false], 4)
test([['W', 'Y', 'R', 'W', 'U', 'W'], true ], 4)
test([['W', 'Y', 'R', 'Y', 'R', 'B'], true ], 4)
test([['W', 'Y', 'W', 'U', 'U', 'B'], true ], 4)
test([['W', 'Y', 'Y', 'Y', 'R', 'B'], false], 4)
test([['Y', 'B', 'B', 'R', 'W', 'R'], false], 4)
test([['Y', 'B', 'R', 'R', 'U', 'B'], true ], 4)
test([['Y', 'B', 'R', 'Y', 'W', 'R'], false], 4)
test([['Y', 'B', 'W', 'Y', 'B', 'R'], true ], 4)
test([['Y', 'B', 'Y', 'W', 'W', 'Y'], true ], 6)
test([['Y', 'U', 'B', 'U', 'B', 'U'], false], 6)
test([['Y', 'U', 'B', 'U', 'U', 'U'], false], 6)
test([['Y', 'U', 'B', 'U', 'Y', 'Y'], false], 6)
test([['Y', 'U', 'B', 'W', 'R', 'Y'], true ], 4)
test([['Y', 'U', 'U', 'B', 'R', 'W'], false], 4)
test([['Y', 'U', 'R', 'B', 'W', 'U'], false], 4)
test([['Y', 'U', 'Y', 'R', 'Y', 'Y'], true ], 4)
test([['Y', 'R', 'B', 'B', 'U', 'R'], false], 4)
test([['Y', 'R', 'B', 'B', 'U', 'W'], true ], 4)
test([['Y', 'R', 'B', 'B', 'R', 'B'], false], 4)
test([['Y', 'R', 'B', 'R', 'B', 'W'], false], 4)
test([['Y', 'R', 'U', 'U', 'U', 'R'], false], 4)
test([['Y', 'R', 'R', 'U', 'B', 'W'], true ], 4)
test([['Y', 'R', 'R', 'W', 'B', 'W'], true ], 4)
test([['Y', 'R', 'R', 'W', 'U', 'W'], false], 4)
test([['Y', 'R', 'W', 'B', 'Y', 'B'], true ], 4)
test([['Y', 'R', 'W', 'Y', 'Y', 'R'], false], 4)
test([['Y', 'R', 'Y', 'B', 'Y', 'B'], false], 4)
test([['Y', 'W', 'B', 'R', 'W', 'W'], false], 4)
test([['Y', 'W', 'U', 'R', 'W', 'W'], false], 4)
test([['Y', 'W', 'R', 'B', 'Y', 'U'], false], 4)
test([['Y', 'W', 'R', 'U', 'U', 'Y'], false], 4)
test([['Y', 'W', 'R', 'R', 'W', 'B'], true ], 4)
test([['Y', 'W', 'W', 'U', 'Y', 'W'], true ], 6)
test([['Y', 'W', 'Y', 'U', 'U', 'U'], true ], 6)
test([['Y', 'W', 'Y', 'R', 'B', 'B'], false], 4)
test([['Y', 'Y', 'B', 'B', 'B', 'B'], true ], 6)
test([['Y', 'Y', 'B', 'B', 'W', 'R'], true ], 4)
test([['Y', 'Y', 'B', 'R', 'W', 'Y'], false], 4)
test([['Y', 'Y', 'B', 'Y', 'Y', 'B'], false], 6)
test([['Y', 'Y', 'R', 'B', 'Y', 'W'], false], 4)
test([['Y', 'Y', 'R', 'Y', 'U', 'W'], true ], 4)
console.log('Passed: ' + passed + '/379')
```
### All possible inputs
This should take one or two seconds to complete, mostly because *eval()* is slow.
```
const color = ['B', 'U', 'R', 'W', 'Y'];
let all = n => [...Array(5 ** n).keys()].map(c => [...Array(n).keys()].map(i => color[(c / 5 ** i | 0) % 5]))
let wire_to_cut = (wires, serial_odd) => {
let num_wires = wires.length,
last_wire = wires[num_wires - 1],
wires_count = c => wires.reduce((s, x) => s += x == c, s = 0);
if(num_wires == 3) {
if(wires_count('R') == 0)
return 2;
else if(last_wire == 'W')
return num_wires;
else if(wires_count('U') > 1)
// Last blue wire
return wires.lastIndexOf('U') + 1;
else
return num_wires;
}
else if(num_wires == 4) {
if(wires_count('R') > 1 && serial_odd)
// Last red wire
return wires.lastIndexOf('R') + 1;
else if(last_wire == 'Y' && wires_count('R') == 0)
return 1;
else if(wires_count('U') == 1)
return 1;
else if(wires_count('Y') > 1)
return num_wires;
else
return 2;
}
else if(num_wires == 5) {
if(last_wire == 'B' && serial_odd)
return 4;
else if(wires_count('R') == 1 && wires_count('Y') > 1)
return 1;
else if(wires_count('B') == 0)
return 2;
else
return 1;
}
else if(num_wires == 6) {
if(wires_count('Y') == 0 && serial_odd)
return 3;
else if(wires_count('Y') == 1 && wires_count('W') > 1)
return 4;
else if(wires_count('R') == 0)
return num_wires;
else
return 4;
}
}
let f = w=>o=>(([,,C,D,E,F]=w).map(c=>eval(c+`=${++i}+`+c),i=B=U=R=W=Y=''),F?!Y&o?3:7/Y&7&&W>7||R?4:6:E?E<'C'&o?4:7/R&7&&Y>7||B?1:2:D?R>7&o?+R[0]:D>'X'&!R|7/U&7?1:Y>7?4:2:!R?2:U<7?3:+U[0])
for(let N = 3; N <= 6; N++) {
let total = 0, passed = 0;
all(N).forEach(l => {
passed += f(l)(false) === wire_to_cut(l, false);
passed += f(l)(true) === wire_to_cut(l, true);
total += 2;
})
console.log(N + ' wires: ' + passed + ' / ' + total);
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~300~~ 214 bytes
-12 bytes thanks to a [comment made by nore](https://codegolf.stackexchange.com/questions/125665/which-wire-to-cut?answertab=active#comment310352_125665) (for length 3 the last wire white test is redundant!)
```
def f(w,o):e=w[-1];r,u,y,x=map(w.count,'RUYW');g=r>0;return[2+(u<2or'R'<e)*g,[1+(e<'Y'or g)*(1+2*(y>1))*(u!=1),`w`.rfind('R')/5+1][(r>1)*o],[2-(y>r==1or'B'in w),4][(e<'C')*o],3*o*(y<1)or[6-2*g,4][x>y==1]][len(w)-3]
```
**[Try it online!](https://tio.run/##lVvbTuNIEH2Gr8jOS2wws@vgzQNDRlqvNB9Q2lapFEUaNDizSGyCTBDw9ayZCxN3n6rqvCAkH1eX@1J16lTn7nn373Yze3m57taTdfFYbcuLbvG4PKtXH/rqoXqunhb/Xd0Vj@@/bB82u2pKQXhafvi66D/@8aHvdg/9Zjk7LR4uZ9t@StPLrjz5Wi3r06K7nMp020@@lidFfTo7KZ4/1uXw/8Nvi7qsPj9@ft@vbzbXxfBS@fufp/VqWfQD4mS7qpazswHdLxb1YLOd3mwmj2XVDIDB5t/Tb5Dzk@1g8bIut/1yfjYbxhyeP318Ht5ZrZa33aZ4LM/OVy@7/vni@Gg9@FHsuvtdNeme7rovu@66nAxmi6JYDgNUk59/VtXk09XtfVdWk1lZHY8fy@vjf/qH5Cl9/7P38vn@Y379E8DLYTyy@lSQX@G71Z8jo5fD28DwZYpfPt9/KurI9OZYQN9M2O/R45BM9@gx2caTCf35lN@GZuQ4m0vJ45GRadbWis115rf5ZPBUxhOiPoWfJPZ0ydvIrfq2aEO3e@usfNkvCGmfF0HUQxT2cHuu1gmGkslIMRxvbQUiJkRsbwguXA0iQwQ5TyBizh6Nz@MPSJPEmGTz1glE7DinbKcaY0gNLa29UGHvnMZxogbhL5qcGoRAZf7CeL1bO5I63iiBLw2qYkb8aMX1ocR2h/c2qolheyzBCVDBqAshfkISe1vQeOuQmnxw4qwTCKsfReP1JHCuaM/ZPAjagGSsZmNgkBke5wL02VEigp/NeP@NhnICwb6zsZ0mybZBjaMRRlSMQoZSTNAWgjMSCINQCjFODOTx9Dh2RMtE@wdTOVYyjqRwpAij84gwztLQDuE0jfiIcmhknBjhiZDxwQq2O2lSawwMcocxKa0TDJlfxTBazDBEXXG2N46AmI2cEdPfNt5bJqmKyIzDvnDVoxCjYFI1FGF1MiYZrI3HHrY2MIxTvsqryAzNES5nYM5gYnwI8@PckQVy9ZQCZqyygEyM9qGMKbfDGSmXOLJdUiBgHl31LeKirjFwOSTYYdRhfKaDT5mDz5slU2dwCtWIQEsG03ZyfohDg0lgLcaSMubWX76Ictg4Gi8zmkQehzvKxOmTzX51GeKM5JL3nKJNMssyiROB9iUCKhB9ZIE1d4Nx@lmm8WFyOHWbsWEJZFLRiHyr8wkLp9dVwU9nEY5sBTA60c7IZG4wistry0PSRacaF2atOdUU7zGzcAoZ1ROPN6z6JZL5xaJraArO3jQRSw92GShmAkc4tCQMdj9l1HI6K2ewXR0g2YyAx3xFZfIcS4RWzUlx5lPmhmP@7OLYLkBzaB8Csm1RfK2bM@Irx7HadFEATUOTI76HEusSVhGVIwYnp9MsoFtQb6oji31UBByVkFHes13pInVRbUuIHQ8lPvFaTklkAV9iUMSutN5uzRpJAJ1js3534o1k8jkBNI3sL2EzqUjusZe40DPrTKQVBCS3IKDaZUwMQmbZGDKE3VhBRfxoMuYeOvimGapz56B3PIpLpH5i8GjnPEEHXVdqMFgJzQ3uteHc1eCOWpvphxhMwELrWl8LCsfgt97IlwiREmWvOWJtbDstgK1CNHsld2OoU7ldxGzTDDQCHW1JyApaUUPnWI@yWzqJNJNpmuIpt0wbTaEUzD4bQBHBvrqBdE74hViv0hYmaPFJVNvInVZzO4Bo6ZgOoH/0w7QFzjYtOI3OTTXNWpoAV15ZdCR@6CtDgIYehhbNEVSeO6Y5Jg4@WmAh3GjddSspBeiCeQxY05dtUY/MZBCA8C@@XMhxAeCC2U4zKlpMicxSnhtD8gtqBkNoybBNMUf30Ur/tTGVRSuICAjxoikiyeUp7RsjtNgMGx1b@wZDCzZ3a5tmMNnRxibgsNjfGMBxZM108NqTDdYsg91XJhDeQ4ZtAppQNjrHds6yB0@DVNBsBvik@DLLMIpFX38C8b5S1p20PpZuOoqxrW/aKX8IBBw2dyuByM0ZN33CQWiBPKdJhOfW74IQrHaVJEZa1aHvECRo2k5b3SUFHexiiaBiae4n0TovOtrqgijonLMuziUJRX136BlBQum7LT4fIdBX048Ym7KSequ7zbhMxyCf5jhCoCeiOkKARemmRS@/5xhM9hZhUNOQFqFQm4TtCUE9eNt0kljTHYLAdIhlZ6qDdmR0NB/iNfuEC/WFWk0E4Lj3YaZSFS2@aclYcoLlurIwKJXaflBGeGegyQWVrjLUWlxH2CegrCXp1rQsuuTdgB@RuGUEqgTV6hh3Bt3fsgS/KmWQ/RPwHF@gJf@MY1@09RZIP300vjmtgG3qhBmFC0ZXU@Bt1RYmGRNN@q9RGqNHmWM6I@gJiDNqIS1Qn9eEGYQOB6F1pU9AwFPPopgJF05fyN2qonU5xLw83WbwPTFTTIZpyrhZ3WYwYAEcIcdtg4MoYD4YHDK8jsJwa5rmDN4pQMJxrrEj9sk2OhyEJqMnoqCDXQsKvLDoXsRHGgeKI4lqHOU7BUy2Kp3cr0fpf26A2YyU4t1jVtDKBbU57ui3tkKE@//JoSkvjo@Oru7vu35XrIuT119Ql4vF20@oj7unL93dbgDd9Teb3eTdp6ub2@56sr7p73eT9ba/eFdNXl86Puqvbu67427w4hf6r9vbb0/vJ3evY1y/e/kf "Python 2 – Try It Online")** (Tries to assert all the tests and prints a message upon completion or error.)
There may be some nice way to use bit-twiddling and get a shorter solution.
Definitely harder to understand than the manual!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~264~~ ~~237~~ 233 bytes
```
s,i,r,u,y,b,w,z,x,t,q,p;f(S,o)char*S;{for(;s=S[i++];b+=t=s==66,r+=s==82&&(p=i),u+=s==85&&(q=i),y+=x=s==89,w+=z=s==87);S=i==4?r?z?3:u>1?q:3:2:i==5?r*o>1?p:x*!r||u==1?1:y<2?2:4:i==6?t*o?4:r==1&y>1||b?1:2:i==7?!y*o?3:y==1&w>1||r?4:6:0;}
```
[Try it online!](https://tio.run/##fZrbbiPHEYbv9RTjBbyQVpPA0tJ0QmVMoC/yALUuFApJYEgU5RBYi1oeImm9@@ybrqEETY/70x05/1QfquvwV/Us/vLbYvHt27ZdtZt23z62V@19@7l9aHftp/bu4ub4Q7s@Wfz3cvPuw8UfN@vN8cW2@/Cv1enpfy6uTrtdt@266bTdnMaPv52/fXt8161O2v3h/4/5/6f4/3jaPfRP/t7en3af@58/nVx86FZdN5lv5p/n72f7n8/mn2bvZ@ez/PDH@ebdOj@4mz28@27z5cu@687mZ7PHf5zPz2eTeGM6371bzyezTUbePv589uXLVX6hF/5p/t1jxt7PHgO7D2yT35zOfrj4@u1/69V1s1lul7tff/u4vrr8uD0@af44apptXsym23eP3VV3n9f4kHf3qbvrfrg4@np0tLrdNbf733/dLbe7bdM1@enzo@1@sVgur5fXh8f9BPHa8WJ9u901vfKa@1Wes21CZn19ffixfLhbLnbL68P88eRysdtffszj3Bw/CeSXTy4CvWmOn9FuJNmUyzg9DYGvR83LguNR/j/admzs98vV7fHJ8/z/zM@XsY22@WWzj19nMVa/mzcppTft4ZW2OT8ZAv7mIDB6LvIi8H4ImFYFtJ@h9tzrM6tKXUAVBORFYLgidZhBktb3IMM1FYAmAISGGqhj@NyS1RdloHATGMjqejU4B3OrPndN8BwW6rRld7ClA1CxpaQKgBgBYJaaBnZ5ViBihNiL4YwAB8BpFhmosQQkVc8v7wT2KP4y@6TwsIEpFHMYaT4Vh3VWIgLulEhhmswJGWzmrHRmA2@2RP6PsxSOW4YAh@hz0HJ1MKdpTBExGs2HgXSEgGqcAp3TAUiiQ5NhmC1ECj0XiCSp2pmIIVA/TCl0OfkzUhExratFDgGstmBzCEmCZp6nt/rKLCn4ckbg/K1IWiWiddUYhh8zWrShb5o7yng9ZmXDrJuZJ1J0Rij2q4ACXJJgvqibU94lWI0LLk2GoW7yZ6QyjSl4gJvAysxAZwaZwY0Oxj3BuhxmTwkjcEY4mw0Z2CgFqRBCAS2yEOW6zGESQZooRwk4fEZ4OPSRZ6g2nvF4LpDZHbXnavUDzAgml3yCmCqNqEpAr6RelBpSuMkI4YSNWT6nEqVkrpTNMZkpEsmczjEFC0baHE/peLWM9mXmTqSkHLoJEa0nr4yIIELbNWJ8mVY4UQGmXI7UyouqpIQcLSz7O@jBMRRIwiSSuRodYdCYuhtKMuDkgRArUgo6GRGqAbP14XgCx5Epk8JMMixZSmRY2Z2NuBFxM1PkOpnswxocV@eJFJ7tARSe87YS3XIIiYHU1ZCDnghyJ8rQGRKEJOGAlL/tiVvXymyBY8p8FBh8RoyIGiehgKgHkBkuVO@GPphjB9UeeThautNM2YggDjiXv56wmorESuM5mYQrdnsi7BGfe6rcas0Md2xnCMWIIKhIaosypeSICZiJY5XghnbumGsygsvL1kdrQMPMFkYkNgUn1TrxDgg6cCFkTmKCrZEwmcEip2NMScwSLSSfv8BCtExixWyqQ8ZfimnhkiVWRJMSsoQjehEjxxhVPtF7UmoyCZVFwf1JW5EvjCZzS3SkVpK9cfOK@1qviJkr6cTKonOEFRXZtOT61PoIKs1ieQcKYkVrpITMkJ4no9Z1VAKwjp7vw7aDuw8dblpilupmkiF3FNM0iKpj6BUxt0SYDFuv5Up82MAu95bpEu07H6i/htUtL9xUUcyKy5ER5gqrFFdwfY0B6VDtqWKsliECjpohcypespsKQUbu3WOwDi9rxsmoGFFnzFEuM11FrOh2TcZ1DBilu8AOJC4cYCUZc8pw0gdEGDIfXCIxM62nqpwdUCfRyh2wttE1FAbmzNaV@mmiHJglCmp5BWM5VpiW9csIM3DHIAuGjeRkuIVe03WNiRY@V4pl/0kkhsldonUN5xO9CVyk6yuYK@gk3BiKrWBC9cAQ9SP5YzDXRJOV/YYRpokxdOOoMNG@vKzCRxjblws1laOmVpyOeU1gjkOiMdgzMa7d9Ca8FrEgpDikiNKQYoJD@pBgTUtISJXR/ZK6NUfxTSdn0aEjsQg3VU0GJCyFW9On465ixrMZhe3oA6Q6YbPIEnRnFJiTGFYYFrqqB5qeFdOIgs4YNaEmxKhmiU47nVqEpwRSLnBVEQUXJNvgH8CR@r4JfdWgxGgyNPyQYFpepQnZVT8iaCqMQBEb3lCOIArJfRwk6KnBWru7irQuhIlgA0WcxdD4PRXXWNPyYxAlihqYvoJRJRBpD2zEVTEg96lBCXOi9NEMo1jhz65dF8PTyfyPspT3tIuwIkaOIHsFUpwtOxXYghhmlGgd4LVp5BSaLi6vEZNE7DxjSuwj2llGF7VPrLFil1FvKUFCdVrcvaZ6yAgIPnPoWYLjiEXTvhxSErHevrc2PvC7zep2d3P85vvrZr3fNeub5vvDV4bb5u5yu11e//Xft1mk@BCwffkAML71@/Z/ "C (gcc) – Try It Online")
Version without the globals and non-portable return trick, 264 bytes:
```
f(S,o)char*S;{int s,i,r,u,y,b,w,z,x,t,q,p=q=t=x=z=w=b=y=u=r=i=0;for(;s=S[i++];b+=t=s==66,r+=s==82&&(p=i),u+=s==85&&(q=i),y+=x=s==89,w+=z=s==87);return i==4?r?z?3:u>1?q:3:2:i==5?r*o>1?p:x*!r||u==1?1:y<2?2:4:i==6?t*o?4:r==1&y>1||b?1:2:i==7?!y*o?3:y==1&w>1||r?4:6:0;}
```
Variable reference (unless I made a mistake):
* r: # of red wires
* u: # of blue wires
* y: # of yellow wires
* b: # of black wires
* w: # of white wires
* z: last wire is white (0 or 1)
* x: last wire is yellow (0 or 1)
* t: last wire is black (0 or 1)
* q: index of last blue wire (1-indexed)
* p: index of last red wire (1-indexed)
[Answer]
# JavaScript (ES6), ~~237~~ 222 bytes
```
(a,o,[b,u,r,w,y]=[..."BURWY"].map(c=>a.filter(x=>x==c).length),q="lastIndexOf")=>[!r?2:a[2]=="W"|u<2?3:a[q]("U")+1,r>1&o?a[q]("R")+1:a[3]>"X"&!r|u==1?1:y>1?4:2,a[4]<"C"&o?4:r==1&y>1|b?1:2,!y&o?3:y==1&w>1|r?4:6][a.length-3]
```
## Test Snippet
```
f=
(a,o,[b,u,r,w,y]=[..."BURWY"].map(c=>a.filter(x=>x==c).length),q="lastIndexOf")=>[!r?2:a[2]=="W"|u<2?3:a[q]("U")+1,r>1&o?a[q]("R")+1:a[3]>"X"&!r|u==1?1:y>1?4:2,a[4]<"C"&o?4:r==1&y>1|b?1:2,!y&o?3:y==1&w>1|r?4:6][a.length-3]
```
```
<div oninput="O.value=I.value.length>2?f([...I.value],C.checked):''">Wires: <input id="I"> Odd serial? <input type="checkbox" id="C"></div>
Result: <input id="O" disabled size="2">
```
## Tests
Tests from challenge are emulated [here](https://codepen.io/justinm53/pen/bREzpX).
[Answer]
# [Haskell](https://www.haskell.org/), ~~315 301 295 284~~ 277 bytes
Thanks to nore for saving 7 bytes.
```
c o s|l<4=z|l<5=x|l<6=q|l<7=p where b:u:r:w:y:_="BURWY";t=last s;l=length s;m=n r;k=n y;f c=[i|(x,i)<-zip s[1..],x==c];n=length.f;z|m<1=2|n u>1,t/=u=2|1>0=3;x|o,m>1=last(f r)|t==y,m<1=1|n u==1=1|k>1=4|1>0=2;q|o,t==b=4|m==1,k>1=1|n b<1=2|1>0=1;p|o,k<1=3|k==1,n w>1=4|m<1=6|1>0=4
```
[Try it online!](https://tio.run/##lVpdT1xHDH3vr7iKKiWRtmmXvd1KbG4e5qE/wKplWQhVgEiDWAjhQyGI/07vQoEd@9hz@7IimXM9nrHHH2fmy8HV6fF6/fBw1H3tru7XH/vhbvz9fbgdf5fDt/H3j@Gi@/7l@PK4O9y92b3c/b77Y/fv4U1hEn2zuh7WB1fX3dVqPayPz/@5/jL@eTacd5er0/H3x@pzdzTsndy/u52dvP/4y93JRXe1N//wYX92OwxH@6vz/7768Hl1d3/2cT7s3J93N5/ms@tfh5vxH/NPvw2L1e3919nZp/njVO8@d5fv76@H4cdsg59v8MOw@eN0RPSPX@ysvo1fjJjD8T/OxtHZZmwDPXycYoOZry5GzOn478X96QZy3n1/FLCRunyE9A933dDtHXV/Hqyvjru9t@XtrHv@2e@6YdiZHXV/Xd4cd9WgjoNPY9WH9PTz@OHCfiibH3758HmMqxlroVxNiAb5WSiS@qLOkzbVhxpIpZcp@XUdflCDQd7aOjdIRuyzsmS2Z/tDeZlS/CoFGKQao1poNSb1nvsxxmP6rEw9ptXy6019HRO/44q2phrUwB/rwchXGa/lFUB4QQYQuDxvoR4VnEMEbS1@bifhly1/ctYEoC8AP4caLSoRZMyDAfQKWECAJntF1bkahh5GgC2XdMsQZO0K4ZxlHiMoiBkFGcQjZOucz2HA2toMB2DgWT5ySbBW9lZHerpghUOg1ifAi9BsM8iGS4eQLRdMEJLNojbxuB3VKhJGAH49RjtwjsjwVLsG@Q2l@rwX58ME7Tq3IqgKGfU5oS0VpwC8cxG0GRahOHVQbVTBC60TRYjQIOxT8zhvq/gqo4fJkYMIbBAaIFyhMbdZj8127EARkXOJD38IkcYuqbeDA0XVGHZuE2Yx7udycckMaxBRPucqbyIZZBOny@xkznMPRZDxco9Il0I25fRQja0qw00itvBzWy6mGu0hQGqbBABfAWh91jhQQk3k6iGA8H4X6znYz4sNoq2qx3YGSVnCdYGEGo8kybgKJanYpNasBAswkSNYgNQLkKTyITSlh8E44uecVm3JtGWqqYMdSidZU32GBH6mdUmbVmnULJKMSWkabEppiMttUx8yXihCpSvQ7ECxLU2gCUxhyriW53r3s4KKrU1xIUv1ItJqFmZiD5PsqDA469GmmQLBh0ZT4TZRVJkTbK3UASvYWoFBNBGmiTXFO21UHrdbH53U3qgN3tg11Ff24ZxqOtQ@FhaFd6qPSFq9lmZhSCDb@fBItmKCaQyhJJiSo8TjGxFXh@1AGGUWICsIlilkG1IYglwDBNs5stkQ1j0EjnnJWhFG/YhvejQJoWQBU1CZY5hDFziGqYc5UH873MEwhVC@IhHg15R1Towq4ABGTRihXO2bsaxmFkuKwdgolveCZhJQ6wV7Jp7NQ02cNDMYgkX8r9TmZNyeSjM2io2xuCYU62PwBAtwNMatTfGuAZqsmOb0MMhY@TklKc8U1F3RnGx/Wi2xZL0iYNQiYZrxK2rPL84BrpHGfqug8uKgbzfhgzEN0WRVDIqmNtgxsSHhMoNeO0ivOu0Qq22cEtYa9dfsCQkEC265nDBT1/XxVQe6CvBixdOhI3YJxcJWeRFDxXBUWAMTX8iTQAX0Rdu@u4SkBCPGBYtlGFZ7KBZmmj6@6ymTNFCYp1vYiPEqoBHj1qUQRTRZAG1aF9VPEiyMQD7SACtx09o3eBtN7CD2jCfqiiXrEpuhjNzGOiZwGXM16CoioGLKNLFktxj6ggakXQSVKF@jVwSAcF002Z56XRlLE5mBo1ijfr8YEKAFB1wGFtCmWPb3HmBlWDbeBbYdFI75mGOqDBEQTfbhQR@zTdq0A4FiEATnEKtYBdTkpiqITe6JCiYqMHZygscSaiugsuDAZBIwqinNRSCQB1BJ0gODvK84KDEovSgI4yFWE/oIc60Yy57vm4DVplyy9XEL624F@5hAs1XFssG1BTtG1q2SxGewmlW46DAGCYogu49PGaLXGL@4IqCoBi5GIOZvdcTR87BWYUOgrYzuOQkEZ27KJc@gTMW25UIDB48keNr2Og5jPxerqN3xxGHxLx3CxxIFJanojR@KuVisiZOlJTZtNgiED0n8kUDklWzD1PNgrdcldQ3SQ8q1RPx@8CSlmJupRYPv5ewpDCL4AgeT@J4kwXLWmBDk8JKzo8F9QojFDH@CbQdoDa/m@/gBT1oyESzuEhdTmLIbKqSHRzIiJnqVW8LnVgF2ogrkGf9IBfLVTShWUUO7hGLxDV4fP4yyNzqLxiWAZJuAboQFP2Rmu1Uw2CBoU1lqpl8B9A43FybTtZWoDMruOkrdUFfKospNAmURVltitWlcgu0vNC5KfJkG1AzOAngrDspGgTxFbDHU80myMEVPSvsYSslDMgGVMCW6oqDACZTRo6JFA6rJsgQ29bYnEcjvx@cWa4G9QGEhiL1AYWm1n0OzkgbnfHgbJTCB1S7rb65KM9JqlG6yCzFqnnEFD6VK8voR8Xw@MylkpTFvh7D8P7ARwaYgcAUNsmbJMcS2nVEjNl@TR7IlrL/8U1eQGtpiU28kwDdLhnWtb6IurBESqCT5EUGj/KjwjUp8dii@he@zR8ngssbfQxb4/rVv3Ka2sQSZ/wTLWbel8GFb/CBZApYAnEnHnb5kqGX8UpoyXta9ma6T9LIBleTdusavVxOse@S0jO@aS8aq4Hvp1wOx/9PZwcn5cHF5cn7d/dwdrNfdu2HYfP2@u3v4Fw "Haskell – Try It Online")
A totally uncreative solution in Haskell.
Ungolfed
```
c o s
| l<4=z -- different function for each length; no funny business
| l<5=x
| l<6=q
| l<7=p
where
b:u:r:w:y:_="BURWY" -- saving space on the quotes
t=last s -- last is often used
l=length s
m=n r
k=n y -- caching the number of reds and yellows
f c=[i|(x,i)<-zip s[1..],x==c] -- find 1-indexed indices of the character c in the string s
n=length.f
z
| m<1=2
| n u>1,t/=u=2
| 1>0=3
x
| o, m>1=last(f r)
| t==y,m<1=1
| n u==1=1
| k>1=4
| 1>0=2
q
| o, t==b=4
| m==1,k>1=1
| n b<1=2
| 1>0=1
p
| o, k<1=3
| k==1,n w>1=4
| m<1=6
| 1>0=4
```
[Answer]
# [Python 2](https://docs.python.org/2/), 193 bytes
```
def f(s,o):b,u,w,r,y=map(s.count,'BUWRY');l=s[-1];return+[2+(r>0<s!='UUR'),[r<1<l>'X'or u==1or y/2*2+2,1+s.rfind('R')][o*r>1],[r==1<y or-~0**b,4][l<'C'*o],[4+2*(1>r+(y==1<w)),3][y<o]][len(s)-3]
```
[Try it online!](https://tio.run/##pVZLj6JAED7Lr6hxMwG0dQUdDzNisu7jtCezrmsIMSiNskHaNE1cL/vXZ6sbfDA@J0uMYNfrq6@KKtdbsWSJ/foa0BBCIyXMfJ6RjGwIJ1tn5a@NtDlnWSKIPhiNhxPdfImd1G1Y3gunIuNJ3bXrBu@3eumDo49GQ90kLu9Zvbiv/9IZh8xxLLxtP9o1u24Tq542eRglgaGjqueyGu9bHpqgWm8LjDf@tmq1Gel4btzTP@s1hsJO3a4ZVp/Xja1U25gmaXvutsc81KKJkZqNtqcy2EScTgWbzjNhyOeUQEp55MdTFgTmswZ4VavVoYIOYkkBodA/wEL1Q5qAYIDmBFhCG0pKgyb8WEYp4MeHJFvNKAdL6nWbyqOK9AyfII5SIX210Rtn2WIJXZizGPOfL33uzwXlKYScrWAwGo4nyviAT3oYMBZTP4EQbTZLiqC4Qhb76DmIFpHYYc3tJCY0RYA8o7BC0/y3pnz3@/0SJS6STkAfyC/1NNY9okwLbto7htQdU52q3MABybN6NpVI4lEyFKlj2RJ50Cg8NnSgnbsuROo4bynVAlKjddCQV95YYO8PaYyGRxEdCfyszT5w2bYUdIRB@2CV7T/Ad8nwLM7yLjjnXNebv1m0o6HJVXPk/upgHUVM6Q1w2h5ZianOdaYQNPhJcNwx53LgNHhvCsOTFE4In@gq9v3ls26UAA2tdxtOztXuSu0vVMK@VIGnUgXKDAz0q@wXrjtX0Bd8WadMXsvrGh@De1@gC0RYl4joXm7FSRHzHjbaN2p5no3xFTbu4Lf1v@3R2bFyLOd@lFL46eOE@Mo540Z1zFmy2O0DtsNSNTUtWq0ZFxDhvBc40PGFl8tpQRPKfUGnfhxPo2SdidQo5q5aEnLMuvlwHh1NaCJfvmK2yrVwqFOUgNsm0CHwRKDrHbCq7bFT2aNorjkLsrkw8mgE011TXzh7h2aZDenlUF8V7ZuPnOQbwysry2sb0TgAQ27BYsKU1q@mqTqB7B1tD5G8iXGBpYrw@YKKinNjx2sVPMliGSU0yuPujV4Opo4dqFWwk3L/8OBA7gBDVtY4IMUpTFIok0IVNbVctfoF/zWgmKYCp/CjTEgmUIVHyMO9/gM "Python 2 – Try It Online")
Thanks to nore for [pointing out](https://codegolf.stackexchange.com/questions/125665/which-wire-to-cut#comment310352_125665) that the second three-wire condition doesn't matter.
```
3 wires: 2+(r>0<s!='UUR')
4 wires: [r<1<l>'X'or u==1or y/2*2+2,1+s.rfind('R')][o*r>1]
5 wires: [r==1<y or-~0**b,4][l<'C'*o]
6 wires: [4+2*(1>r+(y==1<w)),3][y<o]
```
Many techniques are mixed together to do the condition logic:
* [Selecting from two list elements](https://codegolf.stackexchange.com/a/62/20260)
* [Arithmetic selection](https://codegolf.stackexchange.com/a/40795/20260)
* Boolean multiplication for logical-and
* Chaining inequalities for logical-and
* Using `or` to move past a false condition
[Answer]
# [Retina](https://github.com/m-ender/retina), 297 bytes
```
^[^R]{3}\d
2
^..W\d
3
^BB.\d
2
^...\d
3
^(?=(.*R){2,})(?=.{4}\d)(.)+(?<2>R).*1
$#2
^[^R]{3}Y\d
1
^(?=.{4}\d)[^U]*U[^U]*\d
1
^(?=.{4}\d)(.*Y){2,}.*\d
4
^.{4}\d
2
^.{4}B1
4
^(?=.{5}\d)(?=[^R]*R[^R]*\d)(.*Y){2,}.*\d
1
^[^B]{5}\d
2
^.{5}\d
1
^[^Y]+1
3
^(?=[^Y]*Y[^Y]*\d)(.*W){2,}.*.
4
^[^R]+.
6
^.+.
4
```
[Try it online!](https://tio.run/##ZZY9j51FDIX7@zcAaXeDrvYmgYoQyQ29Jcuywq6CBAUNBaKL8tuXcx7PNtDY73g@3hn7nDPz9x///PnXby/f3f3y@eX503M@fXn39dffL28vz9dr6@Pd5Tni@hq5buTu44e760Pef3n7/dd7Na5f3mvS/d31/s3dx5/e/pz314fb5dtvNOcsOZp4Y@IZ@@m5nh4K@98uLT0sfXXXe/2XODvQV9wcY/gPDP/4wT95SOz/5t@8h3hi7C7BF@F5enM753HjYbC7RJ8lrv6bl35zvfyo6XLvX14i4vESMbdLZOqr63apCJt5vFSVTKaao2ZG2firNC3TTc/o6EcZrdLpZoeNv6Zvl6mw0ZDxjJnA6JdRZZuN9SYqvIvKtu10pImP4@mVtFGsl5Z1L3@N9sLBP2Q1Xou1bfso4fFVie3w4YhzqMrxwbUm3453YduRcZZkPXeKdHjlJGdJvpI1tTX1ZvbatiVz7FO5ckSZcd78r2S36iR/lViNb9Lf5fFNNro9sjlXz/DtNbW1tPWask6yDuBUO5Na3r25EcYk6U/nf9plnHaBp3ut1@zZOnnMuDeCVMpuZcCJGl7dMQd1ChAUToQGRG1lGrdBDoFzsDc4VH52TeEkcJRCf6V2Hbnu1JMWuLLb8lJr1aIoc1HnLVYBPlWawuZCO/l7be71UxZTxnFZgwP6zaHlQJAyBAAWVbOAGrggkrBBJSKgjPeZQW0EM4ijbBkJQbrtjIIiWXIJtzII5oAiSGJggSZYZjgF3ANEAr6HzI4cmCTHH4SAgzCDVM6I0iYSeLn@cokDMYKo57URbjonrFY1G9cesoWzA5gD05vTKjnmimJMGPq0MSdklsXe3wBWdGGpOoXWOJ2GpNlnzaA4GrD4TaYvf/QDg2iWI9OcYbZicozUNhnCdrU9ozoM5fW5yE50gCaapG2hiQfBKlEwTntBm7aeynWvMtXivjZV0qt4VSwUtZZx1q6jXnDPrGFd12vp0waIFgetZs7RttMWKXPpEuthqXiD5pgN29Y8iLT6I9nr5UnAc0hUhz65jAHJ7vA4dcxKf0ACArRnVTPRZTe5LAz6hF0kHe95Bi7t5o6Rn1qNrYBcChfMyz5ki2VbDxxUOmgLj71KbFzXHKYrG3UYCIMtb3AwUUe4yPg5jHPFoONqLomHgmHomIrQR92QSnkxhO1zOXrYufVJC0ge/0pXr1uHlIbHcC9McwMo7b2@IXRx/nQ6g/bKhS@JZTpql87X@inukEBd0vBMPAJoViANvcrkdMf6XgWI3e8cedGsvXtWxa0oRf/i0X42vsSGN9aOpW@bEMQ1n7guPeIDbr1NbqwqlMsqg3hYf/dWK5/HPk@b@eX9oEOnv6mTBYl5LqRlx54HR8DL9rLBA4R70XByHqwIqJwTSrxj1xnubUuFeWGWJ1IX4BStO372OTPrNRwtbHTDdOy9mbndfZu5PqQd79vgkXu6V/1ydS9n23u@iXP3WiZQwjiKGLy9jIKkf181lJH@gW/W3UIenZ9t818BPfbpVdu/@bc8vPp9mung3leukFu1eCm4sO73MwSf6Ix8GXeW3OYtYdzv26FQ3b0J/IrYd0RwIQGvIX4egi7gkee@/Qs "Retina – Try It Online")
A horrid mess! Takes input with the wires listed with no delimiter followed by a 1 for odd and a zero for even. I verified that it matches all the test cases given. Currently each stage (pair of lines) pretty much just encodes one rule. The main save is in the third stage where the cases where the last blue wire is the third wire can be saved by the "else" condition.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~486 474 464~~, 421 bytes
Started off as the reference example (1953 bytes originally!) Is now about as unreadable as python could possibly be.
*-10 bytes by pre-joining array to string*
*-43 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) for helping get it all on one line.*
```
def f(w,o):n=len(w);l=w[-1];s=''.join(w);return[2if not'R'in w else n if l=='W'else s.rindex('U')+1if'UU'in s else n,s.rindex('R')+1if w.count('R')>1and o else 1if l=='Y'and not'R'in w else 1if w.count('U')==1else n if w.count('Y')>1else 2,4if l=='B'and o else 1if w.count('R')==1and w.count('Y')>1else 2if not'B'in w else 1,3if not'Y'in w and o else 4if w.count('Y')==1and w.count('W')>1else n if not'R'in w else 4][n-3]
```
[Try it online!](https://tio.run/##lVvBbhtHDD0nX7ENEEhuFQOyFzokUA8bJNcCRAcEYRiFYcuxC1UyJLlOv96VbEXZnXl8XF0Me/cthzPDIR/J8cN/m7vl4uz5@WZ2W90On0bLk4@L6Xy2GD6dfJpPny4@jC8/raeDwenfy/uXh6vZ5nG1uDi7v60Wy81ABveL6qmazdezalFtH86n04EOXv5en67uFzez78NBGpz8Nr6/HaS0g6/38NFPgLwCqqfT6@XjYvPy4Pfx1eKmWr6Cx3vRNtg9zEfufLodbDod/9To8MJ2Ml@en43qvbxmkA3S1mArZvcWCdhPv2krMTrfP7XXpy3JdaZHLlkPkl9UzudXX14sPpxfPm9W/318@@bp7n6@HW7725vNbL356/pqPRtVm6vVt9mmmlb3i4fHzfBk@3Y1Wz/Od49uh78ekLsX2yH2736Z7j/cSXvzsN2PTfVOV8vFt2r5uNkKqm6Xq@r9@rT6vP39/XpUre@Wj/Ob6u7q31l1/fLsXfW@GrY0eRX9Q6OTt7Pv17OHTfXlj69fVqvlajvSfpzPy38e5rPN7KbafV3tvl6fvnseDi@2Czuqfvy4HFVfr7bLcDKqzk7edt/a7u2fq8f8pbz@aH163nqrux@p/DR1R/VeGlApvYr8MSr4NB0GRZ9K/ul566V5o8pBpwTmKljj9ttULHH7rVDJxSruX@phWAUqK9s77Y4K5KqzO8r2VQ@LqOVL666D9xLNxegi2WHUxvvWnGGb1r7iKf1EiDOvDOGdlNSCtbQc5xApFqGAaG7DGGEMYVQTgXs1Lg9@hjjPEcYWTbpnbo@ocwdS2Ok4Rxh1YI71jCFEPMfR0M1JrbOY@4Fx6deyRRmXvg0vW@rucEMdJNfEcWmFrzTmw7M9dscxqoq2rJJBlA5kOJRhiLf6FoYXo3YgXVMRL5bgCDjOEepNR7pbKOX5kZaevRDA3IRsYO1DgBDt@ncw3yywoPkqtrb2OPyst/XMpdR52Eyeh8wg5kEcIlNAkrP6GscEBU4SQbh/0@6ycCnmhJb28cPHx7o@Eg2TQVwukLrhFkkRHG8Bo8Cnw7pRDtm@dQ9QoqqUMar2IUAVxTRynEOEzUehPziDCG@PlRqKAVcMFDGmapObEmNEGRvhzAlnJZjXJMaykO90iZTFhEu72jUUl7qh22NFwnxuBusxqsY0So/gbNpzWIPMuiBv8c4aiKrA7qxLkTnZk56MTyn5R7heJDOUh3Ou2of1IK6cA6fu2U0hy00h1bV@KT9PITPOazE35uE75Q6A8U7GOwqW24R7llEHCpPu1oLF064/k34wd401zP1SHmcitt0jr7J@qZPlLt6ZhIFswR3WYCpcQ5h7ZqV7bjgRbmL7FBAbzaHejU8NCMxNf1IYozKY0LJbdnL5sMIsSvK8l2gnft1nDNOnhq2w5EbFMpwUpznatU9vEtZvruZXsDCMmklGrRNN1YzFYwQDG6HA1CXOuFwurcA6OU5oeNcu8fDot@a1OZIVSh7N8KJoTnwjmNIUsQdvQzil8iwsKGvsPTX3w0w9A0wLrIqF2lleKyAJT4/Ka3EMWXrbgJzQG9bosTBwLFKceCtNRVFdz6v4G/V3lh9sJ1YU@XqY@TsVpyIbblhCY4CQKcutuU@xfozMANMSOgllwcJ6nm7LEzKWDKIsPoH6B8J5XbpCHCSGtV8eoB0LlGF3lmESgFMoWGGB7Lxst3Z8j3izSxFrnOTg5Bd5aoh1HG8N@1Y4JNWwPdX0U8JIYCdgt9zWgAQvhX0sCYt0qCxENxpRL6UKGyCbCKxRTlz7paKe7bi@ghUk8C6Y1W0x2KlFTmB1iLZLinJJP8GSLzURTPotBVbD8I6OPr3cgOqMaHK4euTsR/K8kHmSkS6No3ICDpELTqA3sxdMsH0FG46OE1bYIjuS4HbjnUZlCXdDBDDJo8DmaIEyaC5YcyoQgg3mq7XTlybxJsHxmdWrV9il1TVhrj6BOruFVTvNuXuEVRpCXLCxghUr@dZ@7S15sQmBLZYsOcMOwU4rs2YFPuIsDHhwc6oVxYUiZ3oZ2ChDRieUtv0bYMwNFaxgkbuGLEBZo9NL4OipIzhFLb8aVg4T7c8K8N4pliygVNMX3ENyj71OUS0Qg5X57yJhYqmT5DXXcOWwKeHNFq9R5ArOvGgTCuZZiwC/osw8BXhmjW/DpGPABllLnVd9m7DlIDAzxeFJvHzBtQpUWKQKsxYOBiea4ggsHTITMq/J4YJZzwGDe5xqC@4X4Ko3J1oCaWGosoX8QkDfyj1PSus93q3lJr5dpiBM9tBCQAvC00IAI3IFm58nTyBWqFkoyEXE8UOoK6F0KVArmwou4mVhFQgrR8jlS5y8A@KC9QiNNeROqAPTOKm65s0GFiFdsIWCLd5ngWk13g8UIakSEntvBVWy5FFOhZWQSAsNWaR6kbdhcs2vONflP0NEGQBK3bxEFjfeon/ISGEOqSCgF9gJvD0q4WnGijibbJBDhmB8UxhjKQ3CFCHCohsd6MJmAwMIA4v/jxW13wDsITh2bAbciZfyGiyNO1UTBE7HgN3KmwGn5p07o2EUrVvqaZvmdRaMXRhuYt5mNHzEgiW@TdzEHNZA1O@hMuEUGKvHYlOsceZnGyZYY/JooLzCr2wjCqkUnI4BC2lDYHCiyZvBS3zRhXNUhAD@oijcZoEMY4WWhYub5CiiT3ysMmdo0RVeDHaucE1ge7yhtRvcSy@OyP8 "Python 2 – Try It Online")
[Answer]
# R, 407 Bytes
Golfed Code
```
pryr::f(a,n,{r=a=='R';u=a=='U';l=paste(length(a));s=sum;R=s(r);Y=s(a=='Y');v=4;switch(l,'3'={v=3;if(R<1){v=2}else if(s(u)>1){v=tail(which(u),1)}else{}},'4'={if(R>1&&n){v=tail(which(r),1)}else if(a[4]=='Y'&&R<1||s(u)==1){v=1}else if(Y>1){}else{v=2}},'5'={v=1;if(a[5]=='B'&&n){v=4}else if(R==1&&Y>1){}else if((a=='B')<1){v=2}else{}},'6'={if(Y<1*1){v=3}else if(Y==1&&s(a=='W')<2){}else if(R<1){v=6}else{}});v})
```
Ungolfed
```
function(a,n){
r=a=='R'
u=a=='U'
l=paste(length(a))
s=sum
R=s(r)
Y=s(a=='Y')
v=4
switch(l,'3'={
v=3
if(R<1){
v=2
}else if(s(u)>1){
v=tail(which(u),1)
}else{}
},'4'={
if((R>1)*n){
v=tail(which(r),1)
}else if((a[4]=='Y')*(R<1)||s(u)==1){
v=1
}else if(Y>1){
}else{
v=2
}
},'5'={
v=1
if((a[5]=='B')*n){
v=4
}else if(R==1&&Y>1){
}else if((a=='B')<1){
v=2
}else{}
},{
if((Y<1)*n){
v=3
}else if((Y==1)*(s(a=='W')<2)){
}else if(R<1){
v=6
}else{}
})
v}
```
### Explanation
This assumes that the input will be an ordered list.
Saved bytes by storing the logical array of where the Red and Blue wires were.
The logical array can be summed to count the number of wires of that color and be used to find the last red and last blue wire index.
Storing the function sum as s saved bytes due to the number of times it was called.
Converting the number of wires to a character for the switch statement was done using paste, which is less bytes than as.character()
Initializing the variable v, the number of the wire to cut,to 4 before switch statement allows for the me not to have to add that statement each time the wire number is 4.
For length of 4 the second and third conditions can be combined with an or statement to reduce the numbers of ifelse since they evaluate to the same wire to cut.
[Answer]
# Excel VBA, ~~521~~ ~~446~~ 419 Bytes
Full subroutine that takes input of expected type `Array` and `Boolean (or Truthy/Falsy)` and outputs which wire you should cut to range `[A4]`.
```
Sub c(x,s)
i=UBound(x)
[A1].Resize(1,i+1)=x
[A2].Resize(1,5)=Split("B U R W Y")
[A3]="=COUNTIF(1:1,A2)"
[A3].AutoFill[A3:E3]
j=x(i)
B=[A3]
u=[B3]
R=[C3]
W=[D3]
y=[E3]
[A4]=Choose(i-1,IIf(R,IIf(j="U",i+1,IIf(U>1,InStrRev(Join(x,""),"U"),i)),2),IIf(s*(R>1),InStrRev(Join(x,""),"R"),IIf((j="Y")*(R=0)Or u=1,1,IIf(y>1,i,2))),IIf(s*(j=8),4,IIf((r=1)*(y>1),1,IIf(b,1,2))),IIf((y=0)*s,3,IIf((y=1)*(w>1),4,IIf(r,4,i))))
End Sub
```
### Example I/O
*Note:* In order to pass an array in VBA it is necessary to use either an Array or split statement
```
c Array("B","R","R"),FALSE
3
```
[Answer]
## JavaScript (ES6), ~~252~~ 244 bytes
Test cases can be viewed in [this codepen](https://codepen.io/ajxs/pen/ZyWJRz).
```
d=(a,o,[b,u,r,y,w]=[..."BURYW"].map(i=>a.filter(t=>t==i).length),q="lastIndexOf")=>[!r?2:a[2]=='W'?3:u>1?a[q]('U')+1:3,r>1&&o?a[q]('R')+1:a[3]=='Y'&&!r?1:u==1?1:y>1?4:2,a[4]=='B'&&o?4:r==1&&y>1?1:!b?2:1,!y&&o?3:y==1&&w>1?4:!r?6:4][a.length-3];
```
] |
[Question]
[
[Merge sort](https://en.wikipedia.org/wiki/Merge_sort) is a sorting algorithm which works by splitting a given list in half, recursively sorting both smaller lists, and merging them back together to one sorted list. The base case of the recursion is arriving at a singleton list, which cannot be split further but is per definition already sorted.
The execution of the algorithm on the list `[1,7,6,3,3,2,5]` can be visualized in the following way:
```
[1,7,6,3,3,2,5]
/ \ split
[1,7,6,3] [3,2,5]
/ \ / \ split
[1,7] [6,3] [3,2] [5]
/ \ / \ / \ | split
[1] [7] [6] [3] [3] [2] [5]
\ / \ / \ / | merge
[1,7] [3,6] [2,3] [5]
\ / \ / merge
[1,3,6,7] [2,3,5]
\ / merge
[1,2,3,3,5,6,7]
```
# The Task
Write a program or function which takes a list of integers in any reasonable way as input and visualizes the different partitions of this list while being sorted by a merge sort algorithm. This means you **don't** have to output a graph like above, but just the lists are fine:
```
[1,7,6,3,3,2,5]
[1,7,6,3][3,2,5]
[1,7][6,3][3,2][5]
[1][7][6][3][3][2][5]
[1,7][3,6][2,3][5]
[1,3,6,7][2,3,5]
[1,2,3,3,5,6,7]
```
Furthermore, any reasonable list notation is fine, therefore the following would also be a valid output:
```
1 7 6 3 3 2 5
1 7 6 3|3 2 5
1 7|6 3|3 2|5
1|7|6|3|3|2|5
1 7|3 6|2 3|5
1 3 6 7|2 3 5
1 2 3 3 5 6 7
```
Finally, the way to split a list in two smaller lists is up to you as long as the length of both resulting lists differs at most by one. That means instead of splitting `[3,2,4,3,7]` into `[3,2,4]` and `[3,7]`, you could also split by taking elements at even and odd indexes (`[3,4,7]` and `[2,3]`) or even randomize the split every time.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code *in any language* measured in bytes wins.
### Test cases
As noted above, the actual format and the way to split lists in half is up to you.
```
[10,2]
[10][2]
[2,10]
[4,17,1,32]
[4,17][1,32]
[4][17][1][32]
[4,17][1,32]
[1,4,17,32]
[6,5,4,3,2,1]
[6,5,4][3,2,1]
[6,5][4][3,2][1]
[6][5][4][3][2][1]
[5,6][4][2,3][1] <- Important: This step cannot be [5,6][3,4][1,2], because 3 and 4 are on different branches in the the tree
[4,5,6][1,2,3]
[1,2,3,4,5,6]
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~137~~ ~~128~~ ~~127~~ ~~125~~ ~~121~~ ~~109~~ 106 bytes
(-2)+(-4)=(-6) bytes thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi)! Changing it to collect all the steps in a list (again due to nimi) saves 12 more bytes.
Another 3 bytes due to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni), with pattern guard binding and a clever use of list comprehension to encode the guard.
```
import Data.List
g x|y<-x>>=h=x:[z|x/=y,z<-g y++[sort<$>x]]
h[a]=[[a]]
h x=foldr(\x[b,a]->[x:a,b])[[],[]]x
```
[Try it online!](https://tio.run/##Dcq/DoIwEIDxnae4gUFDW@OgA6GdHPUJzos5okIj/wIdroR3ryxffsPX8vL7dF1Kvp/GOcCNA5u7X0LWgGyx0uKcba2UuG5yslGtlW4gFgUu@17lToiyFpks7tkJYr9j954PT8FaMWmHUrKq6YhICokk9ewH2/P0eME0@yFADg3iVV2MOROlPw "Haskell – Try It Online")
Splitting the lists into the odd and the even positioned elements is a shorter code than into the two sequential halves, because we're spared having to measure the `length`, then.
Works by "printing" the lists, then recursing with the split lists (`x >>= h`) *if* there actually was any splitting done, and "printing" the sorted lists; starting with the one input list; assuming the non-empty input. And instead of actual printing, just *collecting* them in a list.
The list produced by `g[[6,5..1]]`, printed line-by-line, is:
```
[[6,5,4,3,2,1]]
[[6,4,2],[5,3,1]]
[[6,2],[4],[5,1],[3]]
[[6],[2],[4],[5],[1],[3]]
[[2,6],[4],[1,5],[3]]
[[2,4,6],[1,3,5]]
[[1,2,3,4,5,6]]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~146~~ ~~127~~ ~~111~~ 102 bytes
```
Join[u=Most[#/.a:{_,b=__Integer}:>TakeDrop[a,;;;;2]&~FixedPointList~#],Reverse@Most@u/.a:{b}:>Sort@a]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ys/My@61NY3v7gkWllfL9GqOl4nyTY@3jOvJDU9tajWyi4kMTvVpSi/IDpRxxoIjGLV6twyK1JTAoA6S3wyi0vqlGN1glLLUouKUx1A5jiUgs1JAuoNzi8qcUiMVfsfUARUrO@QFs3FVW2oY65jpmMMhEY6prVcXLH/AQ "Wolfram Language (Mathematica) – Try It Online")
Returns a `List` that contains the steps.
## Explanation
```
#/.a:{_,b=__Integer}:>TakeDrop[a,;;;;2]&
```
In an input, split all `List`s containing 2 or more integers in half. The first sublist has the odd-indexed elements (1-indexed), and the second one has the even-indexed elements.
```
u=Most[... &~FixedPointList~#]
```
Repeat that until nothing changes (i.e. all sublists are length-1). Keep all intermediate results. Store this (the `List` of all steps) in `u`.
```
Reverse@Most@u
```
Drop the last element of `u` and reverse it.
```
... /.a:{b}:>Sort@a
```
From the result above, sort all occurrences of a list of integers.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~228~~ ~~206~~ ~~168~~ ~~157~~ ~~140~~ ~~121~~ 104 bytes
Builds the list of stages from the ends inwards, using the fact that the `n`-th element from the end is the sorted version of the `n`-th element from the beginning.
*Idea from [JungHwan Min's comment](https://codegolf.stackexchange.com/questions/150675/visualize-merge-sort/150686#comment368300_150675)*
```
import StdEnv
@u#(a,b)=splitAt(length u/2)u
=if(a>[])[[u]:[x++y\\y<- @b&x<- @a++ @a++ @a]][]++[[sort u]]
```
[Try it online!](https://tio.run/##NYy9CsIwFEb3PkVAkJakiBUVxEoFHQS3jrcZbn8NJGkxibQvb2wH@eCcM32VbFB71ddONkSh0F6ooX9bktv6rj9B5lYhsjJKzSCFvdpQNrqzL@I2SeSCVLQhXoBHAI6fYKR0KorpHJOsXI@LkNI/OAdOKYBZ3h3nPrc4V0oyAlt2ZAe2m5ewPfffqpXYGR8/nv42aVSiMj8 "Clean – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~145~~ ~~133~~ ~~123~~ 122 bytes
```
≔⟦⪪S ⟧θW⊖L§θ⁰«⟦⪫Eθ⪫κ ¦|⟧≔EE⊗Lθ§θ÷λ²✂κ﹪λ²Lκ²θ»⟦⪫ΦEθ⪫ι ι|⟧W⊖Lθ«≔⮌θη≔⟦⟧θWη«≔⊟ηε≔⟦⟧ζF⊟η«≔εδ≔⟦⟧εFδ⊞⎇‹IμIλζεμ⊞ζλ»⊞θ⁺ζε»⟦⪫Eθ⪫κ ¦|
```
[Try it online!](https://tio.run/##hVHLTsMwEDw3X7HqyZaMBEXAgROiQiqiUkS5VRxCsjRWXSexnQKFfHvwq8IcEIkSObszszObsi5U2RRiHG@05htJ1qtWcEMWsu3NyiguN4QymMKUPjPo6HX2VnOBQOZYKtyhNFiRB5QbU5Mbs5AVvpOOwSm1F3xmk9wqGLK@b7gky6J1PX/eBk37/rLKVnYS5zuQe@ZN/yJ@tDtqscmAhTRzvucVEsFgRl13JXiJTnjZVL1oQoNBFNhSjwsZhiz1dceFQfXLHj/a44nFv5N3MW3M8Ih7VBptmUGdZFvHFU6iUu1Jx27etLbCAB0ipRx84bVREDGBdoQgg8ojUk4QCaSKQt7rmjyhkoX6sKa1JreFNmRnx/mDcJs5OBqDXaB6ii0J/zlksWI3lIteEw92reHfn5yscBjHM7iCSzi39wwusvFkL74B "Charcoal – Try It Online") Link is to verbose version of code. ~~Still having to work around Charcoal bugs...~~ Edit: Saved 5 bytes by using a double `Map` as a poor man's array comprehension. Saved 4 bytes by using `Pop` to double iterate over an array. Saved 3 bytes by using concatenation instead of `Push`. Saved 10 bytes by coming up with a golfier `while` condition that also avoids a Charcoal bug. Saved 1 byte by discovering that Charcoal does indeed have a filter operator. Explanation:
```
≔⟦⪪S ⟧θ
```
Split the input on spaces, and then wrap the result in an outer array, saving that to `q`.
```
W⊖L§θ⁰«
```
Repeat while the first element of `q` has more than one element. (The first element of `q` always has the most elements because of the way the lists are divided into two.)
```
⟦⪫Eθ⪫κ ¦|⟧
```
Print the elements of `q` joined with spaces and vertical lines. (The array causes the result to print on its own line. There are other ways of achieving this for the same byte count.)
```
≔EE⊗Lθ§θ÷λ²✂κ﹪λ²Lκ²θ»
```
Create a list by duplicating each element of `q`, then map over that list and take half of each list (using the alternate element approach), saving the result back in `q`.
```
⟦⪫ΦEθ⪫ι ι|⟧
```
Print the elements of `q` joined with spaces and vertical lines. Actually, at this point the elements of `q` are either empty or single-element lists, so joining them just converts them to empty strings or their elements. The empty strings would add unnecessary trailing lines so they are filtered out. A flatten operator would have been golfier though (something like `⟦⪫Σθ|⟧`).
```
W⊖Lθ«
```
Repeat while `q` has more than one element. (The following code requires an even number of elements.)
```
≔⮌θη≔⟦⟧θ
```
Copy `q` to `h`, but reversed (see below), and reset `q` to an empty list.
```
Wη«
```
Repeat until `h` is empty.
```
≔⊟ηε
```
Extract the next element of `h` into `e`. (`Pop` extracts from the end, which is why I have to reverse `q`.)
```
≔⟦⟧ζ
```
Initialise `z` to an empty list.
```
F⊟η«
```
Loop over the elements of the next element of `h`.
```
≔εδ≔⟦⟧ε
```
Copy `e` to `d` and reset `e` to an empty list.
```
Fδ
```
Loop over the elements of `d`.
```
⊞⎇‹IμIλζεμ
```
Push them to `z` or `e` depending on whether they are smaller than the current element of the next element of `h`.
```
⊞ζλ»
```
Push the current element of the next element of `h` to `z`.
```
⊞θ⁺ζε»
```
Concatenate `z` with any elements remaining in `e` and push that to `q`. This completes the merge of two elements of `h`.
```
⟦⪫Eθ⪫κ ¦|
```
Print the elements of `q` joined with spaces and vertical lines.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~145~~ 144 bytes
Idea from [JungHwan Min's comment](https://codegolf.stackexchange.com/questions/150675/visualize-merge-sort/150686#comment368300_150675)
-1 byte thanks to Jonathan Frech
```
p=input()
l=[[p]]
i=0
while 2**i<len(p):l[i+1:i+1]=[sum([[x[1::2],x[::2]][len(x)<2:]for x in l[i]],[]),map(sorted,l[i])];i+=1
for s in l:print s
```
[Try it online!](https://tio.run/##HYvBCsMgEETvfoVHTfZQLW3Bxi9Z9lBoShaskWio/XobyzAMPN6kb1nWaFtLnmPai9IieMREJNifxGfhMEs7DDyFOaqkXUAejTtKHvP@VogVjXOWoGIfwi5WPVlHr3WTVXKUx4kIkDS8H0nldSvzEzrUdOfRG9HN/Ddd2jgWmVtDAze4wvmIhQv9AA "Python 2 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
S+ȯ†O↔hUmfL¡ṁ½
```
Takes an array containing a single array.
[Try it online!](https://tio.run/##AS8A0P9odXNr//9TK8iv4oCgT@KGlGhVbWZMwqHhuYHCvf///1tbNiw1LDQsMywyLDFdXQ "Husk – Try It Online")
## Explanation
```
S+ȯ†O↔hUmfL¡ṁ½ Implicit input, say A = [[4,17,32,1]].
¡ Iterate this function on A:
ṁ½ Split each array in two, concatenate results: [[4,17],[32,1]]
Result is [[[4,17,32,1]],
[[4,17],[32,1]],
[[4],[17],[32],[1]],
[[4],[],[17],[],[32],[],[1],[]],
...
mfL Map filter by length, removing empty arrays.
Result is [[[4,17,32,1]],
[[4,17],[32,1]],
[[4],[17],[32],[1]],
[[4],[17],[32],[1]],
...
U Longest prefix of unique elements:
P = [[[4,17,32,1]],[[4,17],[32,1]],[[4],[17],[32],[1]]]
h Remove last element: [[[4,17,32,1]],[[4,17],[32,1]]]
↔ Reverse: [[[4,17],[32,1]],[[4,17,32,1]]]
†O Sort each inner array: [[[4,17],[1,32]],[[1,4,17,32]]]
S+ȯ Concatenate to P:
[[[4,17,32,1]],
[[4,17],[32,1]],
[[4],[17],[32],[1]],
[[4,17],[1,32]],
[[1,4,17,32]]]
Implicitly print.
```
The built-in `½` takes an array and splits it at the middle.
If its length is odd, the first part is longer by one element.
A singleton array `[a]` results in `[[a],[]]` and an empty array `[]` gives `[[],[]]`, so it's necessary to remove the empty arrays before applying `U`.
[Answer]
## JavaScript (ES6), 145 bytes
```
f=a=>a.join`|`+(a[0][1]?`
${f([].concat(...a.map(b=>b[1]?[b.slice(0,c=-b.length/2),b.slice(c)]:[b])))}
`+a.map(b=>b.sort((x,y)=>x-y)).join`|`:``)
```
Takes input as an array within an array, i.e. `f([[6,5,4,3,2,1]])`. Works by generating the first and last lines of the output, then splitting and calling itself again, until every sub-array has length 1. Here's a basic demonstration of how it works:
```
f([[6,5,4,3,2,1]]):
6,5,4,3,2,1
f([[6,5,4],[3,2,1]]):
6,5,4|3,2,1
f([[6,5],[4],[3,2],[1]]):
6,5|4|3,2|1
f([[6],[5],[4],[3],[2],[1]]):
6|5|4|3|2|1
end f
5,6|4|2,3|1
end f
4,5,6|1,2,3
end f
1,2,3,4,5,6
end f
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~116(÷3>)~~ ~~38~~ 29 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437
-9 bytes per comment by @recursive. Now the input is given as a singleton whose only element is an array of the numbers to be sorted.
```
ƒ3s}óºE/ßB╢↕êb∩áαπüµrL╞¶è,te+
```
[Try it online!](https://staxlang.xyz/#c=%C6%923s%7D%C3%B3%C2%BAE%2F%C3%9FB%E2%95%A2%E2%86%95%C3%AAb%E2%88%A9%C3%A1%CE%B1%CF%80%C3%BC%C2%B5rL%E2%95%9E%C2%B6%C3%A8%2Cte%2B&i=%5B%5B10%2C2%5D%5D%0A%5B%5B4%2C17%2C1%2C32%5D%5D%0A%5B%5B6%2C5%2C4%2C3%2C2%2C1%5D%5D&a=1&m=2)
Unpacked version with 35 bytes:
```
{c{Jm'|*Pc{2Mm:f{fc{Dm$wW{{eoJm'|*P
```
## Explanation
The code can be splitted to two parts. The first part visualizes splitting and the second visualizes merging.
Code for visualizing splitting:
```
{ w Do the following while the block generates a true value
c Copy current nested array for printing
{Jm Use spaces to join elements in each part
'|* And join different parts with vertical bar
P Pop and print
c Copy current nested array for splitting
{2Mm Separate each element of the array to two smaller parts with almost the same size
That is, if the number of elements is even, partition it evenly.
Otherwise, the first part will have one more element than the second.
:f Flatten the array once
{f Remove elements that are empty arrays
c Copy the result for checking
{Dm$ Is the array solely composed of singletons?
If yes, ends the loop.
```
The code for visualizing merging:
```
W Execute the rest of the program until the stack is empty
{{eoJm For each part, sort by numeric value, then join with space
'|* Join the parts with vertical bar
P Pop and print the result
```
## Old version, actually building the nested list structure.
```
{{cc0+=!{x!}Mm',*:}}Xd;%v:2^^{;s~{c^;<~sc%v,*{2M{s^y!svsm}M}YZ!x!Q,dmU@e;%v:2^{;%v:2^-N~0{c;={scc0+=Cc%v!C:f{o}{scc0+=C{s^y!svsm}?}Y!cx!P,dcm
```
`cc0+=` is used thrice in the code to check whether the top of stack is a scalar or an array.
`{{cc0+=!{x!}Mm',*:}}X` builds a block that recursively calls itself to output a nested array of numbers properly. (Default output in Stax vectorizes a nested array before printing).
```
{ }X Store the code block in X
{ m Map each element in the list with block
cc Make two copies of the element
0+ + 0. If the element is a scalar, nothing will change
If the element is an array, the element 0 will be appended
=!{ }M If the element has changed after the `0+` operation
Which means it is an array
x! Recursively execute the whole code block on the element
',* Join the mapped elements with comma
:} Bracerizes the final result
```
There are two other blocks that performs the splitting and the merging, respectively. They are too verbose and I don't care to explain (there are a little bit more information in the historical version of this post but don't expect too much).
] |
[Question]
[
Most common computer [keyboard layouts](http://en.wikipedia.org/wiki/Keyboard_layout) have the decimal digit keys
`1``2``3``4``5``6``7``8``9``0`
running along at their top, above the keys for letters.
Let a decimal digit's *neighborhood* be the set of digits from its own digit key and from the digit keys immediately to the left and right, if they exist.
For example, the neighborhood of 0 is `{0, 9}`, and the neighborhood of 5 is `{4, 5, 6}`.
Now, define a ***keyboard friendly number*** as a positive integer (in decimal form with no leading zeros) that can be typed on the layout above such that every consecutive digit in the number after the first digit is in the neighborhood of the preceding digit.
* All single digit numbers (1-9) are trivially keyboard friendly.
* A number such as 22321 is keyboard friendly because every digit (not counting the first) is in the neighborhood of the digit just before.
* A number such as 1245 is **not** keyboard friendly because 4 is not in the neighborhood of 2 (nor vice versa).
* A number such as 109 is **not** keyboard friendly because 0 is not in the neighborhood of 1. The ends do not loop around.
By putting the keyboard friendly numbers in order from smallest to largest, we can create an [integer sequence](http://en.wikipedia.org/wiki/Integer_sequence).
Here are the first 200 terms of the keyboard friendly numbers sequence:
```
N KFN(N)
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 11
11 12
12 21
13 22
14 23
15 32
16 33
17 34
18 43
19 44
20 45
21 54
22 55
23 56
24 65
25 66
26 67
27 76
28 77
29 78
30 87
31 88
32 89
33 90
34 98
35 99
36 111
37 112
38 121
39 122
40 123
41 211
42 212
43 221
44 222
45 223
46 232
47 233
48 234
49 321
50 322
51 323
52 332
53 333
54 334
55 343
56 344
57 345
58 432
59 433
60 434
61 443
62 444
63 445
64 454
65 455
66 456
67 543
68 544
69 545
70 554
71 555
72 556
73 565
74 566
75 567
76 654
77 655
78 656
79 665
80 666
81 667
82 676
83 677
84 678
85 765
86 766
87 767
88 776
89 777
90 778
91 787
92 788
93 789
94 876
95 877
96 878
97 887
98 888
99 889
100 890
101 898
102 899
103 900
104 909
105 987
106 988
107 989
108 990
109 998
110 999
111 1111
112 1112
113 1121
114 1122
115 1123
116 1211
117 1212
118 1221
119 1222
120 1223
121 1232
122 1233
123 1234
124 2111
125 2112
126 2121
127 2122
128 2123
129 2211
130 2212
131 2221
132 2222
133 2223
134 2232
135 2233
136 2234
137 2321
138 2322
139 2323
140 2332
141 2333
142 2334
143 2343
144 2344
145 2345
146 3211
147 3212
148 3221
149 3222
150 3223
151 3232
152 3233
153 3234
154 3321
155 3322
156 3323
157 3332
158 3333
159 3334
160 3343
161 3344
162 3345
163 3432
164 3433
165 3434
166 3443
167 3444
168 3445
169 3454
170 3455
171 3456
172 4321
173 4322
174 4323
175 4332
176 4333
177 4334
178 4343
179 4344
180 4345
181 4432
182 4433
183 4434
184 4443
185 4444
186 4445
187 4454
188 4455
189 4456
190 4543
191 4544
192 4545
193 4554
194 4555
195 4556
196 4565
197 4566
198 4567
199 5432
200 5433
```
# Challenge
Write a program or function that takes a positive integer N (via stdin/command line/function arg) and prints (to stdout) or returns the Nth term in the keyboard friendly numbers sequence.
For example, if the input is `191`, the output should be `4544`.
The output may optionally have a single trailing newline.
**The shortest submission in bytes wins.**
[Answer]
# Pyth, ~~27~~ 24 bytes
```
uf!f/h-FY3.:metsd`T2hGQ0
```
[Demonstration.](https://pyth.herokuapp.com/?code=uf!f%2Fh-FY3.%3Ametsd%60T2hGQ0&input=191&debug=0)
Improvements to the original:
* Using `metd`, instead of `.r ... _UJ`: 2 less bytes. 1 direct, 1 for not having to use J.
* Using `s` and ``T` instead of `JT10`: 1 less byte.
---
We start with the string representation of a number: ``T`.
Then, we convert the string to a list of digits, and rotate the digits digits backwards by one, (9876543210) with `metsd`. Then, we take the 2 element subsequences with `.: ... 2`. These subsequences are filtered on `/h-FY3`. This expression corresponds to `((a-b)+1)/3`, which is zero if and only if the difference between `a` and `b` is at most 1. Thus, the filtered list will be empty if and only if the number is keyboard friendly. With `!`, the result is true only if the number is keyboard friendly.
`f ... hG` filters upwards from `G+1` until the result is true, giving the first keyboard friendly number at `G+1` or above. `u ... Q0` applies this function to its own output `Q` times, starting from 0, where `Q` is the input. This gives the `Q`th Keyboard Friendly Number, as desired.
[Answer]
# Python 3, ~~112~~ 102 bytes
```
f=lambda n,k=0:n+1and f(n-all(-2<~-int(a)%10-~-int(b)%10<2for a,b in zip(str(k),str(k)[1:])),k+1)or~-k
```
We keep track of the count of friendly numbers still needed to find in `n` and the last checked number in `k`.
5 and 5 bytes saved thanks to @isaacg and @Sp3000.
[Answer]
# CJam, ~~29~~ 28 bytes
```
ri_4#{AbAfe|_1>.-W<3,:(-!},=
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri_4%23%7BAbAfe%7C_1%3E.-W%3C3%2C%3A(-!%7D%2C%3D&input=30).
[Answer]
# CJam, ~~34~~ 31 bytes
*3 bytes saved by Dennis.*
I'm sure the gap to Pyth can be closed somehow, but I don't have time right now to golf this further...
```
0q~{{)_s:_2ew{A,s(+f#~m2/},}g}*
```
[Test it here.](http://cjam.aditsu.net/#code=0q~%7B%7B)_s)_%2B%2B2ew%7BA%2Cs(%2Bf%23~-z1%3E%7D%2C%7Dg%7D*&input=50)
[Answer]
# JavaScript (ES6), 95
```
F=k=>{for(i=0;k;k-=(f=1,p=NaN,[for(d of''+i)(d=(8-~d)%10,d-p>1|p-d>1?f=0:p=d)],f))++i;return i}
```
**Ungolfed**
```
F=k=>{
for(i=0; k>0; )
{
++i;
f = 1; // presume i it's friendly
p = NaN; // initial value so that first comparison gives false
for(d of ''+i) // loop for each digit of i
{
// rotate digits 1->0, 2->1 ... 9->8, 0->9
// note d is string, ~~ convert to number (golfed: 8-~d)
d = (~~d+9) % 10
if (p-d>1 || p-d<-1)
f = 0 // not friendly
else
// this can go in the 'else', if not friendly I don't care anymore
p = d // move current digit to prev digit
}
k -= f // count if it's friendly, else skip
}
return i
}
```
**Test** : execute snippet in Firefox
```
F=k=>{
for(i=0;k;k-=(f=1,p=NaN,[for(d of''+i)(d=(8-~d)%10,d-p>1|p-d>1?f=0:p=d)],f))++i
return i
}
```
```
<input id=N><button onclick="R.value=F(N.value)">-></button><input readonly id=R>
```
[Answer]
# Haskell, ~~90~~ 80 bytes
```
([x|x<-[0..],all((<2).abs)$zipWith(-)=<<tail$[mod(1+fromEnum c)10|c<-show x]]!!)
```
This is a function without a name. To use it, call it with a parameter, e.g.:`([x|x<-[0..],all((<2).abs)$zipWith(-)=<<tail$[mod(1+fromEnum c)10|c<-show x]]!!) 199` which returns `5432`.
How it works:
```
[x|x<-[0..] ] make a list of all integers x starting with 0
, where
c<-show x each character in the string representation of x
mod(1+fromEnum c)10 turned into the number '(ascii+1) mod 10'
zipWith(-)=<<tail then turned into a list of differences between neighbor elements
all((<2).abs) only contains elements with an absolute value less than 2
!! ... take the element given by the parameter (!! is 0
based, that's why I'm starting the initial list with 0)
```
Edit: @Mauris found some bytes to save. Thanks!
[Answer]
## Dart, 92 bytes
```
f(n,[x=0]){t(x)=>x>9?((x+9)%10-((x~/=10)+9)%10).abs()>1||t(x):--n>0;while(t(++x));return x;}
```
With linebreaks:
```
f(n,[x=0]){
t(x)=>x>9?((x+9)%10-((x~/=10)+9)%10).abs()>1||t(x):--n>0;
while(t(++x));
return x;
}
```
See/run it on [DartPad](https://dartpad.dartlang.org/026a368cb2d94e71dc2d)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 83 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 10.375 bytes
```
Þ∞'f0₀V¯ȧ2<A;i
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiw57iiJ4nZjDigoBWwq/IpzI8QTtpIiwiIiwiMTkzIl0=)
## Explanation
```
Þ∞'f0₀V¯ȧ2<A;i­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏⁠⁠‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌­
√û‚àû # ‚Äé‚Å°Natural numbers
' ; # ‚Äé‚Å¢Filtered by:
f0‚ÇÄV # ‚Äé‚Å£The list of digits where 0 is replaced with 10, ie [9,0] becomes [9,10]
¯ # ‎⁤Consecutive differences between digits
ȧ2<A # ‎⁢⁡Are the absolute values of those difference all less than 2
i # ‎⁢⁢index (from input)
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# Batch - 520 Bytes
*Shudder.*
```
@echo off&setLocal enableDelayedExpansion&set a=0&set b=0
:a
set/ab+=1&set l=0&set c=%b%
:b
if defined c set/Al+=1&set "c=%c:~1%"&goto b
set/am=l-2&set f=0&for /l %%a in (0,1,%m%)do (
set x=!b:~%%a,1!&set/an=%%a+1&for %%b in (!n!)do set y=!b:~%%b,1!
set z=0&set/ad=x-1&set/ae=x+1&if !e!==10 set e=0
if !d!==-1 set d=9
if !y!==!d! set z=1
if !y!==!e! set z=1
if !y!==!x! set z=1
if !y!==0 if !x!==1 set z=0
if !y!==1 if !x!==0 set z=0
if !z!==0 set f=1)
if !f!==0 set/aa+=1
if %a% NEQ %1 goto :a
echo %b%
```
[Answer]
# Bash + coreutils, 120 bytes
```
seq $1$1|tr 1-90 0-9|sed 's#.#-&)%B)/3)||(((C+&#g;s/^/(0*((/;s/$/))*0)/'|bc|nl -nln|sed '/1$/d;s/ 0//'|sed -n "$1{p;q}"
```
### Some testcases:
```
$ for i in 1 10 11 99 100 200; do ./kfn.sh $i; done
1
11
12
889
890
5433
$
```
[Answer]
# Pyth, 19 bytes
```
e.f.AgL1.aM.+|RTjZT
```
[Try it here.](http://pyth.herokuapp.com/?code=e.f.AgL1.aM.%2B%7CRTjZT&input=200&debug=0)
Note: Uses commit newer than this challenge, so shouldn't be considered as an outgolf of isaacg's answer. This is still competing, though.
[Answer]
# JavaScript ES6, 126 bytes
```
f=n=>{b=s=>[...++s+''].every((e,i,a,p=(+a[i-1]+9)%10)=>i?p==(e=+e?e-1:9)|p-e==1|e-p==1:1)?s:b(s)
for(p=0;n--;)p=b(p)
return p}
```
Ungolfed code and tests below. This could certainly be improved more.
```
f=function(n){
b=function(s){
return (s+'').split('').every(function(e,i,a){
e=+e?e-1:9
p=i?(+a[i-1]+9)%10:e
return p==e|p-e==1|e-p==1
})?s:b(s+1)
}
for(p=i=0;i<n;i++){
p=b(p+1)
}
return p
}
var input = document.getElementById('n'), results = [];
input.onchange = function(){
document.getElementById('s').innerHTML = f(input.value)
}
for(var i=0;i<200;i++){
results.push(i + ': ' + f(i))
}
document.getElementById('r').innerHTML=results.join('<br />')
```
```
N = <input type="number" id="n" min="1" value="191" /><br />
KBD(N) = <samp id="s">4544</samp>
<div id="r"></div>
```
[Answer]
# Cobra - 135
Haven't done this in a while, but here goes:
```
def f(n,i=0)
while n,if all for x in (s='[i+=1]').length-1get s[x+1]in' 1234567890'[(int.parse(s[x:x+1])+9)%10:][:3],n-=1
print i
```
Ungolfed:
```
def fn(n as int)
i = 0
while n <> 0
i += 1
s = i.toString
l = s.length - 1
v = true
for x in l
k = (int.parse(s[x].toString) + 9) % 10
if s[x + 1] not in ' 1234567890'[k : k + 3], v = false
if v, n -= 1
print i
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
Do⁵IỊẠ
1Ç#Ṫ
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//RG/igbVJ4buK4bqgCjHDhyPhuar///8yMDA "Jelly – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
f=(n,i)=>n?f(n-![...~i+f].some(e=v=>(e-(e=+v||1+v))**2>1),-~i):i
^ ^
If exist, don't decrease 1=>1, 0=>10, s=>1s
```
[Try it online!](https://tio.run/##JcpNCsIwEEDhs7jLND8YwY018SDiorQTGakzpZHgovTqUdrV@xbv1ZUu9zNNH8syYK0pKDYEIfItKbaHu3NuJZ0eLssbFYYSokL7hy7L4nUBaJpT9GDsSnChmmRWxAN@g2@3Xs/HVuuN0AtnGdGN8twnk/YC1B8 "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
[Sandboxed](https://codegolf.meta.stackexchange.com/a/17913/75681)
Given a set of closed non-overlapping 2d contours (separated by at least one space even on diagonals) with arrows oriented consistently in the same clockwise or counter-clockwise direction (each contour has its own direction) and a positive number `n`, move the arrows `n` steps along the contours in the respective direction.
The arrows are represented by `> v < ^` respectively for right, down, left and up directions. There the other characters are `-` (horizontal), `|` (vertical) and `+` (corner).
When an arrow is on a corner, it keeps its current direction and changes it only after the turn is taken.
There will always be a straight segment (or a space) between any two corners (like `+-+` for the horizontal and similar for the vertical) - in other words the sharp `U` turns are forbidden. The segments between the corners are either vertical or horizontal and the bend at a corner is always 90 degree.
# Input:
* a positive integer - `n` - number of steps
* an ASCII representation of the contours - it can be a multiline string, a list of strings, a list of characters and so on.
# Output:
The same contours with all arrows shifted `n` steps in each contour's overall direction.
# Test cases:
# 1.
Input:
`n` = 1
```
+----->->
| |
| v---+
| |
+---<-------+
```
Output:
```
+------>+
| v
| +>--+
| |
+--<--------+
```
# 2.
Input:
`n` = 2
```
+-----+ +---+
| | | |
+-->--+ | v
| |
+--->---+ |
| |
+------<<---+
```
Output:
```
+-----+ +---+
| | | |
+---->+ | |
| |
+----->-+ v
| |
+----<<-----+
```
# 3.
Input:
`n` = 3
```
+---+ +---+ +-------+
| | | v | |
^ | | | +-<-+ |
| | ^ | | v
| +---+ +-->----+ |
| |
| +-------+ +---+ |
| | | v | |
+---+ +---+ +---+
```
Output:
```
+>--+ ^---+ +-------+
| | | | ^ |
| | | | +---+ |
| | | | | |
| +---+ v----->-+ |
| |
| +-------+ +---+ v
| | | | | |
+---+ +-<-+ +---+
```
# 4.
Input:
`n` = 1
```
+--+
| |
| +---+
| |
+----+ |
| |
+-+
```
Output:
```
+--+
| |
| +---+
| |
+----+ |
| |
+-+
```
# 5.
Input
`n` = 4
```
^>>>>
^ v
^ v>>>>
^ v
<<<<<<<<v
```
Output:
```
^>>>>
^ v
^ v>>>>
^ v
<<<<<<<<v
```
# 6.
Input:
`n` = 1
```
^->
^ v
<<v
```
Output:
```
^>+
^ v
<<v
```
Write a function or a program solving the above task. The shortest code in bytes in every language wins. Don't be discouraged by the golfing languages. Explanation of the algorithm and the code is highly appreciated.
[Answer]
# JavaScript (ES6), ~~210 ... 182~~ 180 bytes
Takes input as `(m)(n)`, where \$m\$ is a list of lists of characters. Returns the result in the same format.
```
m=>g=n=>n?g(n-1,m=m.map((r,y)=>r.map((c,x)=>(i=0,h=$=>~$?(m[Y=y+($-2)%2]||0)[X=x+~-$%2]>h?"-|+"[n+=`;m[${Y}][${X}]=S[${$}]`,i?2:$&1]:h($^++i):c)((S="<^>v").indexOf(c)))),eval(n)):m
```
[Try it online!](https://tio.run/##hVLBbuIwEL3zFaMou9iyHRW6JxqbT9hDL63SREVpgFTYqQKyqGr669QmsJsYVx3Jmczk5c2b8bwu9GJbtvXbjqnmpTou@VFyseKKCzVfIcUmVHKZyMUbQi19x1y0XVDSvQ1QzW/omsdcfMZzJLNH/k5QzKb41zQ35gZnD3xPPllsQ7GeR8yQKFOEP9/JLP54POT2@XDI@b318SF/pvV8Oot/T/LZGsUFITWelRihex6lhdARTmr1Uu3/LlGJrdFKLzZIYTyTx1213QEHJCkoDFzAB5SN2jabKtk0K7REElvkSXrrPrfJa1MrNB5jfH57UmMMBE7@Dg6jkaNE2QggS5IkIsyZYCLK6SVnoDMTyGmLJoG8j3e8KevM4kc5hQkO1iZAgpwGzDWncHiX1738v/oBDeJUIdxLSLOTnf7XPA1pdnx9zwL6L0efvV@r6GHMiScN6nSn6HN4vZuhFsF@6Be@6d30e@lxhvSA15s/Q3LGDGbVzfM2ME9vdF7F8HJc3xsZpC4b5KfIt8tYCGveBWk/DmDAw6Vn012dP1d12JBh@K@@qDt@AQ "JavaScript (Node.js) – Try It Online")
## How?
You can [follow this link](https://tio.run/##jVLbbqMwEH3nK0aI3dgyRk12n1ogn7APfWmVBTWipKUKUJEIparTX8@OuSTgDLs7Eox9PHPmzNhv63q9S6rsfS@L8jk9bYJTDkFoAbxAAEW7BFwsG48w6xYalDB3z1vMg9zL1@@MVS588D63tao9SVw4GCcAbLQDyJDpxjXAVwQdM1Pbl3MW9zfSTuSKhAEekf4DBDAHu1pw@AYLMjICpW6IE04TPyDtAWm/pDNBGUGIvS3JbFsqYU8pLkAE8HSXr5zPx2OE/4djFNyjd47RkzuRlMESFnCLk/wOc7pBAr0lI19xVjEIkXHrfxKSEcbN@2H3OCrbj8Pa5l5WPKeHXxuWjKmHu8uaX5pN6/WWFf1R63st@Wmf7vZYhOUuFPoRwickZbErt6m3LV/YhuUck5uHWunjynsrs4LNZpx3q9/FjONtNv4OjpalKZm@oZXnebaQ2kIZ2pHbY6qTpgisxmhB4Ga85vVlaxhvRS7MOVlbgCA5FahrzlDHa7we4Of6hIawqUD3QmnWsv2L5gWlWfMNvST091/debNWPIhRDY9P6tRfPOQweldjLaH8R78w0bsa9jLgpPSA0Zs5Q9HFjGbVzvMHMU9jdEZF@nFc35sYQf0LMiEx@RjjEM24oNrcEzFgxPmd1W2dn1d15JhhnFv36k5/AA) to see a formatted version of the source.
### Wrapper
The recursive function \$g\$ is just used as a wrapper that invokes the main code to move all arrows by 1 step and keeps calling itself with \$n-1\$ until \$n=0\$.
### Update method
We can't safely move each arrow one at a time because we would run the risk of overwriting non-updated arrows with updated ones. Instead, we first remove all arrows and compute their new positions. We apply the new positions in a second time.
This is done by re-using \$n\$ as a string to store the position updates as JS code.
For instance, in the first test case, \$n\$ is set to:
```
"1;m[0][7]=S[2];m[1][8]=S[3];m[2][9]=S[2];m[4][3]=S[0]"
```
(Note that the leading number -- which is the original value of \$n\$ -- is harmless.)
The new positions are applied by just doing `eval(n)`.
### Directions
Each arrow is converted into a direction \$d\$ (named `$` in the code), using the following compass:
$$\begin{matrix}
&1\\
0&+&2\\
&3
\end{matrix}$$
The corresponding values of \$dx\$ and \$dy\$ are computed this way:
```
d | dx = (d - 1) % 2 | dy = (d - 2) % 2
---+------------------+------------------
0 | -1 | 0
1 | 0 | -1
2 | +1 | 0
3 | 0 | +1
```
### Corners
If the next character in the identified direction is a space or is out of bounds, it means that we're located on a corner and we need to take a 90° or 270° turn. This is why the helper function \$h\$ is testing up to 3 distinct directions: \$d\$, \$d\operatorname{xor}1\$ and \$d\operatorname{xor}3\$.
If we're located on a corner, we overwrite the cell with `+`. Otherwise, we overwrite it with either `-` or `|`, depending on the parity of \$d\$.
**Note**: The parameter of \$h\$ is not named `$` just because it looks uber l33t but also because it allows us to compare a given character with \$h\$ (implicitly coerced to a string) to know if it's a space (below `"$"`), a contour character (above `"$"`) or another arrow (also above `"$"`).
## Animated version
```
f=
m=>g=n=>n?g(n-1,m=m.map((r,y)=>r.map((c,x)=>(i=0,h=$=>~$?(m[Y=y+($-2)%2]||0)[X=x+~-$%2]>h?"-|+"[n+=`;m[${Y}][${X}]=S[${$}]`,i?2:$&1]:h($^++i):c)((S="<^>v").indexOf(c)))),eval(n)):m
m = [
[..."+---+ +---+ +-------+"],
[..."| | | v | |"],
[..."^ | | | +-<-+ |"],
[..."| | ^ | | v"],
[..."| +---+ +-->----+ |"],
[..."| |"],
[..."| +-------+ +---+ |"],
[..."| | | v | |"],
[..."+---+ +---+ +---+"]
];
(F = _ => (o.innerHTML = m.map(r => r.join('')).join('\n'), m = f(m)(1), window.setTimeout(F, 100)))()
```
```
<pre id=o></pre>
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~183 161 157~~ 155 bytes
```
{A:"^>v<";D,:-D:(-1 0;!2);s:#'1*:\x;r:" -+|"r*+/'3':|0,|0,r:~^x;$[p:+s\&~^t:A?,/x;;:r];s#@[,/r;s/+q;:;A@D?-p-q:q@'*'&'~^x ./:/:q:+p+/:D@4!(t^0N)+/:0 1 3]}/
```
[Try it online!](https://ngn.bitbucket.io/k#eJy9VMtuwjAQvOcr3BSRhMUECqfdyAWJc0/caKz2glS1UiGgKFVTvr2xgciOk4pD21UsK6P17sz4scHPBfpS5IlPyyHyJYZ8wsZ0cxfRHm+DyQAfC8rQZxxKPxtAHEwDLMfD6svwKAvqrbcI+8f+UR5wcT+MCyLMUtrfztfDOKN9DDtCWsyX93zLd7ibB4OgH1Qr2SjGGHcIW4hxOZ/dhAc5foiqnzGbsGn6FXveCj97649jhhs2YgU9vb9S+LR5fnmjgj4oi9Ivb7UOJxT6wFUILlgVvsd0+OVpZmUrmlcrwEF1fo2qugk/BfhRdMIv/biA9sqtKIir+l3aqX6p0ndX6wMGLZxLrc+qoTppNK/RupejT+jKJtrthbIjafXiam7aNRvt5qbYgaXjB25JYvk2Pfum1pszd3heRn6e7drSyCh1jaTFLzWkud5hbXAQ/EfPzSidGryhyeVR92/1FM4ZljfmfooTLq/y7KLb5Wp71sW1ydnVq/ffOAu/4Vne6Vk9OjxLTM9S4/1xngLn1Wm7IM0zDM1rUTYBaF6+f22sFc8qxVJUYTVSpyB3EZVnIczyPzlHboj6g9r1TklurjBzbQbQnZV631VLRgo=)
`{` `}/` when called with an int left arg n, this will apply the function in `{` `}` n times to the right arg
`A:"^>v<"` arrows
`D,:-D:(-1 0;!2)` ∆y,∆x for the 4 cardinal directions
`s:#'1*:\x` shape of the input: height,width
`r:~^x` countours - boolean matrix showing where the non-spaces are
`r:" -+|"r*+/'3':|0,|0,r` recreate the character matrix with a countour but without arrows, by counting self+upper+lower for each cell in `r` and replacing 1->`-`, 2->`+`, 3->`|`
`t:A?,/x` types of arrows: 0 1 2 3 for `^>v<`, all other cells are represented as `0N` (null)
`p:+s\&~^t` coordinates of the arrows
`$[#p` `;;:r]` if there aren't any arrows, return `r`
`q:+p+/:D@4!(t^0N)+/:0 1 3` all 3 possible new positions for each arrow - if it keeps going forward, if it turns left, and if it turns right
`q:q@'*'&'~^x ./:/:q` for each arrow choose the first option that lands on the countour
`@[,/r;s/+q;:;A@D?q-p]` flatten `r` and put on it the arrows at their new positions and with their new directions
`s#` reshape to the original shape
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 105 bytes
```
W¬ΦυΣκ⊞υS≔⊟υη≔⪫υ⸿θ≔⟦⟧υ≔>^<vζPθFθ¿№ζι«⊞υ⟦⌕ζιⅉⅈ⟧§+|-↨EKV›κ ²»ιFυ«J⊟ι⊟ι≔⊟ιιFIη«≔⊟Φ⁴∧﹪⁻⊖ι⊕λ⁴›§KV⁻⁵λ ιM✳⊗黧ζι
```
[Try it online!](https://tio.run/##ZVHBSsNAED03XzHkNEvTi9STRagtlRYiBUWUWiEmW7N0uxuT3Soavz3ubFpTdA6ZzLy8mfcmaZ6UqU5k07znQnLAG21wJqThJdoIbu0Ot4wxWNoqp8ZcFdbcmlKoV2TsIhhXlXhVuNQFWhZB3rUWWihihE9l6JC3DlmtI7BdGV4@j/ZhBJ@uFVtpROGmGyTCRpfgXkBsACfauu5nBMLJ@Qp6R0WrmVBZ24/gEd3jAdnakXtLP2ds5irjHxj264HbcpVUHOOkwCXn23utbrjdJUoR77rkCfneOtEQMtc5Y@TxO@Cy4tCOE0dZ1qtY2F1xp71/2t9mWn5yGAKI1vO8SVIZzFsPp18djj6MYOz8xDqzUmMslK1wytOS77gyPPPD5qqrJekcnqg/@v3vrx12HoHneIvsKK0X6z3HqSh5aoRWONX2Rfp13s3332u2/8Hdpmn6A4o@UO4HNVDUQLkOXO@SMKr2ARziFyPQoVTV0EWLuRiN/MyzZrCXPw "Charcoal – Try It Online") Link is to verbose version of code. Includes 22 bytes used to avoid requiring a cumbersome input format. Explanation:
```
W¬ΦυΣκ⊞υS≔⊟υη≔⪫υ⸿θ≔⟦⟧υ
```
Conveniently input the contours and the number of steps.
```
≔>^<vζ
```
The direction characters are used several times so the string is cached here. The index of a direction character in this string is known as its direction.
```
Pθ
```
Print the original contours without moving the cursor.
```
Fθ
```
Loop over the characters in the contour.
```
¿№ζι«
```
If the current characters is a direction character...
```
⊞υ⟦⌕ζιⅉⅈ⟧
```
... then save the direction and position in a list...
```
§+|-↨EKV›κ ²
```
... and replace the character with the appropriate line character.
```
»ι
```
Otherwise output the character and move on to the next character.
```
Fυ«
```
Loop over the saved positions.
```
J⊟ι⊟ι
```
Jump to the saved position.
```
≔⊟ιι
```
Extract the saved direction.
```
FIη«
```
Loop over the appropriate number of steps.
```
≔⊟Φ⁴∧﹪⁻⊖ι⊕λ⁴›§KV⁻⁵λ ι
```
Find the direction of the next step, which is any direction that is neither reverse nor empty.
```
M✳⊗ι
```
Take a step in that direction. (Charcoal direction indices for the `Move` command are twice the value of my direction.)
```
»§ζι
```
Print the appropriate direction character.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 111 bytes[SBCS](https://github.com/abrudz/SBCS)
```
{A[D⍳q-p]@q⊢' |+-'[c×3+/0,c,0]⊣q←⊃¨(⍸c←' '≠⍵)∘∩¨↓⍉D[4|0 1 3∘.+4~⍨,t]+⍤1⊢p←⍸4>t←⍵⍳⍨A←'v>^<'⊣D←9 11∘○¨0j1*⍳4}⍣⎕⊢⎕
```
[Try it online!](https://tio.run/##rVRfaxNBEH@/TzFvq27O5kxelGOxkI/Qt5CDkDZSLeYP4UCy8UWJSdotipT6Ikjbh@irBEpBhPhN5ovEmb07s3dNFNSFy@3szPx@v5mbTbN75O@/aB51nqzw9Oywg@O3ZQ8nb9qr4W69huZrz@82HvdwdiFAS1/UWz/OK3KnXGqVyg2cXfYoAWevlvM7aK5bZAgQOP2EZnEXJx9w8nk5x/F7NNNavarLEECFju/L6ks089KgIdFcBQTeZRhzXVUDu1kQMQXsMl6solAQU42MhxAEDHt@vJyXnwb3KKw6QnNJ0gmEflck3WtbjNMAT76J0VCUxC837/oCzQ2bZiFwMuPdyXc6b/VFWwCajzDoN/fbz2HQAXp5e4Q2ZEnTi35SbHuHEB4xKPPckK@Px69F55kYrZp0BgA4fiekz0v5imygtmhIli7YMUVJx7YxZHN@6CdLCi@AJuytcX0lizgFW6qtuBks43q3JEuQOUnaSk5TGdTaMdnglJRJVhYhsTeVxFWFCfWDfEm/5bUFZ/YmXmaWqa6NvGG4rWROc9@@IyN74uzLpZCR49M2L8yVzU/k5lhpxGy@WHLm1nle5W9pHRTK0a5OB8PlhoLurA0ymw43V3gHTkdU4on@0JGsQigwrztyW1VRnWbmLR2JnY/6tx2JN3REb@1I6HakwsMJB8VhcW6dc5Hzg7ueObkeV73eyuJ9/m@grthI0UrRIuf/we7Zl@4h7VOYLprSaqbtHzByUvwkMAmJneIjJXOenw "APL (Dyalog Unicode) – Try It Online")
similar to [my k answer](https://codegolf.stackexchange.com/a/188981/24908)
] |
[Question]
[
## Introduction
Help! I accidentally dropped my TI-84 calculator out my window (don't ask how) and it broke. I have a math test tomorrow and the only calculator I can find is one with these buttons:
```
7 8 9 +
4 5 6 -
1 2 3 *
0 = /
```
My math test is a review test on evaluating expressions. I need a program to take an expression such as `1+(5*4)/7` and convert it to the keystrokes needed to solve it on my spare calculator. (And in case you were wondering, this actually happened to me).
## Challenge
Given a non-empty input string containing *only* the characters `0-9`, `(`, `)`, `+`, `-`, `*`, and `/`, output the keystrokes in a space-separated string (eg. `1 + 3 / 3 =`). There must always be an equal sign at the end of the output. Standard loopholes are not allowed.
Examples:
* Input: `1+(5*4)/7`, Output: `5 * 4 / 7 + 1 =`
* Input: `6*(2/3)`, Output: `2 / 3 * 6 =`
* Input: `(7-3)/2`, Output: `7 - 3 / 2 =`
### To make this challenge easier:
* You may assume that the input has a series of keystrokes linked to it that does not require clearing the calculator (`1-(7*3)` is not valid since it would require you to find `7 * 3`, then clear the calculator to do `1 - 21`. All the above examples are valid since there is one, continuous output that does not require the user to clear the calculator and remember a number).
* You may assume that there will only be a single integer after a `/`, as having an input such as `21/(7*3)` would not pass the first assumption either.
* You may assume that there will always be a `*` between an integer and a left parentheses (Valid: `6*(7)`, Invalid: `6(7)`).
* You may assume the input always produces integer output.
* You may assume the input only has three levels of parentheses.
Non-examples
* `2-(14/2)` as you would have to do `14 / 2`, then *clear*, then `2 - 7`.
* `36/(2*3)` as you would have to do `2 * 3`, then *clear*, then `36 / 6`.
* `1024*4/(1*2+2)` as you would have to do `1*2+2`, then *clear*, then `1024 * 4 / 4`.
## Bonuses
* **-5%** if your program can recognize parentheses multiplication (it knows that `6(7)=6*(7)`).
* **-5%** if your program can handle input with decimal numbers (`3.4`, `2.75`, `7.8`) and the output includes `.` (as there must be a `.` key on my spare calculator in this case).
* **-5%** if your program can handle unlimited levels of parentheses.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes (including the bonuses) wins!
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=61751,OVERRIDE_USER=141697;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# TI-BASIC, 605.2 bytes
Eligible for lirtosiast's TI-BASIC bounty under [**Fitting but Unsuitable Languages**](https://codegolf.meta.stackexchange.com/a/8219/31957).
Qualifies for all 3 bonuses, `712 - 15% = 605.2`. There are some golfing opportunities here and there, but I wanted to get this out first, as some of the potential golfs are non-trivial. Please note that TI-BASIC is a tokenized language, and the below is a textual representation of that program. Thus, the program is *not* 1182 bytes, since this program is not encoded under UTF-8. Note that `~` is equivalent to unary negation and `->` to the `STO>` operator. Output is a string, retrievable from `Ans` or `Str1`.
The below program is the result of a few programmer hours thinking and programming, spread over the course of a few weeks.
```
Input "",Str1
0->dim(L1
0->dim(L2
1->I
DelVar S
While I<length(Str1
DelVar T
".->Str3
1->C
While C and I<length(Str1
sub(Str1,I,1->Str2
inString("0123456789.",Str2->C
If C:Then
I+1->I
1->T
Str3+Str2->Str3
End
End
If T=0:Str3+Str2->Str3
sub(Str3,2,length(Str3)-1->Str3
If T=1:Then
expr(Str3->L2(1+dim(L2
End
inString("*+/-",Str3->M
If M:Then
I+1->I
2->T
1->C
While C
dim(L1->C
If C:Then
2fPart(L1(dim(L1))/2)>2fPart(M/2->C
If C:Then
~L1(dim(L1->L2(1+dim(L2
dim(L1)-1->dim(L1
End
End
End
M->L1(1+dim(L1
End
If Str3="(":Then
If S=1:Then
sub(Str1,1,I-1)+"*"+sub(Str1,I,length(Str1)-I+1)->Str1
Else
I+1->I
0->L1(dim(L1)+1
End
End
If Str3=")":Then
I+1->I
While L1(dim(L1
~L1(dim(L1->L2(1+dim(L2
dim(L1)-1->dim(L1
End
dim(L1)-1->dim(L1
End
T->S
End
augment(L2,-seq(L1(X),X,dim(L1),1,-1)->L2
0->dim(L1
1->C
{0,1->L3
For(I,1,dim(L2
L2(I->M
If M>=0:Then
M->L1(dim(L1)+1
Else
If C:Then
L1(dim(L1)-1
Goto S
Lbl A
Ans->Str1
L1(dim(L1->L1(dim(L1)-1
dim(L1)-1->dim(L1
0->C
End
Str1+" "+sub("*+/-",-M,1)+" ->Str1
L1(dim(L1
Goto S
Lbl B
Str1+Ans->Str1
dim(L1)-1->dim(L1
End
End
Goto F
Lbl S
L3Ans->L4
LinReg(ax+b) L3,L4,Y1
Equ►String(Y1,Str2
sub(Str2,1,length(Str2)-3
If C:Goto A
Goto B
Lbl F
Str1
```
## General explanation
Here's the key I worked with while developing the program:
```
Str1 The input string.
Str2 Counter variable (e.g. current character)
Str3 The current token being built.
L1 The operator stack
L2 The output queue
L3 Temporary list
L4 Temporary list
I Iterator index
T Type of token (enum)
S Type of previous token (enum)
M Temporary variable
C Conditional variable
Token Types (T)
0 Undefined
1 Number
2 Operator
3 Open Parenthesis
Operator Elements
0 left parenthesis ("(")
1 multiplication ("*")
2 addition ("+")
3 division ("/")
4 subtraction ("-")
5 right parenthesis (")")
Precedence Rule: Remainder(prec, levelno)
0 - add, sub
1 - mul, div
(levelno = 2)
```
And here is the equivalent, hand-written JavaScript code I used to test and develop this program.
```
let Str1, Str2, Str3, L1, L2, I, S, T, M, C;
let error = (type, ...args) => {
let message = "ERR:" + type + " (" + args.join("; ") + ")";
throw new Error(message);
};
let isInteger = (n) => n == Math.floor(n);
let inString = (haystack, needle, start=1) => {
if(start < 1 || !isInteger(start)) {
error("DOMAIN", haystacak, needle, start);
}
let index = haystack.indexOf(needle, start - 1);
return index + 1;
};
let sub = (string, start, length) => {
if(start < 1 || length < 1 || !isInteger(start) || !isInteger(length)) {
error("DOMAIN", string, start, length);
}
if(start + length > string.length + 1) {
error("INVALID DIM", string, start, length);
}
return string.substr(start - 1, length);
}
let fPart = (value) => value - Math.floor(value);
// Input "", Str1
Str1 = process.argv[2];
// 0->dim(L1
L1 = [];
// 0->dim(L2
L2 = [];
// 1->I
I = 1;
// DelVar S
S = 0;
// While I<=length(Str1
while(I <= Str1.length) {
// DelVar T
T = 0;
// Disp "Starting",I
console.log("Starting, I =", I);
// " read token
// ".->Str3
Str3 = ".";
// 1->C
C = 1;
// While C and I<=length(Str1
while(C && I <= Str1.length) {
// sub(Str1,I,1->Str2
Str2 = sub(Str1, I, 1);
// inString("0123456789",Str2->C
C = inString("0123456789", Str2);
// If C:Then
if(C) {
// I+1->I
I++;
// 1->T
T = 1;
// Str3+Str2->Str3
Str3 += Str2;
}
}
// If T=0:
if(T == 0) {
// console.log("Huh?T=0?", Str3, Str2);
// Str3+Str2->Str3
Str3 += Str2;
}
// " remove placeholder character
// sub(Str3,2,length(Str3)-1->Str3
Str3 = sub(Str3, 2, Str3.length - 1);
// " number
// If T=1:Then
if(T == 1) {
// expr(Str3->L2(1+dim(L2
L2[L2.length] = eval(Str3);
}
// Disp "Str3",Str3
console.log("post processing, Str3 = \"" + Str3 + "\"");
// inString("*+/-",Str3->M
M = inString("*+/-", Str3);
// " operator
// If M:Then
if(M) {
// I+1->I
I++;
// 2->T
T = 2;
// Disp "op",M,dim(L1
console.log("op", M, L1.length);
// " parse previous operators
// 1->C
C = 1;
// While C
while(C) {
// dim(L1->C
C = L1.length;
// If C:Then
if(C) {
// 2fPart(L1(dim(L1))/2)>2fPart(M/2->C
C = 2 * fPart(L1[L1.length - 1] / 2) > 2 * fPart(M / 2);
// If C:Then
if(C) {
// ~L1(dim(L1->L2(1+dim(L2
L2[L2.length] = -L1[L1.length - 1];
// dim(L1)-1->dim(L1
L1.length--;
}
}
}
// " push current operator
// M->L1(1+dim(L1
L1[L1.length] = M;
}
// If Str3="(":Then
if(Str3 == "(") {
// 3->T
T = 3;
// If S=1:Then
if(S == 1) {
// sub(Str1,1,I-1)+"*"+sub(Str1,I,length(Str1)-I+1)->Str1
Str1 = sub(Str1, 1, I - 1) + "*" + sub(Str1, I, Str1.length - I + 1);
}
// Else
else {
// I+1->I
I++;
// 0->L1(dim(L1)+1
L1[L1.length] = 0;
}
// End
}
// If Str3=")":Then
if(Str3 == ")") {
// I+1->I
I++;
// While L1(dim(L1
while(L1[L1.length - 1]) {
// ~L1(dim(L1->L2(1+dim(L2
L2[L2.length] = -L1[L1.length - 1];
// dim(L1)-1->dim(L1
L1.length--;
}
// End
// dim(L1)-1->dim(L1
L1.length--;
}
// Disp "Ending",I
console.log("Ending", I);
// T->S
S = T;
// Pause
console.log("-".repeat(40));
}
// augment(L2,-seq(L1(X),X,dim(L1),1,-1)->L2
L2 = L2.concat(L1.map(e => -e).reverse());
// Disp L1, L2
console.log("L1", L1);
console.log("..", "[ " + L1.map(e=>"*+/-"[e-1]).join`, ` + " ]");
console.log("L2", L2);
console.log("..", "[ " + L2.map(e=>e<0?"*+/-"[~e]:e).join`, ` + " ]");
// post-processing
let res = "";
// 0->dim(L1
L1.length = 0;
// 1->C
C = 1;
// For(I,1,dim(L2
for(I = 1; I <= L2.length; I++) {
// L2(I->M
M = L2[I - 1];
// If M>=0:Then
if(M >= 0) {
// M->L1(dim(L1)+1
L1[L1.length] = M;
}
// Else
else {
// If C:Then
if(C) {
// L1(dim(L1)-1
// Goto ST
// Lbl A0
// Ans->Str1
res += L1[L1.length - 2];
// L1(dim(L1->L1(dim(L1)-1
L1[L1.length - 2] = L1[L1.length - 1];
// dim(L1)-1->dim(L1
L1.length--;
// 0->C
C = 0;
}
// End
// Str1+" "+sub("*+/-",-M,1)+" ->Str1
res += " " + "*+/-"[-M - 1] + " ";
// L1(dim(L1
// Goto ST
// Lbl A1
// Str1+Ans->Str1
res += L1[L1.length - 1];
// dim(L1)-1->dim(L1
L1.length--;
}
}
// Goto EF
// Lbl ST
// L3Ans->L4
// LinReg(ax+b) L3,L4,Y1
// Equ►String(Y1,Str2
// sub(Str2,1,length(Str2)-3
// If C:Goto A0
// Goto A1
// Lbl EF
// Str1
console.log(res);
```
I will provide a more in-depth explanation once I'm sure I'm done golfing, but in the meantime, this might help provide a cursory understanding of the code.
[Answer]
# Python 3. ~~337~~ 327 - 10% = 295 bytes
Supports floating-point and unlimited levels of parentheses, so qualifies for **bonus -10%.**
```
import re
def v(s):
if s[:1]=='(':l,s=e(s[1:]);return l,s[1:]
m=re.match(r"\d+\.?\d*|\.\d+",s)
if m:return[m.group()],s[m.end():]
def b(s,f,*O):
l,s=f(s)
while s[:1]in O:
o=s[0]
r,s=f(s[1:])
if len(r)>1:l,r=r,l
l+=[o]+r
return l,s
m=lambda s:b(s,v,'*','/')
e=lambda s:b(s,m,'+','-')
print(' '.join(e(input())[0]))
```
[Answer]
## Javascript (ES6), 535 - 80 (15% bonus) = 455 bytes
```
f=z=>{a=[],i=0;c=n=>{while(n[M='match'](/\(/)){n=n[R='replace'](/\(([^()]+)\)/g,(q,p)=>{m=++i;a[m]=c(p);return'['+m+']'})}n=n[R](/(\](?=\[|[\d])|[\d](?=\[))/g,'$1*');n=n[R](/\[?[\d\.]+\]?[*/]\[?[\d\.]+\]?/g,q=>{a[++i]=q;return'['+i+']'});n=n[R](/([\d.]+)\+(\[[\d]+\])/g,'$2+$1');while(n[M](/\[/)){n=n[R](/(\[?[\d\.]+\]?)\*(\[?[\d\.]+\]?)/g,(q,p,r)=>{t=a[r[R](/[\[\]]/g,'')];return r[M](/\[/)?(t&&t[M](/\+|\-/)?(r+'*'+p):q):q});n=n[R](/\[(\d+)\]/g,(q,p)=>{return a[p]+(a[p][M](/\+|-/)?'=':'')})}return n};return c(z)[R](/./g,'$& ')+'='}
```
Not a minimal solution I'm sure, but pretty complete, allowing for all three bonuses. Some instances require multiple pressings of equals key, but do not require clearing of calculator contents. (ex. 3,5,6 & 7 in fiddle)
Link to JSFiddle with some tests: <https://jsfiddle.net/2v8rkysp/3/>
Here's some unfolded, semi-unobfuscated code with a few comments for good measure.
```
function f(z) {
var a=[],i=0;
function c(n) {
//// Tokenize parentheses groups recursively
while (n.match(/\(/)) {
n = n.replace(/\(([^()]+)\)/g, function(q,p) {
m = ++i;
a[m]=c(p);
return '['+m+']';
});
}
//// Allow implied multiplication with parentheses
n = n.replace(/(\](?=\[|[\d])|[\d](?=\[))/g, '$1*');
//// Tokenize mult/division
n = n.replace(/\[?[\d\.]+\]?[*\/]\[?[\d\.]+\]?/g, function(q) {
a[++i]=q;
return '['+i+']';
});
//// Move addition tokens to the front
n = n.replace(/([\d.]+)\+(\[[\d]+\])/g,'$2+$1');
//// Detokenize
while (n.match(/\[/)) {
//// If a token includes addition or subtraction,
//// move it to the front of other tokens
n = n.replace(/(\[?[\d\.]+\]?)\*(\[?[\d\.]+\]?)/g,function(q,p,r) {
t=a[r.replace(/[\[\]]/g,'')];
return r.match(/\[/)?(t&&t.match(/\+|\-/)?(r+'*'+p):q):q;
});
//// If a token includes addition or subtraction,
//// add the equals keypress
n = n.replace(/\[(\d+)\]/g, function(q,p) {
return a[p]+(a[p].match(/\+|-/)?'=':'');
});
}
return n;
}
//// Add spaces and final equals keypress
return c(z).replace(/./g, '$& ')+'=';
}
```
] |
[Question]
[
I like making dank memes out of my own images. But all those so called "quick meme" sites just have *too much code*. I realized that the only way to make the dankest meme generator is to ask you guys at PPCG to golf one for me. So let me give you the low down on what you have to do.
# Specs
* Take an image as input as a file name, image object, etc. to make a meme out of.
* Then take two strings for top text and bottom text (with no line breaks).
* Render the text on the image in size 22pt Impact white font with 5px black outline (You can assume Impact is installed.
* The text should be centered horizontally.
* You can assume the text fits horizontally.
* The respective texts should be 10px from the top and 8px from the bottom.
* Then output the image by saving in a file, displaying, etc.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
Happy Memeing!
[Answer]
## HTML/JS/CSS, ~~341~~ ~~329~~ 300 bytes
```
<input onblur=i.src=this.value><table><td><img id=i><p style=top:10px contenteditable><p style=bottom:8px contenteditable></p><style>td{position:relative}p{position:absolute;margin:0;width:100%;text-align:center;font:22px Impact;color:#fff;text-shadow:0 0 5px #000,0 0 5px #000,0 0 5px #000,0 0 5px #000}
```
To use: First paste the desired image URL into the provided input box, then tab to the top text and type in the desired text, then tab to the bottom text and type in the desired text.
Edit: Saved 12 bytes thanks to @Downgoat. Saved a further 29 bytes thanks to @dev-null.
```
td {
position: relative;
}
div {
position: absolute;
left: 0;
right: 0;
text-align: center;
font: 22px "Impact";
color: #fff;
text-shadow: 0 0 5px #000, 0 0 5px #000, 0 0 5px #000, 0 0 5px #000;
}
```
```
<input onchange="i.src=this.value">
<table>
<td>
<img id=i>
<div style="top: 10px;" contenteditable></div>
<div style="bottom: 8px;" contenteditable></div>
```
[Answer]
# Jelly, 141 bytes
```
⁴;@€“¢ÇẎȧsẊỊ>ɼẈAẋ®ŀȮĠq⁼ṫṁḢĠZỴċƊ£²ÆṗÑḊ°>oÆl{(¢ɗpḅ]µṖÑb¹ƁịṾ¦Ç\ṭO4»“1kịXḥɗ"Ụɦḷ©Ƈ&Ṭ19“£ŀ³³.Ṗ<ṂqṬỵ.ṣȦƇƈ2ƭḂXƊ»ż³;“ßƑ_!]²Rȧ⁵⁴°ṁD⁽a{⁼!z¿ıṾƇDẇḤḶṡÇẈg»;
```
[Try it online!](http://jelly.tryitonline.net/#code=4oG0O0DigqzigJzCosOH4bqOyKdz4bqK4buKPsm84bqIQeG6i8KuxYDIrsSgceKBvOG5q-G5geG4osSgWuG7tMSLxorCo8Kyw4bhuZfDkeG4isKwPm_Dhmx7KMKiyZdw4biFXcK14bmWw5FiwrnGgeG7i-G5vsKmw4dc4bmtTzTCu-KAnDFr4buLWOG4pcmXIuG7pMmm4bi3wqnGhybhuawxOeKAnMKjxYDCs8KzLuG5ljzhuYJx4bms4bu1LuG5o8imxofGiDLGreG4gljGisK7xbzCszvigJzDn8aRXyFdwrJSyKfigbXigbTCsOG5gUTigb1he-KBvCF6wr_EseG5vsaHROG6h-G4pOG4tuG5ocOH4bqIZ8K7Ow&input=&args=ImdvYXQuanBnIg+IlVwZ29hdCBsaW5lIiwiRG93bmdvYXQgbGluZSI)
Takes command line arguments as in the example, and returns a HTML file. The result looks like this in Chrome:
[](https://i.stack.imgur.com/17ZVd.jpg)
[Answer]
# bash+imagemagick+gs ~~690 575 456~~ 440 bytes
See earlier revisions for "ungolfed" code.
```
#!/bin/bash
d=`identify $1|cut -d' ' -f3`
x=`echo $d|cut -d'x' -f1`
y=`echo $d|cut -d'x' -f2`
convert $1 $1.eps
gs -g"$d" -o $1.png -sDEVICE=png48 -c "
/s/showpage load def/showpage{}def($1.eps)run
matrix defaultmatrix setmatrix/Helvetica-Bold 22
selectfont/c{dup stringwidth pop neg 2 div 0 rmoveto dup
gsave 1 setgray show grestore 0 setgray false charpath stroke}def
$x 2 div $y 42 sub moveto($2)c $x 2 div 8 moveto($3)c s"
echo :$1.png
```
eg.
```
./meme.sh Superman1.jpg "I AM CORNHOLIO" "Are you threatening me??!"
GPL Ghostscript 9.15 (2014-09-22)
Copyright (C) 2014 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Loading NimbusRomNo9L-Regu font from /usr/share/ghostscript/9.15/Resource/Font/NimbusRomNo9L-Regu... 4186304 2700982 3995248 2685490 2 done.
Loading NimbusSanL-Bold font from /usr/share/ghostscript/9.15/Resource/Font/NimbusSanL-Bold... 4203248 2760390 3833712 2536130 1 done.
:Superman1.jpg.png
```
[](https://i.stack.imgur.com/j1N1I.png)
] |
[Question]
[
You are paddling a canoe down a fairly fast whitewater river. Suddenly, your paddles explode, and you find yourself in a dangerous situation hurtling down a river rapid without any paddles. Luckily, you still have your programming skills, so you decide to carve a program on the side of your canoe to help you survive the rapids. However, there is not much surface area on the side of the canoe to write your program with, so you must make the program as short as possible.
The river can be represented as an 8 by 16 grid. We will label the columns with the numbers `0` to `7` and the rows with the numbers `0` to `15`.
```
y
--------15
--------14
--------13
--------12
--------11
--------10
--------9
--------8
--------7
--------6
--------5
--------4
--------3
--------2
--------1
--------0
01234567
x
```
*Above: A completely calm, ordinary river with no obstructions. Naturally, this is not the river you are on.*
You begin at the coordinate (4, 0) and from there move uncontrollably up the river (i.e. the vector `(0,1)`) until you hit a rock (represented by an `o` in these examples). When you hit a rock, you will have a 55% chance of moving past the rock to the left (i.e. the vector `(-1,1)`) and a 45% chance of moving past the rock to the right (i.e. the vector `(1,1)`). If the canoe is on the far left or right columns, it will always move towards the centre. If there are no rocks, it will move straight upwards.
```
y
----x---15
----xo--14
-o--x---13
----x---12
---ox---11
---x----10
---xo---9
---ox---8
----xo--7
-----x--6
----ox--5
-o--x---4
----x---3
----xo--2
----x---1
----x---0
01234567
```
*Above: A possible route the canoe might take, represented using the character `x`*
Given the map of the river, write a program that will output the probability of the canoe finishing at a given column.
Accept input in whichever method is convenient for your program (e.g. STDIN, command line argument, `raw_input()`, reading from a file, etc). The first part of the input is a single integer from 0 to 7, representing the column the program will find the probability for. Following that is a list of tuples in the form `x,y` representing the position of the stones.
An example:
Input:
```
4 4,1 5,5 3,5
```
This would indicate a river with rocks at the positions (4,1), (5,5), and (3,5), and asks for the probability of the canoe ending at the 4th column.
Output:
```
0.495
```
Note that in this example, the positions of the rocks were symmetrical, allowing the problem to be solved with a binomial distribution. This won't always be the case!
Also, the river will always be crossable. That is, there will never be two rocks that are positioned adjacent to each other horizontally. See [Glenn's comment](https://codegolf.stackexchange.com/questions/36337/extreme-whitewater-canoeing#comment81244_36337) for an example of an impossible case.
This is code golf, so lowest number of characters wins. Feel free to ask questions in the comments if the specification isn't clear.
[Answer]
# Ruby, ~~204~~ ~~191~~ 172 characters
```
c,*r=gets.split
o=[0]*8
s=->x,y,p{y>14?o[x]+=p :(r.index("#{x},#{y+=1}")?(x<1?s[x+1,y,p]:(x>6?s[x-1,y,p]:(s[x-1,y,p*0.55]+s[x+1,y,p*0.45]))):s[x,y,p])}
s[4,0,1]
p o[c.to_i]
```
It recursively simulates all possibly outcomes while keeping track of each individual outcome's probability, then it adds that probability to a cumulative counter when `y == 15`.
Fancy tricks:
* `c,*r=gets.split` - the "splat" operator (`*`) takes all the remaining elements of `gets.split` and sticks them in the `r` array
* ~~`next {something} if {condition}`: essentially equivalent to~~
```
if {condition}
{something}
return
end
```
"Discovered" by evolving from `if condition; something; return; end` to `return something if condition` to `break something if condition`, and then I figured I would try a shorter "loop operator" to see if it would work (which it did, of course).
* Thanks to @MartinBüttner for suggesting to use chained ternary operators (which ended up becoming the enormous third line in the golfed code above) and eliminating the above point (which saved 19 (!) characters).
I did use a somewhat fancy trick with those, though: I realized that `s[foo],s[bar]` doesn't work in Ruby for two method calls in one statement. So at first I changed it to `(_=s[foo],s[bar])` (a dummy variable), but then I realized I could just add and throw away the return values: `s[foo]+s[bar]`. This only works because calls to `s` will only ever "return" other calls to `s` or a number (`o[x]+=p`), so I don't have to worry about checking for `nil`.
* Other various optimizations: `p` instead of `puts` for printing numbers, `<1` instead of `==0` (since the canoe never leaves the river) and similar comparisons elsewhere, `[0]*8` for initial probabilities as Ruby's numbers are always "pass by value"
Ungolfed:
```
column, *rocks = gets.chomp.split
outcomes = Array.new(8, 0)
simulate = -> x, y, probability {
if y == 15
outcomes[x] += probability
elsif rocks.index("#{x},#{y + 1}")
case x
when 0 then simulate[x + 1, y + 1, probability]
when 7 then simulate[x - 1, y + 1, probability]
else
simulate[x - 1, y + 1, probability * 0.55]
simulate[x + 1, y + 1, probability * 0.45]
end
else
simulate[x, y + 1, probability]
end
}
simulate[4, 0, 1.0]
p outcomes
puts outcomes[column.to_i]
```
[Answer]
## C# ~~418~~ 364bytes
Complete C# program expecting input from STDIN. Works by reading the rocks into an array of all locations in the river, effectively creating a map, and then it just performs 16 iterations of moving probabilities around an 8-width decimal array before outputting the result.
```
using C=System.Console;class P{static void Main(){var D=C.ReadLine().Split();int i=0,j=D.Length;var R=new int[8,16];var p=new decimal[8];for(p[4]=1;--j>0;)R[D[j][0]-48,int.Parse(D[j].Substring(2))]=1;for(;i<16;i++){var n=new decimal[j=8];for(;j-->0;)if(R[j,i]>0){n[j<1?1:j-1]+=p[j]*0.55M;n[j>6?6:j+1]+=p[j]*0.45M;}else n[j]+=p[j];p=n;}C.WriteLine(p[D[0][0]-48]);}}
```
Formatted code:
```
using C=System.Console;
class P
{
static void Main()
{
var D=C.ReadLine().Split();
int i=0,j=D.Length;
var R=new int[8,16];
var p=new decimal[8];
for(p[4]=1;--j>0;) // read rocks into map (R)
R[D[j][0]-48,int.Parse(D[j].Substring(2))]=1;
for(;i<16;i++) // move up the river
{
var n=new decimal[j=8];
for(;j-->0;)
if(R[j,i]>0)
{ // we hit a rock!
n[j<1?1:j-1]+=p[j]*0.55M;
n[j>6?6:j+1]+=p[j]*0.45M;
}
else
n[j]+=p[j];
p=n; // replace probability array
}
C.WriteLine(p[D[0][0]-48]); // output result
}
}
```
[Answer]
### GolfScript, 105 characters
```
~](\2/:A;8,{4=}%15,{:B;{20*}%A{~B={[\\,.1,*\[2$=..20/9*:C-\~)C]+(1,\+1,6*2$8>+]zip{{+}*}%.}*;}/}/=20-15?*
```
A GolfScript version which became much longer than intended - but each attempt with a different approach was even longer. The input must be given on STDIN.
Example:
```
> 4 4,1 5,5 3,5
99/200
```
*Annotated code:*
```
# Evaluate the input
# - stack contains the first number (i.e. column)
# - variable A contains the rock coordinates (pairs of X y)
# where X is an array of length x (the coordinate itself)
~](\2/:A;
# Initial probabilities
# - create array [0 0 0 0 1 0 0 0] of initial probabilities
8,{4=}%
# Loop over rows
15,{:B; # for B = 0..14
{20*}% # multiply each probability by 20
A{ # for each rock
~B={ # if rock is in current row then
# (prepare an array of vectors [v0 vD vL vR]
# where v0 is the current prob. before rocks,
# vD is the change due to rocks,
# vL is a correction term for shifting out to the left
# and vR the same for the right side)
[\\ # move v0 inside the array
, # get x coordinate of the rock
.1,* # get [0 0 ... 0] with x terms
\[2$= # get x-th item of v0
..20/9*:C- # build array [0.55P -P 0.45P]
\~)C]+ # and append to [0 0 ... 0]
(1,\+ # drop the leftmost item of vD and prepend [0] again
# which gives vL
1,6*2$8>+ # calculate vR using the 8th item of vD
] #
zip{{+}*}% # sum the columns of this list of vectors
. # dummy dup for end-if ;
}*; # end if
}/ # end for
}/ # end for
# take the n-th column and scale with 20^-15
=
20-15?*
```
[Answer]
# Haskell, 256 bytes
```
import Data.List
m=map;v=reverse
a p n x=take n x++(x!!n+p:drop(n+1)x)
l=abs.pred
o[_,n]s=n#(s!!n)$s
n#p=a(11*p/20)(l n).a(9*p/20)(7-(l$7-n)).a(-p)n
b=0:0:0:0:1:b
k(c:w)=(foldl1(.)$m o$v$sort$m(v.read.('[':).(++"]"))w)b!!read c
main=getLine>>=print.k.words
```
Here is a very ungolfed version along with some tricks that were used:
```
import Data.List
-- Types to represent the distribution for the canoe's location
type Prob = Double
type Distribution = [Prob]
-- Just for clarity..
type Index = Int
-- An Action describes some change to the probability distribution
-- which represents the canoe's location.
type Action = Distribution -> Distribution
-- Helper to add k to the nth element of x, since we don't have mutable lists.
add :: Index -> Prob -> Action
add n k x = take n x ++ [p] ++ drop (n + 1) x
where p = k + x!!n
-- A trick for going finding the index to the left of n,
-- taking the boundary condition into account.
leftFrom n = abs (n - 1)
-- A trick for getting the other boundary condition cheaply.
rightFrom = mirror . leftFrom . mirror
where mirror = (7 -)
-- Make the action corresponding to a rock at index n.
doRock :: Index -> Action
doRock n p = (goLeft . goRight . dontGoForward) p
where goLeft = (leftFrom n) `add` (p_n * 11/20)
goRight = (rightFrom n) `add` (p_n * 9/20)
dontGoForward = (at n) `add` (-p_n)
p_n = p!!n
at = id
initialProb = [0,0,0,0,1,0,0,0]
-- Parse a pair "3,2" ==> (3,2)
readPair :: String -> (Index,Index)
readPair xy = read $ "(" ++ xy ++ ")"
-- Coordinate swap for the sorting trick described below.
swap (x,y) = (y,x)
-- Put it all together and let it rip!
main = do
input <- getLine
let (idx : pairs) = words input
let coords = reverse . sort $ map (swap . readPair) pairs
let rockActions = map (doRock . snd) coords
let finalProb = (foldl1 (.) rockActions) initialProb
print $ (finalProb !! read idx)
```
The last trick I used was to note that you can act as if rocks in a single row are actually separated by some infinitesimal amount. In other words, you can apply the probability distribution transformer for each rock in the same row sequentially and in whatever order you want, rather than applying them all simultaneously. This only works because the problem disallows two horizontally adjacent rocks.
So the program turns each rock's location into a probability distribution transformer, ordered by the rock's y coordinate. The transformers are then just chained in order and applied to the initial probability distribution. And that's that!
[Answer]
# Haskell, 237
I just hope the canoe comes with ghc installed...
The trick with the infinite list is stolen from Matt Noonan, kudos to him!
```
import Data.List
r=reverse
(a:b:x)%0=0:a+b:x
x%7=r(r x%0)
x%n=take(n-1)x++(x!!(n-1)+x!!n*0.55:0:x!!(n+1)+x!!n*0.45:drop(n+2)x)
q=0:0:0:0:1:q
u(w:x)=(foldl(%)q.map last.sort.map(r.read.('[':).(++"]"))$x)!!read w
main=interact$show.u.words
```
I hope I got the logic right, but Matt's example `"5 4,4 1,5 5,3 3,6 2,9 4,12 3,13"` yields `0.5613750000000001` and OP's example `"4 4,1 5,5 3,5"` yields `0.49500000000000005`, which seems to be correct apart from some floating point errors.
Here it is in action:
```
>>> echo 5 4,4 1,5 5,3 3,6 2,9 4,12 3,13 | codegolf
0.5613750000000001
```
[Answer]
# Perl 169 Bytes
Reads from STDIN.
```
$_=<>;s/ (.),(\d+)/$s{$1,$2}=1/eg;/./;$x{4}=1.0;for$y(1..15){for$x(0..7){if($s{$x,$y}){$x{$x-1}+=$x{$x}*($x%7?.55:1);$x{$x+1}+=$x{$x}*($x%7?.45:1);$x{$x}=0}}}print$x{$&}
```
Pretty straight forward, implicitly uses columns -1 and 8 to smoothen border cases. Probabilities can safely be propagated to each next level because there arent any adjacent stones, thus a single run suffices.
[Answer]
## PHP, 358
Using brainpower to determine the possible paths and their probabilities is hard, and would probably require more code than simply simulating 1,000,000 canoe accidents. *Oh, the humanity!*
```
define('MX',7);
define('MY',16);
define('IT',1000000);
error_reporting(0);
function roll(){return rand()%100 > 44;}
function drift($rocks,$print=false) {
for($px=4,$py=0;$py<MY;$py++) {
if(isset($rocks[$px][$py])){
if(roll()) $px--;
else $px++;
}
else if($px==0) $px++;
else if($px==MX) $px--;
if($print) {
for($i=0;$i<MX;$i++){
if($i==$px) echo 'x';
else if(isset($rocks[$i][$py])) echo 'o';
else echo '-';
}
echo " $py\n";
}
}
return $px;
}
$input = $argv[1];
$tmp = explode(' ',$input);
$end_target = array_shift($tmp);
$rocks = array();
array_map(function($a) use(&$rocks) {
list($x,$y) = explode(',',$a);
$rocks[$x][$y]=1;
}, $tmp);
$results=array();
for($i=0;$i<IT;$i++) {
$results[drift($rocks)]++;
}
drift($rocks, true); // print an example run
foreach($results as $id=>$result) {
printf("%d %0.2f\n", $id, $result/IT*100);
}
```
Example:
```
php river.php "4 4,1 5,5 3,3 6,2 9,4 12,3 13,5"
----x-- 0
---xo-- 1
---x--o 2
--xo--- 3
--x---- 4
--x--o- 5
--x---- 6
--x---- 7
--x---- 8
--x---- 9
--x---- 10
--x---- 11
--x---- 12
--x---- 13
--x---- 14
--x---- 15
4 49.53
2 30.18
6 20.29
```
Golfed:
```
<? function d($r){for($x=4,$y=0;$y<16;$y++){if(isset($r[$x][$y])){if(rand()%100>44)$x--;else $x++;}elseif($x==0)$x++;elseif($x==7)$x--;}return $x;}$t=explode(' ',$argv[1]);$e=array_shift($t);$r=array();array_map(function($a)use(&$r){list($x,$y)=explode(',',$a);$r[$x][$y]=1;},$t);$c=0;for($i=0;$i<1000000;$i++){if(d($r)==$e)$c++;}printf("%.4f", $c/1000000);
```
This version does not do any pretty printing and outputs the float probability of the canoe landing at the specified position.
```
# php river_golf.php "4 4,1 5,5 3,3 6,2 9,4 12,3 13,5"
0.4952
```
[Answer]
## PHP, 274
I can't read/write GolfScript to save my life, but glancing over @Howard's submission pointed me in a better direction than simply simulating 1 million canoe accidents.
Starting with an array of probabilities for starting positions we can simply split those numbers each time a rock is encountered.
```
function psplit($i){ return array(.55*$i,.45*$i); }
function pt($a) {
foreach($a as $p) {
printf("%1.4f ", $p);
}
echo "\n";
}
$input = $argv[1];
$tmp = explode(' ',$input);
$end_target = array_shift($tmp);
$rocks = array();
array_map(function($a) use(&$rocks) {
list($x,$y) = explode(',',$a);
$rocks[$x][$y]=1;
}, $tmp);
$state = array(0,0,0,0,1,0,0,0);
pt($state);
for($y=1;$y<16;$y++){
for($x=0;$x<8;$x++){
if(isset($rocks[$x][$y])){
echo(' o ');
list($l,$r)=psplit($state[$x]);
$state[$x]=0;
$state[$x-1]+=$l;
$state[$x+1]+=$r;
} else { echo ' - '; }
}
echo "\n";
pt($state);
}
```
Example Output:
```
# php river2.php "4 4,1 5,5 3,3 6,2 9,4 12,3 13,5"
0.0000 0.0000 0.0000 0.0000 1.0000 0.0000 0.0000 0.0000
- - - - o - - -
0.0000 0.0000 0.0000 0.5500 0.0000 0.4500 0.0000 0.0000
- - - - - - o -
0.0000 0.0000 0.0000 0.5500 0.0000 0.4500 0.0000 0.0000
- - - o - - - -
0.0000 0.0000 0.3025 0.0000 0.2475 0.4500 0.0000 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.2475 0.4500 0.0000 0.0000
- - - - - o - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
- - - - - - - -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
```
Golfed:
```
<? $t=explode(' ',$argv[1]);$e=array_shift($t);$r=array();foreach($t as $n){list($j,$k)=explode(',',$n);$r[$j][$k]=1;}$s=array(0,0,0,0,1,0,0,0);for($y=1;$y<16;$y++){for($x=0;$x<8;$x++){if(isset($r[$x][$y])){$s[$x-1]+=$s[$x]*.55;$s[$x+1]+=$s[$x]*.45;$s[$x]=0;}}}echo $s[$e];
```
Example run:
```
# php river2_golf.php "4 4,1 5,5 3,3 6,2 9,4 12,3 13,5"
0.495
```
] |
[Question]
[
You are going to be planting pumpkins soon, and you are preparing your supplies. Pumpkins come in all sorts of sizes and have their sizes written on the seed bag. A pumpkin that is size n will grow to be n units wide. However pumpkins need their space.
If a pumpkin is stuck between two other pumpkins with not enough space to reach its full size it will be ruined. So you want to make a program that takes a plan of how you are going to plant your pumpkins and determines if there is enough space for all the pumpkins.
As input it will take a list of non-negative integers. A zero will represent space with no pumpkins planted, and a positive number will represent that a pumpkin of that size will be planted there. So for example:
```
[0,0,0,1,0,0,0,0,0,5,0,0,0,6,0,0]
```
There are three pumpkins planted here of sizes `1`, `5` and `6`.
A pumpkin will grow to fill as much space as is given, but it can't detach from it's root, and it can't grow past the fence (the start and end of the list).
So for example in the above the 5 pumpkin *could* grow as follows:
```
[0,0,0,1,0,0,0,0,0,5,0,0,0,6,0,0]
^^^^^^^^^
```
Since that is 5 units wide and contains the place we planted it. But it *can't* grow like:
```
[0,0,0,1,0,0,0,0,0,5,0,0,0,6,0,0]
^^^^^^^^^
```
Because even though that is 5 units wide it doesn't include the root.
In perhaps a miracle of nature, pumpkins will push each other out of the way if they get in space they need. So for example if the `5` starts growing to the right, the `6` will push it back to the left since it needs that space.
Ultimately this means if there is a valid way for the pumpkins to grow without ruining each other they will.
It's only when there isn't enough space at all will a pumpkin get ruined.
So in the example everything is ok, this plan works:
```
[0,0,0,1,0,5,5,5,5,5,6,6,6,6,6,6]
```
But here:
```
[6,0,0,0,0,3,0,0,0,0,0]
```
There's not enough space for the `6` to grow even when the `3` grows as far to the right as possible
## Task
Take as input a non-empty list of non-negative integers. Output whether that list is a working plan. You should output one of two distinct values if it is a working plan and the other if it is not.
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 scored in bytes.
## Test cases
```
[1] -> True
[0,0] -> True
[3] -> False
[3,0] -> False
[3,0,0,2,0] -> True
[0,3,0,4,0,0,0] -> True
[0,0,1,0,3,1,0,0] -> False
[0,0,0,1,0,0,0,0,0,5,0,0,0,6,0,0] -> True
[6,0,0,0,0,3,0,0,0,0,0] -> False
[0,0,5,0,0,1] -> True
[2,0,2] -> False
[0,0,2,2] -> False
[2,2,0,0] -> False
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Hmm, I don't think we want any `ṀȯLƊ` on our pumpkins :( I also feel like this is beatable\*!
```
ŒṖṀȯLƊ⁼LƊȧTE$Ɗ€Ȧ$ƇẸ
```
A monadic Link accepting a list that yields `1` if a valid plan or `0` otherwise.
**[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3c2XBivc@xrkeNe4DkieUhripATtOaE8tUjrU/3LXj////0QY6BjqGQGwMJg1iAQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opIc7pz3c2XBivc@xrkeNe4DkieUhripATtOaE8tUjrU/3LUDrGqGzuH2rEcNcxR07RQeNczVjPz/PzraMFYn2kDHAEgagzCEpQMU0TECsw10QDwTsAiEb6BjqAMSNUQSgYjBoCmUNoOqMIPLGCNUQXVC1IJcYQSyEypqBGYZgdwAVBkLAA "Jelly – Try It Online").
### How?
```
ŒṖṀȯLƊ⁼LƊȧTE$Ɗ€Ạ$ƇẸ - Link: list of integers, Plan
ŒṖ - all ways to partition Plan
Ƈ - filter keep those partitions for which:
$ - last two links as a monad:
Ɗ€ - for each part, last three links as a monad:
Ɗ - last three links as a monad:
Ɗ - last three links as a monad:
Ṁ - maximum of the part
L - length of the part
ȯ - logical OR
L - length of the part
⁼ - equal? (1 if enough space for the largest pumpkin
ignoring others in the part; 0 otherwise)
$ - last two links as a monad:
T - truthy indices
E - all equal? (1 for those parts with up to one
non-zero; 0 otherwise)
ȧ - logical AND (1 for good parts; 0 otherwise)
Ạ - all? (1 for good partitions; 0 otherwise)
Ẹ - any? (1 if the plan will work; 0 otherwise)
```
---
\* Maybe it's not that bad...
This [different approach](https://tio.run/##y0rNyan8///hjq5HjTsO7TzW/nDHokO7Qx7umA/EXSppXiD@kkMLH@6cdWjr4Qk@D3ft@H@4/VHTmqOTHu6c8f9/dLRhrE60gY4BkDQGYQhLByiiYwRmG@iAeCZgEQjfQMdQByRqiCQCEYNBUyhtBlVhBpcxRqiC6oSoBbnCCGQnVNQIzDICuQGoMhYA "Jelly – Try It Online") is much more efficient but a couple of bytes longer (greedily grow the outermost pumpkin using outer zeros if possible) - outputs `0` if the plan is valid or `1` otherwise:
```
Ḋ⁸¹ƇḢ»TḟTḊ$fJḢ¤¡ṚµÐLẸ
```
[Answer]
# [Python 3](https://docs.python.org/3/), 73 72 67 bytes
```
f=lambda p,*v,s=0:p*s<1==f(*v,s=max(s+p,0<p or s)-1)if v else p+s<2
```
[Try it online!](https://tio.run/##XZDBjsIgEIbvfYoJJ9CpgXbXgykefYK96R7YLM2S0JYUbPTpK9SuVpkD/PN/M2HGXcNf15bjWEurmp9fBQ5XA3rJd27lKyFlTSfdqAv1a4e8ctD14FkumKlhAG29Brf2VTEG7QNIIIScsqP4hnwPX/1ZZ0eOfKHK6X1QsTCK2XrKGMULzzFlPybnNc9RYHLFw5nbTOg9PcfnfG/fmmwfRPmk31vdi5cTFemXCyzOnNVxLwY7MC3QRjmqB2XRbryzJlCS7wljkBibiLSrf@vURmuXQTyuN22gBuPWDcOOjTc "Python 3 – Try It Online")
Takes input as varargs
`s` represents the amount of tiles a pumpkin can grow. Negative values, such as `-2` mean that the pumpkin has two spaces to the left that it can grow. If `s` is positive, it means that this space will be occupied by a pumpkin, thus no pumpkins can grow.
[Answer]
# [Haskell](https://www.haskell.org/), ~~55~~ 54 bytes
-1 byte thanks to Wheat Wizard!
```
(!0)
(x:y)!i|x>0=i<1&&y!max(i+x-1)0|w<-i-1=y!w
_!i=i<1
```
[Try it online!](https://tio.run/##TY/fCoMgFMbve4rjTShT0Nq6GNUb7AkqQmJtsopYQQY9@1xm@4Oo3/n5Hc7nXQ6Pa9OYOskNRpx4WJ9ngtSiU56oWPj@jFqpsTpoJghfppgpJpIZTV6JlHWY8TqMAySQZaKgGad8PUO7naIrocGmObXVcSOu5lRQS8UfceyzTvsd7Y7o@xL@XHun89oUgZ2502BTgc2wOgvPa6Xq1ryt7C8l4FwDS6F/qm4ErCnUoAmB7VPmVdWNvA2GVX3/Bg "Haskell – Try It Online")
The recursive function `(!)` looks at first like it should be implemented with a `foldl`, but the `i<1&&` check makes this infeasible.
[Answer]
# [J](http://jsoftware.com/), 35 32 bytes
```
*=&(+/)0=[:(],(+{:)0&>.~0<:[)/<:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tWzVNLT1NQ1so600YnU0tKutNA3U7PTqDGysojX1baz@a3KlJmfkKxgq2CqkKRgicwwUDCBcAzDXGIUDkzOEcYHQCKEFaoKOsY6BjgkQAyGydpCAoQ5I2hAhZQiXgkjCoCmUNkM3xQyuxBihHN0siG5DZH0gdxr9BwA "J – Try It Online")
## the idea
We'll devise an adjusted scan sum such that the number of zeros in that sum will tell us the number of possible fully grown pumpkins.
Example using `0 0 0 3 0 4 0 0 0`:
* First, subtract 1:
```
_1 _1 _1 2 _1 3 _1 _1 _1 (A)
```
* Also, note the locations of our input pumpkins seeds, as these indexes will require special treatment in our scan sum:
```
0 0 0 1 0 1 0 0 0 (B)
```
* Now, consider the scan sum of A, but with a twist: If the sum is negative at one of the B locations, we'll reset it to 0:
```
_1 _2 _3 0 _1 2 1 0 _1
^
would be _1, but we reset it to 0
```
* Finally, realize what 0 means: It means a pumpkin has finished fitting into some available space. The zero reset reflects that in a configuration like:
```
0 0 0 0 3 0 2 input
0 0 3 3 3 2 2 grown pumpkins
_1 _1 _1 _1 2 _1 1 input - 1
_1 _2 _3 _4 0 _1 0 adjusted scan sum
```
where the 3 pumpkin can fit entirely to the left of its seed with extra space to spare, pumpkin 2 cannot avail itself of that space.
* So, if the number of zeros in our scan-sum-with-a-twist equals the number of positive integers in our input, the input is valid.
[Answer]
# JavaScript (ES6), ~~55~~ 54 bytes
Returns a Boolean value.
This algorithm attempts to put each pumpkin as far as possible to the left.
```
a=>[...a,1].every((v,i)=>v?p=p+v>i++?p<i&&p+v:i:1,p=0)
```
[Try it online!](https://tio.run/##jdJND4IgGAfwe5/CU8okfKsOLuzWJ@hGHlhR0ZwwNbY@vWlmbxMSDgzm7wH@eKGKlvuCy2qWiwOrj7imOCEIIQqDFDHFipvjKMgBTtRaYumqhLvuWq74dNpMYh4HUGIf1HuRlyJjKBMnxybb4lqdb6kNJp/rR4cEKQCWuXme1XD2K33o/7MaGcHGwtDktXu2dv7wGq0/bdODTj764jku@1oG2X2rzaqXX9Te5WRDs3Io9WhU6q0eCm9E7IO0TyDqchgqo6PLV2zRO8LvAjoatm9tPrKehvDPb2a6a2jet6f1HQ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 49 bytes
*A port of [@AnttiP's answer](https://codegolf.stackexchange.com/a/241561/58563) suggested by @AnttiP*
Returns \$0\$ or \$1\$.
```
a=>a.every(p=>1>s*p*(s=(s+=p-1)*p<0?0:s),s=0)&s<1
```
[Try it online!](https://tio.run/##jdJND4IgGAfwe5@iU4JhgZaHJnbrE3QzD6ywlzllPtXWpzdfsrcJBQc2xu8B/nASVwHb4qjOTpbvZJnwUvBQTORVFjekeMhCsJWNgCMYc@UwbKuALukCMAFO8QgCVm7zDPJUTtJ8j6xoXVzOh1ts4cH7fIIiFmM8NLfpdFhx@S0pob@sRnqkssQ1ee2etZ01XqP1p606a2XT54/R72oZZLtWm1UnP6i1yaKVSKEvde@v1GvdF94fsffSLgGvzaGvjI76z9i8V4SfBXTUrd/afGQ9dcmPb2a6q2vet6PlHQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
¹≔⁰η⊞θ¹Fθ¿ι¿‹η⁰⎚≔⌊⟦⁰⁻⊖ιη⟧η≦⊕η
```
[Try it online!](https://tio.run/##PU1BCoMwELz3FXvcQAp6aC@eSnspVPAuHoJdm0CMNWv6/TRRkYGdXWZnptfK95OyMTbeuAVLUZ1uzObjsJCg09UE1jhLyMowecBZgBkAzUYvYkYtoRAC7paUR1EBWSbYY2rjzBhGbFNe2gPjg3pPI7mF3iklt3Rr1War1Xd3Pt3xt@oxtikko5TFgcvO1zy7Lp5/9g8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for enough space, nothing if not. Explanation:
```
¹
```
Assume there is enough space.
```
≔⁰η
```
Start with no space to the left of the patch. This variable becomes positive if there is space for a pumpkin to grow to the left or negative if a pumpkin is growing to the right.
```
⊞θ¹
```
End with no space to the right of the patch. This is handled by appending a pumpkin of size 1, which makes the calculations easier without changing the result.
```
Fθ
```
Loop through the patch.
```
¿ι
```
If there is a pumpkin, then:
```
¿‹η⁰
```
If a pumpkin to the left needs the space, then...
```
⎚
```
... there is a conflict, so clear the canvas.
```
≔⌊⟦⁰⁻⊖ιη⟧η
```
Otherwise, make this pumpkin grow as far to the left as it can.
```
≦⊕η
```
Otherwise, there is either less pumpkin growing to the right or more space for pumpkin to grow to the left.
Alternative formulation, also 29 bytes:
```
¹≔⁰η⊞θ¹Fθ«≦⊕η¿ι¿›η⁰≔⌊⟦⁰⁻ιη⟧η⎚
```
[Try it online!](https://tio.run/##PY0xC8IwEIXn9lfceIEI6aCLkziIQ6F76RDq1RykqU1aF/G3x0SLPLh3x73vrjfa95O2MTae3YKVOJanEPjuUEkwaWrWYHCWkDfD5AFnAa@yqPVjy11d72kkt9DtRxQ8ALKAbBdPeiGPRoISAjakZsfjOmKbfqR@DcgZ7b48kA0EZ0vaY7r2jrFNuaxKqr/2mx9y7bq4e9oP "Charcoal – Try It Online") Link is to verbose version of code. The only difference here is that the amount of space is incremented before the conditions, which just requires an adjustment to the condition and space calculation.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes
```
\d+
$*
+1`\B((,)+(?<-2>1)+)1|1(1+)(,)\B
1$1$4$3
M`11
^0
```
[Try it online!](https://tio.run/##RY3BCgIxDETv@Y4KqY2Qadc9icJePPkHRSrowYsH2aP/Xptd3SWQzJsMzPsxPl@3uuFzqfkeyG0poOSBWXzg02EXj/DB4wNG8M3MA8HBdS7RpQB01VpBKkqJkm1pWmJTKqa7iY1UIOZh4dn5z/53@@nfL35aM7TmQNF6aG6LjYz1Cw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert the input to unary.
```
+1`
```
Repeatedly process the leftmost pumpkin that still needs space.
```
\B((,)+(?<-2>1)+)1
```
Match a pumpkin that can grow to the left (but only as far as its size),
```
|1(1+)(,)\B
```
... or a pumpkin that can grow to the right.
```
1$1$4$3
```
Mark that space as consumed by that pumpkin.
```
M`11
^0
```
Check that all of the pumpkins are fully grown.
[Answer]
# Python 3, 108 bytes:
```
def f(l):
p=s=0
for i in l:
if i:
if p:return 1
p=max(i-1-s,s:=0)
else:s+=p<1;p-=p>0
return p>s
```
[Try it online!](https://tio.run/##XVHBbsMgDL3nK6xcSjRSQbtVUzZy3HGn3bppoipoSIQgTKft6zNIs6StfLD93vMTNv43fvVu@@jDMByVBk1s1RTgBQpWgO4DGDAObMLAaDA558I3QcVTcMAz4EUnf4ipeY0UG8GqBCqLqsE74Z/5k6@Fb5PfNONbHEzn@xBBYixQlGW55x9Qt/AWTqrYM8ouuu1Yv8hkmJqJWtoUmys9oxm9H5lrnFFOM8tnZrIZpWd4iocp725MdrNiu6hvrc7Dlxtt8isXWVq4mI@rjY0qkNfeKQq4Rm9NJKt3t6ryV4CkBxDQSU/SsdaJU0HaT/UtLQXzr87OSZ/liCodVhNZCUFcH@FQFcMf)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.œεεày0¢>yg)Ëy_P~]Pà
```
[Try it online](https://tio.run/##yy9OTMpM/f9f7@jkc1vPbY0qNji0yK4yXfNwd2V8QF1swOEF//9HG@oY6RjoGAKxMRCbADEYxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXSf72jk89tPbc1qtjg0CK7ynTNw92V8QF1sQGHF/xX0gvT@R8dbRirE22gYwAkjXWAtI4RmG2gA@KZgEUgfBA0hPDB0BRKmyGpgIiBTDSGmAcVB@kzhugGipjBzTBGmAcUNwLZDtVhBGYZgVwDlIsFAA).
**Explanation:**
Check if there is any partition for which each part satisfies one of two conditions: either all items are 0; or the maximum, length, and amount of 0s + 1 are all three the same.
```
.œ # Get all partitions of the (implicit) input-list
ε # Map over each partition:
ε # Map over each part:
Z # Push the maximum (without popping)
s0¢> # Swap, and count the amount of 0s + 1
yg # And also push the length of the part
) # Wrap all three values into a list
Ë # Pop and check if all three are the same
~ # OR:
y_P # Check if all values in this part are 0s
] # Close the nested loop
P # Product of each: Check if all parts in a partition are truthy
à # Pop and push max: Check if any partition is truthy
# (after which the result is output implicitly)
```
] |
[Question]
[
[Resistors](http://en.wikipedia.org/wiki/Resistor) commonly have [color coded bands](http://en.wikipedia.org/wiki/Electronic_color_code#Resistor_color-coding) that are used to identify their [resistance](http://en.wikipedia.org/wiki/Electrical_resistance_and_conductance) in [Ohms](http://en.wikipedia.org/wiki/Ohm). In this challenge we'll only consider the normal 4-band, tan, axial-lead resistors. We'll express them as:
```
xyzt
```
Where `x` is the first band for the first significant figure, `y` is the second band for the second significant figure, `z` the third band for the multiplier, and `t` is the fourth band for the [tolerance](http://en.wikipedia.org/wiki/Engineering_tolerance).
Each of `xyzt` represents a letter that abbreviates the color of the band:
```
K = Black
N = Brown
R = Red
O = Orange
Y = Yellow
G = Green
B = Blue
V = Violet
A = Gray
W = White
g = Gold
s = Silver
_ = None
```
So, for example, `NKOg` is some particular resistor.
The resistance can be calculated with the help of this table:
[](http://en.wikipedia.org/wiki/Electronic_color_code#Resistor_color-coding)
As the table suggests:
* `x` and `y` can be any letters except `g`, `s`, and `_`.
* `z` can be anything except `_`.
* We'll restrict `t` to only be `g`, `s`, or `_`.
([Here's a handy resistance calculator that deals with exact same set of resistors we are.](http://www.dannyg.com/examples/res2/resistor.htm))
The resistance is `10 * x + y` times the `z` multiplier, to a tolerance of the `t` percentage.
>
> For example, to calculate the resistance of `NKOg`, we see that:
>
>
> 1. `N` means Brown for 1.
> 2. `K` means Black for 0.
> 3. `O` means Orange for 103.
> 4. `g` means Gold for ±5%.
>
>
> So the resistance is `(10*1 + 0)*10^3` → `10000 Ω ±5%`.
>
>
>
# Challenge
Write a program or function that takes in a 4 character string of the form `xyzt` and prints or returns the resistance in the form `[resistance] Ω ±[tolerance]%`.
* **The resistor may be "upside-down", i.e. in the reverse order `tzyx`. For example, both `NKOg` and `gOKN` should produce `10000 Ω ±5%`.**
* The resistance is always in plain ohms, never kilohms, megohms, etc.
* [`Ω`](http://www.fileformat.info/info/unicode/char/03a9/index.htm) may be replaced with `ohms`, e.g. `10000 ohms ±5%`.
* [`±`](http://www.fileformat.info/info/unicode/char/b1/index.htm) may be replaced with `+/-`, e.g. `10000 Ω +/-5%`.
* Having trailing zeros to the right of a decimal point is fine. (e.g. `10000.0 Ω +/-5%`)
* You can assume input is always valid (`x` and `y` never `gs_`; `z` never `_`; `t` only `gs_`).
* All 10×10×12×3 = 3600 possible resistors (2×3600 possible inputs) need to be supported even if some color band combinations aren't produced in real life.
**The shortest code in bytes wins.**
# Examples
1. `gOKN` → `10000 ohms +/-5%`
2. `KKR_` → `0 Ω +/-20%`
3. `ggKN` → `1 ohms ±5%`
4. `ggGO` → `3.5 Ω ±5%`
5. `ssGO` → `0.350 Ω ±10%`
6. `GOOs` → `53000 ohms +/-10%`
7. `YAK_` → `48.0 ohms +/-20%`
8. `_WAV` → `78000000000 Ω ±20%`
9. `gBBB` → `66000000.000 ohms ±5%`
10. `_RYR` → `2400.00 ohms ±20%`
[Iff](http://en.wikipedia.org/wiki/If_and_only_if) you enjoy my challenges, consider checking out [Block Building Bot Flocks!](https://codegolf.stackexchange.com/q/50690/26997)
[Answer]
# CJam, ~~59~~ ~~58~~ ~~56~~ 50 bytes
```
r_W%e>"sgKNROYGBVAW"f#2f-~A*+A@#*" Ω ±"@[KA5]='%
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r_W%25e%3E%22sgKNROYGBVAW%22f%232f-~A*%2BA%40%23*%22%20%CE%A9%20%C2%B1%22%40%5BKA5%5D%3D'%25&input=ggGO).
[Answer]
# CJam, ~~53~~ ~~51~~ 50 bytes
```
" Ω ±"l_W%e<)iB%5*F-'%@"gKNROYGBVAW"f#:(2/'e*s~o
```
[Try it online](http://cjam.aditsu.net/#code=%22%20%CE%A9%20%C2%B1%22l_W%25e%3C%29iB%255*F-'%25%40%22gKNROYGBVAW%22f%23%3A%282%2F'e*s~o&input=_RYR).
*(Thanks to @user23013 for a byte)*
---
I started out in Python, but
```
eval("%d%de%d"%tuple("gKNROYGBVAW".find(x)-1for x in L))
```
was too expensive...
[Answer]
## Python 3, ~~130~~ 114 bytes
```
def f(v):
a,b,c,d=["_sgKNROYGBVAW".index(x)-3for x in v[::(1,-1)[v[0]in'sg_']]]
return "%s Ω ±%s%%"%((10*a+b)*10**c,2.5*2**-d)
```
*edit:* @Sp3000 points out that the ordering can be better detected with `min(v,v[::-1])` rather than `v[::(1,-1)[v[0]in'sg_']]` (saving 10 bytes), not check the index of `_` and remove some unnecessary whitespace.
```
def f(v):a,b,c,d=["sgKNROYGBVAW".find(x)-2for x in min(v,v[::-1])];return"%s Ω ±%s%%"%((10*a+b)*10**c,2.5*2**-d)
```
[Answer]
# Perl, 93 bytes
```
#!perl -lp
ord>90and$_=reverse;s/./-3+index zsgKNROYGBVAW,$&/ge;$_=s/..\K/e/*$_." Ω ±"./.$/*5*$&."%"
```
[Answer]
# Haskell, ~~135 132~~ 130 bytes
```
r y|y<"["=p[k|j<-y,(c,k)<-zip"_ sgKNROYGBVAW"[-4..],c==j]
r y=r.reverse$y
p[a,b,c,d]=show((a*10+b)*10**c)++" Ω ±"++show(-5*d)++"%"
```
**Explanation:**
```
r y|y<"["= If first letter of argument is a capital
p[..] Call p on the list created
[k| Make a list of all k
j<-y Draw character j from input
,(c,k)<- With (c,k) being a pair from
zip A list of pairs of corresponding elements from the lists:
"_ sgKNROYGBVAW" The space at 2nd position is to match '_' with -4, but 's' with -2
[-4..] An infinite list starting at -4
,c==j] Only use element k if j equals the character c
r y=r.reverse$y If first call fails, call again with reversed argument.
p[a,b,c,d]= Assign the first four elements of the argument to a,b,c,d respectively.
show Turn (number) into string
10**c 10 to the power of c
++ Concatenate strings
-5*d This works for the tolerance because '_' makes d=-4
```
*Thanks to nimi, I shaved off another 2 bytes.*
] |
[Question]
[
As computer scientists, you're probably all familiar with the basic list operations of *pop* and *push*. These are simple operations that modify a list of elements. However, have you ever heard of the operation *flop*? (as in *flip-**flop***)? It's pretty simple. Given a number **n**, reverse the first **n** elements of the list. Here's an example:
```
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a.flop(4)
[4, 3, 2, 1, 5, 6, 7, 8, 9, 10]
```
The cool thing about the flop operation, is that you can use it do some cool things to a list, such as [sorting it](https://en.wikipedia.org/wiki/Pancake_sorting). We're going to do something similar with flops:
>
> Given a list of integers, "Neighbor it". In other words, sort it so that every duplicate element appears consecutively.
>
>
>
This can be done with flops! For example, take the following list:
```
>>> a = [3, 2, 1, 4, 3, 3, 2]
>>> a.flop(4)
[4, 1, 2, 3, 3, 3, 2]
>>> a.flop(3)
[2, 1, 4, 3, 3, 3, 2]
>>> a.flop(6)
[3, 3, 3, 4, 1, 2, 2]
```
This leads us to the definition of today's challenge:
>
> Given a list of integers, output any set of flops that will result in the list being neighbored.
>
>
>
Using the last list as an example, you should output:
```
4
3
6
```
because flopping the list by 4, then by 3, then by 6 will result in a neighbored list. Keep in mind that you do *not* need to print the shortest possible list of flops that neighbors a list. If you had printed:
```
4
4
4
3
1
1
6
2
2
```
instead, this would still be a valid output. However, you may *not* ever output a number larger than the length of the list. This is because for a list `a = [1, 2, 3]`, calling `a.flop(4)` is nonsensical.
Here are some examples:
```
#Input:
[2, 6, 0, 3, 1, 5, 5, 0, 5, 1]
#Output
[3, 7, 8, 6, 9]
#Input
[1, 2]
#Output
<any list of integers under 3, including an empty list>
#Input
[2, 6, 0, 2, 1, 4, 5, 1, 3, 2, 1, 5, 6, 4, 4, 1, 4, 6, 6, 0]
#Output
[3, 19, 17, 7, 2, 4, 11, 15, 2, 7, 13, 4, 14, 2]
#Input
[1, 1, 1, 1, 2, 2, 2, -1, 4]
#Output
[]
#Input
[4, 4, 8, 8, 15, 16, 16, 23, 23, 42, 42, 15]
#Output
[12, 7]
```
Keep in mind that in each of these examples, the output given is just one potential valid output. As I said before, *any set of flops that neighbors the given list is a valid output*. You can use [this python script](https://tio.run/##VVBNa8QgEL3nV0xvSm1gN6UHYa/9Bb2JlDQZu4JMRF26@@uzakLSDCK8@Xpvnn@k60TdPA@ujxEI/76djYmVj8sGcoxowLjJs4jOCKA1XWKY/AMuUApK6i1dcDs47APjxyTeE9LIypySpJWUbycNr3WRIql50xQ6Qvt7/ZkCjsytdBGRMpVaWMwUwIIlcLsYa5ZU7expzOjlUpHKJHtfiYDpFgg@exdxK2AGx7Yy3PbeF812OWWd/Ao3XLQmLHaJalFcxbqsdLeSb5JN0Vcbdx7XVnNNPv3f/oMDsw@WEqtMqhNwFnAS8C6gq@@sBagFfWjO5yc "Python 3 – Try It Online") to verify if a given list of flops correctly neighbors a list.
You may take input and output in any reasonable format. For example, function arguments/return value, STDIN/STDOUT, reading/writing a file etc. are all valid. As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make the shortest program you can, and have fun! :)
[Answer]
# [Haskell](https://www.haskell.org/), ~~98~~ 71 bytes
```
h.r
h(x:s)|(a,b)<-span(/=x)s=l b:l s:h(b++r a)
h e=e
r=reverse
l=length
```
[Try it online!](https://tio.run/##VY3BqsIwEEX3@YpBXCS0KuqumK94y/dcpHaaFMc0zERx8b7dGEEENwP33HOZ4OSMRMXbvxLWrIK@d2L@tWt7c1hJclFv7N2IJeg7AumC7puGwRkVAC0qtow3ZEFFljD6HIqAhd9tu2v3bb1HpUaaEwjEyt@yzu6MFYiBpoGBa1@DurjpJQ2zgnTNP5lh8dpKB4tKeIoZluCr@KkZ5Up5ih5okvzljTMNBO/fuq5MeZxGcl7K6pTSEw "Haskell – Try It Online")
### Explanation
For a list of length `n` this method produces `2*n` flops. It works by looking at the last element of the list, looking for the same element in the list before and flipping it to the second to last position. Then the list with the last element removed is recursively "neighboured".
For the list `[1,2,3,1,2]` the algorithm works like this:
```
[1,2,3,1,2] flip longest prefix that ends in 2: flop 2
[2,1,3,1,2] bring first element to second to last position: flop n-1 = flop 4
[1,3,1,2,2] recursively work on n-1 list
[1,3,1,2] there is no other 2: flop 0
[1,3,1,2] flop n-1 = flop 3
[1,3,1,2] recurse
[1,3,1] flop 1
[1,3,1] flop 2
[3,1,1] recurse
[3,1] flop 0
[3,1] flop 1
...
```
All together this yields the flops `[2,4,0,3,1,2,0,1,0,0]` and the neighboured list `[3,1,1,2,2]`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes
```
If[(n=Tr[1^#])<1,{},{i=Last@Ordering@#,n,n-1,i-1}~Join~#0[#~Drop~{i}]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8zLVojzzakKNowTjlW08ZQp7pWpzrT1iexuMTBvyglFagq3UFZJ08nT9dQJ1PXsLbOKz8zr07ZIFq5zqUov6CuOrM2Nlbtv4KDQrWxjoKRjoKhjoKJjoIxGBnVxv4HAA "Wolfram Language (Mathematica) – Try It Online")
## How it works
Given an array of length `n`, outputs a sequence of `4n` flops that sort the array in increasing order: in particular, putting duplicate elements next to each other.
The idea is that to sort an array, we move its largest element to the end, and then sort the first `n-1` elements of the array. To avoid implementing the flop operation, we move the largest element to the end in a way which does not disturb the other elements:
```
{3, 2, 1, 5, 3, 3, 2} starting array, with largest element in position 4
{5, 1, 2, 3, 3, 3, 2} flop 4 to put the largest element at the beginning
{2, 3, 3, 3, 2, 1, 5} flop 7 to put the largest element at the end
{1, 2, 3, 3, 3, 2, 5} flop 6 (7-1) to reverse the effect of flop 7 on other elements
{3, 2, 1, 3, 3, 2, 5} flop 3 (4-1) to reverse the effect of flop 4 on other elements
```
In general, if the largest element is in position `i`, the sequence of flops that moves it to the end is `i, n, n-1, i-1`.
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
l=input()
while l:k=l.index(max(l));print-~k,len(l),;l=l[:k:-1]+l[:k]
```
[Try it online!](https://tio.run/##PU09D4IwFNz5FS9MEIuhFYmBMOLq4kYYEF8CoRbSlIiLfx37ISR3fe29u@v0Ud0o2NqOTyyk7/srL3oxzSoIvXfXcwSeDQU/9uKJS/BqloCHYT7JXqjoOxCOQgsk5wWvsiGLaH0wl3rVTf/8Xc6YeQBKfswAwAVbMP/Zl63yjNripKC8XUspR@msD4nNsFaMQEogJnAiQAmcLWJ70tqrtMT02F3MuhK3tyG25VKrJ5shdRHXsYNtiIxLL13kYkFNaerITo4Jc6Tn@gc "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 17 bytes
```
ỤỤạ‘Ḣ
ỤÇÐƤĖµUż’ṚF
```
Sorts the list.
[Try it online!](https://tio.run/##y0rNyan8///h7iUgtGvho4YZD3cs4gJyDrcfnnBsyZFph7aGHt3zqGHmw52z3P4fbn/UtObopIc7ZwDpyP//o6ONdBTMdBQMdBSMdRQMdRRMwcgATBrG6nApRAMFjcAMuEojsEoTiBqwRiOYXjOwuAlMgRlEC8wcODKCIV2QOrA0RJsFGBmCDDaDYCNjCDYxgmBD09hYAA "Jelly – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), 88 bytes
I think there's a possibly shorter one with guards, but I haven't found it yet.
```
import StdEnv
$[h:t]#(a,b)=span((<>)h)t
=map length[b,t]++ $(b++r a)
$e=e
r=reverse
```
#
```
$o r
```
[Try it online!](https://tio.run/##RU89b8MgFNz5FU@KB5CJkrZJhqpkaoZK2TK6HrDBMSofFpBI/fOlGPdDYrh73N2712vJbTJO3LQEw5VNykzOR7hEcbJ3VDXjc2xXmNOOsDBxi/HLkYwkImb4BFraaxybjsa2rqHCXV174ARVkknkmZd36YNMl8h9RCvQKkRg0DxSOFDYUsjggcKOwr6Ap9/Jvgh25S2Cw2Jpc8qg3ZRT8HsAC@sj4J81OPIPmUeBEMhthM@ymc2Wm@2zpXLgEVvY3AVtNjnnj1IYnBZ6WVC6/v8Rkr76QfNrSOu3c75InFVX4Oun5Ub14Rs "Clean – Try It Online")
As a function literal. Works the same way as [Laikoni's Haskell answer](https://codegolf.stackexchange.com/a/154453/18730), but golfed slightly differently, and of course also in a different language.
[Answer]
# JavaScript, 150 bytes
```
(a,f=n=>(a=[...a.slice(0, n).reverse(),...a.slice(n)],n),l=a.length,i=0)=>a.reduce(c=>[...c,f(a.indexOf(Math.max(...a.slice(0, l-i)))+1),f(l-i++)],[])
```
[Try it online!](https://tio.run/##VY7BasMwEETv@Qrdsos3S5LeAus/KP0A48Mirx0VRQqWGvL3rtJTcxkG5jEz3/rQ4tdwr4eUJ9uiVbfIBkqzJOlBZWBm5RKDNziSS8irPWwtBkj/ooQjJaQoytHSUq8U5IjSa8OnnwZ46V9VnmZQDmmy59cMn1qvfNMnvI/EQ0DE7oQNbr7rWvkw4t@7Sas6ccOJzvRBTcfdzudUcjSOeYH9HPO9XNzedW6BF424/QI "JavaScript (Node.js) – Try It Online")
# JavaScript, 151 bytes
```
a=>{f=n=>(a=[...a.slice(0,n).reverse(),...a.slice(n)],n),r=[];for(i=a.length+1;--i>0;)r.push(f(a.indexOf(Math.max(...a.slice(0, i)))+1),f(i));return r}
```
[Try it online!](https://tio.run/##VY5BasMwEEX3OYV2mcHyECe7GPkGpQcwXgz2yFZQJSMpIVBydsftqt18PrwH/9/4wXlMbi11iJNsXoqazcam@7YmmA7Y9ETElL0bBU46ICV5SMoCqP@QgMPOdDL90NqYwBkmL2EuS9W0de26U4uJ1ntewAKTC5M8Py18cFnoi5/wb0Q5RKwa1Bb21iYp9xRUev3em7iwMqpv9Flf9J7D4TDGkKMX8nGGo/VxzVd1VJWa4cdG3N4 "JavaScript (Node.js) – Try It Online")
Both basically sort the array by flipping the max number to the beginning and then flipping it to the back, repeating this with the remaining array. The first one uses reduce, the second one uses a for loop.
## Ungolfed:
```
array => {
let flop = n => {
array = [...array.slice(0, n).reverse(), ...array.slice(n)];
return n;
}
let flops = [];
for (let i = array.length + 1; --i > 0;)
{
let maxIndex = array.indexOf(Math.max(...array.slice(0, i)));
flops.push(flop(maxIndex + 1), flop(i));
}
return flops;
}
```
[Answer]
# Perl 5.10 (or higher), 66 bytes
Includes `+3` for `-n`
The `use 5.10.0` to bring the language to level perl 5.10 is considered free
```
#!/usr/bin/perl -n
use 5.10.0;
$'>=$&or$.=s/(\S+) \G(\S+)/$2 $1/*say"$. 2 $."while$.++,/\S+ /g
```
Run with the input as one line on STDIN:
```
flop.pl <<< "1 8 3 -5 6"
```
Sorts the list by repeatedly finding any inversion, flopping it to the front then flopping the inversion and flopping everything back to its old position.
It was surprisingly hard to get in the same ballpark as python on this one :-)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~165~~ 160 bytes
* Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for saving five bytes.
```
m,j,t;f(A,l)int*A;{for(j=0;j+j<l;A[j]=A[l+~j],A[l+~j++]=t)t=A[j];}F(A,l)int*A;{for(;l;f(A,++m),printf("%d,%d,",m,l),f(A,l--))for(j=m=0;j<l;j++)m=A[j]>A[m]?j:m;}
```
* [Try it online!](https://tio.run/##jY/daoNAEIWvm6dYhIJbR3A3ibTdbIr5e4aAeGE0KVnctKT2KthXtzO72D9K6c6IODvnO8cqfqyqvrdgoFWHMIOGH0/tTaYuh6dzaHSiTGRmjcpyU@gsb6I3U4B/R1GhW95qulLd5qdWNY4XRZbD8xkvDmFwXQN2ABZXwbnFMefeyZIXOiGXWwedZ7ktHsy9VV2/xeUSzGAwAPOAq4@gs9KJv5gFQByuhlHB4jkjDaUtcf7avuAUB93IlsdTyC@jK1xlWV7oi4QUEhiDgClWgo9gv5xOkaLUIlFbj/WMBTEESPaP4xk7zSQyFrAbGMvPHBJzTCgDJpIuU4rfEzdNacMzKi0pxxKqgbHyOXxJVzGK/shRa3aHjBXUA2NNDHK7xRIYIqWWY@qJpBbT74y9FvQva9gjo@vfAQ "C (gcc) – Try It Online")
* [Verification](https://tio.run/##fVDRboMwDHzvV2RvoLkVAUpbpL7uC/aG0MRKWJGigIBq69czn2GllaolJML2@e7i9jqcGxeN48kWfa@c@f6wdT94uPx0pXiVplKVbVqvN7Yi5eY01qlpr@qoUMjS/JZGvDlZU3Se/5g0P4NxpYe@LHV5lqZrnatXIcpcmvurFeScqb/On01nSs/Ocr0xjqWySaVqOlWr2im7mKmrKSXIwpUcvRwlylhkwWF1Zrh0Tr0Vtje3guHgEYbmTdG28FxPT5k737uLmbwOBuMiGVE/m7XsdBmlf7NcwZ8AFx27keFW/PQ7/ocJjG1Xu8ETpSykhAKKSNOWd8BHU65IcUEHFNKBM3uu7wjISOoxH3QwBGjfX90zIj8zPAdMkqEQbYUqFPmE41iyiSD@SAR7IM33Hr87sCak@UaTRo@GQ0ZskY5hXbN1TWgAPqFwth79a33aoew14GLiMI8BXNs7rvAfLrxlz5s9wiw3RfjiEB8nhRg@ZUyiGxCEdmiaTevnpsdf "Python 3 – Try It Online")
] |
[Question]
[
## Introduction
On March 24th, 2015 *@isaacg* golfed [his Pyth answer](https://codegolf.stackexchange.com/a/48101/52210) from 44 to 42 bytes. Since a crossed out 44 (~~44~~) looks a lot like a regular 44, *@Optimizer* made the following comment:
>
> [striked out 44 is still normal 44 :(](https://codegolf.stackexchange.com/questions/48100/very-simple-triangles/48101#comment113015_48101)
>
>
>
After that, on October 21st, 2015, *@Doorknob♦* golfed [his Ruby answer](https://codegolf.stackexchange.com/a/61414/52210) from 44 to 40 (and later 38) bytes and added the following part to his answer, with a link to that original comment of *@Optimizer*:
>
> [crossed out 44 is still regular 44 ;(](https://codegolf.stackexchange.com/questions/48100/very-simple-triangles/48101#comment113015_48101)
>
>
>
This was the start of [an answer-chaining meme](https://codegolf.stackexchange.com/search?tab=newest&q=crossed%20out%2044%20is%20still%20regular%2044), where every crossed out 44 (and in some occasions 4 or 444) linked back to the previous one.
Then on April 8th, 2017 (I'm not sure if this was the first answer to do so, but it's the earliest one I could find), *@JonathanAllan* golfed [his Python answer](https://codegolf.stackexchange.com/a/115873/52210) from 44 to 39. He however used `<s> 44 </s>` so the 44 would look like this: ~~44~~, and added the following to his answer:
>
> Crossed out 44 is no longer 44 :)
>
>
>
And that was basically the (beginning of the) end of the meme.
## Challenge
As for this challenge: Given a list of positive integers and a date, output the list comma-and-space separated where every number except for the last one is placed between `<s>...</s>` tags.
In addition, if any of the crossed out numbers is in the sequence `[4, 44, 444, 4444, ...]` ([A00278 on oeis.org](http://oeis.org/A002278)):
* If the date is before April 8th, 2017: Also output the exact (all lowercase and with semicolon emoticon) text `crossed out N is still regular N ;(` (`N` being the crossed out number from the sequence) on a second line.
* If the date is April 8th, 2017 or later: The crossed out number `N` from the sequence should have the leading and trailing ` ` added. No need for any additional lines of output.
**Examples:**
Input: `list = [50, 48, 44, 41]`, `date = January 1st, 2017`
Output:
```
<s>50</s>, <s>48</s>, <s>44</s>, 41
crossed out 44 is still regular 44 ;(
```
Input: `list = [500, 475, 444, 301, 248]`, `date = June 2nd, 2018`
Output:
```
<s>500</s>, <s>475</s>, <s> 444 </s>, <s>301</s>, 248
```
## Challenge rules:
* You can assume the input-list is a sorted list from largest to smallest, only containing positive integers. In reality a byte-count can also go up due to bug-fixes, but for the sake of this challenge we pretend it only goes down.
* You can assume only a single number from the sequence `[4, 44, 444, 4444, ...]` is present in the input-list (if any).
* The output format is either printed to STDOUT, or returned as a string (or character array/list/2D-array if that's preferable). A trailing newline is of course optional.
* The output format is strict. `<s>...</s>` is mandatory; ` ... ` is mandatory; `", "` (comma and space) is mandatory; and `\ncrossed out ... is still regular ... ;(` exactly is mandatory (on a separated line).
* You may take the input-date as date-objects; timestamps; loose integers for year, month, and day; a single number in the format `yyyyMMdd`; integer days since December 31st, 1899 (which would be `42832` for April 8th, 2017); or any other reasonable input-format. The date if-statement isn't the major part of this challenge.
* The input integer-list can also be a list of strings if you want.
* You don't have to add the `<sup>...</sup>` tags to the `crossed out ... is still regular ... ;(` line as is usually done with the actual meme answers.
* You can assume the input-list will never contain byte-counts outside the `[1, 50000]` range (so you'll only have these five `{4, 44, 444, 4444, 44444}` to worry about).
## 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 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.
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: [50, 48, 44, 41] and January 1st, 2017
Output:
<s>50</s>, <s>48</s>, <s>44</s>, 41
crossed out 44 is still regular 44 ;(
Input: [500, 475, 444, 301, 248] and June 2nd, 2018
Output:
<s>500</s>, <s>475</s>, <s> 444 </s>, <s>301</s>, 248
Input: [8, 6, 4] and December 5th, 2017
Output:
<s>8</s>, <s>6</s>, 4
Input: [8, 6, 4, 3, 2] and September 15th, 2015
Output:
<s>8</s>, <s>6</s>, <s>4</s>, <s>3</s>, 2
crossed out 4 is still regular 4 ;(
Input: [119, 99, 84, 82, 74, 60, 51, 44, 36, 34] and February 29th, 2016
Output:
<s>119</s>, <s>99</s>, <s>84</s>, <s>82</s>, <s>74</s>, <s>60</s>, <s>51</s>, <s>44</s>, <s>36</s>, 34
crossed out 44 is still regular 44 ;(
Input: [404, 123, 44] and March 4th, 2016
Output:
<s>404</s>, <s>123</s>, 44
Input: [4, 3] and April 8th, 2017
Output:
<s> 4 </s>, 3
Input: [44] and October 22nd, 2017
Output:
44
Input: [50000, 44444, 1500] and August 1st, 2018
Output:
<s>50000</s>, <s> 44444 </s>, 1500
Input: 50, 38, 23 and September 8th, 2001
Output:
<s>50</s>, <s>38</s>, 23
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~444~~, ~~94~~, 93 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ñȧ$“ ”,¤j$€io.ɗ¦@Ṗj@€“<s>“</s>”oj⁾,
⁴>⁽A€
“¢⁻$gẆẠ⁷Ṭ]ḳṁṛż?=çỊI×V»Ỵjṭ⁷ẋǬȧẠƲ
ṖḟÐḟ”4Ḣµñ³,Ç
```
A full program. The inputs are a list of strings and a date taken as integer days since January the first 1970 (making 17264 April the eighth 2017)
**[Try it online!](https://tio.run/##y0rNyan8///wxBPLVR41zFHLSyousH7UMFfn0JIslUdNazLz9U5OP7TM4eHOaVkOQD5QjU2xHYjUB1Fz87MeNe7TUeB61LjF7lHjXkegEi6g7KFFjxp3q6Q/3NX2cNeCR43bH@5cE/twx@aHOxsf7px9dI@97eHlD3d3eR6eHnZo98PdW7Ie7lwLUrWr@3D7oTUnlgM1HdvEBbTz4Y75hycACaBNJg93LDq09fDGQ5t1Drf///9fydTAQElHycTcFESamABJYwNDIGlkYqH039DcyMwEAA "Jelly – Try It Online")**
### How?
```
Ñȧ$“ ”,¤j$€io.ɗ¦@Ṗj@€“<s>“</s>”oj⁾, - Link 1: L = list of characters ("4...4") OR integer (0),
- R = list of lists of characters (the strings provided to the program)
$ - last 2 links as a monad:
Ñ - call next Link (2) as a monad
- ...gets: is date input to program greater than 2017-04-07?
ȧ - AND (if so gets the value of L, else 0), say X
¦@ - sparse application (with swa@pped @rguments)...
Ṗ - ...with right argument = popped R (without it's rightmost entry)
ɗ - ...to: last 3 links as a dyad
i - first index of X in popped R (0 if no found, so 0->0)
. - literal 0.5
o - OR (change any 0 to 0.5)
- ...i.e. index of "4...4" if L was one or 0.5, an invalid index
$€ - ...do: for €ach... last 2 links as a monad:
¤ - nilad followed by link(s) as a nilad:
“ ” - literal list of characters = " "
, - pair (with itself) = [" ", " "]
j - join (with the item) e.g.: " 444 " or [" ", 0, " "]
“<s>“</s>” - literal list of lists of characters = ["<s>", "</s>"]
j@€ - for €ach... join (with swa@pped @rguments)
o - OR with R (vectorises, so adds the popped entry back onto the right-side)
⁾, - literal list of characters = ", "
j - join
⁴>⁽A€ - Link 2: greater than 2017-04-07?
⁴ - program's 4th argument (2nd input)
⁽A€ - literal 17263 (days(2017-04-07 - 1970-01-01))
> - greater than?
“¢⁻$gẆẠ⁷Ṭ]ḳṁṛż?=çỊI×V»Ỵjṭ⁷ẋǬȧẠƲ - Link 3: L = list of characters ("4...4") OR integer (0)
“¢⁻$gẆẠ⁷Ṭ]ḳṁṛż?=çỊI×V» - compressed list of characters = "crossed out \n is still regular \n ;("
Ỵ - split at newlines = ["crossed out ", " is still regular ", " ;("]
j - join with L
⁷ - literal newline character
ṭ - tack (add to the front)
Ʋ - last 4 links as a monad:
Ç - call last Link (2) as a monad
¬ - NOT
Ạ - All (1 if L is "4...4", 0 if L is 0)
ȧ - AND
ẋ - repeat (i.e. get the list of characters to print or an empty list)
ṖḟÐḟ”4Ḣµñ³,Ç - Main Link: list of strings, integer (days since 1970-01-01)
Ṗ - pop (list of strings without it's rightmost entry)
Ðḟ - filter discard if:
ḟ - filter discard any which are in...
”4 - ...literal character '4'
Ḣ - head (yields 0 if list is now empty)
µ - new monadic chain, call that X
³ - program's 3rd argument (1st input) - call that Y)
ñ - call next Link (1) as a dyad (i.e. f1(X, Y))
Ç - call last Link (3) as a monad (ie. f3(X))
, - pair
- implicit (smashing) print
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~208~~ ~~204~~ ~~203~~ ~~201~~ 197 bytes
Takes input as a list of strings, and an int of `yyyymmDD`
```
def f(l,d):
A=a=d>20170407;r=[]
for n in l[:-1]:x=set(n)=={'4'};S=' '*x*a;r+=['<s>'+S+n+S+'</s>'];A=x*n or A
print', '.join(r+l[-1:])+'\ncrossed out %s is still regular %s ;('%(A,A)*(a*A<A)
```
[Try it online!](https://tio.run/##dZHLboMwEEX3fMVsUvNKa4MJrzgS35AlZUELtFTUIJtIqap@Ox1oEqkSWYwsW2funbkevsb3XnrTVNUNNGbnVlZiQCZKUR08ykLKaZgqkRcGNL0CCa2ELk@2rEjOQtejKS0hvgknP@lRkAf5ooeU2Ge7TJUjcrLXB@IcHYlF9k94KdJMnG0JqJUZMKhWjsQF8vjRt9JUTpdvWVJYDnmWr6rXuq6gP42w0dBq0GPbdaDqt1NXqvktNcnGzNzMss3SzvaZNTXmZzmYelRuHlAXeITFsVhhubDswyizjMXX@AfPdBjMOPI@ZYjz6NIV0R31VrpQfYcdFypmHg3uU6iK2IUNaMzWWMZiF2KsCPnIcyHEc4ezBexvEx@l/KsjTuXFKyqcIsk8f265oT7layjK3bLhNFpDrhohQ7/18Jb4@JId7kZvuUV30kZXjMW7WOOnxLP19As "Python 2 – Try It Online")
[Answer]
# Excel VBA, 217 bytes
VBE immediate window function that takes input array from range `[A:A]`, and date from range `[B1]` and outputs to the console.
```
c=[Count(A:A)]:d=[B1]>42832:For i=1To c-1:n=Cells(i,1):l=InStr(44444,n):s=IIf(d*l," ",""):v=IIf((d=0)*l,n,v):?"<s>"s;""&n;s"</s>, ";:Next:?""&Cells(i,1):?IIf(v,"crossed out "&v &" is still regular "&v &" ;(","");
```
### Ungolfed and Commented
```
c=[Count(A:A)] '' Get numer of elements
d=[B1]>42832 '' Check if date is after 7 Apr 2017,
For i=1To c-1 '' Iterate over index
n=Cells(i,1) '' Get array val at index
l=InStr(44444,n) '' Check if val is all 4s
s=IIf(d*l," ","") '' If after 7 Aug 2017, and All 4s, let `s` be " "
v=IIf((d=0)*l,n,v) '' If all 4s, and not after date, let v hold n, else hold v
?"<s>"s;""&n;s"</s>, "; '' Print striked vales, with " ", if applicable
Next '' Loop
?""&Cells(i,1) '' Print last value in array
'' (below) Print meme, if needed
?IIf(v,"crossed out "&v &" is still regular "&v &" ;(","");
```
-2 bytes for changing date format to `YYYYMMDD`
-1 byte for comparing to `42832` (int value for `07 Apr 2017`), Thanks [@Neil](https://codegolf.stackexchange.com/users/17602/neil)
-2 bytes for removing `1,` from the `InStr` statement, Thanks [@SeaDoggie01](https://codegolf.stackexchange.com/users/47117/seadoggie01)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 130 bytes
```
$
;42833
O`;.{5}
\b(4+),(?=.*;42833;)
&$1&,
&
.{12}$
\b(4+),.*
$&¶crossed out $1 is still regular $1 ;(
(.+?),
<s>$1</s>,
```
[Try it online!](https://tio.run/##NZBLTsNADIb3PsUsQpS0Vhg/kkw0pV2y5AIs2kKEIkUtyqSrqtfiAFwszFDwyv5s/35M/TycDstD8bxfMvDKTgRe9r661jd4PRa6LrHYPVWre8qXkGeUI@SQn47h00N1Jb5l8F9brSDLv7/epnMI/bs5X2aTkRmCCfMwjmbqPy7jYUrMF1BU612JsAnbjDaPYYtmWWqL6lAVleLIVhqobURtHZmiWEJW51W4FnDYoEbftnr3UZBjFzcMRB12HTpFx9gqNhZrSrrSoMQmVu5ArSKxRJxAvDym/36gv8Ji0/i0QDKkGEQsJBGjOGTx0pLyDw "Retina 0.8.2 – Try It Online") Link includes test cases. Uses Excel date stamps (days since 1899-12-31 but including 1900-02-49). 141 bytes for a version that takes ISO dates:
```
$
;2017-04-08
O`;.{10}
\b(4+),(?=.*;2017-04-08;)
&$1&,
&
.{22}$
\b(4+),.*
$&¶crossed out $1 is still regular $1 ;(
(.+?),
<s>$1</s>,
```
[Try it online!](https://tio.run/##TVBLbsIwEN3PKbJIowDjdGY8ThyFwrLLXqALoEUVUgRVDCvEtXqAXiy1C0hY3vh95r3xsD3u9uvxqXxdjTl0QtwYUkMe3lZddWa6wPum1NkEy@VLNX0QdBMoci4QCij2m/DdQXUWueRwN1RTyIvfn4/hEML2MzucjlnO2S5k4bjr@2zYfp369ZCwroSymi0nCPOwyHn@HBaYjaMjVI@qqHzL5XjBUcQbFwlFS4yiPtHeUG1IwGONetWzGHJXAC1KAp2h1rAD5hbbFr2iF2wUa0LHKcvWaP/taZiRFpQUWWzkbqiN@0MUPn6W3hPJiKSGqWM6yPFxq@ev7dF6lORO67QR/gM "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
$
;2017-04-08
```
Append the cut-off date to the input.
```
O`;.{10}
```
Sort the dates. If the given date is on or after the cut-off date then the first date will be the cut-off date.
```
\b(4+),(?=.*;2017-04-08;)
&$1&,
&
```
In that case, wrap the `4+` in ` ` (using two stages as it saves a byte).
```
.{22}$
```
Delete the dates as they have done their job.
```
\b(4+),.*
$&¶crossed out $1 is still regular $1 ;(
```
If there's an unspaced `4+`, then append the meme.
```
(.+?),
<s>$1</s>,
```
Strike out all of the obsolete byte counts.
[Answer]
# Ruby, ~~208~~ ~~184~~ 180 bytes
[TIO-test](https://tio.run/##JYvdDoIgGIZv5Yuaa0n1aVQuhC7EPLCMYjNtAgdNvXbDOnn2/rbu@hmVGNeypmW3elIraq5FjNERGSay5EqcLzV/bl7Fu@td3wi3KfVDW9NnuRAZy/2iCQINZxWSW9sYcy@hcRbmnRtAGzBWVxW094erivaf8iU5Ke5fM38jqZFBfTVvPnV/lW6NJKepmbKfG1aEAgk95p0dSKiGcSHTVGXZHpECO@49GKOww4hCzJLcE6MEDxjn4xc)
Thanks for @KevinCruijssen for saving 2 bytes!
```
->n,d{*h,t=n;i=20170408>d;f=?\n;h.map{|u|o=u.digits|[]==[4];f=o&&i ?f+"crossed out #{u} is still regular #{u} ;(":f;o&&!i ?"<s> #{u} </s>":"<s>#{u}</s>"}*", "+", #{t}"+f}
```
It's a lambda function that takes a list of numbers and an integer as a date in the format of `YYYYmmdd`.
[Answer]
# [Haskell](https://www.haskell.org/), 227 bytes
```
i[]=1>0;i('4':s)=i s;i(_:_)=0>1
f l d=m l++c where a=head$filter i l;t d|d<42832=("","\ncrossed out "++a++" is still regular "++a++" ;(")|1>0=(" ","");(b,c)=t d;w n|i n=b++n++b|1>0=n;m[n]=n;m(x:s)="<s>"++w x++"</s>, "++m s
```
[Try it online!](https://tio.run/##PY9Bi4MwFITv@yuGUFolQrXrQmmMf2KPrpSosYaNaUki9uB/d6OHvczjMe99zAzC/Uqt11VVNc/KlKnolJ9uLuYKLiz32z3maZl99NDo@AhNaYt5kFZC8EGK7tAr7aWFgmYe3dIV@eX6eeERIQn5Ma19Oic7PCcPQqmglEA5OK@0hpWPSQv7b7CIxEtIEZ6PpnEvFhAkZlGTtDEPcDbDLAqGN5QaSpv91rCxMvU2ovcWnBSuDMAZ74Aszq5MNv4It45CGXC8Jv/tLQ7oUZGvlAQ/v@6a75qRGluHbP0D "Haskell – Try It Online")
Run `f` with list `l` and date `d`. 42832 is the changing date.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 173 bytes
```
a=>d=>a.map(x=>--i<1?x:`<s>${(b=/^4+$/.exec(x)?(c=x,d)<14915808e5?n=[]:" ":"")+x+b}</s>`,n="",c=0,i=a.length).join`, `+(n&&`
crossed out ${c} is still regular ${c} ;(`)
```
[Try it online!](https://tio.run/##jZHLbuIwGIX3fYooQsgWh@BbiAM4bOYRZld1lBBcGhQchNM2UtVnZ4JmVTJq6qWl7/zncizeCl9eqnM7d83eXp/NtTDZ3mRFdCrOpDPZfF5t@LZb5RufTT7Iziz@qNlkEdnOlqSjW1KaDnu64SrlsWbaxltnHp9W4dTt/HkdrsKQzrrZ7nOz8FkOZ8IQpWGoTBHV1h3aFxodm8rlCPIZcdNp/lBeGu/tPmhe22DyUX4GlQ98W9V1cLGH17q4/Ptdk5xe12XjfFPbqG4O5Jk8xgxKQyko/kSJs@/Br6K1RDCegIHT6GDb39XJEkrpwxDu6STucQXJOITSdyIaMcT3IhpLqMFtzhH/gIOEuGNjaPARlvMUaQqtoAUShSVDzG8tyCXkvZkl@mTp94KKKXAhe4kBLKBGWMhBfAk9Ag0rSyHE6F63xW6vr4ixwVjJ@OKQGuLOcD@9HjcM@b@cyRfs@hc "JavaScript (Node.js) – Try It Online")
Using curry syntax `f(array)(js_timestamp)`
[Answer]
# JavaScript, 194 bytes
```
(a,d,l=a.pop(),n=a.find(x=>/^4+$/.exec(x)),s=a.map(n=>`<s>${n}</s>, `).join``+l)=>d<1491609600?n?s+`
crossed out ${n} is still regular ${n} ;(`:s:s.replace(/>(4+)</g,(_,m)=>`> ${m} <`)
```
```
f=
(a,d,l=a.pop(),n=a.find(x=>/^4+$/.exec(x)),s=a.map(n=>`<s>${n}</s>, `).join``+l)=>d<1491609600?n?s+`
crossed out ${n} is still regular ${n} ;(`:s:s.replace(/>(4+)</g,(_,m)=>`> ${m} <`)
const date = s => Date.parse(s) / 1000
for(const output of [
f([50, 48, 44, 41], date('January 1, 2017')),
f([500, 475, 444, 301, 248], date('June 2, 2018')),
f([8, 6, 4], date('December 5, 2017')),
f([8, 6, 4, 3, 2], date('September 15, 2015')),
f([119, 99, 84, 82, 74, 60, 51, 44, 36, 34], date('February 29, 2016')),
f([404, 123, 44], date('March 4, 2016')),
f([4, 3], date('April 8, 2017')),
f([44], date('October 22, 2017')),
f([50000, 44444, 1500], date('August 1, 2018')),
f([50, 38, 23], date('September 8, 2001')),
]) console.log(output)
```
] |
[Question]
[
I'm looking out of my attic window into my neighbor's yard. They have a dog chained to a post in the center of the yard. The dog runs around the yard but is always on the end of its chain, so it ends up leaving a track in the dirt. Normally this track would be perfectly circular, but my neighbors have some other poles in their yard that the dog's chain gets caught on. Each time the dogs chain hits a pole the dog begins rotating about the new pole with whatever length of chain is left as its radius. Since the poles, the dog and the chain all have zero width (my neighbors are mathematicians) the chain can wind around a pole indefinitely without the radius of the circle shortening. The dog can also pass through the chain (just not its collar) if the chain is in its path. After observing this oddity for a while I decide I will write some code to simulate my neighbor's dog. The code will take the locations of a center pole, to which the dog is chained, the locations of the other poles in my neighbors yard, the length of the chain, and the starting location of the dog, and will output a diagram indicating the path where the dog has worn down the grass. You may assume that any combination of the following are constant (and thus not take them as input):
* Location of the pole to which the dog is chained
* Length of the chain
* Starting location of the dog
The sun is rising, so the space on the floor of my attic illuminated by the window is shrinking, giving me less and less space to write my code. Please try to minimize the byte count of your code so that I have space to draft it on my attic floor.
## Test cases
Here I assume that the dog starts 3 units south from the to which pole it is chained (the red dot), located at `0,0`. I have indicated where the poles are with dots for clarity, you do not need to include them in your output.
`Poles at 1,2 -1,2`
[](https://i.stack.imgur.com/eNkFY.png)
`Poles at 0,.5`
[](https://i.stack.imgur.com/Czprq.png)
`Poles at 0,1 1,1 -2,1 -1,-.5`
[](https://i.stack.imgur.com/thYVM.png)
`Poles at 0,1 1,1`
[](https://i.stack.imgur.com/kcSYo.png)
[Answer]
## Python 3 using matplotlib, 457 bytes
```
from cmath import*
from matplotlib import pyplot as g,patches as i
def x(p):
p+=[0];d=180/pi;a=2;h=g.gca();h.set_xlim(-5,5);h.set_ylim(-5,5)
while a:
a-=1;c=0;y=3;z=-pi/2
while 1:
s=[n for n in p if abs(n-c)<=y and n!=c]
if not s:h.add_patch(i.Arc((c.real,c.imag),y*2,y*2));break
n=[max,min][a](s,key=lambda n:(z-phase(n-c))%(2*pi));l,r=polar(n-c);h.add_patch(i.Arc((c.real,c.imag),y*2,y*2,[z,r][a]*d,0,[r-z,z-r][a]*d));y-=l;z=r;c=n
g.show()
```
Because your neighbors are mathematicians I've assumed that your neighbor's garden occupies the complex domain and any coordinates of objects in the garden are therefore complex numbers. To use this function, you should therefore pass it a list of complex numbers signifying the locations of the poles in your neighbor's garden. The default coordinate system representation has been chosen, where to the right are positive real numbers and upwards are positive imaginary numbers. This means the examples become:
```
x([2j+1,2j-1])
x([.5j])
x([1j,1+1j,-2+1j,-1-.5j])
x([1j,1+1j])
```
Furthermore, the program assumes the following things: the leash is tied to the point 0, the leash is 3 units long, and the plot area is 10 by 10 centered around 0. For these parameters, the results match up exactly with the examples, and this is how the result looks like (for the final example):
[![x([1j,1+1j])](https://i.stack.imgur.com/rTW3q.png)](https://i.stack.imgur.com/rTW3q.png)
The algorithm is quite simple, only requiring one conditional to differentiate the clockwise and the counterclockwise search. The state of the algorithm is defined by the current rotation point and the orientation/remaining length of the leash when it hit the current rotation point. It works as follows:
* Filter out points from the collision set that are further away from the current rotation point than the remaining leash length, as well as the current rotation point.
* If this set is empty, draw a circle with the radius of the remaining belt length around this point as the end of this arm has been reached.
* Determine the point where the phase difference between the difference vector and the leash orientation is minimal/maximal. This is the next point the leash will hit in the clockwise/counterclockwise direction respectively.
* Draw the arc based on these vectors, take the leash length, subtract the magnitude of the distance and set the leash orientation to the orientation of the difference vector. Update the rotation point and continue from the start.
This algorithm is then performed first in the clockwise direction, after which the state is reset and it is executed in the counterclockwise direction. The simplicity of the algorithm means that about half of the program bytecount is spent on the drawing functions. If the drawing routines were stripped out it would remove 218 bytes from the program size.
The following is an ungolfed version that also contains debug code, which also displays points and leash collisions:
```
from cmath import pi, rect, polar, phase
from matplotlib import pyplot, patches
def x_ungolfed(points):
degrees = 180/pi # conversions
# add the center point to the collision points
points.append(0.0)
# configure plot area
axes=pyplot.gca()
axes.set_xlim(-5,5)
axes.set_ylim(-5,5)
# plot the points
x, y =zip(*((p.real, p.imag) for p in points))
axes.scatter(x, y, 50, "b")
# first iteration is clockwise, second counterclockwise
clockwise = 2
while clockwise:
clockwise -= 1
# initial conditions
center = 0 + 0j;
leash_size = 3
leash_angle = -pi / 2
# initial leash plot
leash_start = rect(leash_size, leash_angle)
axes.plot([center.real, leash_start.real], [center.imag, leash_start.imag], "r")
# search loop
while 1:
# find possible collission candidates
candidates = [n for n in points if abs(n - center) <= leash_size and n != center]
# if we reached the end, draw a circle
if not candidates:
axes.add_patch(patches.Arc(
(center.real, center.imag),
leash_size*2, leash_size*2
))
break
# find the actual collision by comparing the phase difference of the leash angle vs the difference between the candidate and the current node
new = (min if clockwise else max)(candidates, key=lambda n: (leash_angle - phase(n - center)) % (2 * pi))
# convert the difference to polar coordinates
distance, new_angle = polar(new - center)
# draw the arc
if clockwise:
axes.add_patch(patches.Arc(
(center.real, center.imag),
leash_size * 2, leash_size * 2,
new_angle * degrees,
0,
(leash_angle-new_angle) * degrees
))
else:
axes.add_patch(patches.Arc(
(center.real, center.imag),
leash_size * 2, leash_size * 2,
leash_angle * degrees,
0,
(new_angle - leash_angle) * degrees
))
# draw intermediate lines
edge = rect(leash_size, new_angle) + center
axes.plot([center.real, edge.real], [center.imag, edge.imag], "g")
# perform updates: decrease remaining leash size, set new leash angle, move rotation center to the collision
leash_size -= distance
leash_angle = new_angle
center = new
# show the graph
pyplot.show()
```
The output it produces looks like this:
[](https://i.stack.imgur.com/FrIXS.png)
[Answer]
# Processing 3, 815 ~~833~~ ~~835~~ ~~876~~ ~~879~~ bytes
*Saved two bytes thanks to @ZacharyT by removing unnecessary parentheses*
```
void settings(){size(600,600);}int i,w,x,n;float l,d,t,a,f,g,m,R,U;float[][]N,T;float[]S,p;void s(float[][]t){N=new float[t.length+1][2];N[0][0]=N[0][1]=i=0;for(float[]q:t)N[++i]=q;translate(w=300,w);noFill();pushMatrix();f(N,0,-w,w,1,0);popMatrix();f(N,0,-w,w,0,0);}float p(float a,float b){for(a+=PI*4;a>b;)a-=PI*2;return a;}void f(float[][]P,float x,float y,float L,int c,int I){l=2*PI;d=i=0;S=null;for(;i<P.length;i++){float[]p=P[i];g=atan2(y,x);m=atan2(p[1],p[0]);if(p(f=(c*2-1)*(g-m),0)<l&(t=dist(0,0,p[0],p[1]))<=L&I!=i){l=p(f,0);S=new float[]{g,m};d=t;n=i;}}if(S==null)ellipse(0,0,2*(L-d),2*(L-d));else{arc(0,0,L*2,L*2,p(S[c],S[1-c]),S[1-c]);R=cos(a=S[1]);U=sin(a);translate(d*R,d*U);T=new float[P.length][2];for(int i=0;i<T.length;T[i][1]=P[i][1]-d*U,i++)T[i][0]=P[i][0]-d*R;f(T,(L-d)*R,(L-d)*U,L-d,c,n);}}
```
Run this program like so:
```
void setup() {
s(new float[][]{{0,100},{100,100},{-200,100},{-100,-50}});
}
```
(the function `s` takes in a `float[][]`). This is essentially testcase #3, but multiplied by 100 to fit the window.
Several things to note:
* the program does NOT draw poles
* the images appear flipped upside-down because in Processing's coordinate system, the positive y-axis goes down
* because Processing uses floats, the calculations are not very accurate, so you might see this in the images. I have asked the OP if these floating-point error matter.
* the size of the window is 600 pixels by 600 pixels
* very small input coordinates will bork the program because the stack `pushMatrix()` and `popMatrix()` operate on can only hold 32 matrices.
* the dog starts at (0, -300) and the chain starts at 300 pixels long
* the images below have been minified for convenience
Sample output for the above testcase.
[](https://i.stack.imgur.com/pD7Uzm.png)
If you want to see the prettified output, add this line right after the `translate(w,w);` in function `s`.
```
background(-1);scale(1,-1);fill(255,0,0);ellipse(0,0,25,25);fill(0);for(float[]q:N)ellipse(q[0],q[1],25,25);
```
And this gives us this result:
[](https://i.stack.imgur.com/6XKBRm.png)
# Ungolfed `f()` and explanation
(contains debug code as well)
```
void f(float[][]points, float x, float y, float len, int c, int pindex) {
print(asd+++")");
float closest = 2*PI;
float d=0,t;
float[]stuff = null;
int index = 0;
for(int i=0;i<points.length;i++) {
if(pindex != i) {
float[]p = points[i];
float originAngle = atan2(y, x);
float tempAngle = atan2(p[1], p[0]);
//println(x,y,p[0],p[1]);
float diff = c<1?tempAngle-originAngle:originAngle-tempAngle;
println("@\t"+i+"; x=\t"+x+"; y=\t"+y+"; tx=\t"+p[0]+"; ty=\t",p[1], diff, originAngle, tempAngle);
if(p(diff) < closest && (t=dist(0,0,p[0],p[1])) < len) {
println("+1");
closest = p(diff);
stuff = new float[]{originAngle, tempAngle};
d=t;
index = i;
}
}
}
if(stuff == null) {
ellipse(0,0,2*(len-d),2*(len-d));
println("mayday");
} else {
println("d angles",d,p(stuff[c],stuff[1-c],c), stuff[1-c]);
//println(points[0]);
arc(0, 0, len*2, len*2, p(stuff[c],stuff[1-c],c), stuff[1-c]);
float angle = stuff[1];
translate(d*cos(angle), d*sin(angle));
println("Translated", d*cos(angle), d*sin(angle));
println("angle",angle);
float[][]temp=new float[points.length][2];
for(int i=0;i<temp.length;i++){
temp[i][0]=points[i][0]-d*cos(angle);
temp[i][1]=points[i][1]-d*sin(angle);
println(temp[i]);
}
println(d*sin(angle));
pushMatrix();
println();
f(temp, (len-d)*cos(angle), (len-d)*sin(angle), (len-d), c, index);
popMatrix();
//f(temp, (len-d)*cos(angle), (len-d)*sin(angle), (len-d), 0, index);
}
}
```
To put it shortly, the program sends two "seekers", one goes anti-clockwise and the other clockwise. Each of these seekers finds the closest pole and draws an arc to it if the chain is long enough, other wise it draws a circle. Once it draws an arc, it sends another seeker to that pole and the process continues. `f()` contains the process of each seeker. A more detailed explanation will come as soon as I golf this more.
[Answer]
## LOGO, ~~305~~ ~~298~~ ~~297~~ 293 bytes
Try the code on FMSLogo.
Define a function `draw` (golfed as `d`) that, given input as a list of pole coordinate (for example `draw [[0 100] [100 100] [-200 100] [-100 -50][0 0]]`, will draw on screen the result.
Requirements:
1. Initial rope length = 300 pixels. (as 3 pixels is too small)
2. `[0 0]` must be included in pole list. If debug code (draw poles) is turned on, then `[0 0]` must be the last item.
3. The dog start at coordinate `x=0, y=-300` (as in the problem description)
Possible optimizations:
1. -1 byte if exceptional case (the dog run into a pole) is not required to be mathematically correct by replacing `>=` with `>`
---
Golfed code:
```
to f
op(if ?=pos 360 modulo :m*(180+heading-towards ?)360)
end
to x :m[:1 300]
home
forever[make 2 filter[:1>=u ?](sort :p[(u ?)<u ?2])invoke[pd
arc -:m*f :1
pu
if 360=f[stop]make 1 :1-u ?
lt :m*f
setpos ?]reduce[if f<invoke[f]?2[?][?2]]:2]
end
to d :p
copydef "u "distance
foreach[1 -1]"x
end
```
---
Ungolfed code (`;` starts an inline comment (used for explanation), and `:` starts a variable name):
```
to f
op ifelse ? = pos 360 modulo :m*(180 + heading - towards ?) 360
end
to x
home
foreach :poles [pu setpos ? pd circle 5] ; debug code
make "length 300 ; initial length of rope
forever [
make "tmp filter [:length >= distance ?] ; floating point error makes > and >= similar, ~
; but >= is correct mathematically ~
(sort :poles [(distance ?) < distance ?2])
; the last = longest element will be rotated
invoke [
pd
arc -:m*f :length
pu
if 360=f [stop]
make "length :length - distance ?
lt :m*f
setpos ?
] reduce [
if f < invoke[f]?2 [?] [?2]
] :tmp ; apply to use ? instead of :pos
]
end
to draw :poles
foreach [1 -1] [[m]
x
]
end
```
[Answer]
# Python 2 + PIL, 310 bytes
```
from PIL import Image
from cmath import*
I,_,X,P=Image.new('1',(300,300),'white'),abs,polar,input()
def r(s):
a,C,l=0,0,3
while _(a)<99:
c=C+l*exp(1j*a);I.load()[c.real*30+150,150-c.imag*30]=0
for p in P+[0]:
N,E=X(C-c);n,e=X(C-p)
if n<=N and _(E-e)<.1:l-=_(p-C);C=p
a+=s
r(.01)
r(-.01)
I.show()
```
The script reads the list of points from stdin as a list of complex numbers.
```
printf '[complex(0,0.5)]' | python2 snippet.py
```
[](https://i.stack.imgur.com/mJxZ6.png)
```
printf '[complex(0,1), complex(1,1)]' | python2 snippet.py
```
[](https://i.stack.imgur.com/l25D7.png)
] |
[Question]
[
    
It's winter, and the time of year has come for it to start getting cold (and for strange colorful headcloths to start appearing... soon). Let's write some code to make avatar pictures and other images frozen over, to fit the theme!
# Input
The input to submissions to this challenge should be an image (the image to make frozen) and a number (the threshold, which will be explained later).
You may input the image in any way your language supports them (a file path or URL as an argument, taking it from the clipboard, dragging and dropping an image, etc.) and in [any format listed here](https://en.wikipedia.org/wiki/Image_file_formats) that expresses colors in RGB (you can support / require RGBA instead if you want, but this is not a requirement).
You can input the number in any way you would like as well (command line argument, STDIN, input dialog, etc.), with the exception of hardcoding it into your program (ex. `n=10`). If you use a file path / URL for the image, it must be input in this manner as well.
# Output
The program must process the image according to the description below and then output it in any way you would like (to a file, showing it on screen, putting it on the clipboard, etc.).
# Description
Submissions should process the image with the following three steps. `n` refers to the number that your program received as input along with the image.
1. Apply a blur of radius `n` to the input image by replacing each pixel's R, G, and B values with the average R, G, and B values of all pixels within a [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry) of `n` pixels, ignoring all out-of-bounds coordinates. (I.e. all pixels where the sum of the difference in X and the difference in Y is less than or equal to `n`.)
(note: I used a Gaussian blur for the images above because there was a convenient built-in function for it, so your images might look a little different.)
2. Set each pixel to a random pixel within a distance of `n/2` pixels ("distance" is defined the same way as in the previous step).
This should be done by looping through the image and setting each pixel to a random pixel in this range, so some pixels might disappear entirely and some might be duplicated.
All changes must apply at the same time. In other words, use the old values of the pixels (after step 1 but before this step), not the new values after setting them to a random pixel.
3. Multiply the "blue" RGB value of each pixel by 1.5, capping it at 255 (or whatever the maximum value for a band of pixels is) and rounding down.
# Rules
* You may use image libraries / image processing-related functions built into your language; however, you may not use any functions that perform one of the three major tasks mentioned in the description. For example, you can't use a `blur` function, but a `getPixel` function is fine.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
## Python 2 - 326 ~~339 358~~
Takes input from the user. File first, then `n`.
```
from PIL.Image import*;from random import*
a,N=input()
i=open(a)
d=list(i.getdata())
x,y=i.size
R=range(x*y)
m=lambda p,n,r:[p[i]for i in R if abs(n%x-i%x)+abs(n/y-i/y)<=r]
k=d[:]
for p in R:t=map(lambda x:sum(x)/len(x),zip(*m(k,p,N)));d[p]=t[0],t[1],min(255,t[2]*3/2)
i.putdata([choice(m(d,p,N/2))for p in R])
i.save('t.png')
```
This could probably be golfed much more :P Thanks to @SP3000 for golf ideas!
Sample input:
(Windows)
```
"C:/Silly/Optimizer/Trix/Are/For/Kids.png",7
```
**Edit**: Bug fixed where blue was being propagated (Martin with n=20 is no longer a river ;\_; )
Martin with n=2:

Martin with n=10:

Martin with n=20:

[Answer]
## Python 2 - 617 Bytes
EDIT: golfed some, looks like FryAmTheEggMan has me beat though :)
```
from PIL import Image
import sys,random
j,i,n=sys.argv
n=int(n)
i=Image.open(i)
w,h=i.size
o=Image.new("RGB",(w,h))
D=list(i.getdata())
D=[D[i*w:i*w+w] for i in range(h)]
O=[]
d=n/2
z=range(-n,n+1)
M=lambda n:[[x,y] for x in z for y in z if abs(x)+abs(y)<=n]
m=M(n)
L=w*h
for i in range(L):
y,x=i/w,i%w;c=r=g=b=0
for q in m:
try:C=D[y+q[1]][x+q[0]];r+=C[0];g+=C[1];b+=C[2];c+=1
except:pass
r/=c;g/=c;b/=c
O.append((r,g,min(b*3/2,255)))
R=lambda:random.randint(-d,d)
for i in range(L):
x,y=i%w,i/w;u=R();v=R()
while not(0<x+u<w and 0<y+v<h):u=R();v=R()
O[y*w+x]=O[(y+v)*w+(x+u)]
o.putdata(O)
o.save("b.png")
```
[Answer]
# Java - 1009 bytes
eh, I thought I could do better than this...
```
import java.awt.*;import java.io.*;import java.util.*;import javax.imageio.*;class r{public static void main(String[]v)throws Exception{java.awt.image.BufferedImage i=ImageIO.read(new File("y.png"));int n=Byte.valueOf(v[0]),w=i.getWidth(),h=i.getHeight();for(int z=0;z<w*h;z++){int x=z/h,y=z%h,r=0,g=0,b=0,c=0,x2,y2,k;for(x2=x-n;x2<=x+n;x2++){for(y2=y-n;y2<=y+n;y2++){if(Math.abs(x2-x)+Math.abs(y2-y)<=n&&x2>=0&&x2<w&&y2>=0&&y2<h){k=i.getRGB(x2,y2); r+=(k>>16)&0xFF;g+=(k>>8)&0xFF;b+=k&0xFF;c++;}}}i.setRGB(x,y,new Color(r/c,g/c,b/c).getRGB());}int[]t=new int[w*h];for(int z=0;z<h*w;z++){int x=z/h,y=z%h,x2,y2;ArrayList<Integer>e=new ArrayList<>();for(x2=x-n;x2<=x+n;x2++){for(y2=y-n;y2<=y+n;y2++){if(Math.abs(x2-x)+Math.abs(y2-y)<=n/2&&x2>=0&&y2>=0&&x2<w&&y2<h)e.add(i.getRGB(x2,y2));}}int p=e.get((int)(Math.random()*e.size())),b=(int)((p&0xFF)*1.5);t[x*h+y]=new Color((p>>16)&0xFF,(p>>8)&0xFF,b>255?255:b).getRGB();}for(int d=0;d<w*h;d++){i.setRGB(d/h,d%h,t[d]);}ImageIO.write(i,"PNG",new File("n.png"));}}
```
---
```
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;
class IceBlur{
public static void main(String[]v)throws Exception{
java.awt.image.BufferedImage i=ImageIO.read(new File("blah.png"));
int n=Byte.valueOf(v[0]),w=i.getWidth(),h=i.getHeight();
for(int z=0;z<w*h;z++){
int x=z/h,y=z%h,r=0,g=0,b=0,c=0,x2,y2,k;
for(x2=x-n;x2<=x+n;x2++){
for(y2=y-n;y2<=y+n;y2++){
if(Math.abs(x2-x)+Math.abs(y2-y)<=n&&x2>=0&&x2<w&&y2>=0&&y2<h){
k=i.getRGB(x2,y2);
r+=(k>>16)&0xFF;
g+=(k>>8)&0xFF;
b+=k&0xFF;
c++;}}}i.setRGB(x,y,new Color(r/c,g/c,b/c).getRGB());}
int[]t=new int[w*h];
for(int z=0;z<h*w;z++){
int x=z/h,y=z%h,x2,y2;
ArrayList<Integer>e=new ArrayList<>();
for(x2=x-n;x2<=x+n;x2++){
for(y2=y-n;y2<=y+n;y2++){
if(Math.abs(x2-x)+Math.abs(y2-y)<=n/2&&x2>=0&&y2>=0&&x2<w&&y2<h)e.add(i.getRGB(x2, y2));}}
int p=e.get((int)(Math.random()*e.size())),b=(int)((p&0xFF)*1.5);
t[x*h+y]=new Color((p>>16)&0xFF,(p>>8)&0xFF,b>255?255:b).getRGB();}
for(int d=0;d<w*h;d++){i.setRGB(d/h, d%h, t[d]);}
ImageIO.write(i,"PNG",new File("blah2.png"));}}
```
Martin with n=5:

n=20:

Me with 10:

[Answer]
# C, 429 (391 + 38 for define flags)
```
i,R,G,B,q;char*c,t[99];main(r,a,b,k,z,p){scanf("%*[^ ]%d%*6s%d%[^N]%*[^R]R\n",&a,&b,t);int j=a*b,d[j],e[j];F(c=d;c<d+j;*c++=getchar());F(;i<j;e[i++]=X<<24|B/q<<16|G/q<<8|R/q,R=G=B=q=0)F(k=0;k<j;)p=d[k++],D<r&&(++q,R+=p&X,G+=p>>8&X,B+=p>>16&X);F(i=!printf("P7\nWIDTH %d\nHEIGHT %d%sNDHDR\n",a,b,t);i<j;d[i++]=e[k])F(;k=rand()%j,D>r/2;);F(c=d;q<j*4;i=(q%4-2?2:3)*c[q]/2,putchar(i>X?X:i),++q);}
```
Input format: `pam` file with no comments or extra whitespace in header, contents passed via STDIN.
`n` arguments are required (they can be anything).
Output format: `pam` file in STDOUT.
To compile:
```
gcc -DX=255 -DF=for "-DD=z=abs(k-i),z/b+z%a" -Wl,--stack,33554432 -funsigned-char icyavatars.c -o icyavatars
```
`-Wl,--stack,33554432` increases the stack size; this may be changed or removed, depending on the size of the picture being processed (the program requires a stack size greater than twice the number of pixels times 4).
`-funsigned-char` has gcc use `unsigned char` instead of `signed char` for `char`. The C standards allows for either of these options, and this option is only needed here because gcc uses `signed char` by default.
To run (n=5):
```
./icyavatars random argument here fourth fifth < image.pam > output.pam
```
**Note:** If compiling on Windows, `stdio.h`, `fcntl.h` and `io.h` must be included, and the following code added to the start of `main()` in order for the program to read/write to STDIN/STDOUT as binary, not text, streams (this is irrelevant on Linux, but Windows uses `\r\n` instead of `\n` for text streams).
```
setmode(fileno(stdin), _O_BINARY);
setmode(fileno(stdout), _O_BINARY);
```
### Commented version
```
int i,R,G,B,q;
char *c,t[99];
main(r,a,b,k,z,p){
// read all of header
// save a large chunk to t, save width to a, save height to b
scanf("%*[^ ]%d%*6s%d%[^N]%*[^R]R\n", &a, &b, t);
// create arrays for holding the pixels
int j = a * b, d[j], e[j];
// each pixel is 4 bytes, so we just read byte by byte to the int arrays
for(c = d; c < d + j; ++c)
*c=getchar();
// calculating average rgb
for(i = 0; i < j; ++i){
// check every pixel; add r/g/b values to R/G/B if manhattan distance < r-1
for(k = 0; k < j; ++k){
// pixel being checked
p = d[k];
// manhattan distance
z = abs(k - i)/b + abs(k - i)%a;
if(z < r){
// extract components and add
++q;
R += p & 255;
G += p >> 8 & 255;
B += p >> 16 & 255;
}
}
// set pixel in e (not d) to average RGB and 255 alpha
e[i]= 255<<24 | B/q<<16 | G/q<<8 | R/q;
// clear temporary variables
R = G = B = q = 0;
}
// print header
printf("P7\nWIDTH %d\nHEIGHT %d%sNDHDR\n",a,b,t);
// choose random pixels
for(i = 0; i < j; ++i){
// loop until randomly generated integer represents a pixel that is close enough
do{
k = rand() % j;
// manhattan distance
z = abs(k - i)/b + abs(k - i)%a;
}while(z > r/2);
// set d to the new pixel value
d[i] = e[k];
}
// apply blue scaling and output
for(c = d, q = 0; q < j * 4; ++q){
// 3/2 if blue component, 1 otherwise
i = (q % 4 - 2 ? 2 : 3)*c[q]/2;
// cap components at 255
putchar(i > 255 ? 255 : i);
}
}
```
Martin with n=10:

Martin with n=20:

Martin with n=100:

[Answer]
# R, 440 chars
```
f=function(n,p){a=png::readPNG(p);b=a;N=nrow(a);M=ncol(a);r=row(a[,,1]);c=col(a[,,1]);for(i in 1:N)for(j in 1:M)b[i,j,]=apply(a,3,function(x)mean(x[abs(r-i)+abs(c-j)<=n]));for(i in 1:N)for(j in 1:M){g=which(abs(r-i)+abs(c-j)<=n/2,arr.ind=T);o=sample(1:nrow(g),1);b[i,j,]=b[g[o,1],g[o,2],]};b[,,3]=b[,,3]*1.5;b[b>1]=1;png(w=M,h=N);par(mar=rep(0,4));plot(0,t="n",xli=c(1,M),yli=c(1,N),xaxs="i",yaxs="i",ax=F);rasterImage(b,1,1,M,N);dev.off()}
```
With line breaks for legibility:
```
f=function(n,p){
a=png::readPNG(p) #use readPNG from package png
b=a
N=nrow(a)
M=ncol(a)
r=row(a[,,1])
c=col(a[,,1])
for(i in 1:N){ #braces can be deleted if all is contained in one line
for(j in 1:M){
b[i,j,]=apply(a,3,function(x)mean(x[abs(r-i)+abs(c-j)<=n]))
}
}
for(i in 1:N){ #i'm sure this loop could be shortened
for(j in 1:M){
g=which(abs(r-i)+abs(c-j)<=n/2,arr.ind=T)
o=sample(1:nrow(g),1)
b[i,j,]=b[g[o,1],g[o,2],]
}
}
b[,,3]=b[,,3]*1.5 #readPNG gives RGB values on a [0,1] range, so no need to round
b[b>1]=1
png(w=M,h=N)
par(mar=rep(0,4))
plot(0,t="n",xli=c(1,M),yli=c(1,N),xaxs="i",yaxs="i",ax=F)
rasterImage(b,1,1,M,N)
dev.off()
}
```
Sample input: `f(2,"avatar.png")`
Results with n=2

... with n=10

... with n=20

] |
[Question]
[
*Inspired by [this](https://codegolf.stackexchange.com/questions/187313/golf-the-smallest-circle) challenge, as well as a problem I've been working on*
## **Problem:**
Given a non-empty set of points in `3D` space, find the diameter of the smallest sphere that encloses them all. The problem is trivial if the number of points is three or fewer so, for the sake of this challenge, the number of points shall be greater than three.
**Input:** A list of 4 or more points, such that no three points are colinear and no four points are coplanar. Coordinates must be floats, and it is possible that two or more points may share a coordinate, although no two points will be the same.
**Output:** The diameter of the set (the diameter of the smallest sphere that encloses all points in the set), as a float. As has been pointed out, this is *not* necessarily the same as the largest distance between any two points in the set.
## Rules:
1. You may assume that the points are not colinear.
2. The smallest program (in bytes) wins. Please include the language used, and the length in bytes as a header in the first line of your answer.
## Example I/O:
**Input:**
```
[[4, 3, 6], [0, 2, 4], [3, 0, 4], [0, 9, 1]]
```
**Output:**
`9.9498743710662`
---
**Input:**
```
[[8, 6, 9], [2, 4, 5], [5, 5, 4], [5, 1, 6]]
```
**Output:**
`7.524876236605994`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
2#2&@@CircumscribedBall@#&
```
Version 13.3 introduced [`CircumscribedBall`](https://reference.wolfram.com/language/ref/CircumscribedBall.html).
[](https://i.stack.imgur.com/1jwUe.png)
---
For versions 13.2 and below,
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
2#2&@@#~BoundingRegion~"MinBall"&
```
[Try it online!](https://tio.run/##Pcy9CoMwFAXg3acoBpxO4UaN1KFF3AulHUuHYP0JaIRip2BePU2D7fZx7rlnksvQTnJRjXTd0aUsTaqK2Xp@66fS/bXt1axtfFa6luMYJ@7yUnq5s/2pq9gjsbdGamsiY3JkKFZEO0NIkQdloE2EEnz1NOaAAmUIfQ0iSEBsRQHuZ0KR/DeFkP9F/vwTfRej1X0A "Wolfram Language (Mathematica) – Try It Online")
Nearly exactly the same as the Mathematica answer to the 2D version. Works for input points of any dimension.
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
```
lambda l:2*m.get_bounding_ball(numpy.array(l))[1]**.5
import numpy,miniball as m
```
[Try it online!](https://tio.run/##VVHRbqMwEHznK1Z9ASLHwoAhVNf@CEWRIU5rnTEWNlLTKN@esw1JdUgLO7Mzu4utL/ZrUsVdjHqaLZil1/M0cGOQuZjoF@Lhiw9/jwOTMmldCfNvPiyW9ZIjeNmPL@6thfYfoYx1Mp@OQone510and8@7pKN/YmBfM13I/7k9thPizoJ9Xn0qkQto75gNs/sksg0bUm322EabbuFKnq0BGZgvFturIE3SCJwT9uWGEHhosIdgjZzWe6iDMjz2RP5rHFBcNehzX0ITs97xepEQAOiIXu4aXCGOU93tvXPgoL8h7JN/4uy5@w04t@aD5afnj/S4KZsDnVZ1CSrqnydUGOal4e6youqymjTlCtNcFXkTVOQihwoLWle@JbhuvjsO8YfS16XQ4wgZKSI3UQtjJyUKxO@z@roPM1gEQeh4EfoJBwrgsde6WuY5A/6LCdmk3Ni0zRwJy4tczzrTWL2fCX1LJQTxVd7g/07XM0NrttC7Wr4A9sG3S1O7/8A "Python 3 – Try It Online") (can't get it to work on TIO - no PyPI `miniball` module and won't let me install it through code - but works fine on my laptop)
Uses [PyPI's miniball module](https://pypi.org/project/miniball/) and works in any dimension.
Inputs a list of floating-point points (at least one coordinate of one point must be a float - i.e. have a decimal point - or `numpy` gets upset) and returns the diameter of the smallest enclosing circumsphere.
## How?
PyPI's module `miniball`'s function `get_bounding_ball` takes a `numpy` `ndarray` as the input points (with optional parameter `epsilon` which defaults to `1e-07`) and returns the centre and the squared radius of the circumsphere as a tuple. We return double the square-root of the second element which is the diameter of the circumsphere.
[Answer]
# MATLAB/Octave, ~~3931~~ 1898 bytes
The MathWorks File Exchange often has user-submitted functions for tasks like this. One function that could work is `minboundsphere`. You can access the function [here](https://www.mathworks.com/matlabcentral/fileexchange/34767-a-suite-of-minimal-bounding-objects).
\$ 3391 \text{bytes} \rightarrow 1898 \text{bytes} \$ thanks to the comment of @ceilingcat
---
Golfed version. [Try it online!](https://pastebin.com/A5rdrQPF)
```
function[c,r]=f(x)
if(n=size(x,1))<5
[c,r]=E(x);
else
l=10*eps*max(max(y=abs(x),[],1)-min(y,[],1));
c=inf(1,3);
r=inf;
if n>15
for i=1:250
a=randperm(n);
I=a(5:n);
for y=0:11
[C,R]=E(x(a(1:4),:));
[Q,k]=max(sqrt(sum((x(I,:)-repmat(C,n-4,1)).^2,2)));
if Q-R>l
[b,q]=E(x([a(2:4),I(k)],:));
if norm(b-x(a(1),:))>q
[b,q]=E(x([a([1 3 4]),I(k)],:));
if norm(b-x(a(2),:))>q
[b,q]=E(x([a([1 2 4]),I(k)],:));
if norm(b-x(a(3),:))>q
[b,q]=E(x([a(1:3),I(k)],:));
if norm(b-x(a(4),:))>q
l+=l;
else
C=b;
R=q;
w=a(4);
a=[I(k),a(1:3)];
I(k)=w;
end
else
C=b;
R=q;
w=a(3);
a=[I(k),a([1 2 4])];
I(k)=w;
end
else
C=b;
R=q;
w=a(2);
a=[I(k),a([1 3 4])];
I(k)=w;
end
else
C=b;
R=q;
w=a(1);
a=[I(k),a(2:4)];
I(k)=w;
end
else
break
end
end
if R<r
c=C;
r=R;
end
end
else
for i=1:size(A=nchoosek(1:n,4),1)
[C,R]=E(x(a=A(i,:),:));
[Q,k]=max(sqrt(sum((x(I=setdiff(1:n,a),:)-repmat(C,n-4,1)).^2,2)));
if Q-R<=l&R<r
c=C;
r=R;
end
end
end
end
end
function[c,r]=E(x)
u=inline('(A(:,z=[1 1 1 1])-A(:,z)'').^2','A');
D=sqrt(u(x(:,1))+u(x(:,2))+u(x(:,3)));
[d,i]=max(D(:));
[i,j]=ind2sub([4 4],i);
o=setdiff(1:4,[i,j]);
r=d/2;
c=(x(i,:)+x(j,:))/2;
if norm(c-x(o(1),:))>r|norm(c-x(o(2),:))>r
[c,r,n]=N(x(d=1:3,:),x(4,:),D(d,d));
if~n
[c,r,n]=N(x(d=[1 2 4],:),x(3,:),D(d,d));
if~n
[c,r,n]=N(x(d=[1 3 4],:),x(2,:),D(d,d));
if~n
[c,r,n]=N(x(d=2:4,:),x(1,:),D(d,d));
if~n
c=(2*(x(2:4,:)-repmat(x(1,:),3,1))\sum(x(2:4,:).^2-repmat(x(1,:).^2,3,1),2))';
r=norm(c-x(1,:));
end
end
end
end
end
end
function[c,r,n]=N(x,T,D)
if D(1,2)>=max(D(1,3),D(2,3))
c=mean(x(1:2,:),1);
r=D(1,2)/2;
n=norm(x(3,:)-c)<=r&norm(T-c)<=r;
elseif D(1,3)>=max(D(1,2),D(2,3))
c=mean(x([1 3],:),1);
r=D(1,3)/2;
n=norm(x(2,:)-c)<=r&norm(T-c)<=r;
elseif D(2,3)>=max(D(1,2),D(1,3))
c=mean(x(2:3,:),1);
r=D(2,3)/2;
n=norm(x(1,:)-c)<=r&norm(T-c)<=r;
end
if~n
t=x(2:3,:)-[z=x(1,:);z];
t*=o=orth(t');
c=(2*t\sum(t.^2,2))';
r=norm(c-t(1,:));
c=c*o'+z;
n=norm(T-c)<=r;
end
end
```
Ungolfed version. [Try it online!](https://tio.run/##zVpbc9u2En7Xr8CLayqlFZGS40aK22bqdibn4cyZtmf64LodmIQsxBSggKRlZzr96znfLsCLFDmOm3ZOnPhCErtY7H57pWxWyRv17t2iNlmlrRHnmTKVcrGTua7LWJfaXIhToUw2@X0a3d69jfFdqbKKz/RwcCBW2uhVvRJ@Pa0rLGiuRLleKqfEwjqhbmVWFXdiItZWm6oU2ogff5sMDkAPbuJISDG5nQjpnLyLxUZXS6FkthTOboQs8ZTpdshICJAmILxRWWVd3C6srLhUghaoXOiF0KAtQeW/tCl1jsdLJa6UUU7Sql3BR1iO/2caW7SyCQtepB6/Ta7LSppMlQOsZHGI50I6/MLFWmpHFP7QI5Fben5HKllB1FzLlQIv0GIRUfqdvxlA4jMdJXE6/Pp0JW8jvpgMofEoxe/hQAhvJRhmpaQhs0TniUgv4tkwToZzLAj2OG04PU3pLpkT9yIDEZhqAgqc0LMbvjj1ZEPxxRfdoqDo3TXzgSpK1cg66cuaPizr5F5ZJ/fJmv49sqb7ZE3ulzW9V9b0flmTT5LV5IQBYgreB2JDblSbnEHCDieL9z1NFk7J/I5kVFXtDLMBuF4tiEHu7BoI3BhyDlofC2MF0deFdLrSqhTl0tZFDpKlXK@VEdGrw5uWr8hkfbWshDR3IlfecTJQjYa0yS/wJydNydgmMaulU6rzd2wK5yykwb54bECS2dW6rrwfvncYqLNaysqTjNi/iH0hiYD9SFinr6AgKHIM1TdKn9ONKtxIZwHf57RqTj8u5oOBs7TAwk3ZDIcgwgb1DTTOUtkSAQE@mQb5YxInPcpjiAPbbxSr6Eb1xBCRXBBw@OhBUoTT4QBcWZbqCXbFPi9xmT6pb@YDtyQYlfUqqm9Gv6UA4nzQwi96@SueDw@xrAEcwyYsOIK0fFwvOliTYiRBpFXTpcyuO4b@DxLiUHwpWB1t1NI@/EwRdkOgbQI59CCL0g528f1B6DZf9@SUkE44mTw2g0zvySCaksS0CdN8@9@WsQUM0WZIKkUhZFWp1Zrzw1qWRBP2AFot0I3DFiCdtgG5Xq8LDSU0IfwXQNc/UVUX2sXa2Rv4D9iCGpmn8Y8KaF8rB3cqcRsOVCqiymxRaKPI7TilTAAiUoR1qtm5AR7O3hCyiZodJZZmlrxDupjs2ArmD7QhTwZkoFyc6c7DVZsFdA21eFWPxE8a2ctTg2ZVw6iQXoqtZa2ObAMKjgFeAyAOi29kUbeaintKJ@X4fAtbtO6N1CzzEVvqlREyzzVBJQ6i0PFKu1I4gTnqtEmblp3eaXMoaLPUqBXo8Jl2Wb06ajYpQV41AXPUx0GxkXclB5U7OheO0Auu92ORA9GeAkCsZOX0rTjD4xywB8K/jV4O4cXRLEay438XFIi2bxwO4fjzQSDRhlARHT5IxWSH8eFLilxnFETeuCoiLpx7ZkhVQzh570a6ewPZzoeOH9qj27I5kC9dRuLnLjigktlSLigpMDSIKH0oJOO1vvKK667cqtKHfMpCkilzSzH9PNevY/2awgEn44ij2bmO@RbESsv6MjqfiukFluERs@eYqapcLxZRMpvGvH7YC5PgSjm5i6R0YE1pgMNe9JqiJq3AwaLtmEqP/SZRMqRlW3l7NBoht36AJt2maVJ3Jo0oK2Rfj6Dd9GzUbRXTOqPgPpTbSOtc/gJT66IfaGJGKuGRTQLq9xBKan8vmLOpfNnb2oIsCCfxtiAQnIpkNoEBHmoAIiymeoj@nNIfZ3wH32S/ft2yLcdGll3prfc517ZqvExU1gIBj5Rr8qBcE5d/qlyTx8uVPihXqTJrPlG09K@Iljwo2kI76mr@kmQHXYzdDtK@ykMy5hjSZuE204GypCxFHsJJjNfmvKaLOeQzZedFCPug21iH8O7zyaWtq51qV4eEeYdUtPKpTL2puWwrR6FO833HjGB@5NQaYb6t7uMJhdl@GdetRXhGaNghoBqPaB5Z6DXkO8XVh6orZLFL6he8int1Vu/uTHzXq78fqsEQgWRT80S38V38dthEJ7JQXcorcPxISTjyXNUrLC5nAoiDGCRgmAWYfre9vRlMnKsyc/qSZNspBUN3TwMDZzelr6Qo@BEvrjR2NgYkmp1bbfenCXDESgLkrKFGkMxahwiMYqT0mAlfjGzPJZRwD@iUxWkeHokyk0Am/sgV0BsSani6zbDbcx9LPP3@Vq6grGAV3PgpXBtN7RmqwYWzvkvjWkZb5w2MBVWbR0D30ktRevJSvyWCDN1gGXL6HglCEwkr3KHStpXOuP5EQ@ks5bQW@OdjgX8XMXUt1MI06E98UejRcIr7Jo@SMb5QszxJj5I5P3RN1RMczzdQw3lDGbmvuQXHPhdz0X4diOPk@FmDHAQo2FflTARJ448C8LyyGVPwj@8LFPeUuPWKK87xKHn@fPrsJATysjlN79wjHCY5SU@Ocfur0fF4/EwdjenCP0nHyfFFoGq1Mh49x9cHzdsatazdQmZqj01/0fAII9SanBZWL603o1NlXVSN6S7Vfit90EamNdK894Qs8zTEwT3mipN2/SPVf4/unyXTk2fpfbpvPGeKdemJOkpOhDhKR8fHX039hTgZpSdJQhc7BmidLglO9pNSXFbNWhkdwkbcXlGWKxqPfFlXS@tm4l92acTZ4ffO6cySKY9WUhczZCqbZ0u9Lr91NqPZoXIj50aZJWf/URXkcTNofdxdihwhCPeeppOn4xMuJKnXoc5MOQfbgk92zT2pz4OcAgeltwv5stcml8GFMlfVMqKHwz9P06H44w/BV6hp/zydUCnrmR4Sedsnmu1Y7b3qkNMU9TPMIPFtBtoKh@yBJMzTXY6W1tyoW7Gskcm3ul7ITAFB5XXmsxNCx2WBHJ07CSD5iDLqNfg4NAi6dLAb2XZ3812IUTcABdULCo0o1GC@nuKgyDQ0LsFyWmuClrgIKtAdNfzgV2/qVmJr3ttEV6UqFqBbMtlpoIjA33c6zFLdZkXNRRT11e0R2gG1l9c3sg6Wv0F3Nuh5V8Tcee5F6GybCruhYogt1RZe@7K635e0yCoHHM3IGy8gJG4MuFaZlgW6GawvV1R@mXp1SQ1Zb8TtZ42UrINRvLZKxXTbjSC3HjFiUCgUR4MS2ECKoIqTtxkPfMymmc0dEHdF3T9f8IMuSF3407fxqb3hK9DALgnsGIHY20sd91P3kooHz@WtcnZ7G2hjZ5/xvm3SsI01yHvVxrbKCYyoJKlCQs/52fY2zeQ5DJx7290zXd4nxKRR3c6rl5H4wTpfF9k857WxeE0woRETTUjiQMkjYO41JZxkE@r@IDnt7KzOR@JnYoX/paYk5AIxAGVCaV7aouaa2vuqH0xxJe89nLEZyBpHR9BKj/L@xIbfnXhX31A1R@vvGSvSrHfeU@LFXgVNdxTU9hsf4OxDQY9X8La1zq6hpcpCATQOGuAvypLjJ8i0T2i4Qd/ysmQO8fkFpIL5kCp2bnpX4zkga3DaWo3mXMb2HiXHOwGPIgVNAtmYUBfWqNulxJW@obZSumzpw5x4AdmOOfwQ25ZTf/jG4DXZ0iI8XEfJcTylWiqZPPN0PIeDlQprr5u2beRhRcgiYt9yyZCLyWKSqU57bGcGfEmj/Tcv2iwiXxf0oI@bdE3yap5UcHxijtDbwNf9isIs3@OBjzeV9re7mZGJaUkTMD0KEFn2h8iF9TP9rHYOAhKbPkJ0gIjuY4TF8h1bbwvJr2iKkJwAOm@Wak/Q97XDNx5pul/p@qbds@86zEYWczQlELW1cLv7uQMA4@tm1OZ0oxvk/oieES9/kCGhA/j1r6rCTfFCNIOwgS@Ddt4r6Hm43xosUPr75CfNT34TxyD6L0@SRU8VZUVT3qu7mBIq1zJkM0WaZwoqNFHkcjHBRoKpRx@LnS34pMfjPmiI8VohuprhnGy1tVMsLoHkNzVNuWXOMwLVhxbxiI5nJii1h0OaUPbtsCjkFR5VrlbBAF7skEeCLnfO0ZxEd0cRNPOmkp/4kZ2YzwuRpMNgh8CYf30pksY8g6YNejTgHwX53kZ/EfafDvxWhvvA7@G/H/2DrmEkyXpi73nt2o3B8x6d7Mra9tztayTVm702JAEcCzBUjYTBVxqeaOWa4pswFDKqHzFDJQV3fShsVooqM24AO/u1pQ@pMboeUu4G@fUhfdoCWVeFsV77@QXEbyrPtvcvlVrRyyw8j6S4ciifEeuLK@vAejWkpFBu5Jo/cmFoi778TX5ve4Bd@pjSB0i50kMwQA3S1ylSnRTZHVDChQjaPijz0k/2/IiQ1IputgkQ1db27TbQYlHRQMnziH3m4kIDzdJ1Z5MyoWqSXTlMVYdxUN/FvF11niWxS7b8oUz63uCh5ud6SZjp@fjArwwIdC4ZDro5RRcJsmTeu99FArd1f9AfcdTrXIa5nsfd077jlb21bKkmVA37DEMQOw@HjbdUcNFfGVaQs4LbvUJRU0zorKvm/b0PYagg1v2DWwPD1Z3VfNJ43xrJP2CN9POxRvoR1kgeYY1/2Bbp326Lyedji8lH2SL9fDyDPrH091pj@vlYY/qR1pj8/6zRz1g8EPHVln@5xVyRbbrhg@GPOtBk9gqLKQs7a65GPS4ve2WTT6Ej8SpM4qlcCWzo0wzyikc47WsJ7kTTJ/j9XjBoRG5@h0aFe3MIjYaePtaSC3sTPtjEWZ/rdEtVwjdND7HbJXxij8BdNX68OxBnaqGNhwi/Fs/C5FMO6PJ3uvydoT@NxSQWz@ZiHIs0FtM5XY75D/x8HosEYOhoUqL5CgR4NmeCWBzPxXFM/6f8R4KnWzQTHocz1/GcHvs/xrzU/zH2@6AL/66pebcn2KJ9a8efauKX/M25mte1SSiwkz0D8N6ph@373TQQpB8kSDuCSSCYfJBg4qcR/3H8idr2LUE5WKzp1iI6/Lk1STIT37XTuINFLPz3RSzOwqdc8eBg8as5jEVzSqAyHBQb7eGZPppn2vFM9/OcPJrnpONJCnn3Pw)
```
function [center,radius,isin] = enc3_4(xyz,xyztest,Di)
% minimum radius enclosing sphere for exactly 3 points in R^3
%
% xyz - a 3x3 array, with each row as a point in R^3
%
% xyztest - 1x3 vector, a point to be tested if it is
% inside the generated enclosing sphere.
%
% Di - 3x3 array of interpoint distances
% test the farthest pair of points. do they form a diameter
% of the sphere?
if Di(1,2)>=max(Di(1,3),Di(2,3))
center = mean(xyz([1 2],:),1);
radius = Di(1,2)/2;
isin = (norm(xyz(3,:) - center)<=radius) && (norm(xyztest - center)<=radius);
elseif Di(1,3)>=max(Di(1,2),Di(2,3))
center = mean(xyz([1 3],:),1);
radius = Di(1,3)/2;
isin = (norm(xyz(2,:) - center)<=radius) && (norm(xyztest - center)<=radius);
elseif Di(2,3)>=max(Di(1,2),Di(1,3))
center = mean(xyz([2 3],:),1);
radius = Di(2,3)/2;
isin = (norm(xyz(1,:) - center)<=radius) && (norm(xyztest - center)<=radius);
end
if isin
% we found the minimal enclosing sphere already
return
end
% If we drop down to here, no singularities should
% happen (I've already caught any degeneracies.)
% We transform the three points into a plane, then
% compute the enclosing sphere in that plane.
% translate to the origin
xyz0 = xyz(1,:);
xyzt = xyz(2:3,:) - [xyz0;xyz0];
rot = orth(xyzt');
% uv is composed of 2 points, in 2-d, plus we
% have the origin (after the translation)
uv = xyzt*rot;
A = 2*uv;
rhs = sum(uv.^2,2);
center = (A\rhs)';
radius = norm(center - uv(1,:));
% rotate and translate back
center = center*rot' + xyz0;
% test if the 4th point is enclosed also
isin = (norm(xyztest - center)<=radius);
end
function [center,radius] = enc4(xyz)
% minimum radius enclosing sphere for exactly 4 points in R^3
%
% xyz is a 4x3 array
%
% Note that enc4 will attempt to pass a sphere through all
% 4 of the supplied points. When the set of points proves to
% be degenerate, perhaps because of collinearity of 3 or
% more of the points, or because the 4 points are coplanar,
% then the sphere would nominally have infinite radius. Since
% there must be a finite radius sphere to enclose any set of
% finite valued points, enc4 will provide that sphere instead.
%
% In addition, there are some non-degenerate sets of points
% for which the circum-sphere is not minimal. enc4 will always
% try to find the minimum radius enclosing sphere.
% interpoint distance matrix D
% dfun = @(A) (A(:,[1 1 1 1]) - A(:,[1 1 1 1])').^2;
dfun = inline('(A(:,[1 1 1 1]) - A(:,[1 1 1 1])'').^2','A');
D = sqrt(dfun(xyz(:,1)) + dfun(xyz(:,2)) + dfun(xyz(:,3)));
% Find the most distant pair. Test if their circum-sphere
% also encloses the other points. If it does, then we are
% done.
[dij,ij] = max(D(:));
[i,j] = ind2sub([4 4],ij);
others = setdiff(1:4,[i,j]);
radius = dij/2;
center = (xyz(i,:) + xyz(j,:))/2;
if (norm(center - xyz(others(1),:))<=radius) && ...
(norm(center - xyz(others(2),:))<=radius)
% we can stop here.
return
end
% next, we need to test each triplet of points, finding their
% enclosing sphere. If the 4th point is also inside, then we
% are done.
ind = 1:3;
[center,radius,isin] = enc3_4(xyz(ind,:),xyz(4,:),D(ind,ind));
if isin
% the 4th point was inside this enclosing sphere.
return
end
ind = [1 2 4];
[center,radius,isin] = enc3_4(xyz(ind,:),xyz(3,:),D(ind,ind));
if isin
% the 3rd point was inside this enclosing sphere.
return
end
ind = [1 3 4];
[center,radius,isin] = enc3_4(xyz(ind,:),xyz(2,:),D(ind,ind));
if isin
% the second point was inside this enclosing sphere.
return
end
ind = [2 3 4];
[center,radius,isin] = enc3_4(xyz(ind,:),xyz(1,:),D(ind,ind));
if isin
% the first point was inside this enclosing sphere.
return
end
% find the circum-sphere that passes through all 4 points
% since we have passed all the other tests, we need not
% worry here about singularities in the system of
% equations.
A = 2*(xyz(2:4,:)-repmat(xyz(1,:),3,1));
rhs = sum(xyz(2:4,:).^2 - repmat(xyz(1,:).^2,3,1),2);
center = (A\rhs)';
radius = norm(center - xyz(1,:));
end
function [center,radius] = minboundsphere(xyz)
% minboundsphere: Compute the minimum radius enclosing sphere of a set of (x,y,z) triplets
% usage: [center,radius] = minboundsphere(xyz)
%
% arguments: (input)
% xyz - nx3 array of (x,y,z) triples, describing points in R^3
% as rows of this array.
%
%
% arguments: (output)
% center - 1x3 vector, contains the (x,y,z) coordinates of
% the center of the minimum radius enclosing sphere
%
% radius - scalar - denotes the radius of the minimum
% enclosing sphere
%
%
% Example usage:
% Sample uniformly from the interior of a unit sphere.
% As the sample size increases, the enclosing sphere
% should asymptotically approach center = [0 0 0], and
% radius = 1.
%
% xyz = rand(10000,3)*2-1;
% r = sqrt(sum(xyz.^2,2));
% xyz(r>1,:) = []; % 5156 points retained
% tic,[center,radius] = minboundsphere(xyz);toc
%
% Elapsed time is 0.199467 seconds.
%
% center = [0.00017275 8.5006e-05 0.00012015]
%
% radius = 0.9999
%
% Example usage:
% Sample from the surface of a unit sphere. Within eps
% or so, the result should be center = [0 0 0], and radius = 1.
%
% xyz = randn(10000,3);
% xyz = xyz./repmat(sqrt(sum(xyz.^2,2)),1,3);
% tic,[center,radius] = minboundsphere(xyz);toc
%
% Elapsed time is 0.614762 seconds.
%
% center =
% 4.6127e-17 -2.5584e-17 7.2711e-17
%
% radius =
% 1
%
%
% See also: minboundrect, minboundcircle
%
%
% Author: John D'Errico
% E-mail: [[email protected]](/cdn-cgi/l/email-protection)
% Release: 1.0
% Release date: 1/23/07
% not many error checks to worry about
sxyz = size(xyz);
if (length(sxyz)~=2) || (sxyz(2)~=3)
error 'xyz must be an nx3 array of points'
end
n = sxyz(1);
% start out with the convex hull of the points to
% reduce the problem dramatically. Note that any
% points in the interior of the convex hull are
% never needed.
if n>4
tri = convhulln(xyz);
% list of the unique points on the convex hull itself
hlist = unique(tri(:));
% exclude those points inside the hull as not relevant
xyz = xyz(hlist,:);
end
% now we must find the enclosing sphere of those that
% remain.
n = size(xyz,1);
% special case small numbers of points. If we trip any
% of these cases, then we are done, so return.
switch n
case 0
% empty begets empty
center = [];
radius = [];
return
case 1
% with one point, the center has radius zero
center = xyz;
radius = 0;
return
case 2
% only two points. center is at the midpoint
center = mean(xyz,1);
radius = norm(xyz(1,:) - center);
return
case 3
% exactly 3 points. For this odd case, just use enc4,
% appending a new point at the centroid. This is simpler
% than other solutions that would have reduced the
% problem to 2-d. enc4 will do that anyway.
[center,radius] = enc4([xyz;mean(xyz,1)]);
return
case 4
% exactly 4 points
[center,radius] = enc4(xyz);
return
end
% pick a tolerance
tol = 10*eps*max(max(abs(xyz),[],1) - min(abs(xyz),[],1));
% more than 4 points. for no more than 15 points in the hull,
% just do an exhaustive search.
if n <= 15
% for 15 points, there are only nchoosek(15,4) = 1365
% sets to look through. this is only about a second.
asets = nchoosek(1:n,4);
center = inf(1,3);
radius = inf;
for i = 1:size(asets,1)
aset = asets(i,:);
iset = setdiff(1:n,aset);
% get the enclosing sphere for the current set
[centeri,radiusi] = enc4(xyz(aset,:));
% are all the inactive set points inside the circle?
ri = sqrt(sum((xyz(iset,:) - repmat(centeri,n-4,1)).^2,2));
[rmax,k] = max(ri);
if ((rmax - radiusi) <= tol) && (radiusi < radius)
center = centeri;
radius = radiusi;
end
end
else
% Use an active set strategy, on many different
% random starting sets.
center = inf(1,3);
radius = inf;
for i = 1:250
aset = randperm(n); % a random start, but quite adequate
iset = aset(5:n);
aset = aset(1:4);
flag = true;
iter = 0;
centeri = inf(1,3);
radiusi = inf;
while flag && (iter < 12)
iter = iter + 1;
% get the enclosing sphere for the current set
[centeri,radiusi] = enc4(xyz(aset,:));
% are all the inactive set points inside the circle?
ri = sqrt(sum((xyz(iset,:) - repmat(centeri,n-4,1)).^2,2));
[rmax,k] = max(ri);
if (rmax - radiusi) <= tol
% the active set enclosing sphere also enclosed
% all of the inactive points. We are done.
flag = false;
else
% it must be true that we can replace one member of aset
% with iset(k). That k'th element was farthest out, so
% it seems best (a greedy algorithm) to swap it in. The
% problem with the greedy algorithm, is it gets trapped
% in a cycle at times. but since we are restarting the
% algorithm multiple times, this will work.
s1 = [aset([2 3 4]),iset(k)];
[c1,r1] = enc4(xyz(s1,:));
if (norm(c1 - xyz(aset(1),:)) <= r1)
centeri = c1;
radiusi = r1;
% update the active/inactive sets
swap = aset(1);
aset = [iset(k),aset([2 3 4])];
iset(k) = swap;
% bounce out to the while loop
continue
end
s1 = [aset([1 3 4]),iset(k)];
[c1,r1] = enc4(xyz(s1,:));
if (norm(c1 - xyz(aset(2),:)) <= r1)
centeri = c1;
radiusi = r1;
% update the active/inactive sets
swap = aset(2);
aset = [iset(k),aset([1 3 4])];
iset(k) = swap;
% bounce out to the while loop
continue
end
s1 = [aset([1 2 4]),iset(k)];
[c1,r1] = enc4(xyz(s1,:));
if (norm(c1 - xyz(aset(3),:)) <= r1)
centeri = c1;
radiusi = r1;
% update the active/inactive sets
swap = aset(3);
aset = [iset(k),aset([1 2 4])];
iset(k) = swap;
% bounce out to the while loop
continue
end
s1 = [aset([1 2 3]),iset(k)];
[c1,r1] = enc4(xyz(s1,:));
if (norm(c1 - xyz(aset(4),:)) <= r1)
centeri = c1;
radiusi = r1;
% update the active/inactive sets
swap = aset(4);
aset = [iset(k),aset([1 2 3])];
iset(k) = swap;
% bounce out to the while loop
continue
end
% if we get through to this point, then something went wrong.
% Active set problem. Increase tol, then try again.
tol = 2*tol;
end
end
% have we improved over the best set so far?
if radiusi < radius
center = centeri;
radius = radiusi;
end
end
end
end
```
] |
[Question]
[
Your task is to write a program that, on input n, outputs the *minimal expression* of each number 1 through n in order. The shortest program in bytes wins.
A minimal expression combines 1's with addition and multiplication to result in the given number, using as few 1's as possible. For example, `23` is expressed as `23=((1+1+1)(1+1)+1)(1+1+1)+1+1` with eleven ones, which is minimal.
Requirements:
1. The program must take as input a positive natural number n.
2. Output must be in this format: `20 = ((1+1+1)(1+1+1)+1)(1+1)`
3. Your output may not have needless parentheses, like `8 = ((1+1)(1+1))(1+1)`.
4. The multiplication sign `*` is optional.
5. Spaces are optional.
6. You don't have to output all the possible equations for given value: For example, you have the choice to output `4=1+1+1+1` or `4=(1+1)(1+1)`. You don't have to output both.
7. The shortest program (in bytes) in each language wins.
```
1=1
2=1+1
3=1+1+1
4=1+1+1+1
5=1+1+1+1+1
6=(1+1+1)(1+1)
7=(1+1+1)(1+1)+1
8=(1+1+1+1)(1+1)
9=(1+1+1)(1+1+1)
10=(1+1+1)(1+1+1)+1
11=(1+1+1)(1+1+1)+1+1
12=(1+1+1)(1+1)(1+1)
13=(1+1+1)(1+1)(1+1)+1
14=((1+1+1)(1+1)+1)(1+1)
15=(1+1+1+1+1)(1+1+1)
16=(1+1+1+1)(1+1)(1+1)
17=(1+1+1+1)(1+1)(1+1)+1
18=(1+1+1)(1+1+1)(1+1)
19=(1+1+1)(1+1+1)(1+1)+1
20=((1+1+1)(1+1+1)+1)(1+1)
```
Here are some more test cases: (remember, that other expressions with the same number of 1's are also allowed)
```
157=((1+1+1)(1+1)(1+1)+1)(1+1+1)(1+1)(1+1)+1
444=((1+1+1)(1+1+1)(1+1)(1+1)+1)(1+1+1)(1+1)(1+1)
1223=((1+1+1)(1+1+1)(1+1+1)(1+1+1)(1+1+1)+1)(1+1+1+1+1)+1+1+1
15535=((((1+1+1)(1+1+1)(1+1+1)(1+1+1)+1)((1+1+1)(1+1)+1)+1)(1+1+1)+1)(1+1+1)(1+1+1)+1
45197=((((1+1+1)(1+1)(1+1)(1+1)+1)(1+1+1+1+1)(1+1)+1)(1+1+1)(1+1)(1+1)+1)(1+1+1+1+1)(1+1+1)+1+1
```
Good Luck!
- The Turtle üê¢
[Answer]
# Pyth, 60 bytes
```
LjWqeb\1b`()L?tbho/N\1++'tb"+1"m+y'/bdy'df!%bTr2b1VSQ++N\='N
```
[Demonstration](https://pyth.herokuapp.com/?code=LjWqeb%5C1b%60%28%29L%3Ftbho%2FN%5C1%2B%2B%27tb%22%2B1%22m%2By%27%2Fbdy%27df%21%25bTr2b1VSQ%2B%2BN%5C%3D%27N&input=1223&debug=0)
The online compiler can reach 1223 before the time out, thanks to Pyth's automatic function memoization.
```
1223=((1+1+1)(1+1+1)(1+1+1)(1+1+1)(1+1+1)+1)(1+1+1+1+1)+1+1+1
```
In abbrieviated notaion,
```
1223=(3^5+1)*5+3
```
This uses a recursive function `'`, which calculates all possbile products and sums which could give the desired output, finds the shortest string with each final operation, then compares them by `1` count and returns the first one.
It uses a helper function, `y`, which parenthesizes an expression only if it needs to be parenthesized.
Offline, I am running the program with the input `15535`, and it is nearly complete. Results are printed incrementally, so it is easy to see the progress.
Final lines of the output:
```
15535=((((1+1+1)(1+1+1)(1+1+1)(1+1+1)+1)((1+1+1)(1+1)+1)+1)(1+1+1)+1)(1+1+1)(1+1+1)+1
real 7m8.430s
user 7m7.158s
sys 0m0.945s
```
In abbreviated notation,
```
15535=(((3^4+1)*(3*2+1)+1)*3+1)*3^2+1
```
[Answer]
# CJam, ~~105~~ ~~102~~ ~~98~~ 96 bytes
```
q~{)'=1$2,{:I{I1$-'+}%3/1>Imf'*+aImp!*+{)\{j}%\+}:F%{e_"+*"-:+}$0=}j2,{F)_'*={;{'(\')}%1}&*}jN}/
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%7B)'%3D1%242%2C%7B%3AI%7BI1%24-'%2B%7D%253%2F1%3EImf'*%2BaImp!*%2B%7B)%5C%7Bj%7D%25%5C%2B%7D%3AF%25%7Be_%22%2B*%22-%3A%2B%7D%240%3D%7Dj2%2C%7BF)_'*%3D%7B%3B%7B'(%5C')%7D%251%7D%26*%7DjN%7D%2F&input=20).
### Test run
The online interpreter is too slow for the larger test cases. Even with the Java interpreter, the larger test cases will take a *long* time and require a significant amount of memory.
```
$ time cjam integer-complexity.cjam <<< 157
1=1
2=1+1
3=1+1+1
4=1+1+1+1
5=1+1+1+1+1
6=(1+1)(1+1+1)
7=1+(1+1)(1+1+1)
8=(1+1)(1+1)(1+1)
9=(1+1+1)(1+1+1)
10=1+(1+1+1)(1+1+1)
11=1+1+(1+1+1)(1+1+1)
12=(1+1)(1+1)(1+1+1)
13=1+(1+1)(1+1)(1+1+1)
14=(1+1)(1+(1+1)(1+1+1))
15=(1+1+1)(1+1+1+1+1)
16=(1+1)(1+1)(1+1)(1+1)
17=1+(1+1)(1+1)(1+1)(1+1)
18=(1+1)(1+1+1)(1+1+1)
19=1+(1+1)(1+1+1)(1+1+1)
20=(1+1)(1+1)(1+1+1+1+1)
21=(1+1+1)(1+(1+1)(1+1+1))
22=1+(1+1+1)(1+(1+1)(1+1+1))
23=1+1+(1+1+1)(1+(1+1)(1+1+1))
24=(1+1)(1+1)(1+1)(1+1+1)
25=1+(1+1)(1+1)(1+1)(1+1+1)
26=(1+1)(1+(1+1)(1+1)(1+1+1))
27=(1+1+1)(1+1+1)(1+1+1)
28=1+(1+1+1)(1+1+1)(1+1+1)
29=1+1+(1+1+1)(1+1+1)(1+1+1)
30=(1+1)(1+1+1)(1+1+1+1+1)
31=1+(1+1)(1+1+1)(1+1+1+1+1)
32=(1+1)(1+1)(1+1)(1+1)(1+1)
33=1+(1+1)(1+1)(1+1)(1+1)(1+1)
34=(1+1)(1+(1+1)(1+1)(1+1)(1+1))
35=(1+1+1+1+1)(1+(1+1)(1+1+1))
36=(1+1)(1+1)(1+1+1)(1+1+1)
37=1+(1+1)(1+1)(1+1+1)(1+1+1)
38=(1+1)(1+(1+1)(1+1+1)(1+1+1))
39=(1+1+1)(1+(1+1)(1+1)(1+1+1))
40=(1+1)(1+1)(1+1)(1+1+1+1+1)
41=1+(1+1)(1+1)(1+1)(1+1+1+1+1)
42=(1+1)(1+1+1)(1+(1+1)(1+1+1))
43=1+(1+1)(1+1+1)(1+(1+1)(1+1+1))
44=(1+1)(1+1)(1+1+(1+1+1)(1+1+1))
45=(1+1+1)(1+1+1)(1+1+1+1+1)
46=1+(1+1+1)(1+1+1)(1+1+1+1+1)
47=1+1+(1+1+1)(1+1+1)(1+1+1+1+1)
48=(1+1)(1+1)(1+1)(1+1)(1+1+1)
49=1+(1+1)(1+1)(1+1)(1+1)(1+1+1)
50=(1+1)(1+1+1+1+1)(1+1+1+1+1)
51=(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
52=(1+1)(1+1)(1+(1+1)(1+1)(1+1+1))
53=1+(1+1)(1+1)(1+(1+1)(1+1)(1+1+1))
54=(1+1)(1+1+1)(1+1+1)(1+1+1)
55=1+(1+1)(1+1+1)(1+1+1)(1+1+1)
56=(1+1)(1+1)(1+1)(1+(1+1)(1+1+1))
57=(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
58=1+(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
59=1+1+(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
60=(1+1)(1+1)(1+1+1)(1+1+1+1+1)
61=1+(1+1)(1+1)(1+1+1)(1+1+1+1+1)
62=(1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
63=(1+1+1)(1+1+1)(1+(1+1)(1+1+1))
64=(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)
65=1+(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)
66=(1+1)(1+1+1)(1+1+(1+1+1)(1+1+1))
67=1+(1+1)(1+1+1)(1+1+(1+1+1)(1+1+1))
68=(1+1)(1+1)(1+(1+1)(1+1)(1+1)(1+1))
69=1+(1+1)(1+1)(1+(1+1)(1+1)(1+1)(1+1))
70=(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
71=1+(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
72=(1+1)(1+1)(1+1)(1+1+1)(1+1+1)
73=1+(1+1)(1+1)(1+1)(1+1+1)(1+1+1)
74=(1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
75=(1+1+1)(1+1+1+1+1)(1+1+1+1+1)
76=(1+1)(1+1)(1+(1+1)(1+1+1)(1+1+1))
77=1+(1+1)(1+1)(1+(1+1)(1+1+1)(1+1+1))
78=(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
79=1+(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
80=(1+1)(1+1)(1+1)(1+1)(1+1+1+1+1)
81=(1+1+1)(1+1+1)(1+1+1)(1+1+1)
82=1+(1+1+1)(1+1+1)(1+1+1)(1+1+1)
83=1+1+(1+1+1)(1+1+1)(1+1+1)(1+1+1)
84=(1+1)(1+1)(1+1+1)(1+(1+1)(1+1+1))
85=1+(1+1)(1+1)(1+1+1)(1+(1+1)(1+1+1))
86=(1+1)(1+(1+1)(1+1+1)(1+(1+1)(1+1+1)))
87=(1+1+1)(1+1+(1+1+1)(1+1+1)(1+1+1))
88=(1+1)(1+1)(1+1)(1+1+(1+1+1)(1+1+1))
89=1+(1+1)(1+1)(1+1)(1+1+(1+1+1)(1+1+1))
90=(1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
91=1+(1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
92=1+1+(1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
93=(1+1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
94=1+(1+1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
95=(1+1+1+1+1)(1+(1+1)(1+1+1)(1+1+1))
96=(1+1)(1+1)(1+1)(1+1)(1+1)(1+1+1)
97=1+(1+1)(1+1)(1+1)(1+1)(1+1)(1+1+1)
98=(1+1)(1+(1+1)(1+1+1))(1+(1+1)(1+1+1))
99=(1+1+1)(1+1+1)(1+1+(1+1+1)(1+1+1))
100=(1+1)(1+1)(1+1+1+1+1)(1+1+1+1+1)
101=1+(1+1)(1+1)(1+1+1+1+1)(1+1+1+1+1)
102=(1+1)(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
103=1+(1+1)(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
104=(1+1)(1+1)(1+1)(1+(1+1)(1+1)(1+1+1))
105=(1+1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
106=1+(1+1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
107=1+1+(1+1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
108=(1+1)(1+1)(1+1+1)(1+1+1)(1+1+1)
109=1+(1+1)(1+1)(1+1+1)(1+1+1)(1+1+1)
110=1+1+(1+1)(1+1)(1+1+1)(1+1+1)(1+1+1)
111=(1+1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
112=(1+1)(1+1)(1+1)(1+1)(1+(1+1)(1+1+1))
113=1+(1+1)(1+1)(1+1)(1+1)(1+(1+1)(1+1+1))
114=(1+1)(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
115=1+(1+1)(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
116=(1+1)(1+1)(1+1+(1+1+1)(1+1+1)(1+1+1))
117=(1+1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
118=1+(1+1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
119=(1+(1+1)(1+1+1))(1+(1+1)(1+1)(1+1)(1+1))
120=(1+1)(1+1)(1+1)(1+1+1)(1+1+1+1+1)
121=1+(1+1)(1+1)(1+1)(1+1+1)(1+1+1+1+1)
122=(1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1+1+1))
123=(1+1+1)(1+(1+1)(1+1)(1+1)(1+1+1+1+1))
124=(1+1)(1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
125=(1+1+1+1+1)(1+1+1+1+1)(1+1+1+1+1)
126=(1+1)(1+1+1)(1+1+1)(1+(1+1)(1+1+1))
127=1+(1+1)(1+1+1)(1+1+1)(1+(1+1)(1+1+1))
128=(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)
129=1+(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)
130=(1+1)(1+1+1+1+1)(1+(1+1)(1+1)(1+1+1))
131=1+(1+1)(1+1+1+1+1)(1+(1+1)(1+1)(1+1+1))
132=(1+1)(1+1)(1+1+1)(1+1+(1+1+1)(1+1+1))
133=(1+(1+1)(1+1+1))(1+(1+1)(1+1+1)(1+1+1))
134=1+(1+(1+1)(1+1+1))(1+(1+1)(1+1+1)(1+1+1))
135=(1+1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
136=1+(1+1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
137=1+1+(1+1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
138=(1+1)(1+1+1)(1+1+(1+1+1)(1+(1+1)(1+1+1)))
139=1+(1+1)(1+1+1)(1+1+(1+1+1)(1+(1+1)(1+1+1)))
140=(1+1)(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
141=1+(1+1)(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
142=(1+1)(1+(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1)))
143=(1+1+(1+1+1)(1+1+1))(1+(1+1)(1+1)(1+1+1))
144=(1+1)(1+1)(1+1)(1+1)(1+1+1)(1+1+1)
145=1+(1+1)(1+1)(1+1)(1+1)(1+1+1)(1+1+1)
146=(1+1)(1+(1+1)(1+1)(1+1)(1+1+1)(1+1+1))
147=(1+1+1)(1+(1+1)(1+1+1))(1+(1+1)(1+1+1))
148=(1+1)(1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
149=1+(1+1)(1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
150=(1+1)(1+1+1)(1+1+1+1+1)(1+1+1+1+1)
151=1+(1+1)(1+1+1)(1+1+1+1+1)(1+1+1+1+1)
152=(1+1)(1+1)(1+1)(1+(1+1)(1+1+1)(1+1+1))
153=(1+1+1)(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
154=1+(1+1+1)(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
155=(1+1+1+1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
156=(1+1)(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
157=1+(1+1)(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
real 0m3.896s
user 0m4.892s
sys 0m0.066s
```
Given enough time, it would produce these solutions for the next test cases:
```
444=(1+1)(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
1223=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]
# Julia, 229 bytes
```
n->(F=i->K[i]>0?E[i]:"("E[i]")";C=[1;3:n+1];K=0C;E=fill("1",n);for s=1:n for i=1:s√∑2 (D=C[i]+C[s-i])<C[s]?(C[s]=D;E[s]=E[i]"+"E[s-i];K[s]=0):s%i>0||(D=C[i]+C[j=s√∑i])<C[s]&&(C[s]=D;E[s]=F(i)F(j);K[s]=1)end;println("$s="E[s])end)
```
This is actually pretty fast. Assigning the function to `f` and running `@time f(15535)` gives the output (last two lines only)
```
15535=1+(1+1+1)(1+1+1)(1+(1+1+1)(1+(1+(1+1)(1+1+1))(1+(1+1+1)(1+1+1)(1+1+1)(1+1+1))))
32.211583 seconds (263.30 M allocations: 4.839 GB, 4.81% gc time)
```
and for `@time f(45197)`, it gives
```
45197=1+1+(1+1+1)(1+1+1+1+1)(1+(1+1)(1+1)(1+1+1)(1+(1+1)(1+1+1+1+1)(1+(1+1)(1+1)(1+1)(1+1+1))))
289.749564 seconds (2.42 G allocations: 43.660 GB, 4.91% gc time)
```
So, what's the code doing? Simple - `C` holds the current one-`C`ount for the number, `K` is an indicator array keeping track of whether the expression is, fundamentally, a sum or a product, for the purposes of dealing with bracketing, and `E` holds the `E`xpression itself. Working its way up from `s=1` through to `n`, the code searches for the minimal representation of number `s` in terms of lower values, by looking for either a sum or a product. If it's a product, then it checks the two components and puts brackets around them if they're sums. That check is done in function `F`, to save bytes (because it has to be done twice, for the two factors).
[Answer]
# [Haskell](https://www.haskell.org/), 208 bytes
```
import Data.List;f n=mapM putStrLn[show x++"="++m x|x<-[1..n]];m 1="1";m n=head$sortOn(filter(>'0'))[let b=m$div n x;q=last b>'0'in concat["(",m x,")",['('|q],b,[')'|q]]|x<-[2..n-1],mod n x<1]++[m(n-1)++"+1"]
```
[Try it online!](https://tio.run/##HY4xb8MgFIT3/oqnp0gGQayQ1aFTx1QZMiIGEtsyKmDH0MZD/rvz3OlOd9J3N7j804Wwrj5O41zgyxVXn30uTQ9JRzd9w/RbrmU@J5OH8QmLEKhRiAjLazntjarrZG0TQWlUSJr00Ll2l4l2Saz3oXQz@6wOFecmdAVuOu5a/wcJluahg8sUbbVPcB/T3RWDDCXhJXKUpmLV62HljRzfnP1fPdLqXlkZx3YDnZQVwkRGGad/QqFdoyOihh6Oh4/1DQ "Haskell – Try It Online")
] |
[Question]
[
The turtle wants to move along the grid to get to his food. He wants to know how many moves it will take for him to get there.
As well since he is slow he has teleporters set up around his domain that he will utilize if it shortens his path. Or avoid them if it lengthens his path.
## *Meet the turtle*
`üê¢`
The turtle lives on a grid
$$\begin{matrix}
X&X&X&X&X\\
X&X&X&X&X\\
X&X&üê¢&X&X\\
X&X&X&X&X\\
X&X&X&X&X\\
\end{matrix}$$
The turtle can move to any adjacent square...
$$\begin{matrix}
X&X&X&X&X\\
X&\nwarrow&\uparrow&\nearrow&X\\
X&\leftarrow&üê¢&\rightarrow&X\\
X&\swarrow&\downarrow&\searrow&X\\
X&X&X&X&X\\
\end{matrix}$$
However, the turtle cannot move to a square with a mountain
$$\begin{matrix}
X&üåÑ&X&X&X\\
X&\nwarrow&\uparrow&\nearrow&X\\
X&üåÑ&üê¢&\rightarrow&X\\
X&üåÑ&\downarrow&\searrow&X\\
X&üåÑ&X&X&X\\
\end{matrix}$$
The Turtle wants to eat his Strawberry, and would like to know how long it will take to get to his Strawberry
$$\begin{matrix}
X&üåÑ&üçì\\
üê¢&üåÑ&X\\
X&üåÑ&X\\
X&X&X\\
\end{matrix}$$
This example would take the turtle \$5\$ turns
$$\begin{matrix}
X&üåÑ&üçì\\
\downarrow&üåÑ&\uparrow\\
\searrow&üåÑ&\uparrow\\
X&\nearrow&X\\
\end{matrix}$$
Luckily, the Turtle found a teleporter! There are two teleports on the grid that map to each other. Stepping on the teleporter immediately moves the turtle to the corresponding teleporter. Teleporters are very unstable and after using them once, they disapear and are no longer useable.
$$\begin{matrix}
üîµ&üåÑ&üçì\\
üê¢&üåÑ&üî¥\\
X&üåÑ&X\\
X&X&X\\
\end{matrix}$$
It is now faster for the turtle to move up twice. Now the turtles shortest path is \$2\$
$$\begin{matrix}
üîµ&üåÑ&üê¢\\
\uparrow&üåÑ&üî¥\uparrow\\
X&üåÑ&X\\
X&X&X\\
\end{matrix}$$
## The challenge
Given an initial grid configuration output the number of moves it will take the turtle to reach his strawberry.
## Rules
* You may assume that the input grid has a solution
* Each grid will only have one `strawberry` and two `portals` and one `turtle`
* The input grid may be entered in any convenient format
* You should treat `teleporters` are single use items
* The turn that the turtle moves onto a `teleporter` square he is already on the corresponding `teleporter`. He never moves onto a `teleporter` and stays there for a move
* The shortest path does not need to make use of the portal
* The turtle cannot pass into mountain tiles
* You may use any ASCII character or integer to represent `mountains`, `turtle`, `empty grid square`, `strawberry`
* You may use either the same character or two different ASCII characters or integers to represent the `teleporter` pairs
* A grid can have more than one path with the same shortest path length
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
## Clarifications to Rules
* You should treat `teleporters` are single use items.
**Reasoning**: It was pointed out that the case of:
$$\begin{matrix}
üê¢&X&üîµ&X&üçì\\
üåÑ&üåÑ&üåÑ&üåÑ&üåÑ&\\
üî¥&X&X&X&X
\end{matrix}$$
Could be only solved by entering and exiting the portals twice. At the time of making this clarification both solutions acted by assuming they were either single use, or there was no reason to try previously used squares. To avoid breaking their hard-worked solutions, this seemed the best way account for this set up. Therefore, this would be considered an invalid grid.
## Test Cases formatted as lists
```
[ ['T', 'X', 'X', 'S', 'X'], ['X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 3
[ ['T', 'M', 'X', 'S', 'X'], ['X', 'M', 'X', 'X', 'X'], ['O', 'X', 'X', 'X', 'O'] ] --> 4
[ ['T', 'M', 'X', 'S', 'O'], ['O', 'M', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 2
[ ['T', 'M', 'X', 'S', 'X'], ['O', 'M', 'X', 'X', 'X'], ['O', 'X', 'X', 'X', 'X'] ] --> 4
[ ['T', 'M', 'S', 'X', 'O'], ['X', 'M', 'M', 'M', 'M'], ['X', 'X', 'X', 'X', 'O'] ] --> 7
[ ['T', 'X', 'X', 'S', 'X'], ['O', 'M', 'M', 'M', 'X'], ['X', 'X', 'O', 'X', 'X'] ] --> 3
```
## Test Cases formatted for humans
```
T X X S X
X X X X X
X X X X X --> 3
T M X S X
X M X X X
O X X X O --> 4
T M X S O
O M X X X
X X X X X --> 2
T M X S X
O M X X X
O X X X X --> 4
T M S X O
X M M M M
X X X X O --> 7
T X X S X
O M M M X
X X O X X --> 3
```
**Credits**
Design and structure via: [*Hungry mouse by Arnauld*](https://codegolf.stackexchange.com/q/176251/79844)
Proposed Challenges Edit Advice: [*Kamil-drakari*](https://codegolf.meta.stackexchange.com/users/71434/kamil-drakari), [*beefster*](https://codegolf.meta.stackexchange.com/users/45613/beefster)
General Edit Advice: [*okx*](https://codegolf.stackexchange.com/users/26600/okx) [*nedla2004*](https://codegolf.stackexchange.com/users/59363/nedla2004) [*mbomb007*](https://codegolf.stackexchange.com/users/34718/mbomb007)
[Answer]
# JavaScript (ES7), ~~ 140 139 ~~ 138 bytes
Takes input as a matrix of integers with the following mapping:
* \$-1\$ = üîµ (any portal)
* \$0\$ = \$X\$ (empty)
* \$1\$ = üåÑ (mountain)
* \$2\$ = üê¢ (turtle)
* \$3\$ = üçì (strawberry)
```
m=>(R=g=(t,X,Y,i)=>m.map((r,y)=>r.map((v,x)=>r[(u=0,t?v-t:(x-X)**2+(y-Y)**2<3?v-3?~v?v:u--:R=R<i?R:i:1)||g(u,x,y,u-~i,r[x]=1),x]=v)))(2)|R
```
[Try it online!](https://tio.run/##bY5Bj4IwEIXv/oreOtW2rrDJJsTKzZtpAh40yMEomhopBoFAlvWvswVl3Rjn0MybfvPmnbbF9rpL1SVjOtlHzUE0sZiBJ44CMrqia6qImMU83l4AUloZkd5FQctWBJCLD5q5BcscKNmKDIfWCCq2bpupbea2eyvcwskZczzhTZXrOcqZkLo@Qk5LWtGc3RRNgzIUE0LNWxBCwCK118yRQDESM/SNdom@JueIn5MjxPyUKA14ozFBI4RbApvmAPegaTsIOOdp2GndAXyx9DFXeh@V8gDaHOmWO5OfwWAOAcJLzn2OqYHbejYoJGg8RvaDWvTU4h31@aRk@ynfUtaL1x8l33r5XN4vmuq9ZE99vaSXBnoElP/SN78 "JavaScript (Node.js) – Try It Online")
### How?
The main recursive search function \$g\$ is able to either look for a specific tile \$t\$ on the board (if it's called with \$t\ne 0\$) or for any tile at \$(x,y)\$ which can be reached from the current position \$(X,Y)\$.
It keeps track of the length of the current path in \$i\$ and updates the best result \$R\$ to \$\min(R,i)\$ whenever the turtle finds the strawberry.
It is first called with \$t=2\$ to find the starting position of the turtle.
It calls itself with \$t=-1\$ if a portal is reached, so that the turtle is teleported to the other portal. We do not increment \$i\$ during such an iteration.
Each visited tile is temporarily set to a mountain to prevent the turtle from moving twice on the same tile in the same path. If we get trapped in a dead-end, the recursion simply stops without updating \$R\$.
### Commented
```
m => ( // m[] = input matrix
R = // initialize R to a non-numeric value
g = (t, X, Y, i) => // g = recursive search function taking t = expected tile,
// (X, Y) = current coordinates, i = path length
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each tile v at position x in r[]:
r[ // this statement will eventually restore r[x] to v
( u = 0, // u = next tile to look for, or 0 if none
t ? // if we're looking for a specific tile:
v - t // test whether we've found it
: // else:
(x - X) ** 2 + // compute the squared Euclidean distance between
(y - Y) ** 2 // (x, y) and (X, Y)
< 3 ? // if it's less than 3 (i.e. reachable from (X, Y)):
v - 3 ? // if v is not equal to 3:
~v ? // if v is not equal to -1:
v // test if v = 0
: // else (v = -1):
u-- // set u = -1 to find the other portal
: // else (v = 3):
R = R < i ? // we've found the strawberry: set R = min(R, i)
R : i //
: // else (this tile can't be reached):
1 // yield 1
) || // if the above result is falsy:
g( // do a recursive call:
u, // t = u
x, y, // move to (x, y)
u - ~i, // unless u is set to -1, increment i
r[x] = 1 // set this tile to a mountain
), // end of recursive call
x // restore r[x] ...
] = v // ... to v
)) // end of both map() loops
)(2) | R // initial call to g with t = 2; return R
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~441~~ ~~431~~ 341 bytes
```
from itertools import*
G=input()
W=len(G[0])
H=len(G)
A=[0]*5
E=enumerate
for y,r in E(G):
for x,C in E(r):A[C]=[x,y]
for L in count():
for M in product(*[zip('UDLR'*2,'LRDU ')]*L):
x,y=A[0]
for m in M:
x+='R'in m;x-='L'in m;y+='D'in m;y-='U'in m
if(x,y)==A[3]:x,y=A[2]
if 1-(W>x>-1<y<H)or G[y][x]>3:break
if[x,y]==A[1]:exit(L)
```
[Try it online!](https://tio.run/##TY8xb8MgEIXn8CvYABdLsdMubogUJVEyOEukqANiSFOsosbGoliC/nn3iKOqLLz7uPfu6KP/tF05jo2zLTZeO2/t7RubtrfOZ2gvTNcPnjL0Jm66o3s5VwwdJs3QWkCdvaCd0N3QanfxGjXW4cgdNh3eQU@FcCKBbybiWLWWGyVk4FHdm@v0cLVDB2Me3ceEemc/hqunmfwxPSXnbX0iWclJfdqeMRzCVFYnB4RHsYZNQCZ3m9zHCs3CkyAnAkX7GnJB6klGoNuHBHq@SzQzDYUcJiBpoaopslSJ4yKnb6uwyotlXB4YTNjLqGRQq0X17vTlC@aa5v6h5C5UpYPxtGbjKOWc42eO84LjIl2KY5mKB8v/4OI/4LhU6hc)
Input as lists, but using numbers instead of characters (thanks to Quintec) and a seperate value for the destination of the teleporter. Those large indentations should be tab characters if Stack Exchange removes them. Any tips or ideas especially welcome, as I feel that this could get ~~**much**~~ somewhat shorter.
The table for characters used in the challenge to the numbers used for my program is below, but you can also use [this program](https://tio.run/##hZBPC4JAEMXv@ykGOujGBmadAm@FeggPCgnLEkFqQq0iRvnpbUdN@wM6h2H3vfk9ZjevyksmzbqegYwekMr8XkKcFbdTSUhSpGewWlGn5OBuA4eBs3NtJ1D6NZI6jnBDUNbfKFFBdktyvlgKmENDYiwcVRoUJ5lEeptDBUG9@tM3BFSh9xy8JqizsNIYmg0qwZ8CLAu0QBtcrG6Z9wQYvRtd/2l/gl6O0rsJ2hylvQl6NUrvJ@g1yYtUlnqn07rmwNVvMURVC7H57UkwZYXfVvhheb8qw7cLEC8).
```
Challenge | My program
T | 0
S | 1
E | 2
O | 3
M | 4
X | -1
```
-10 bytes thanks to Quintec by changing the input from using characters to numbers.
-A lot of bytes thanks to Jonathan Frech, ElPedro, and Jonathan Allan.
[Answer]
# [Python 2](https://docs.python.org/2/), 391 ~~397~~ ~~403~~ ~~422~~ bytes
```
M=input()
from networkx import*
a=b=c=d=0
N,h,w,S=[-1,0,1],len(M),len(M[0]),[]
for i in range(h):
for j in range(w):
I,m=(i,j),M[i][j]
if m>7:c,d=a,b;a,b=I
if m<0:Z=I
if m==5:F=I
S+=[I+I]
S+=[(a,b,c,d),(c,d,a,b)]
print len(shortest_path(from_edgelist([((A+p,B+q),(C,D))for A,B,C,D in S for p,q in[(p,q)for p in N for q in N]if-1<A+p<h and-1<B+q<w and M[C][D]*M[A+p][B+q]]),Z,F))-1
```
[Try it online!](https://tio.run/##RVBLi8IwEL73VwT2ktgptAvi0m0EHwg91Is3Q5BqWxvXprFm6e6v706quJBkvkdmmBnza@tWvw9DxpU235Yyr@rahujS9m339UNUY9rOTrycH/mJFzz0tlBDDzsugghCiCRcS00z9ggilAyE9Kq2I4ooTbpcn0tas9gjTrv8a73TSAoNpwouDDKhpLhI1FRFmvksPkHBczh@4uXpU07CeP8inE/jzch2Phepn0rPAYoJgMkMKL6AjEnPdEpb4nq81zhQebcHk9uaumkPZXEur@puqaB04RtY@jdMXsGaMdf0ApaAxLW@G6cwcEMiKMbxg3HWdrRuI5SqCqIESyU1yXWBGEsmvcMkEysp1nKSCfSlQEPizvawYSyIhkG4vZIQyBQIgg8JRDyE53kKr/Mh5VsQzMnsDw "Python 2 – Try It Online")
The problem is translated into a graph and the solution is to find the shortest path form the turtle to the strawberry.
```
Challenge | This code
T | -1
S | 5
O | 8
M | 0
X | 1
```
] |
[Question]
[
In this challenge you will be simulating a frog jumping from lily-pad to lily-pad in a pond. A frog's jump distance is uniquely determined by the size of the lily pad it jumps from. So for example there are lily-pads that let a frog jump `1` unit, lily-pads that let a frog jump `2` units etc. A frog can never jump more or less than the allowed amount, nor can it jump out of the pond, but it can jump in either direction.
So we will represent a lily-pad by the number of units it allows a frog to jump. This number is always positive. We will then represent a pond as a list of lily-pads.
Our question is then: If a frog starts on the first lily-pad can they visit every lily-pad in the pond by following the jumping rules?
For example if we have the following pond the answer is yes
```
[2, 3, 1, 4, 1]
üê∏
[2, 3, 1, 4, 1]
üê∏
[2, 3, 1, 4, 1]
üê∏
[2, 3, 1, 4, 1]
üê∏
[2, 3, 1, 4, 1]
üê∏
```
However for the following pond the answer is no:
```
[3,2,1,2,1,2]
```
The frog can never reach any lily-pad labeled with a 1.
The frog is allowed to visit the same lily-pad more than once. The following example requires it:
```
[2, 1, 1, 1]
üê∏
[2, 1, 1, 1]
üê∏
[2, 1, 1, 1]
üê∏
[2, 1, 1, 1]
üê∏
[2, 1, 1, 1]
üê∏
```
Some lily-pads are dead ends and need to be visited last for example:
```
[2,3,1,1]
```
Here there is nowhere to go from `3` so that has to be the final pad.
## Task
For this task you will take as input a non-empty list of positive integers. You should output one of two distinct values, the first if it a frog can reach every lily-pad the second if not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so your goal is to minimize the size of your source code as measured in bytes.
## Test cases
### Possible
```
[10]
[2,1,1,1]
[3,1,4,2,2,1]
[6,1,1,1,1,1,3]
[2,3,1,1]
[2,2,1,2]
[8,9,1,5,2,5,1,7,4]
```
### Impossible
```
[2,1]
[3,2,1,2,1,2]
[3,2,2,2,2,2]
[3,4,1,2,1,1]
[2,9,1,9]
[3,3,3,1,3,3]
```
[Answer]
# Python3, 151 bytes:
```
f=lambda n,s=[0],p=[]:len({*s})==len(n)or any(f(n,s+[t],p+[j])for i in[n[s[-1]],-1*n[s[-1]]]if-1<(t:=(s[-1]+i))<len(n)and p.count(j:=(s[-1],t))<len(n))
```
[Try it online!](https://tio.run/##ZY/BbsIwEETv/YrcsJNNFceBAsJfYvmQlloYwcZK3AOq@PawMYUqRnuw/WY8mvWXcOhQrn0/jlad2vPnvs0QBqUrA15psz19I/vNhytXaroi7/qsxQuzjGyFDmQr9NFwS9xlDjXqQZfCGChF/rgbZ0uxY2GrWASF43x3j2txn/n3r@4HAzs@dAhPnY@@d6RZpkVlOH97PmsQ08yYJNJATTPnq7s3jkxS5EtK/A/1jK1hQ2xJypLOD2j@1UW5yOtq3ixpFfNeMmVsGifhzZ8/7TV12CReGTeQca/xBg)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~40~~ 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā<©+®I-øε®Ã}.āćU©æε®«œεXšü2εR`нsθå]Pà
```
05AB1E lacks recursive methods unfortunately, so we'll have to use a brute-force approach by first generating all possible results before validating them. Unfortunately, this is both extremely slow and pretty long - although it's probably golfable here and there.
[Try it online](https://tio.run/##yy9OTMpM/f//SKPNoZXah9Z56h7ecW7roXWHm2v1jjQeaQ89tPLwMpDAodVHJ5/bGnF04eE9Rue2BiVc2Ft8bsfhpbEBhxf8/x9tpKNgrKNgCESx/3V18/J1cxKrKgE) or [verify some smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/yONNodWah9aV6l7eMe5rYfWHW6u1TvSeKQ99NDKw8tAAodWH518bmvE0YWH9xid2xqUcGFv8bkdh5fGBhxe8F9JL0znf3S0oUGsTrSRjiEIglnGUNoIWQTMQuabgNgKII1gIUugkCWQZaxjHBv7X1c3L183J7GqEgA).
**Explanation:**
Step 1: For each Lilly-pad index, check which other Lilly-pads the frog can jump to (which will always be 0, 1, or 2 other Lilly-pads):
```
ā # Push a list in the range [1, (implicit) input-length]
< # Decrease each by 1 to the range [0, length)
© # Store it in variable `®` (without popping)
+ # Add it to the input-values at the same positions
® # Push list `®` again
I- # Subtract the input-list at the same positions
√∏ # Create pairs of these two lists
ε # Map each pair to:
®Ã # Only keep the values present in list `®`, removing any out-of-bounds
# indices that are negative or >= the length)
}.ā # After the map: enumerate the list, pairing each list with its index
```
[Try just step 1 online.](https://tio.run/##yy9OTMpM/f//SKPNoZXah9Z56h7ecW7roXWHm2v1jjT@/x9tpKNgrKNgCESx/3V18/J1cxKrKgE)
Step 2: Using the powerset and permutations builtins, create all possible lists that contain either 1 or 2 of these list-index pairs, and also start with the first Lilly-pad:
```
ć # Extract head; pop and push remainder-list and first item separately
U # Pop this first item, and store it in variable `X`
© # Store the remainder-list as new variable `®` (without popping)
æ # Pop and push the powerset of this list
ε # Map over each powerset-list:
®« # Merge list `®` to it
œ # Get all permutations of this list
ε # Map over each permutation:
Xš # Prepend item `X` to each
```
[Try the first two steps online.](https://tio.run/##yy9OTMpM/f//SKPNoZXah9Z56h7ecW7roXWHm2v1jjQeaQ89tPLwMpDAodVHJ5/bGnF04X@d/9FGOgrGOgqGQBT7X1c3L183J7GqEgA)
Step 3: Check if there is any inner list for which all overlapping pairs of list-index pairs are valid jumps for the frog:
```
ü2 # Pop the list and push its overlapping pairs
ε # Map each pair to:
R # Reverse the pair
` # Pop and push both inner pairs separated to the stack
–Ω # Pop and and only leave the list
s # Swap so the other pair is at the top of the stack
θ # Pop and only leave the index
å # Check if this index is in the list
] # Close all three open maps
P # Product to check for each inner-most list if ALL are truthy
à # Flattened-max to check if ANY is truthy
# (which is output implicitly as result)
```
[Answer]
# JavaScript (ES6), 83 bytes
Returns \$0\$ or \$1\$.
Given a list of \$N\$ entries, this recursively tries all possible paths where each lily-pad may be visited up to \$N\$ times.
```
f=(a,i=0,[...b]=a.map(_=>0))=>b.every(v=>v)||a[b[i]++]&&f(a,i+a[i],b)|f(a,i-a[i],b)
```
[Try it online!](https://tio.run/##dZDLDoIwFET3fgi0oTS8fLAoS7/AXW1MQVAMUgJIQsK/1xZZaCyZtM3ccyeZ9MEH3mVt2fRuLa65lAUBHJXEQxRjnDLC8ZM34EISD0KSpDgf8nYEA0kGOE2cprRkjsMsq9AxhyuLUjjNzl2czETdiSrHlbgBm57aV38fmQ033/MCUN9j8G8YIF/LQEI1j1CgZKK7T25WaOAHFCuyVemtevco0js/S/a5pkdedaaqwUoj3XY@K3SRkUZL1jf@gm4bG3Navr4VlW8 "JavaScript (Node.js) – Try It Online")
Or **81 bytes** for this slower version suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh):
```
f=(a,i=0,[...b]=a.map(_=>0))=>a[b[i]++]?f(a,i+a[i],b)|f(a,i-a[i],b):b.every(v=>v)
```
[Try it online!](https://tio.run/##dZDfCoIwGMXvexE3nMP5pzKY3fUE3a0R07QMU1EbCL27beZF0eSwje/7nQOH3YUUXdoWTe9U9SUbx5wCgQrqIoYxTjgV@CEacKaxCyGNBUtYwW2b73Nts4WaUAJf0@TM0y7BmczaAUgaSzimddXVZYbL@gosdmyf/W3gFlx973PAiMvh39JDRMtAfLUPkKdkoutPbpJv4FsUKRKqdKjeDQq058dknSp2EGVnquotNNJtp7NAZxlpMGeJ8Rd028iY0yL6VnR8Aw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input list
i = 0, // i = current position
[...b] = // b[] = a list keeping track of how many times each
a.map(_ => 0) // lily-pad was visited, initially all 0's
) => //
b.every(v => v) // success if all lily-pads were visited at least once
|| // otherwise:
a[b[i]++] // failed if a[b[i]] is not defined (either if we've
// visited this position too many times, or we're out
// of bounds and b[i] itself is undefined)
// if applicable, increment b[i] afterwards
&& // otherwise:
f(a, i + a[i], b) | // do a recursive call where we go to the right
f(a, i - a[i], b) // do a recursive call where we go to the left
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
⊞υ⟦…¹Lθ⁰⟧FυFΦEθ⟦⁻§ι⁰⟦λ⟧λ⟧›⁼§θ§ι¹↔⁻λ§ι¹№υκ⊞υ꬧⌊υ⁰
```
[Try it online!](https://tio.run/##XY49C8IwEIZ3f0XGC0Sw6tZJREWwUlxLh1hjG5omNk3Efx8vFT9wyIXj3ufuqRpuK8NVCLkfGvCMFCeuawEJIweha9dATykjs5Kmk6uxBDwl47@VygkLGb9Bj1QmtR9g5fb6Ih4gkUCqUCXWseys4DG/6T1X3yCiP0wST63Og1HeCXitVP@JmFkbr120bWNP3u4tSuZW4uho3OcG7pGd79A8WlGahlAUC7ZkCZvjS8oyTO/qCQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if possible, nothing if not. Explanation:
```
⊞υ⟦…¹Lθ⁰⟧Fυ
```
Start a breadth-first search having visited the first lily pad while the remaining lily pads are unvisited.
```
FΦEθ⟦⁻§ι⁰⟦λ⟧λ⟧
```
Calculate the result of jumping to each lily pad...
```
›⁼§θ§ι¹↔⁻λ§ι¹№υκ
```
... filtering out those jumps that were the wrong distance or have been seen before, ...
```
⊞υκ
```
... save the resulting position.
```
¬§⌊υ⁰
```
Check whether any of the positions have no unvisited lily pads left.
[Answer]
# [Python 3](https://docs.python.org/3/), 96 bytes
```
f=lambda k,x=0,*s:len({*s})==len(k)or-1<x<len(k)>s.count(x)and f(k,x-k[x],x,*s)|f(k,x+k[x],x,*s)
```
[Try it online!](https://tio.run/##RU3BboMwDL33K3xMOncqhHYrKrt11112QxzSNqgIFlAIW6pt386MQVqeZL9nP790d39rrRrHMmv0x/mqocaQbXHdp42x4nvd/8osm2gtW7eJjuE4i5f@8dIO1osgtb1CKehuU@ehwEDH8ocHD/@D8etWNQbe3WDSFYB39xQ6V1FAKcynbkRlu8ELSY/WJlxM5@H09npyrnUpnJ3R9ZjHCAohQkioFqs82lKJMZpATFFPMCZMaj/PGYp9avGxA2Niz3ggtiO9o/6EyZzHWexZfIpTGaySZTenTRkHniv@g2rxBw "Python 3 – Try It Online")
Port of my answer to [1D Hopping Array Maze](https://codegolf.stackexchange.com/a/247246/87681)
] |
[Question]
[
[RFC 2550](https://www.rfc-editor.org/rfc/rfc2550) is a satirical proposal (published on April 1, 1999) for a space-efficient ASCII representation of timestamps that can support any date (even those prior to the beginning of the universe and those past the predicted end of the universe). The algorithm for computing a RFC 2550-compliant timestamp is as follows (note: all ranges include the start but exclude the end - 0 to 10,000 means all `n` where `0 <= n < 10000`):
* **Year format**
* Years 0 to 10,000: a 4-digit decimal number, left-padded with zeroes.
* Years 10,000 to 100,000: a 5-digit decimal number, prefixed with the character A.
* Years 100,000 to 1030: the decimal number for the year, prefixed with the uppercase ASCII letter whose index in the English alphabet is equal to the number of digits in the decimal year, minus 5 (B for 6-digit years, C for 7-digit years, etc.).
* Years 1030 to 1056: the same format as 10,000 to 1030, starting the letters over with A, and additionally prefixing a caret (`^`) to the string (so the year 1030 is represented by `^A1000000000000000000000000000000`, and the year 1031 is represented by `^B10000000000000000000000000000000`).
* Years 1056 to 10732: the year is prefixed by two carets and two ASCII uppercase letters. The uppercase letters form a base-26 number representing the number of digits in the year, minus 57.
* Years 10732 onwards: the same format for 1056 to 10732 is used, extending it by adding an additional caret and uppercase letter when necessary.
* BCE years (prior to Year 0): compute the year string of the absolute value of the year. Then, replace all letters by their base-26 complement (A <-> Z, B <-> Y, etc.), replace all digits by their base-10 complement (0 <-> 9, 1 <-> 8, etc.), and replace carets with exclamation marks (`!`). If the year string is 4 digits or less (i.e. -1 to -10,000), prepend a forward slash (`/`). If the year string is not prefixed by a forward slash or an exclamation mark, prepend an asterisk (`*`).
* **Months, days, hours, minutes, and seconds**: since these values are only ever 2 digits at the most, they are simply appended to the right of the year string, in decreasing order of significance, left-padded with zeroes if necessary to form 2-digit strings.
* **Additional precision**: if additional precision (in the form of milliseconds, microseconds, nanoseconds, etc.) is needed, those values are left-padded with zeroes to 3 digits (because each value is `1/1000` of the previous value, and thus is at most `999`) and appended to the end of the timestamp, in decreasing order of significance.
This format has the benefit of lexical sorting being equivalent to numeric sorting of the corresponding timestamp - if time A comes before time B, then the timestamp for A will come before the timestamp for B when lexical sorting is applied.
##The challenge
Given an arbitrarily-long list of numeric values (corresponding to time values in decreasing order of significance, e.g. `[year, month, day, hour, minute, second, millisecond]`), output the corresponding RFC 2550 timestamp.
##Rules
* Solutions must work for any given input. The only limitations should be time and available memory.
* Input may be taken in any reasonable, convenient format (such as a list of numerics, a list of strings, a string delimited by a single non-digit character, etc.).
* The input will always contain at least one value (the year). Additional values are always in decreasing order of significance (e.g. the input will never contain a day value without a month value, or a second value followed by a month value).
* Input will always be a valid time (e.g. there won't be any timestamps for February 30th).
* Builtins which compute RFC 2550 timestamps are forbidden.
##Examples
These examples use input as a single string, with the individual values separated by periods (`.`).
```
1000.12.31.13.45.16.8 -> 10001231134516008
12.1.5.1 -> 0012010501
45941 -> A45941
8675309.11.16 -> C86753091116
47883552573911529811831375872990.1.1.2.3.5.8.13 -> ^B478835525739115298118313758729900101020305008013
4052107100422150625478207675901330514555829957419806023121389455865117429470888094459661251.2.3.5.7.11 -> ^^BI40521071004221506254782076759013305145558299574198060231213894558651174294708880944596612510203050711
-696443266.1.3.6.10.15.21.28 -> *V3035567330103061015021028
-5342 -> /4657
-4458159579886412234725624633605648497202 -> !Q5541840420113587765274375366394351502797
```
##Reference implementation
```
#!/usr/bin/env python
import string
# thanks to Leaky Nun for help with this
def base26(n):
if n == 0:
return ''
digits = []
while n:
n -= 1
n, digit = divmod(n, 26)
digit += 1
if digit < 0:
n += 1
digit -= 26
digits.append(digit)
return ''.join(string.ascii_uppercase[x-1] for x in digits[::-1])
year, *vals = input().split('.')
res = ""
negative = False
if year[0] == '-':
negative = True
year = year[1:]
if len(year) < 5:
y = "{0:0>4}".format(year)
elif len(year) <= 30:
y = "{0}{1}".format(string.ascii_uppercase[len(year)-5], year)
else:
b26len = base26(len(year)-30)
y = "{0}{1}{2}".format('^'*len(b26len), b26len, year)
if negative:
y = y.translate(str.maketrans(string.ascii_uppercase+string.digits+'^', string.ascii_uppercase[::-1]+string.digits[::-1]+'!'))
if len(year) == 4:
y = '/' + y
if y[0] not in ['/', '!']:
y = '*' + y
res += y
for val in vals[:5]: #month, day, hour, minute, second
res += '{0:0>2}'.format(val)
for val in vals[5:]: #fractional seconds
res += '{0:0>3}'.format(val)
print(res)
```
[Answer]
# Befunge, ~~418~~ 384 bytes
It's hard to tell in advance how large a Befunge program is likely to end up, and when I started working on this I thought it might actually have some chance of competing. Turns out I was wrong.
```
~:59*-!:00p:2*1\-10p:9*68*+20p>0>#~$_v
68*-:0\`30p\>>:"P"%\"P"/9+p30g#v_1+:~>
0\`v`\0:\p04<<:+1g04-$<_\49+2*v>0>+#1:#\4#g\#0`#2_130p040p5-::01-`\49+2*-:
v:$_\50p\$:130g:1+30p:!^!:-1\*<>g*"A"++\49+2*/50g1-:
_$1+7g00g40g!**:!>_40g:!v!:\g8<^00*55*g01%*2+94:p05
|#9/"P"\%"P":<:_,#!>#:<$_1-00g^v3$\_\#`\0:>#g+
>10g*20g+,1+:^v\&\0+2`4:_@#`<0+<
/*v*86%+55:p00<_$$>:#,_$1+~0^
^!>+\55+/00g1-:^
```
[Try it online!](http://befunge.tryitonline.net/#code=fjo1OSotITowMHA6MioxXC0xMHA6OSo2OCorMjBwPjA+I34kX3YKNjgqLTowXGAzMHBcPj46IlAiJVwiUCIvOStwMzBnI3ZfMSs6fj4KMFxgdmBcMDpccDA0PDw6KzFnMDQtJDxfXDQ5KzIqdj4wPisjMTojXDQjZ1wjMGAjMl8xMzBwMDQwcDUtOjowMS1gXDQ5KzIqLToKdjokX1w1MHBcJDoxMzBnOjErMzBwOiFeITotMVwqPD5nKiJBIisrXDQ5KzIqLzUwZzEtOgpfJDErN2cwMGc0MGchKio6IT5fNDBnOiF2ITpcZzg8XjAwKjU1KmcwMSUqMis5NDpwMDUKfCM5LyJQIlwlIlAiOjw6XywjIT4jOjwkXzEtMDBnXnYzJFxfXCNgXDA6PiNnKwo+MTBnKjIwZyssMSs6XnZcJlwwKzJgNDpfQCNgPDArPAovKnYqODYlKzU1OnAwMDxfJCQ+OiMsXyQxK34wXgpeIT4rXDU1Ky8wMGcxLTpe&input=NDc4ODM1NTI1NzM5MTE1Mjk4MTE4MzEzNzU4NzI5OTAuMS4xLjIuMy41LjguMTM)
[Answer]
## JavaScript (ES6), 325 bytes
```
f=
s=>s.split`.`.map((n,i)=>i?`00${n}`.slice(i>5?-3:-2):n<'0'?g(n.slice(1),'!','*','/').replace(/\w/g,c=>c>'9'?(45-parseInt(c,36)).toString(36):9-c):g(n),g=(n,c='^',d='',e='',l=n.length)=>l<5?e+`000${n}`.slice(-4):l<31?d+(l+5).toString(36)+n:h(l-30,c)+n,h=(n,c)=>n?c+h(--n/26|0,c)+(n%26+10).toString(36):'').join``.toUpperCase()
;
```
```
<input oninput=o.value=f(this.value);><input id=o>
```
Shockingly long.
[Answer]
# [Perl 5](https://www.perl.org/), ~~328 322 317~~ 301 + 1 (`-a`) = 302 bytes
```
$_=shift@F;if(($l=y/-//c)<5){s/^/0 x(4-$l)/e}elsif($l<57){s/^/'^'x($l>30).chr 65+($l-5)%26/e}else{$l-=57;do{s/\^*\K/'^'.chr 65+$l%26/e}while$l=int$l/26;s/^\^\K\D-?\d/^A$&/}if(s/-//){s%^....$%/$&%;eval join'',reverse'!/',0..9,A..Z,"y/A-Z0-9^/";s%^[^!/]%*$&%}printf$_.'%02d'x(@F>5?5:@F).'%03d'x(@F-5),@F
```
[Try it online!](https://tio.run/##tU/tbsIwDHyVgFJCWROHlrR05aNIU/@gvQDrghAE0SmiqEUMhHj1dUbVHmH@5Tvf@eyTqaxqGrqe1odif06zpNj3@9ROb8ABtu5EufcaNEhy7Y84tS6Yh7E1iqidqKgdMs2uiGeBdMX2UJFQvSDkynX8sNWbO@KpipJdiY5cD/Ll0/WnprZVfh8KazC8OJ6pBT9McHuu82X@xuf5DvSC9uCB2fXzOMx2tMCiDtCek5jLxpKvsjgy5lXmYqrasA4wTwoRewshVl73Bgu@kjzW0E3Q/KE78OkM0Pw4VZi5p2vBHOnv8J00m6m5ek0z90kFLYUveWnWNEM/GKkwGsfy/zoyJD4JyIgoEpKIjEn8U57ORXmsG/6uhBzKhm9@AQ "Perl 5 – Try It Online")
**Ungolfed**
```
$_=shift@F; # Store the year in the default variable for easier regex
if(($l=y/-//c)<5){ # if the length of the year is less than 5
s/^/0 x(4-$l)/e # pad with leading zeros to 4 digits
}elsif($l<57){ # if the length is less than 57
s/^/'^'x($l>30).chr 65+($l-5)%26/e # put a carat at the front if there are more than 30 characters
# and map the length minus 5 to A-Z
}else{
$l-=57; # offset the length by 57
do{
s/\^*\K/'^'.chr 65+$l%26/e # put a carat at the front and map the length to base 26 (A-Z)
}while$l=int$l/26; # until the length is down to 0
s/^\^\K\D-?\d/^A$&/ # insert an extra '^A' to pad the result to at least 2 characters if there was only 1
}
if(s/-//){ # if the year is negative
s%^....$%/$&%; # put a '/' in front of a 4 digit year
eval join'',reverse'!/',0..9,A..Z,"y/A-Z0-9^/"; # map A-Z,0-9, and ^ to Z-A,9-0, and ! respectively
s%^[^!/]%*$&% # add a * at the front if there are no other indicators
}
printf$_. # output the year
'%02d'x(@F>5?5:@F). # followed by the month, day, hour, and minutes, padded to 2 digits
'%03d'x(@F-5),@F # followed by fractional seconds, padded to three digits
```
[Answer]
# Java 11, ~~653~~ ~~640~~ ~~637~~ ~~623~~ ~~618~~ ~~595~~ 589 bytes
```
s->{String e="",r=e,q="ABCDEFGHIJKLMNOP",z=q+"QRSTUVWXYZ",y="0123456789",x;int i=0,f=0,t,u,v;for(var p:s){p=p.charAt(v=0)<46?p.substring(f=1):p;t=p.length();if(i++<1){r+=(t<5?"0".repeat(4-t):t<32?(char)(t+60):t<58?"^"+(char)(t+33+(v=1)):e);if(t>57){for(v=2,u=675;u<t-57;u*=26)v++;r+="^".repeat(v);x=e;for(var c:Long.toString(t-57,26).toUpperCase().split(e))x+=z.charAt((y+q).indexOf(c));r+=x;}r+=p;if(f>0){x=t<5?"/":t<32?"*":"!".repeat(v);for(int c:r.getBytes())x+=c>93?e:new StringBuffer(y+z).reverse().charAt((z+y).indexOf(c));r=x;}}else r+=i>6?t<2?"00"+p:t<3?0+p:p:t<2?0+p:p;}return r;}
```
Input as `String`-array and return-type as `String`.
Turned out to be quite long (as expected), but can definitely be golfed some more. I'm just glad it works after fiddling with it for quite a while..
-5 bytes thanks to *@ceilingcat*.
[Try it here.](https://tio.run/##tVXbcts2EH3vV9B4IkyKAUAABEXRGttJWreO3dRNesnEMwwNOUwUiiZBVbJG3@4uSMqtM6361BkRAoHds@fsLoFP2TIbfbr5/JDPs6ZxXmVFufnGcYrS6HqW5dq5sK@Oc2Xqorx1crefvHvvNDiBnS088GtMZorcuXBKJ3UemtHRZnDQKUJ@nWr/LkXHJ6fPX7z89ruz7384f3Vx@SPy79M7D73@6ernN29/@fW335G/ThGhLORCRipG/ioBIk6REn8Gj/Fbf5nMFrW7zGqnGjd4U6VVkH/M6mPjLlOCJ1xOq6BpPzRddHeWUjyuEgNWc13emo8uToqZW3jehOJN7aWumYgpIiiodaUz4/KRwWMzCdnUtbDYNZ4kdkWoKbpG3uNqGHoQkWI81h2kORIR3nTcUua3qYxE0k7MSERJe5gyiZeel0BAANnFWuJklepHPfn4fFHeBmbRZ861vj44wsqbqtL1adZoFwdNNS@MqzFeeen9Tru79u5wUJQ3enU5c3OMbahVsoWxsuxmRwRvVmkn9hnqBaJDNEYHf2djmdh85@M6uNXmZG1043aB8qM4nOpxqf8YGuGknc10DWHvMQAsdd1x27G599ZfsbFktnreaAcoFUdyaibAgBDkVZbNlMC/nbF@Bsy1aevSqZPtQ9K3WNV@mEOLDZ22XBQ3zhfo1seGzHDfqUDauH8xffd@gyiBSD6iDIaQ2lkIAxd2JmFQaOs7nRX0HqXQflQSolDX4f@MaKEsUofRuVtnQokgdI8fFzHvzY/76b@bKmihkMQWn/ZErdvpsEwpLOyJEykVCsFEFIKpYLGiVIU0jISKWByTgb19uqQMSlSfGxvo@uS/MEAsJYyEIJkoAm576BDBKIkgw5wxKohkAtAZiUBMDK6AQbkQQgGuiDiNFZEESsFoqGLYUFJQGnEW84gopUjMIXtSUia@VhD1@eoUXJ@c/Y@BB@kR3VfEkQg569g841JE@yxlLDkPmZRDXayibt4Vy2pjndi@WQ/fhgSKIyOQQIGIhGIIAlrZvrYdAX1FBUiNlZKcMjhqIyYk4zIMJRGSKx5HjPSUD14LwanikDsCXwWUPZKCRRw6IJQyjHkobMwoHnQ9vQu6L7Tj8Hhl2Dd7jPm760SvKp0bfXPZmqo1@MlVU@umnRu4Tsogd3eeg7SrdWP0l2DRmqACYzMv3cHcc5Djwjn9FDnQd202bwYjPEX5oq5hH07Al8dn5y@eHxwg7CG807F9@BM)
**Explanation:**
* `for(var p:s){`: Loop over the parts
+ `p=p.charAt(0)<46?p.substring(f=1):p;`: Determine if it's negative, and if it is, remove the minus sign and set a flag to reduce bytes
+ `t=p.length();`: Get the amount of digits
+ `if(i++<1){`: If it's the first number (the year):
- `t<5?"0".repeat(4-t)`: If it's in the range \$[0, 100000)\$: add leading zeroes if necessary
- `t<32?(char)(t+60)`: If it's in the range \$[100000, 10^{30})\$: Add a leading letter
- `t<58?"^"+(char)(t+33+(v=1))`: If it's in the range \$[10^{30}, 10^{732})\$: Add a literal `"^"` (and set `v` to 1) + leading letter
- `if(t>57)for(v=2,u=675;u<t-57;u*=26)v++;r+="^".repeat(v)`: Add the appropriate amount of literal `"^"` (and set `v` to that amount), plus `x=e;for(var c:Long.toString(t-57,26).toUpperCase().split(e))x+=z.charAt((y+q).indexOf(c));r+=x;`: leading letters (base-26 to alphabet conversion)
- `r+=p;`: Add the year itself to the result-String
- `if(f>0){`: If the year was negative:
* `x=t<5?"/":t<32?"*":"!".repeat(v);`: Create a temp String `x` with the correct `/`, `*` or `v` amount of `!`
* `for(int c:r.getBytes())x+=c>93?e:new StringBuffer(y+z).reverse().charAt((z+y).indexOf(c));`: Do the conversion (A↔Z, B↔Y, 0↔9, 1↔8, etc.)
* `r=x;`: And then set the result to this temp String `x`
+ `else`: If it's the month, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, or smaller:
- `i>6?t<2?"00"+p:t<3?0+p:p`: If it's milliseconds or smaller: Add leading zeroes if necessary
- `:t<2?0+p:p;`: Else (month, days, hours, minutes, seconds): Add single leading zero if necessary
* `return r`: Return the result
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~165~~ 126 bytes
```
ḣ5ṫ€3
ØD,“^ /*!”,ØA
_µ‘l26Ċṗ@€ØAẎị@
Lµç30;€”^UZFµç4⁶;µ®L>30¤?µḟ®L>4¤?;®AṾ€¤µL=4”/x2£FiЀị€2£UF¤µ®S<0¤¡
4R¬+DU$UµḢ©Ç;Ñ;ṫ6ṫ€2$$F
```
[Try it online!](https://tio.run/##y0rNyan8///hjsWmD3euftS0xpjr8AwXnUcNc@IU9LUUHzXM1Tk8w5Er/tDWRw0zcozMjnQ93DndAagOKPpwV9/D3d0OXD6Hth5ebmxgDRQFqo8LjXIDCZg8atxmfWjroXU@dsYGh5bYH9r6cMd8EM8EyLE@tM7x4c59QB2Hlhza6mNrAtSoX2F0aLFb5uEJQFGguUASyA91Ayk4tC7YBmjGoYVcJkGH1mi7hKqEgoxbdGjl4XbrwxOtgU43gzjfSEXF7f///9G6ZpZmJibGRmZmOoY6xjpA0kDH0FTHyFDHyCIWAA "Jelly – Try It Online")
Line 4 does the year formatting with help from lines 2 and 3. The first and last line deal with zero padding the elements of the input to their proper lengths then concatenating them with the formatted year.
* `_µ‘l26Ċṗ@€ØAẎị@` finds the base 26 prefix. It takes the cartesian power of the alphabet (`ØA`) for each number between 1 and ceil(log26(floor(log10(year))-n+1)) (where n is either 30 or 4) then gets indexes into this list with floor(log10(year))-n (`ị@`).
* `ç30;€”^UZF` formats years >= 1030 (`®L>30¤?`)
* `ç4⁶;` formats years < 1030. (*Edit*: Saved a byte by using `⁶;` instead of `;@⁶`)
* ~~`1RḊ`~~ `ḟ` gives an empty prefix for years < 105 (`®L>4¤?`). It takes the list of digits then filters out every element in itself. Just using this to yield `[]` because `⁸` doesn't work here.
~~This just evaluates to `[]`. `⁸` and `[]` don't work here and I couldn't find another 2 bytes that return an empty list.~~
* `;®AṾ€¤` appends the year to the prefix then flattens it.
* `L=4”/x` prefixes a `/` if the length of the year is 4 in the do statement of `®S<0¤¡`.
* `2£FiЀ¹ị€2£UF¤` takes the complements of `A .. Z`, `0 .. 9` and `^ /*!` if the year is negative (`®S<0¤¡`). `2£` refers to the second link, `ØD,“^ *!”,ØA` which is the list `[['0' .. '9'], ['^',' ','/','*','!'], ['A' .. 'Z']]`. With a formatted year like `^C125...` this link finds the index of each character in the flattened version of `2£` then uses those indices to construct a new string from the flattened version of `2£` where each sublist is reversed, i.e. `['9' .. '0','!','*','/',' ','^','Z' .. 'A']`, yielding `!X874...`. `/` maps to itself because it is prefixed before everything has its complement taken.
* ~~`L=4a®S<0x@”/;` adds a `/` to the beginning of negative years in `[-9999 .. -0001]`. My guess is this can be shortened.~~ I ended up including this in the previous do statement (`¡`) and saved 7 bytes because then I didn't need to test for negative years twice.
~~There are a lot of uses of `¡` in line 4 and I think they could be compressed by using `?` instead but I'm not sure how to get those to work.~~ I got `?` to work and saved a few bytes.
James Holderness pointed out that my first submission didn't handle years with 30 digits correct. It turned out the bug was for any year that needed a `Z` in the base 26 prefix. It turns out I couldn't use `ṃ` because when you convert 26 to base 26 it gives you `[1,0]` instead of `26` (duh). Instead I used ordered pairs with replacement. I don't think there is an atom for that but if there is I can save a few bytes. Fixing this ended up costing me ~40 bytes. Definitely my longest Jelly program yet. *Edit*: Found a shorter way to do the cartesian product. I realized that I wasn't sure that the last one worked for prefixes with more than two letters anyway but the new way does work.
Sorry for the many times I've edited this post, I just keep discovering ways of shortening it.
[Answer]
# Excel VBA, ~~500~~ ~~486~~ ~~485~~ 461 Bytes
## Anonymous VBE Immediate Window Function
Anonymous VBE immediate window function that takes input as year from `[A1]`, month from `[B1]`, days from `[C1]`, hours from `[D1]`, minutes from `[E1]`, seconds from `[F1]` and an optional extra precision array from `[G1:Z1]`, calculates the RFC2550 timestamp and outputs to the VBE immediate window. Makes use of the declared helper function below.
```
n=Left([A1],1)="-":y=Mid([A1],1-n):l=Len(y):o=IIf(l<5,Right("000"&y,4),IIf(l<31,"",String(Len(b(l-30)),94))&B(l-IIf(l<31,4,30))&y):For Each c In[B1:Z1]:j=j+1:p=p+IIf(c,Format(c,IIf(j>5,"000","00")),""):Next:If n Then For i=1To Len(o):c=Asc(Mid(o,i,1)):Mid$(o,i,1)=Chr(IIf(c<60,105,155)-c):Next:?IIf(l<5,"/",IIf(InStr(1,o,"="),"","*"))Replace(o,"=","!")p:Else?o;p
```
**Helper Function**
Declared helper function that takes an input number and returns that number in base-26 such that `1->A` and `26->Z`
Must be placed into a public module.
```
Function b(n)
While n
n=n-1
d=n Mod 26+1
d=d+26*(d<0)
n=n\26-(d<0)
b=Chr(64+d)+b
Wend
End Function
```
**Usage**
Must be used in a clear module, or the module must be cleared before execution as the vars `j`, `o` and `p` are assumed to be in their default, uninitialized state at the beginning of execution of the code. For `j`, which is a `Variant\Integer` variable, this default value is `0` and for `o` and `p`, which are `Variant\String` variables, this default value is the empty string (`""`).
Input, an array of strings, is taken from `1:1` on the ActiveSheet and output is to the VBE immediate window.
**Sample I/O**
```
[A1:F1]=Split("4052107100422150625478207675901330514555829957419806023121389455865117429470888094459661251.2.3.5.7.11",".")
n=Left([A1],1)="-":y=Mid([A1],1-n):l=Len(y):o=IIf(l<5,Right("000"&y,4),IIf(l<31,"",String(Len(b(l-30)),94))&B(l-IIf(l<31,4,30))&y):For Each c In[B1:ZZ1]:j=j+1:p=p+IIf(c,Format(c,IIf(j>5,"000","00")),""):Next:If n Then For i=1To Len(o):c=Asc(Mid(o,i,1)):Mid$(o,i,1)=Chr(IIf(c<60,105,155)-c):Next:?IIf(l<5,"/",IIf(InStr(1,o,"="),"","*"))Replace(o,"=","!")p:Else?o;p
^^BI40521071004221506254782076759013305145558299574198060231213894558651174294708880944596612510203050711021028
Cells.Clear:j=0:o="":p="" '' clear the worksheet and vars
[A1:H1]=Array("-696443266","1","3","6","10","15","21","28")
n=Left([A1],1)="-":y=Mid([A1],1-n):l=Len(y):o=IIf(l<5,Right("000"&y,4),IIf(l<31,"",String(Len(b(l-30)),94))&B(l-IIf(l<31,4,30))&y):For Each c In[B1:ZZ1]:j=j+1:p=p+IIf(c,Format(c,IIf(j>5,"000","00")),""):Next:If n Then For i=1To Len(o):c=Asc(Mid(o,i,1)):Mid$(o,i,1)=Chr(IIf(c<60,105,155)-c):Next:?IIf(l<5,"/",IIf(InStr(1,o,"="),"","*"))Replace(o,"=","!")p:Else?o;p
*V3035567330103061015021028
Cells.Clear:j=0:o="":p="" '' clear the worksheet and vars
[A1]="45941"
n=Left([A1],1)="-":y=Mid([A1],1-n):l=Len(y):o=IIf(l<5,Right("000"&y,4),IIf(l<31,"",String(Len(b(l-30)),94))&B(l-IIf(l<31,4,30))&y):For Each c In[B1:ZZ1]:j=j+1:p=p+IIf(c,Format(c,IIf(j>5,"000","00")),""):Next:If n Then For i=1To Len(o):c=Asc(Mid(o,i,1)):Mid$(o,i,1)=Chr(IIf(c<60,105,155)-c):Next:?IIf(l<5,"/",IIf(InStr(1,o,"="),"","*"))Replace(o,"=","!")p:Else?o;p
A45941
Cells.Clear:j=0:o="":p="" '' clear the worksheet and vars
[A1:F1]=Split("4052107100422150625478207675901330514555829957419806023121389455865117429470888094459661251.2.3.5.7.11",".")
n=Left([A1],1)="-":y=Mid([A1],1-n):l=Len(y):o=IIf(l<5,Right("000"&y,4),IIf(l<31,"",String(Len(b(l-30)),94))&B(l-IIf(l<31,4,30))&y):For Each c In[B1:ZZ1]:j=j+1:p=p+IIf(c,Format(c,IIf(j>5,"000","00")),""):Next:If n Then For i=1To Len(o):c=Asc(Mid(o,i,1)):Mid$(o,i,1)=Chr(IIf(c<60,105,155)-c):Next:?IIf(l<5,"/",IIf(InStr(1,o,"="),"","*"))Replace(o,"=","!")p:Else?o;p
^^BI40521071004221506254782076759013305145558299574198060231213894558651174294708880944596612510203050711
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 104 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εþNĀiN6@Ìjð0:ëg©Ž¾S₃в@DUO0®4α×®60+ç®34+ç'^ì®57-D<₂®Ým675*@OÌ'^×sAuÅвJ«)ćèyÄ«y0‹ižK'^ìžL'!쇄/*õªX2£Oèì]J
```
Input as a list of integers.
Based on [my Java answer](https://codegolf.stackexchange.com/a/152495/52210).
[Try it online](https://tio.run/##FY09S8NQFEB/i1OxRrz3vXffhzhE6FSlGUQQpIKCSARxKA7dQlRcundSEAerCUELHRzM8G6zlv6G/JEYpzMcDud2dH4RXzbNasHlYJnEAx3y5Jq/YJezK/9R/fryqE7v1/OwdxyBL9Tqm6e@0LDF776QqkXnjHNfkNnu7dVp6gt@vtGGumHEk1ZNR/t3/Lie9322uXzi2ZgffDaGOvmJq/Lgv63Kw84G53XyWicvO11e@M8T4d8innE@7DfNqQISCAYBlBBIoAUpYwWYduMApQRCRURWOEdGobOgQUgUKK1rhdWEaJRwyoC1FpxS5LRGQRiIQAYUmABx@Ac) or [verify all test cases](https://tio.run/##tZJNS5RRFMf3fgp9NqZd85xzzzn3Xil8mxZaOGQlgYxQEGHQC6jB7AYrgnA/q4JokaUMJQi1cILn6nbwM8wXmc7j2LpVPPC8nP95@f3PfV5sPXy0@Xjwqlh6/nJne2a0mG2en9wYKeo725ffxaB3nLsrp63NFZ3Le0/zd5jJB0/Kr2cnZfduf/f1@dFc7X4dyg73fuR22VG4mr@UHc/2GN/Ih2VHwlTten93t@zkD880yORcPe@Z1N6a38lvz4@Wy4OJ03d5v5nflAdN6Ld@bZ51b1W1Z93b42P5sN/61G99nJ7Mx@W3B1R@ruf9fNhYHhTX1mqzzd7P/N7kpZXcLkav5N@L9dXVm4v3JkYKN1hfX0cAcEjOo0PvWByqiw1XVHEkj@hZUAFi0XCWTQ6d5VhCJQOCAF4oLImr8PzFy0UomhkPyaG1VpMWLwOIqMOaEKMXIQnegkIpIkaPPkgMlJJx2WVoNjEanbXYWPhXjSEhEHgDgwjoh4NACCGYJyZCASWxPgTBgJIlWTayiETrIIExRVAw84Q@JhOiCmJgShwgxgiJzaUqkvzlC@ay4ttYWPqPwy6NBRwueEo8k02dZpUwjGhSZk@qtjnv7G5LFEeGWR3q5JoHW54Gg0BrpbYsAaOl4fFO2aiIYlgpRmUk8hxIlFi9VxDlyCkQVEPH7ogwRjaXYH@JrT@oUGA7Ca/qE3upeodkZI0/).
**Explanation:**
```
ε # Map over each integer `y` of the (implicit) input-list
þ # Only leave digits (same as absolute value `Ä`, but results in a string)
NĀi # If the 0-based map-index is NOT 0 (so not the year):
N6@ # Check if the map-index is >= 6 (1 if truthy; 0 if falsey),
# thus milliseconds or smaller
Ì # Increase that by 2
j # Add leading spaces to abs(y) to make the length (N>=6)+2 long
# (note that builtin `j` requires the first argument to be a string,
# hence the use of `þ` over `Ä` earlier)
ð0: # And replace those leading spaces with 0s
ë # Else (the map-index is 0, thus the year):
g # Pop the absolute value, and push its length
© # Store this length in variable `®` (without popping)
Ž¾S # Push compressed integer 48223
₃в # Convert it to base-95 as list: [5,32,58]
@ # Check for each if they're >= the length (1 if truthy; 0 if falsey)
DU # Store a copy of those checks in variable `X`
O # Sum the checks to get the amount of truthy values
® # Push the length from `®` again
4α # Take its absolute difference with 4
0 × # Repeat 0 that many times as string
® # Push the length `®` again
60+ # Add 60
ç # Convert it to an ASCII character with this codepoint
® # Push the length `®` again
34+ # Add 34
ç # Convert it to an ASCII character with this codepoint
'^ì '# Prepend "^"
® # Push the length `®` again
57- # Subtract 57
D # Duplicate it
< # Decrease it by 1 (thus `®`-58)
®Ý # Push a list in the range [0,`®`]
₂ m # Take 26 to the power of each value in this list
675* # Multiply each by 675
@ # Check for each if the `®`-58 is >= the value
O # Sum those checks
Ì # Increase it by 2
'^× '# Have that many "^"
s # Swap so `®`-57 is at the top of the stack again
AuÅв # Convert it to base-"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
# basically convert it to base-26 and index it into the alphabet
J # And join those characters together to a single string
« # After which we'll append it to the "^"-string
) # Wrap all values on the stack into a list
ć # Extract head; pop and push remainder-list and the first item separated,
# where the first item is the sum of truthy values we calculated earlier
è # Use that to 0-based index into the remainder-list
yÄ # Push the absolute value of integer `y` again
« # And append it to the string
y0‹i # If integer `y` is negative:
žK # Push string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
'^ì '# Prepend a leading "^"
žL # Push string "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210"
'!ì '# Prepend a leading "!"
‡ # Transliterate all characters in the string
„/* # Push string "/*"
õª # Convert it to a list of characters, and append "": ["/","*",""]
X # Push the list of checks we saved in variable `X`
2£ # Only leave the first two checks
O # Sum those
è # Use it to 0-based index into the ["/","*",""]
ì # And prepend it in front of the string
] # Close all if-statements and the map
J # And join all mapped strings together
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž¾S` is `48223`; `Ž¾S₃в` is `[5,32,58]`; and `is`.
] |
[Question]
[
The original 151 Pokemon, in an array format suitable for initializers:
```
["Bulbasaur", "Ivysaur", "Venusaur", "Charmander", "Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise", "Caterpie", "Metapod", "Butterfree", "Weedle", "Kakuna", "Beedrill", "Pidgey", "Pidgeotto", "Pidgeot", "Rattata", "Raticate", "Spearow", "Fearow", "Ekans", "Arbok", "Pikachu", "Raichu", "Sandshrew", "Sandslash", "Nidorina", "Nidoqueen", "Nidoran", "Nidorino", "Nidoking", "Clefairy", "Clefable", "Vulpix", "Ninetales", "Jigglypuff", "Wigglytuff", "Zubat", "Golbat", "Oddish", "Gloom", "Vileplume", "Paras", "Parasect", "Venonat", "Venomoth", "Diglett", "Dugtrio", "Meowth", "Persian", "Psyduck", "Golduck", "Mankey", "Primeape", "Growlithe", "Arcanine", "Poliwag", "Poliwhirl", "Poliwrath", "Abra", "Kadabra", "Alakazam", "Machop", "Machoke", "Machamp", "Bellsprout", "Weepinbell", "Victreebel", "Tentacool", "Tentacruel", "Geodude", "Graveler", "Golem", "Ponyta", "Rapidash", "Slowpoke", "Slowbro", "Magnemite", "Magneton", "Farfetch'd", "Doduo", "Dodrio", "Seel", "Dewgong", "Grimer", "Muk", "Shellder", "Cloyster", "Gastly", "Haunter", "Gengar", "Onix", "Drowzee", "Hypno", "Krabby", "Kingler", "Voltorb", "Electrode", "Exeggcute", "Exeggutor", "Cubone", "Marowak", "Hitmonlee", "Hitmonchan", "Lickitung", "Koffing", "Weezing", "Rhyhorn", "Rhydon", "Chansey", "Tangela", "Kangaskhan", "Horsea", "Seadra", "Goldeen", "Seaking", "Staryu", "Starmie", "Mr. Mime", "Scyther", "Jynx", "Electabuzz", "Magmar", "Pinsir", "Tauros", "Magikarp", "Gyarados", "Lapras", "Ditto", "Eevee", "Vaporeon", "Jolteon", "Flareon", "Porygon", "Omanyte", "Omastar", "Kabuto", "Kabutops", "Aerodactyl", "Snorlax", "Articuno", "Zapdos", "Moltres", "Dratini", "Dragonair", "Dragonite", "Mewtwo", "Mew"]
```
I have omitted the male-female Nidoran distinction because it shouldn't affect any regex generation.
And all subsequent Pokemon:
```
["Chikorita", "Bayleef", "Meganium", "Cyndaquil", "Quilava", "Typhlosion", "Totodile", "Croconaw", "Feraligatr", "Sentret", "Furret", "Hoothoot", "Noctowl", "Ledyba", "Ledian", "Spinarak", "Ariados", "Crobat", "Chinchou", "Lanturn", "Pichu", "Cleffa", "Igglybuff", "Togepi", "Togetic", "Natu", "Xatu", "Mareep", "Flaaffy", "Ampharos", "Bellossom", "Marill", "Azumarill", "Sudowoodo", "Politoed", "Hoppip", "Skiploom", "Jumpluff", "Aipom", "Sunkern", "Sunflora", "Yanma", "Wooper", "Quagsire", "Espeon", "Umbreon", "Murkrow", "Slowking", "Misdreavus", "Unown", "Wobbuffet", "Girafarig", "Pineco", "Forretress", "Dunsparce", "Gligar", "Steelix", "Snubbull", "Granbull", "Qwilfish", "Scizor", "Shuckle", "Heracross", "Sneasel", "Teddiursa", "Ursaring", "Slugma", "Magcargo", "Swinub", "Piloswine", "Corsola", "Remoraid", "Octillery", "Delibird", "Mantine", "Skarmory", "Houndour", "Houndoom", "Kingdra", "Phanpy", "Donphan", "Porygon2", "Stantler", "Smeargle", "Tyrogue", "Hitmontop", "Smoochum", "Elekid", "Magby", "Miltank", "Blissey", "Raikou", "Entei", "Suicune", "Larvitar", "Pupitar", "Tyranitar", "Lugia", "Ho-Oh", "Celebi", "Treecko", "Grovyle", "Sceptile", "Torchic", "Combusken", "Blaziken", "Mudkip", "Marshtomp", "Swampert", "Poochyena", "Mightyena", "Zigzagoon", "Linoone", "Wurmple", "Silcoon", "Beautifly", "Cascoon", "Dustox", "Lotad", "Lombre", "Ludicolo", "Seedot", "Nuzleaf", "Shiftry", "Taillow", "Swellow", "Wingull", "Pelipper", "Ralts", "Kirlia", "Gardevoir", "Surskit", "Masquerain", "Shroomish", "Breloom", "Slakoth", "Vigoroth", "Slaking", "Nincada", "Ninjask", "Shedinja", "Whismur", "Loudred", "Exploud", "Makuhita", "Hariyama", "Azurill", "Nosepass", "Skitty", "Delcatty", "Sableye", "Mawile", "Aron", "Lairon", "Aggron", "Meditite", "Medicham", "Electrike", "Manectric", "Plusle", "Minun", "Volbeat", "Illumise", "Roselia", "Gulpin", "Swalot", "Carvanha", "Sharpedo", "Wailmer", "Wailord", "Numel", "Camerupt", "Torkoal", "Spoink", "Grumpig", "Spinda", "Trapinch", "Vibrava", "Flygon", "Cacnea", "Cacturne", "Swablu", "Altaria", "Zangoose", "Seviper", "Lunatone", "Solrock", "Barboach", "Whiscash", "Corphish", "Crawdaunt", "Baltoy", "Claydol", "Lileep", "Cradily", "Anorith", "Armaldo", "Feebas", "Milotic", "Castform", "Kecleon", "Shuppet", "Banette", "Duskull", "Dusclops", "Tropius", "Chimecho", "Absol", "Wynaut", "Snorunt", "Glalie", "Spheal", "Sealeo", "Walrein", "Clamperl", "Huntail", "Gorebyss", "Relicanth", "Luvdisc", "Bagon", "Shelgon", "Salamence", "Beldum", "Metang", "Metagross", "Regirock", "Regice", "Registeel", "Latias", "Latios", "Kyogre", "Groudon", "Rayquaza", "Jirachi", "Deoxys", "Turtwig", "Grotle", "Torterra", "Chimchar", "Monferno", "Infernape", "Piplup", "Prinplup", "Empoleon", "Starly", "Staravia", "Staraptor", "Bidoof", "Bibarel", "Kricketot", "Kricketune", "Shinx", "Luxio", "Luxray", "Budew", "Roserade", "Cranidos", "Rampardos", "Shieldon", "Bastiodon", "Burmy", "Wormadam", "Mothim", "Combee", "Vespiquen", "Pachirisu", "Buizel", "Floatzel", "Cherubi", "Cherrim", "Shellos", "Gastrodon", "Ambipom", "Drifloon", "Drifblim", "Buneary", "Lopunny", "Mismagius", "Honchkrow", "Glameow", "Purugly", "Chingling", "Stunky", "Skuntank", "Bronzor", "Bronzong", "Bonsly", "Mime Jr.", "Happiny", "Chatot", "Spiritomb", "Gible", "Gabite", "Garchomp", "Munchlax", "Riolu", "Lucario", "Hippopotas", "Hippowdon", "Skorupi", "Drapion", "Croagunk", "Toxicroak", "Carnivine", "Finneon", "Lumineon", "Mantyke", "Snover", "Abomasnow", "Weavile", "Magnezone", "Lickilicky", "Rhyperior", "Tangrowth", "Electivire", "Magmortar", "Togekiss", "Yanmega", "Leafeon", "Glaceon", "Gliscor", "Mamoswine", "Porygon-Z", "Gallade", "Probopass", "Dusknoir", "Froslass", "Rotom", "Uxie", "Mesprit", "Azelf", "Dialga", "Palkia", "Heatran", "Regigigas", "Giratina", "Cresselia", "Phione", "Manaphy", "Darkrai", "Shaymin", "Arceus", "Victini", "Snivy", "Servine", "Serperior", "Tepig", "Pignite", "Emboar", "Oshawott", "Dewott", "Samurott", "Patrat", "Watchog", "Lillipup", "Herdier", "Stoutland", "Purrloin", "Liepard", "Pansage", "Simisage", "Pansear", "Simisear", "Panpour", "Simipour", "Munna", "Musharna", "Pidove", "Tranquill", "Unfezant", "Blitzle", "Zebstrika", "Roggenrola", "Boldore", "Gigalith", "Woobat", "Swoobat", "Drilbur", "Excadrill", "Audino", "Timburr", "Gurdurr", "Conkeldurr", "Tympole", "Palpitoad", "Seismitoad", "Throh", "Sawk", "Sewaddle", "Swadloon", "Leavanny", "Venipede", "Whirlipede", "Scolipede", "Cottonee", "Whimsicott", "Petilil", "Lilligant", "Basculin", "Sandile", "Krokorok", "Krookodile", "Darumaka", "Darmanitan", "Maractus", "Dwebble", "Crustle", "Scraggy", "Scrafty", "Sigilyph", "Yamask", "Cofagrigus", "Tirtouga", "Carracosta", "Archen", "Archeops", "Trubbish", "Garbodor", "Zorua", "Zoroark", "Minccino", "Cinccino", "Gothita", "Gothorita", "Gothitelle", "Solosis", "Duosion", "Reuniclus", "Ducklett", "Swanna", "Vanillite", "Vanillish", "Vanilluxe", "Deerling", "Sawsbuck", "Emolga", "Karrablast", "Escavalier", "Foongus", "Amoonguss", "Frillish", "Jellicent", "Alomomola", "Joltik", "Galvantula", "Ferroseed", "Ferrothorn", "Klink", "Klang", "Klinklang", "Tynamo", "Eelektrik", "Eelektross", "Elgyem", "Beheeyem", "Litwick", "Lampent", "Chandelure", "Axew", "Fraxure", "Haxorus", "Cubchoo", "Beartic", "Cryogonal", "Shelmet", "Accelgor", "Stunfisk", "Mienfoo", "Mienshao", "Druddigon", "Golett", "Golurk", "Pawniard", "Bisharp", "Bouffalant", "Rufflet", "Braviary", "Vullaby", "Mandibuzz", "Heatmor", "Durant", "Deino", "Zweilous", "Hydreigon", "Larvesta", "Volcarona", "Cobalion", "Terrakion", "Virizion", "Tornadus", "Thundurus", "Reshiram", "Zekrom", "Landorus", "Kyurem", "Keldeo", "Meloetta", "Genesect", "Chespin", "Quilladin", "Chesnaught", "Fennekin", "Braixen", "Delphox", "Froakie", "Frogadier", "Greninja", "Bunnelby", "Diggersby", "Fletchling", "Fletchinder", "Talonflame", "Scatterbug", "Spewpa", "Vivillon", "Litleo", "Pyroar", "Flabébé", "Floette", "Florges", "Skiddo", "Gogoat", "Pancham", "Pangoro", "Furfrou", "Espurr", "Meowstic", "Honedge", "Doublade", "Aegislash", "Spritzee", "Aromatisse", "Swirlix", "Slurpuff", "Inkay", "Malamar", "Binacle", "Barbaracle", "Skrelp", "Dragalge", "Clauncher", "Clawitzer", "Helioptile", "Heliolisk", "Tyrunt", "Tyrantrum", "Amaura", "Aurorus", "Sylveon", "Hawlucha", "Dedenne", "Carbink", "Goomy", "Sliggoo", "Goodra", "Klefki", "Phantump", "Trevenant", "Pumpkaboo", "Gourgeist", "Bergmite", "Avalugg", "Noibat", "Noivern", "Xerneas", "Yveltal", "Zygarde", "Diancie"]
```
[Answer]
# Most flavours, ~~332~~ ~~331~~ ~~326~~ ~~325~~ 304 bytes
```
tly|glo|pix|y.?t|key|d.*sh|dod|iw|ung|r.*me|sa?.r$|ras|abr|aic|mac|g.e.*t|t.i?o$|wb|z..d|wg|kh|rs.a|le?s|lld|a.ow|yh|pn|(or.+o|g.*le|(gm|ub.?|o.l|(id.+|a.+n|olt|onc).).).$|^(..(.([lx]?$|g.y|fa|i?ka)|an?s|yd|eg)|.?ra?[bt]|vi.*e|f.?ar|ko|gy)|(t.r.|rt|ow.*|v|w).e|[kt]a.*u|g.l[abd]|e(ak|no|n.a|.dr|o.t|.*od)
```
Thanks to EMBLEM I had to revamp and restart, building a regex with a back-and-forth relay of manual part selection and Peter Norvig's golfer. Saved a whole bunch of bytes, and probably more is still possible, so I guess it was worth it?
[Tested on Regex101](https://regex101.com/r/eU2xP9/9) (includes `hoopa` and `volcanion`, since they aren't matched anyway)
If anyone's wondering, `seel` is the biggest pain to match, thanks to `registeel` and `seedot` in the other list. Other hard-to-match Pokemon include `hitmonchan` (thanks to `hitmontop` and `chandelure/donphan`),`jolteon` (thanks to `joltik` and half the `eevee` evolutions) and `porygon` (thanks to `flygon` and `porygon2/porygon-z`)
] |
[Question]
[
Your task is to implement integer sequence [A130826](https://oeis.org/A130826):
>
> **an** is the smallest positive integer such that **an - n** is an entire multiple of **3** and twice the number of divisors of **(an - n) / 3** gives the **n**th term in the first differences of the sequence produced by the Flavius Josephus sieve.
>
>
>
Lost yet? Well, it's actually quite easy.
The [Flavius Josephus sieve](https://oeis.org/A000960) defines an integer sequence as follows.
1. Start with the sequence of positive integers and set **k = 2**.
2. Remove every **k**th integer of the sequence, starting with the **k**th.
3. Increment **k** and go back to step 2.
**fn** is the **n**th integer (1-indexed) that never gets removed.
If – as usual – **σ0(k)** denotes the number of positive divisors of the integer **k**, we can define **an** as the smallest positive integer such that **2σ0((an - n) / 3) = fn+1 - fn**.
### Challenge
Write a program or function that takes a positive integer **n** as input and prints or returns **an**.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. May the shortest code win!
### Worked examples
If we remove every second element of the positive integers, we are left with
```
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 ...
```
After removing every third element of the remainder, we get
```
1 3 7 9 13 15 19 21 25 27 31 33 37 39 ...
```
Now, removing every fourth, then fifth, then sixth element gets us
```
1 3 7 13 15 19 25 27 31 37 39 ...
1 3 7 13 19 25 27 31 39 ...
1 3 7 13 19 27 31 39 ...
1 3 7 13 19 27 39 ...
```
The last row shows the terms **f1** to **f7**.
The differences of the consecutive elements of the these terms are
```
2 4 6 6 8 12
```
Dividing these forward differences by **2**, we get
```
1 2 3 3 4 6
```
These are the target divisor counts.
* **4** is the first integer **k** such that **σ0((k - 1) / 3) = 1**. In fact, **σ0(1) = 1**.
* **8** is the first integer **k** such that **σ0((k - 2) / 3) = 2**. In fact, **σ0(2) = 2**.
* **15** is the first integer **k** such that **σ0((k - 3) / 3) = 3**. In fact, **σ0(4) = 3**.
* **16** is the first integer **k** such that **σ0((k - 4) / 3) = 3**. In fact, **σ0(4) = 3**.
* **23** is the first integer **k** such that **σ0((k - 5) / 3) = 4**. In fact, **σ0(6) = 4**.
* **42** is the first integer **k** such that **σ0((k - 6) / 3) = 6**. In fact, **σ0(12) = 6**.
### Test cases
```
n a(n)
1 4
2 8
3 15
4 16
5 23
6 42
7 55
8 200
9 81
10 46
11 119
12 192
13 205
14 196622
15 12303
16 88
17 449
18 558
19 127
20 1748
21 786453
22 58
23 2183
24 3096
25 1105
26 786458
27 12582939
28 568
29 2189
30 2730
```
[Answer]
# Jelly, ~~30~~ ~~29~~ ~~27~~ 25 bytes
*Saved 2 bytes thanks to @Dennis notifying me about `Æd`, and another 2 bytes for combining the two chains.*
```
RUð÷‘Ċ×µ/
‘Ç_ÇH0Æd=¥1#×3+
```
[Try it online!](https://tio.run/nexus/jelly#@x8UenjD4e2PGmYc6To8/dBWfS4g83B7/OF2D4PDbSm2h5YaKh@ebqz9//9/MwA)
This was probably the most fun I've ever had with Jelly. I started from the second line, which calculates **fn** from **n** using the formula on OEIS, and is quite beautiful.
### Explanation
```
RUð÷‘Ċ×µ/ Helper link to calculate Fn. Argument: n
R Get numbers [1..n]
U Reverse
/ Reduce by "round up to next 2 multiples":
÷ Divide by the next number
‘ Increment to skip a multiple
Ċ Ceil (round up)
× Multiply by the next number
‘Ç_ÇH0Æd=¥1#×3+ Main link. Argument: n
‘ Increment n
Ç Calculate Fn+1
Ç Calculate Fn
_ Subtract
H Divide by 2
0 1# Starting from 0, find the first candidate for (an-n)/3
that satisfies...
Æd σ0((an-n)/3)
= = (Fn+1-Fn)/2
×3 Multiply by 3 to turn (an-n)/3 into an-n
+ Add n to turn an-n into an
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~121~~ ~~119~~ 118 bytes
```
n=input();r=range(1,4**n);d=s,=r*1,
for k in r:del s[k::k+1];d+=sum(k%j<1for j in r)*2,
print d.index(s[n]-s[n-1])*3+n
```
Run time should be roughly **O(16n)** with **O(4n)** memory usage. Replacing `4**n` with `5<<n` – which I *think* is sufficient – would improve this dramatically, but I'm not convinced that it works for arbitrarily large values of **n**.
[Try it online!](https://tio.run/nexus/python2#HcpLCsIwEADQfU8xGyG/ClFxkTgnKVkIEyWNjmXSgrePn81bvc5YeNlWpaOgXPmelXcnY1hHwuZQjHfD7SVQoTBIoPyANtUQqvUpksW2PVXdzRf/S/M/aXNwwyKFV6B9Ycpv1SZO45fRJ22Olns/fwA "Python 2 – TIO Nexus")
### Asymptotic behavior and upper bounds of an
Define **bn** as **(an - n)/3**, i.e., the smallest positive integer **k** such that **σ0(k) = ½(fn+1 - fn)**.
As noted on the OEIS page, **fn ~ ¼πn2**, so **fn+1 - fn ~ ¼π(n + 1)2 - ¼πn2 = ¼π(2n + 1) ~ ½πn**.
This way, **½(fn+1 - fn) ~ ¼πn**. If the actual number is a prime **p**, the smallest positive integer with **p** divisors is **2p-1**, so **bn** can be approximated by **2cn**, where **cn ~ ¼πn**.
Therefore **bn < 4n** will hold for sufficiently large **n**, and given that **2¼πn < 2n << (2n)2 = 4n**, I'm confident there are no counterexamples.
### How it works
```
n=input();r=range(1,4**n);d=s,=r*1,
```
This sets up a few references for our iterative process.
* **n** is the user input: a positive integer.
* **r** is the list **[1, ..., 4n - 1]**.
* **s** is a copy of **r**.
Repeating the list once with `r*1` creates a shallow copy, so modifying **s** won't modify **r**.
* **d** is initialized as the tuple **(s)**.
This first value is not important. All others will hold divisor counts of positive integers.
```
for k in r:del s[k::k+1];d+=sum(k%j<1for j in r)*2,
```
For each integer **k** from **1** to **4n - 1**, we do the following.
* `del s[k::k+1]` takes every **(k + 1)**th integer in **s** – starting with the **(k + 1)**th – and deletes that slice from **s**.
This is a straightforward way of storing an initial interval of the Flavius Josephus sieve in **s**. It will compute much more than the required **n + 1** initial terms, but using a single `for` loop to update both **s** and **d** saves some bytes.
* `d+=sum(k%j<1for j in r)*2,` counts how many elements of **r** divide **k** evenly and appends **2σ0(k)** to **d**.
Since **d** was initialized as a singleton tuple, **2σ0(k)** is stored at index **k**.
```
print d.index(s[n]-s[n-1])*3+n
```
This finds the first index of **fn+1 - fn** in **d**, which is the smallest **k** such that **2σ0(k) = fn+1 - fn**, then computes **an** as **3k + 1** and prints the result.
[Answer]
# Java 8, 336, 305, 303, 287, 283 279 bytes
57 bytes removed thanks to Kritixi Lithos
Golfed
```
class f{static int g(int s,int N){return s<1?N+1:g(s-1,N+N/s);}static int h(int k){int u=0,t=1,i;for(;u!=(g(k,k)-g(k,k-1))/2;t++)for(i=1,u=0;i<=t;)if(t%i++<1)u++;return 3*t-3+k;}public static void main(String[]a){System.out.print(h(new java.util.Scanner(System.in).nextInt()));}}
```
Ungolfed
```
class f {
static int g(int s,int N){return s < 1 ? N + 1 : g(s - 1, N + N / s);}
static int h(int k) {
int u = 0, t = 1, i;
// get the first number with v divisors
while(u != (g(k, k) - g(k, k - 1))/2){
u = 0;
for (i = 1; i <= t; i++)
if (t % i < 1) u++;
t++;
}
// 3*(t-1)+k = 3*t+k-3
return 3 * t + k - 3;
}
public static void main(String[] a) {
System.out.print(h(new java.util.Scanner(System.in).nextInt()));
}
}
```
[Answer]
# Mathematica, ~~130~~ ~~116~~ ~~106~~ 103 bytes
```
3Catch@Do[f=#2⌈#/#2+1⌉&~Fold~Reverse@Range@#&;If[Tr[2+0Divisors@k]==f[#+1]-f@#,Throw@k],{k,∞}]+#&
```
or
```
3Catch@Do[f=#2⌈#/#2+1⌉&~Fold~Reverse@Range@#&;If[2DivisorSum[k,1&]==f[#+1]-f@#,Throw@k],{k,∞}]+#&
```
Ended up being almost identical to @Pietu1998's Jelly code...
**Explanation**
```
Catch@
```
`Catch` whatever is `Throw`-ed (thrown).
```
Do[ ... ,{k,∞}]
```
Infinite loop; `k` starts from `1` and increments every iteration.
```
f= ...
```
Assign `f`:
```
Reverse@Range@#
```
Find `{1, 2, ... , n}`. Reverse it.
```
#2⌈#/#2+1⌉&
```
A function that outputs ceil(n1/n2 + 1) \* n2
```
f= ... ~Fold~ ... &
```
Assign `f` a function that recursively applies the above function to the list from two steps above, using each output as the first input and each element of the list as the second input. The initial "output" (first input) is the first element of the list.
```
Tr[2+0Divisors@k]==f[#+1]-f@#
```
Check whether twice the number of divisors of `k` is equal to f(n + 1) - f(n).
```
If[ ... ,Throw@k]
```
If the condition is `True`, `Throw` the value of `k`. If not, continue looping.
```
3 ... +#&
```
Multiply the output by 3 and add n.
**130 byte version**
```
Catch@Do[s=#+1;a=k-#;If[3∣a&&2DivisorSigma[0,a/3]==Differences[Nest[i=1;Drop[#,++i;;;;i]&,Range[s^2],s]][[#]],Throw@k],{k,∞}]&
```
[Answer]
# [Perl 6](http://perl6.org), ~~154~~ ~~149~~ ~~136~~ 107 bytes
```
->\n{n+3*first ->\o{([-] ->\m{m??&?BLOCK(m-1).rotor(m+0=>1).flat!!1..*}(n)[n,n-1])/2==grep o%%*,1..o},^Inf}
```
Ungolfed:
```
-> \n { # Anonymous sub taking argument n
n + 3 * first -> \o { # n plus thrice the first integer satisfying:
( #
[-] #
-> \m { # Compute nth sieve iteration:
m # If m is nonzero,
?? &?BLOCK(m-1).rotor(m+0=>1).flat # then recurse and remove every (m+1)-th element;
!! 1..* # the base case is all of the positive integers
} #
(n) # Get the nth sieve
[n,n-1] # Get the difference between the nth and (n-1)th elements (via the [-] reduction operator above)
) / 2 # and divide by 2;
== # We want the number that equals
grep o %% *, 1..o # the number of divisors of o.
}
,^Inf
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ ~~34~~ 39 bytes
```
1Qi4ë[N3*¹+NÑg·¹D>‚vyy<LRvy/>îy*}}‚Æ(Q#
```
It looks awful, so is runtime performance. It takes several seconds for input that yield small values. Don't try numbers like 14; it will eventually find the result but it would take ages.
## Explanation
It works as 2 sequentially called programs. The first one computes **Fn+1 - Fn** and the second one determines **an** based on its definition, using a bruteforce approach.
**Fn+1 - Fn** is evaluated for each iteration even though it is loop invariant. It makes the code time inefficient, but it makes the code shorter.
[Try it online!](https://tio.run/nexus/05ab1e#ATMAzP//xb5ITMK5wrXCvERnTMK@PiUww4rDj33CpcK5PMOoVVtOMyrCuStOw5FnwrdYUSP//zg "05AB1E – TIO Nexus")
] |
[Question]
[
There's a really important problem in cellular automata called the [Majority problem](https://en.wikipedia.org/wiki/Majority_problem_(cellular_automaton)):
>
> The majority problem, or density classification task is the problem of finding one-dimensional cellular automaton rules that accurately perform majority voting.
>
>
> ...
>
>
> Given a configuration of a two-state cellular automata with i + j cells total, i of which are in the zero state and j of which are in the one state, a correct solution to the voting problem must eventually set all cells to zero if i > j and must eventually set all cells to one if i < j. The desired eventual state is unspecified if i = j.
>
>
>
Although it has been proven that no cellular automata can solve the majority problem in all cases, there are many rules that can can solve it in the majority of cases. The Gacs-Kurdyumov-Levin automaton has an accuracy of about 78% with random initial conditions. The GKL rule isn't complicated:
* Radius of 3, meaning that the cell's new state depends on 7 previous cells: itself, the 3 cells to the right, and the 3 cells to the left.
* If a cell is currently `O`, its new state is the majority of itself, the cell to its left, and the cell 3 steps to its left.
* If a cell is currently `1`, its new state is the majority of itself, the cell to its right, and the cell 3 steps to its right.
Here is an example:
```
0 1 0 1 1 1 0 1 1 0 1 0 0 1
0 1 1 1 1 1 1 1 0 0 1 1 0 0
0 1 1 1 1 1 1 1 1 0 1 0 0 0
0 1 1 1 1 1 1 1 0 1 0 1 0 0
0 1 1 1 1 1 1 0 1 0 1 0 1 0
0 1 1 1 1 1 0 1 0 1 0 1 1 1
1 1 1 1 1 0 1 0 1 1 1 1 1 1
1 1 1 1 0 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
```
In this example, the cellular automaton correctly calculated that 8 > 6. Other examples take longer periods of time, and produce some cool patterns in the meantime. Below are two examples I randomly found.
```
0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 1 1 1 0 1 0 0 1 1 1
1 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 1 0 0 1 1
```
---
## Taking it to the next level
As far as my internet research has shown, almost all academic research on the majority problem has been conducted with 2-state CAs. In this challenge, we are going to expand the majority problem to **3-state CAs**. I will call this the *plurality problem*. [Plurality](https://en.wikipedia.org/wiki/Plurality_%28voting%29), or relative majority, refers to the condition in which one of the options has more votes than each of the alternatives, but not necessarily a majority of all votes.
**Problem Statement**
1. There is a 3-state 1D cellular automaton with radius 3.
2. There are **151** cells with a circular boundary condition.
3. These cells are given a random starting state, on the sole condition that 1 of the 3 states has a strict plurality. "Random" means an independent uniform distribution for each cell.
4. The accuracy of a rule is the percentage of (valid) random initial conditions in which all of the cells synchronize to the correct state (the one with plurality) **within 10000 generations**.
5. The goal is to find a rule with high accuracy,
Plurality edge cases: Any configuration with 50/50/51 is a valid starting configuration (since there is a strict plurality), while any configuration with 51/51/49 is not valid (since there is not a strict plurality).
The search space is 3^3^7 (~3e1043), far outside the reach of any exhaustive search. This means that you will need to make use of other techniques, like genetic algorithms, in order to solve this problem. It will also take some human engineering.
The 10000 generation rule is subject to change, depending on the runtimes/accuracy of the rules people find. If it is too low to allow reasonable rates of convergence, then I can raise it. Alternatively, I can lower it to serve as a tie-breaker.
## Winning
The winner is the person who submits the radius-3 CA rule with the highest accuracy out of all of the contestants.
Your submission should include...
* A description of the rule (using [Wolfram code](https://en.wikipedia.org/wiki/Wolfram_code) if necessary)
* The accuracy rate and sample size
* A reasonably-sized *explanation* of how you discovered the rule, including programs you wrote to solve it, or any "manual" engineering. (This being the most interesting part, since everything else is just raw numbers.)
## Prior Work
* A paper by [Juille and Pollack](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.67.6665&rep=rep1&type=pdf), describing how they evolved a 2-state rule with 86% accuracy.
* [This paper](http://web.cecs.pdx.edu/%7Emm/EGSCA.pdf) used r=3, 149-cell, 2-state CAs. It did not attempt to the solve the majority problem, however, but instead to find rules that quickly resulting in an alternating all-`1`-all-`0` pattern. Despite these differences, I suspect many techniques will be similar.
* A (not very helpful because it's behind a paywall) paper by [Wolz and de Oliviera](http://www.oldcitypublishing.com/journals/jca-home/jca-issue-contents/jca-volume-3-number-4-2008/jca-3-4-p-289-312/) which currently hold the 2-state record
[Answer]
# Sort of GKL plus hill climbing, 61.498%
* If a cell is a 0, look at the cells 3 to the left, 1 to the left and at itself. Set value to majority. If it's a tie, stay the way you are.
* If a cell is a 1, look at the cells 3 to the right, 1 to the right and at itself. Set value to majority. If it's a tie, stay the way you are.
* If a cell is a 2, look at the cells 2 to the left, 2 to the right and 3 to the right. Set value to majority. If it's a tie, stay the way you are.
I got 59453 right out of 100000 total, 59.453%
Some mutating and hill-climbing resulted in 61498/100000 = 61.498%.
I'll probably test a bit more and will post some more information later.
[Answer]
# "Just toss out the 2s and do GKL" -- 55.7%
It's not so easy to guess what a good rule would be, so I tried to at least come up with something that would score above 1/3. The strategy is to try to get the right answer when the majority state is 0 or 1, and accept the loss if it's 2. It scored 56.5% over 100,000 trials, which is somehow slightly better than what would be expected from multiplying 78% (score of GKL) \* 2/3 (fraction of the time when answer is 0 or 1) = 52%.
More concretely, the strategy is as follows:
* If the cell is 0 or 1, take the majority of the 3 cells as in the GKL strategy, but ignoring any neighbors that are 2. If it's a tie, leave the cell unchanged.
* If the cell is 2, choose whichever is more numerous of 0 or 1 in the entire neighborhood. If it's a tie, choose the leftmost value that is 0 or 1. If all the neighbors are 2, stay 2.
I used this code to test:
```
#include <iostream>
#include <algorithm>
#include <string.h>
#include <random>
#include <cassert>
#define W 151
#define S 3
#define R 3
typedef int state;
struct tape {
state s[R+W+R];
state& operator[](int i) {
return s[i + R];
}
template<typename Rule> void step(Rule r) {
for(int i = 0; i < R; i++) s[i] = s[W + i];
for(int i = 0; i < R; i++) s[R + W + i] = s[R + i];
for(int i = 0; i < W; i++) {
s[i] = r(s + R + i);
}
memmove(s + R, s, W * sizeof(*s));
}
state unanimous() {
state st = (*this)[0];
for(int i = 1; i < W; i++) {
if((*this)[i] != st)
return -1;
}
return st;
}
};
std::ostream& operator<<(std::ostream& s, tape& t) {
for (int i = 0; i < W; i++)
s << t[i];
return s;
}
state randomize(tape& t) {
static std::mt19937 rg(390332);
begin:
int c[S]{};
for(int i = 0; i < W; i++) {
state s = rg() % S;
c[s]++;
t[i] = s;
}
state* smax = std::max_element(c, c + R);
int nmaj = 0;
for (int n : c) nmaj += n == *smax;
if (nmaj > 1) goto begin;
return smax - c;
}
template<bool PrintSteps, typename Rule> int simulate(Rule r, int trials, int giveup) {
int successes = 0;
for(state s = 0; s < S; s++) {
state t[2 * R + 1];
for(int i = 0; i <= 2 * R; i++) t[i] = s;
assert(r(t + R) == s);
}
while(trials--) {
tape tp;
state desired = randomize(tp);
int steps = giveup;
while(steps--) {
tp.step(r);
state u = tp.unanimous();
if(~u) {
bool correct = u == desired;
if(PrintSteps) {
std::cout << correct << ' ' << giveup - steps << '\n';
}
successes += correct;
break;
}
}
}
return successes;
}
struct ixList {
int n;
int i[2 * R + 1];
};
state rule_justTossOutThe2sAndDoGKL(const state* t) {
const ixList ixl[] = {
{ 3,{ -3, -1, 0 } },
{ 3,{ 0, 1, 3 } },
{ 6,{ -3, -2, -1, 1, 2, 3 } }
};
int c[S]{};
for (int i = 0; i < ixl[*t].n; i++)
c[t[ixl[*t].i[i]]]++;
if (c[0] > c[1]) return 0;
if (c[1] > c[0]) return 1;
if (*t < 2) return *t;
for (int i = -R; i <= R; i++)
if (t[i] < 2) return t[i];
return 2;
}
int main()
{
int nt = 100000;
int ns = simulate<false>(rule_justTossOutThe2sAndDoGKL, nt, 10000);
std::cout << (double)ns / nt << '\n';
return 0;
}
```
[Answer]
# "Just steal whatever's best and evolve it", bleh
Edit: in its current state this answer, rather than finding better patterns, finds a better random sample.
This answer encodes/decodes solutions by enumerating all states as ternary numbers (least-significant digit first). The solution for 59.2%:
```
000000000010010010000000000000000000000000000000000000000000010000010000110000000
000000000010010010000000000111111101111111111111111111000011000010011011000011010
000000000012010011001000000021111111111120111211111111000000000000011010000010000
000011000010022110000000202000000002000000000020000000001010000000011011000011010
020000000010010010001000000111101111111111111111111111010011000011111111010011010
000000000010010010000000000111111111101111111111112111000011010110111011010011011
000000000010010010000000000010000000000000000100002011000000000100011010020010000
000020020010010010000200000111102111111111111111111101000011010010111011000011011
000100000010010010000000000121111111111111111111111111000210000012011011002011010
000000000010010110000000000111112112111111111001111111000010000010011011000011010
000000000010010120000200000111211111111111111111110111110011010011100111010011011
000000000010010010000000000011111111111111111111111111000011010010111211210012020
010000000010010010020100020111110111111111111111111110010111010011011111010111011
002000000010010010000000000111110111111111211111111111001111111111111111111111111
000000000110010010000000000111111111111111211111111111010111011111111111011111011
001000000010010010000000000011111101111111111111110111000011010010111011010011010
001000000010010110000000000111111111111111102111110111010111011111111111011111101
000000000210010010000000000111111111111111111111011111010011010011111111010111011
000000000010010010000000000112111111111111111111101011000000000000011010000010000
000000000010010010000000000111111111111111111111111111000011010010111011010011011
000200000012010010000000000111111111111112111111111111000010000210011211001011010
000000000010010211000002000111111111111111111111111111000001010010111011010011010
000021200010210010000101100111111111111211111110110211010111021111111101010111111
000000000010010010000000000111111111111101111111111111010011010111111111010110021
000200000010010010000000010111111111101111111121112111000210001010011011000011010
000000000010010010000000000111111111111111111111111111210011010021111111010111011
000020000010010010000000000111111111111111111111111111000011010010121011010011012
```
This answer was evolved from feersum's 55.7%, using the following code. This code requires [libop](https://github.com/orlp/libop), which is my personal C++ header-only library. It's very easy to install, just do `git clone https://github.com/orlp/libop` in the same directory as where you've saved the program. I suggest compiling with `g++ -O2 -m64 -march=native -std=c++11 -g`. For speedy development I also suggest precompiling libop by running the above command on `libop/op.h`.
```
#include <cstdint>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <random>
#include "libop/op.h"
constexpr int MAX_GENERATIONS = 500;
constexpr int NUM_CELLS = 151;
std::mt19937_64 rng;
double worst_best_fitness;
// We use a system with okay-ish memory density. We represent the ternary as a
// 2-bit integer. This means we have 32 ternaries in a uint64_t.
//
// There are 3^7 possible states, requiring 4374 bits. We store this using 69
// uint64_ts, or little over half a kilobyte.
// Turn 7 cells into a state index, by encoding as ternary.
int state_index(const int* cells) {
int idx = 0;
for (int i = 0; i < 7; ++i) {
idx *= 3;
idx += cells[6-i];
}
return idx;
}
// Get/set a ternary by index from a 2-bit-per-ternary encoded uint64_t array.
int get_ternary(const uint64_t* a, size_t idx) {
return (a[idx/32] >> (2*(idx % 32))) & 0x3;
}
void set_ternary(uint64_t* a, size_t idx, int val) {
assert(val < 3);
int shift = 2*(idx % 32);
uint64_t shifted_val = uint64_t(val) << shift;
uint64_t shifted_mask = ~(uint64_t(0x3) << shift);
a[idx/32] = (a[idx/32] & shifted_mask) | shifted_val;
}
struct Rule {
uint64_t data[69];
double cached_fitness;
Rule(const char* init) {
cached_fitness = -1;
for (auto i : op::range(69)) data[i] = 0;
for (auto i : op::range(2187)) set_ternary(data, i, init[i] - '0');
}
double fitness(int num_tests = 1000);
Rule* random_mutation(int num_mutate) const {
auto new_rule = new Rule(*this);
auto r = op::range(2187);
std::vector<int> indices;
op::random_sample(r.begin(), r.end(),
std::back_inserter(indices), num_mutate, rng);
for (auto idx : indices) {
set_ternary(new_rule->data, idx, op::randint(0, 2, rng));
}
new_rule->cached_fitness = -1;
return new_rule;
}
int new_state(const int* cells) const {
return get_ternary(data, state_index(cells));
}
void print_rule() const {
for (auto i : op::range(2187)) {
std::cout << get_ternary(data, i);
if (i % 81 == 80) std::cout << "\n";
}
}
};
struct Automaton {
uint64_t state[5];
int plurality, generation;
Automaton() : generation(0) {
for (auto i : op::range(5)) state[i] = 0;
int strict = 0;
while (strict != 1) {
int votes[3] = {};
for (auto i : op::range(NUM_CELLS)) {
int vote = op::randint(0, 2, rng);
set_ternary(state, i, vote);
votes[vote]++;
}
// Ensure strict plurality.
plurality = std::max_element(votes, votes + 3) - votes;
strict = 0;
for (auto i : op::range(3)) strict += (votes[i] == votes[plurality]);
}
}
void print_state() {
for (int i = 0; i < 151; ++i) std::cout << get_ternary(state, i);
std::cout << "\n";
}
bool concensus_reached() {
int target = get_ternary(state, 0);
for (auto i : op::range(NUM_CELLS)) {
if (get_ternary(state, i) != target) return false;
}
return true;
}
void next_state(const Rule& rule) {
uint64_t new_state[5] = {};
std::vector<int> cells;
for (auto r : op::range(-3, 4)) {
cells.push_back(get_ternary(state, (r + NUM_CELLS) % NUM_CELLS));
}
for (auto i : op::range(NUM_CELLS)) {
set_ternary(new_state, i, rule.new_state(cells.data()));
cells.erase(cells.begin());
cells.push_back(get_ternary(state, (i + 4) % NUM_CELLS));
}
for (auto i : op::range(5)) state[i] = new_state[i];
generation++;
}
};
double Rule::fitness(int num_tests) {
if (cached_fitness == -1) {
cached_fitness = 0;
int num_two = 0;
for (auto test : op::range(num_tests)) {
Automaton a;
while (a.generation < MAX_GENERATIONS && !a.concensus_reached()) {
a.next_state(*this);
}
if (a.generation < MAX_GENERATIONS &&
get_ternary(a.state, 0) == a.plurality &&
a.plurality == 2) num_two++;
cached_fitness += (a.generation < MAX_GENERATIONS &&
get_ternary(a.state, 0) == a.plurality);
if (cached_fitness + (num_tests - test) < worst_best_fitness) break;
}
if (num_two) std::cout << cached_fitness << " " << num_two << "\n";
cached_fitness;
}
return cached_fitness;
}
int main(int argc, char** argv) {
std::random_device rd;
rng.seed(42); // Seed with rd for non-determinism.
const char* base =
"000000000010010010000000000000000000000000000000000000000000000000010000000000000"
"000000000010010010000000000111111111111111111111111111000010000010011011000011010"
"000000000010010010000000000111111111111111111111111111000000000000011010000010000"
"000000000010010010000000000000000000000000000000000000000010000010011011000011010"
"000000000010010010000000000111111111111111111111111111010011010011111111010111011"
"000000000010010010000000000111111111111111111111111111000011010010111011010011011"
"000000000010010010000000000000000000000000000000000000000000000000011010000010000"
"000000000010010010000000000111111111111111111111111111000011010010111011010011011"
"000000000010010010000000000111111111111111111111111111000010000010011011000011010"
"000000000010010010000000000111111111111111111111111111000010000010011011000011010"
"000000000010010010000000000111111111111111111111111111010011010011111111010111011"
"000000000010010010000000000111111111111111111111111111000011010010111011010011010"
"000000000010010010000000000111111111111111111111111111010011010011111111010111011"
"000000000010010010000000000111111111111111111111111111011111111111111111111111111"
"000000000010010010000000000111111111111111111111111111010111011111111111011111111"
"000000000010010010000000000111111111111111111111111111000011010010111011010011010"
"000000000010010010000000000111111111111111111111111111010111011111111111011111111"
"000000000010010010000000000111111111111111111111111111010011010011111111010111011"
"000000000010010010000000000111111111111111111111111111000000000000011010000010000"
"000000000010010010000000000111111111111111111111111111000011010010111011010011011"
"000000000010010010000000000111111111111111111111111111000010000010011011000011010"
"000000000010010010000000000111111111111111111111111111000011010010111011010011010"
"000000000010010010000000000111111111111111111111111111010111011111111111011111111"
"000000000010010010000000000111111111111111111111111111010011010011111111010111011"
"000000000010010010000000000111111111111111111111111111000010000010011011000011010"
"000000000010010010000000000111111111111111111111111111010011010011111111010111011"
"000000000010010010000000000111111111111111111111111111000011010010111011010011012"
;
// Simple best-only.
std::vector<std::unique_ptr<Rule>> best_rules;
best_rules.emplace_back(new Rule(base));
worst_best_fitness = best_rules.back()->fitness();
while (true) {
const auto& base = *op::random_choice(best_rules.begin(), best_rules.end(), rng);
std::unique_ptr<Rule> contender(base->random_mutation(op::randint(0, 100, rng)));
// Sort most fit ones to the beginning.
auto most_fit = [](const std::unique_ptr<Rule>& a, const std::unique_ptr<Rule>& b) {
return a->fitness() > b->fitness();
};
if (contender->fitness() >= best_rules.back()->fitness()) {
std::cout << contender->fitness();
double contender_fitness = contender->fitness();
best_rules.emplace_back(std::move(contender));
std::sort(best_rules.begin(), best_rules.end(), most_fit);
if (best_rules.size() > 5) best_rules.pop_back();
std::cout << " / " << best_rules[0]->fitness() << "\n";
worst_best_fitness = best_rules.back()->fitness();
if (contender_fitness == best_rules.front()->fitness()) {
best_rules.front()->print_rule();
}
}
}
return 0;
}
```
[Answer]
# Hand Coded, 57.541%
This actually only looks at the 5 cells above it. It could probably be improved by increasing the range it looks at. Ran with 100,000 test cases.
Algorithm:
```
If above == 0:
if to the left there are only 2s or there is a 1 separated by 2s
next state = 2
else
next state = 0
If above == 1:
if to the right there are only 2s or there is a 0 separated by 2s
next state = 2
else
next state = 1
If above == 2:
ignore 0s to the left if the 0 is left of a 1 on the left
ignore 1s to the right if the 1 is right of a 0 on the right
if the closest 0 on the left is closer than the closest 1 on the right
next state = 0
else if the closest 1 on the right is closer than the closest 0 on the left
next state = 1
else
next state = 2
```
Gene:
```
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222222222222
000000000222222222000222222111111111111111111111111111222111111111111111111111111
000000000222222222000222222111111111111111111111111111000000000111111111222111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222222222222
000000000222222222000222222111111111111111111111111111222111111111111111111111111
000000000222222222000222222111111111111111111111111111000000000111111111222111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222222222222
000000000222222222000222222111111111111111111111111111222111111111111111111111111
000000000222222222000222222111111111111111111111111111000000000111111111222111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
```
Testing code:
```
import java.lang.Math.*
import java.util.*
const val RADIUS = 3;
const val STATES = 3;
const val DIAMETER = 2 * RADIUS + 1
const val TAPE_LENGTH = 151
val CODE_SIZE = pow(STATES.toDouble(), DIAMETER.toDouble()).toInt()
const val GRADE_RUNS = 100000
const val GRADE_MAX_TIME = 10000
operator fun IntArray.inc() : IntArray {
val next = this.clone()
var i = 0
while (i < size) {
if (this[i] == STATES - 1) {
next[i] = 0
} else {
next[i]++
break
}
i++
}
return next
}
val IntArray.index : Int
get() {
var total = 0
for (i in (size - 1) downTo 0) {
total *= STATES
total += this[i]
}
return total
}
interface IRule {
operator fun get(states : IntArray) : Int
}
fun IntArray.equalsArray(other: IntArray) = Arrays.equals(this, other)
class Rule : IRule {
constructor(rule : IRule) {
val start = IntArray(DIAMETER)
var current = start.clone()
code = IntArray(CODE_SIZE)
try {
do {
code[current.index] = rule[current]
current++
} while (!current.equalsArray(start));
} catch (e : Throwable) {
println(Arrays.toString(code))
println(Arrays.toString(current))
throw e
}
}
constructor(code : IntArray) {
this.code = IntArray(CODE_SIZE) { if (it < code.size) code[it] else 0 }
}
val code : IntArray
override fun get(states: IntArray) : Int {
return code[states.index]
}
override fun toString() : String {
val b = StringBuilder()
for (i in 0 until CODE_SIZE) {
if (i > 0 && i % pow(STATES.toDouble(), RADIUS.toDouble() + 1).toInt() == 0) {
b.append('\n')
}
b.append(code[i])
}
return b.toString()
}
fun grade() : Double {
var succeeded = 0
for (i in 0 until GRADE_RUNS) {
if (i % (GRADE_RUNS / 100) == 0) {
println("${i/(GRADE_RUNS / 100)}% done grading.")
}
var tape : Tape
do {
tape = Tape()
} while (tape.majority() == -1);
val majority = tape.majority()
val beginning = tape
var j = 0
while (j < GRADE_MAX_TIME && !tape.allTheSame()) {
tape = tape.step(this)
j++
}
if (tape.stabilized(this) && tape.majority() == majority) {
succeeded++
}/* else if (beginning.majority() != 2) {
println(beginning.majority())
tape = beginning
for (j in 1..100) {
println(tape)
tape = tape.step(this)
}
println(tape)
}*/
}
return succeeded.toDouble() / GRADE_RUNS
}
}
fun getRandomState() : Int {
return (random() * STATES).toInt()
}
class Tape(val tape : IntArray) {
constructor() : this(IntArray(TAPE_LENGTH) { getRandomState() } )
fun majority() : Int {
val totals = IntArray(STATES)
for (cell in tape) {
totals[cell]++
}
var best = -1
var bestScore = -1
for (i in 0 until STATES) {
if (totals[i] > bestScore) {
best = i
bestScore = totals[i]
} else if (totals[i] == bestScore) {
best = -1
}
}
return best
}
fun allTheSame() : Boolean {
for (i in 1 until TAPE_LENGTH) {
if (this[i] != this[0]) {
return false
}
}
return true
}
operator fun get(index: Int) = tape[((index % TAPE_LENGTH) + TAPE_LENGTH) % TAPE_LENGTH]
fun step(rule : IRule) : Tape {
val nextTape = IntArray ( TAPE_LENGTH )
for (i in 0 until TAPE_LENGTH) {
nextTape[i] = rule[IntArray(DIAMETER) { this[i + it - RADIUS] }]
}
return Tape(nextTape)
}
fun stabilized(rule : IRule) = allTheSame() && majority() == step(rule).majority()
override fun toString() : String {
val b = StringBuilder()
for (cell in tape) {
b.append(cell)
}
return b.toString()
}
}
fun main(args : Array<String>) {
val myRule = Rule(object : IRule {
override fun get(states: IntArray): Int {
if (states[3] == 0) {
if (states[2] == 1) {
return 2
} else if (states[2] == 0) {
return 0
} else if (states[1] == 1) {
return 2
} else if (states[1] == 0) {
return 0
} else {
return 2
}
} else if (states[3] == 1) {
if (states[4] == 0) {
return 2
} else if (states[4] == 1) {
return 1
} else if (states[5] == 0) {
return 2
} else if (states[5] == 1) {
return 1
} else {
return 2
}
} else {
if (states[2] == 0) {
if (states[4] != 1) {
return 0
}
} else if (states[4] == 1) {
return 1
}
if (states[1] == 0 && states[2] != 1) {
if (states[5] != 1) {
return 0
}
} else if (states[5] == 1 && states[4] != 0) {
return 1
}
return 2
}
}
})
var tape = Tape()
println(myRule.grade())
}
```
[Example](http://pastebin.com/raw/kTn8pLZb)
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/4481/edit).
Closed 8 years ago.
[Improve this question](/posts/4481/edit)
Excluding trivial programs, what code compiles in the most number of languages?
(By "trivial" I mean to exclude answers such as the empty program or text that will be echoed directly.)
The following code apparently compiles in all of the following programming languages (and prints something different in each one):
C, C++, Perl, TeX, LaTeX, PostScript, sh, bash, zsh and Prolog.
```
%:/*:if 0;"true" +s ||true<</;#|+q|*/include<stdio.h>/*\_/
{\if(%)}newpath/Times-Roman findfont 20 scalefont setfont(
%%)pop 72 72 moveto(Just another PostScript hacker,)show((
t)}. t:-write('Just another Prolog hacker,'),nl,halt. :-t.
:-initialization(t). end_of_file. %)pop pop showpage(-: */
int main(){return 0&printf("Just another C%s hacker,\n",1%
sizeof'2'*2+"++");}/*\fi}\csname @gobble\endcsname{\egroup
\let\LaTeX\TeX\ifx}\if00\documentclass{article}\begin{doc%
ument}\fi Just another \LaTeX\ hacker,\end{document}|if 0;
/(J.*)\$sh(.*)"/,print"$1Perl$2$/"if$_.=q # hack the lang!
/
sh=sh;test $BASH_VERSION &&sh=bash;test $POSIXLY_CORRECT&&
sh=sh;test $ZSH_VERSION && sh=zsh;awk 'BEGIN{x="%c[A%c[K"
printf(x,27,27)}';echo "Just another $sh hacker," #)pop%*/
```
That's 10 different languages. I found it via [pts oldalai](http://pts.szit.bme.hu/index__en.html) (who also has a magnificent Christmas poem written in C, C++, Perl and TeX). Can anyone do better?
[Answer]
# 3 Languages - C, C++, and Python
```
#ifdef _cplusplus
#include <iostream>
#define print() int main(){cout << "Hello world! -- from C++" << endl;}
#elif (defined __STDC__) || (defined __STDC_VERSION__)
#include <stdio.h>
#define print() int main(){printf("Hello world! -- from C\n");}
#else
import builtins
print = lambda : builtins.print("Hello world! -- from Python")
#endif
print()
```
Something different is printed in each language. In C & C++, lines starting with '#' are preprocessing directives, but those same lines are comments in Python.
[Answer]
# 5 languages- Thue, Brainf\*\*\*, Boolf\*\*\*, Treehugger, and Javascript
```
/*::=
alert::=~This is Thue!
::=
-><[[--->+<]>-.[---->+++++<]>-.+.++++++++++.+[---->+<]>+++.-[--->++<]>-.++++++++++.+[---->+<]>+++.+[->++<]>.---[----->+<]>-.+++[->+++<]>++.++++++++.+++++.--------.---[->+++<]>+...---------.[-]]
^^[[--->+^]>-.[---->+++++^]>-.+.++++++++++.+[---->+^]>+++.-[--->++^]>-.++++++++++.+[---->+^]>+++.>-[--->+^]>-.-[--->+^]>+.-------------..+++.[--->+^]>---.++[->+++^]>++..--.+++++++++++++.[--->+^]>-----.[-]]
-+[+;;+;+;+;+;+;+;;;;+;+;+;;+;+;+;;+;+;+;;+;+;;+;;+;;;+;;;;;;+;+;;+;+;;+;+;+;;+;+;;+;;+;;;+;;;;;;+;+;;;+;+;;;;+;+;+;;;;+;+;;+;+;;;;+;+;;+;;;+;;+;+;;+;;+;;+;;+;;+;;+;+;+;+;+;+;;;+;+;+;+;+;+;;;+;+;+;+;+;+;;+;+;;;;+;+;;]
*/alert("This is Javascript!")
```
Note that the Treehugger portion times out in the web-based implementation, unfortunately, so you should use a different Treehugger interpreter.
] |
[Question]
[
You have a bunch of heavy boxes and you want to stack them in the fewest number of stacks possible. The issue is that you can't stack more boxes on a box than it can support, so heavier boxes must go on the bottom of a stack.
## The Challenge
**Input**: A list of weights of boxes, in whole kg.
**Output**: A list of lists describing the stacks of boxes. This must use the fewest number of stacks possible for the input. To be a valid stack, the weight of each box in the stack must be greater than or equal to the sum of the weight of all boxes above it.
### Examples of Valid stacks
(In bottom to top order)
* [3]
* [1, 1]
* [3, 2, 1]
* [4, 2, 1, 1]
* [27, 17, 6, 3, 1]
* [33, 32, 1]
* [999, 888, 99, 11, 1]
### Examples of Invalid stacks
(In order from bottom to top)
* [1, 2]
* [3, 3, 3]
* [5, 5, 1]
* [999, 888, 777]
* [4, 3, 2]
* [4321, 3000, 1234, 321]
## Example Test Cases
### 1
```
IN: [1, 2, 3, 4, 5, 6, 9, 12]
OUT: [[12, 6, 3, 2, 1], [9, 5, 4]]
```
### 2
```
IN: [87, 432, 9999, 1234, 3030]
OUT: [[9999, 3030, 1234, 432, 87]]
```
### 3
```
IN: [1, 5, 3, 1, 4, 2, 1, 6, 1, 7, 2, 3]
OUT: [[6, 3, 2, 1], [7, 4, 2, 1], [5, 3, 1, 1]]
```
### 4
```
IN: [8, 5, 8, 8, 1, 2]
OUT: [[8, 8], [8, 5, 2, 1]]
```
## Rules and Assumptions
* Standard I/O rules and banned loopholes apply
* Use any convenient format for I/O
+ Stacks may be described top to bottom or bottom to top, as long as you are consistent.
+ The order of stacks (rather than boxes within those stacks) does not matter.
+ You may also take input boxes as a presorted list. Order is not particularly important for the input, so long as the general problem isn't being solved by the sorting itself.
* If there is more than one optimal configuration of stacks, you may output any one of them
* You may assume that there is at least one box and that all boxes weigh at least 1 kg
* You must support weights up to 9,999 kg, at minimum.
* You must support up to 9,999 total boxes, at minimum.
* Boxes with the same weight are indistinguishable, so there is no need to annotate which box was used where.
Happy golfing! Good luck!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
Œ!ŒṖ€ẎṖÄ>ḊƲ€¬ȦƊƇLÞḢ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMWjkx7unPaoac3DXX1AxuEWu4c7uo5tAgocWnNi2bGuY@0@h@c93LHo/@F2kMoZ//9HW5jrKJgYG@koWAKBjoKhkbGJjoKxgbFBLAA "Jelly – Try It Online")
Obvious -3 thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)...
Top to bottom.
Explanation:
```
Œ!ŒṖ€ẎṖÄ>ḊƲ€¬ȦƊƇLÞḢ Arguments: S (e.g. [1, 2, 3, 4, 5])
Œ! Permutations (e.g. [..., [4, 1, 5, 2, 3], ...])
€ Map link over left argument (e.g. [..., [..., [[4, 1], [5], [2, 3]], ...], ...])
ŒṖ Partitions (e.g. [..., [[4, 1], [5], [2, 3]], ...])
Ẏ Concatenate elements (e.g. [..., ..., [[4, 1], [5], [2, 3]], ..., ...])
Ƈ Filter by link (e.g. [..., [[1, 3], [2], [4], [5]], ...])
Ɗ Create >=3-link monadic chain (e.g. [[1], [], [0]])
€ Map link over left argument (e.g. [[1], [], [0]])
Ʋ Create >=4-link monadic chain (e.g. [1])
Ṗ Remove last element (e.g. [4])
Ä Cumulative sum (e.g. [4])
Ḋ [Get original argument] Remove first element (e.g. [1])
> Greater than (vectorizes) (e.g. [1])
¬ Logical NOT (vectorizes) (e.g. [[0], [], [1]])
Ȧ Check if non-empty and not containing zeroes after flattening (e.g. 0)
Þ Sort by link (e.g. [[[1, 2, 3], [4, 5]], ..., [[5], [4], [3], [2], [1]]])
L Length (e.g. 4)
Ḣ Pop first element (e.g. [[1, 2, 3], [4, 5]])
```
[Answer]
# JavaScript (Node.js), ~~139 122~~ 116 bytes
Expects the input sorted in ascending order.
```
f=(A,s=[],[n,...a]=A,r)=>n?s.some((b,i,[...c])=>n<eval(b.join`+`)?0:f(A,c,a,c[i]=[n,...b]))?S:r?0:f(A,[...s,[]]):S=s
```
[Try it online!](https://tio.run/##bY3NCsIwEITvPkWOCa6hTdRqMRafwWMImMZWKjWRRvr6desfIi5z2vlm5mx7G13XXG8zH47VMNSK7iAqbUB74Jxbo3bQMbX1ReQxXCpKS2hAo@XM@N5UvW1pyc@h8YfpgRVJXmOFAwtON0Y9a0rDWLHPu5c7xiNoY1i@V3FwwcfQVrwNJ1pTnQIRQCSQOZAFkCWQNZBUYMXkh1xlCEkxuhJhmcgEYbw/LLZ@JN4L3yPZ/5B4@KunEBnu "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
A, // A[] = input array
s = [], // s[] = list of stacks, initially empty
[n, // n = next weight to process
...a] = A, // a[] = array of remaining weights
r // r = recursion flag
) => //
n ? // if n is defined:
s.some((b, i, // for each stack b[] at position i in s[],
[...c]) => // using c[] as a copy of s[]:
n < eval(b.join`+`) ? // if n is not heavy enough to support all values in b[]:
0 // abort
: // else:
f( // do a recursive call:
A, c, a, // using A[], c[] and a[]
c[i] = [n, ...b] // with n prepended to c[i]
) // end of recursive call
) ? // end of some(); if successful:
S // return S[]
: // else:
r ? // if this is a recursive call:
0 // do nothing
: // else:
f(A, [...s, []]) // try again with an additional stack
: // else:
S = s // success: save the solution in S[]
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 178 bytes
```
f=lambda b,s=[[]]:(a for i in range(len(s))if b[0]>=sum(s[i])for a in f(b[1:],s[:i]+[[b[0]]+s[i]]+s[i+1:]+[[]]))if b else[s]
g=lambda a:(c:=sorted(f(a),key=len)[0])[:c.index([])]
```
[Try it online!](https://tio.run/##dY7daoQwEIXvfYqB3kwwlNXsjw3YFxlyEddow7pRjIXu09sktqWlu5MwDMz5zpnptryNTlTTvK5dPehr02pouK@JlJKooRtnsGAdzNr1Bgfj0DNmO2hop15r/35FT1axqNNR12FDhVTck7QqJ4o6lUdN6nnY5dF8MwEzeENeZf13uJZ4lrUf58W02KFm/GJudchlwYiRPD9b15oPJMXUOs3WLdjjYP2CXwxVJw57UXJ4CcWhKMWeg9iJgIfK7jIFhwCIAHI4cDgGOJJ/iaD699Sv/c8ByaNKPxpHl@wJHgUfUnCRsss0HFM/bTdtN6yf "Python 3.8 (pre-release) – Try It Online")
Now works on all possible inputs. *(It times out on TIO with more than ten or so boxes, but it calculates a correct answer)*
] |
[Question]
[
You are a railroad entrepreneur in the 19th-century United States when trains become popular because they are the most efficient means of transporting large volumes of materials by land. There is a national need for railroad tracks from the east coast through some recently colonized lands in the west.
To accommodate this need, the U.S. government is going to levy a tax to subsidize railroads. They have promised to pay money to your railroad company for each mile of track laid. Since laying tracks in hilly and mountainous regions is more expensive than laying tracks in flat land, they adjust the amount they give accordingly. That is, the government will pay
* $5,000 per mile of track laid in flat land
* $12,500 per mile of track laid in hilly land
* $20,000 per mile of track laid in mountains.
Of course, this plan does not accurately reflect how much it actually costs to lay tracks.
You have hired some cartographers to draw relief maps of the regions where you will be laying track to analyze the elevation. Here is one such map:
```
S12321
121234
348E96
```
Each digit represents one square mile of land. `S` is the starting point, `E` is the ending point. Each number represents the intensity of the elevation changes in that region.
* Land numbered 1-3 constitutes flat land.
* Land numbered 4-6 constitutes hilly land.
* Land numbered 7-9 constitutes a mountain range.
You have, through years of experience building railroad tracks, assessed that the cost of track building (in dollars) satisfies this formula:
```
Cost_Per_Mile = 5000 + (1500 * (Elevation_Rating - 1))
```
That means building on certain elevation gradients will cost you more money than the government gives, sometimes it will be profitable, and sometimes you will just break even.
For example, a mile of track on an elevation gradient of 3 costs $8,000 to build, but you only get paid $5,000 for it, so you lose $3000. In contrast, building a mile of track on an elevation gradient of 7 costs $14,000, but you get paid $20,000 for it: a $6,000 profit!
Here is an example map, as well as two different possible paths.
```
S29 S#9 S##
134 1#4 1##
28E 2#E 2#E
```
The first track costs $30,000 dollars to construct, but the government pays you $30,000 for it. You make no profit from this track.
On the other hand, the second costs $56,500 to build, but you get paid $62,500 for it. You profit $6,000 from this track.
**Your goal:** given a relief map, find the most profitable (or perhaps merely the least expensive) path from the start to the end. If multiple paths tie, any one of them is an acceptable solution.
# Program Details
You are given text input separated with a rectangular map of numbers and one start and end point. Each number will be an integer inclusively between 1 and 9. Other than that, the input may be provided however you like, within reason.
The output should be in the same format as the input, with the numbers where track has been built replaced by a hash (`#`). Because of arbitrary regulations imposed by some capricious politicians, tracks can only go in horizontal or vertical paths. In other words, you can't backtrack or go diagonally.
The program should be able to solve in a reasonable amount of time (i.e. <10 minutes) for maps up to 6 rows and 6 columns.
This is a **code golf** challenge, so the shortest program wins.
I have an [example (non-golfed) implementation](http://jsbin.com/osugoz/17/edit#preview).
# Sample I/O
```
S12321
121234
348E96
S12321
######
3##E##
S73891
121234
348453
231654
97856E
S#3###
1###3#
3#####
######
#####E
```
[Answer]
## Python, 307 chars
```
import os
I=os.read(0,99)
n=I.find('\n')+1
I='\0'*n+I+'\0'*n
def P(p):
S=[]
for d in(-n,-1,1,n):
y=p[-1]+d
if'E'==I[y]:S+=[(sum((int(I[v])-1)/3*75-15*int(I[v])+15for v in p[1:]),p)]
if'0'<I[y]<':'and y not in p:S+=P(p+[y])
return S
for i in max(P([I.find('S')]))[1][1:]:I=I[:i]+'#'+I[i+1:]
print I,
```
`P` takes a partial path `p` and returns all ways of extending it to reach `E`. Each returned path is paired with its score so `max` can find the best one.
Takes about 80 seconds on a 6x6 map.
[Answer]
## Python: 529 482 460 bytes
My solution will not win any prizes. However, since there are only two solutions posted and I found the problem interesting, I decided to post my answer anyway.
**Edit:** Thanks to Howard for his recommendations. I've managed to shave a lot of my score!
```
import sys
N=len
def S(m,c,p=0):
if m[c]=='E':return m,p
if m[c]<'S':
b=list(m);b[c]='#';m=''.join(b)
b=[],-float('inf')
for z in(1,-1,w,-w):
n=c+z
if 0<=n<N(m)and m[n]not in('S','#')and(-2<z<2)^(n/w!=c/w):
r=S(m,n,p+(0if m[n]=='E'else(int(m[n])-1)/3*5-int(m[n])+1))
if b[1]<r[1]:b=r
return b
m=''
while 1:
l=sys.stdin.readline().strip()
if l=='':break
w=N(l);m+=l
b,_=S(m,m.index('S'))
for i in range(0,N(b),w):print b[i:i+w]
```
[Answer]
### Ruby, 233 characters
```
R=->s{o=s=~/S/m
s=~/E/m?(q=[-1,1,-N,N].map{|t|s[f=o+t]>'0'?(n=s*1
n[o]='#'
n[f]='S'
a=R[n]
a&&[a[0]-(e=s[f].to_i-1)/3*5+e,a[1]]):nil}-[nil]
q.sort!&&q[0]):[0,(n=s*1;n[o]='E'
n[$_=~/S/m]='S'
n)]}
N=1+(gets(nil)=~/$/)
$><<R[$_+$/*N][1]
```
A Ruby brute-force approach which runs well inside the time constraints on a 6x6 board. The input must be given on STDIN.
*Examples:*
```
S12321
121234
348E96
S#2321
1#####
3##E##
--
S73891
121234
348453
231654
97856E
S#####
1212##
#####3
#3####
#####E
```
] |
[Question]
[
There is a nice way to perform long multiplication for two integers without having to do anything but counting, which occasional gets shared around the internet. You write the digits of each number as a bunch of slanted lines, with the two numbers at a 90 degree angle. Then you can simply count the intersections in the separate columns that arise. A diagram will probably clarify this. Here is an example for calculating `21 * 32`:

If you google for "visual/graphical long multiplication" you'll find a lot more examples.
In this challenge, you are to generate these diagrams using ASCII art. For the same example, the output would look like this:
```
\ /
X /
\ / X /
\ X / X
X X / \ /
/ X X X /
/ X \ / X
/ \ X / \
X X
/ X \
/ \
```
It's probably easiest to figure out the construction rules for these from some examples (see below), but here some details:
* Intersecting segments are `X`, non-intersecting segments of the lines are `/` or `\`.
* There should be exactly one segment after the outermost intersections.
* There should be exactly one segment between intersections belonging to different digits. If there are zero-digits, these will result in consecutive `/` or `\` segments.
* You have to support any positive input (at least up to some reasonable limit like 216 or 232), and any digits from `0` to `9`. However, you may assume that there neither leading nor trailing `0`s.
* You must not print extraneous leading whitespace or leading or trailing empty lines.
* You may print trailing whitespace but it must not exceed the diagram's axis-aligned bounding box.
* You may optionally print a single trailing newline.
* You may choose in which order you take the two input numbers. However, it you must support arbitrary numbers for either orientation, so you can't choose something like "The larger number is given first".
* If you're taking input as a string, you can use any non-digit separator between the two numbers.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
This is code golf, the shortest answer (in bytes) wins.
## Examples
```
1*1
\ /
X
/ \
2*61
\ /
\ X /
X X /
/ X X /
/ X X /
/ X X /
/ X X
/ X \ /
/ \ X
X \
/ \
45*1
\ /
\ X
\ X \
\ X \
\ X \
X \
\ / \
\ X
\ X \
\ X \
X \
/ \
21001*209
\ /
X /
/ X
/ / \
\ / / \ /
X / X /
\ / X / X /
\ X / \ / / X /
X X \ / / / X /
/ X \ X / / / X /
/ \ \ / X / / / X /
\ X / X / / / X /
X X / X / / / X /
/ X X / X / / / X
/ X X / X / / / \
/ X X / X / /
/ X X / X /
/ X X / X
/ X X / \
/ X X
/ X \
/ \
```
[Answer]
## python, 303
```
def f(s):
a,b=s.split('*')
a,b=map(lambda l:reduce(lambda x,y:x+[1]*int(y)+[0],l,[0]),[reversed(a),b])
n=sum(map(len,[a,b]))
l=[[' ']*n for i in xrange(n)]
for i,x in enumerate(a):
for j,y in enumerate(b):
l[i+j][j-i+len(a)]=r' \/x'[x+2*y]
return '\n'.join(''.join(x[2:-1]) for x in l[1:-2])
```
I think it's enough human-readable.
Verification:
```
print '---'
print '\n'.join('"%s"'%x for x in f('21001*209').split('\n'))
print '---'
---
" \ / "
" x / "
" / x "
" / / \ "
" \ / / \ / "
" x / x / "
" \ / x / x / "
"\ x / \ / / x / "
" x x \ / / / x / "
"/ x \ x / / / x / "
" / \ \ / x / / / x / "
" \ x / x / / / x / "
" x x / x / / / x /"
" / x x / x / / / x "
" / x x / x / / / \"
" / x x / x / / "
" / x x / x / "
" / x x / x "
" / x x / \ "
" / x x "
" / x \ "
" / \ "
---
```
[Answer]
# Python 3, 205 bytes
```
L=a,b=[eval("+[0]+[1]*".join("0%s0"%x)[2:])for x in input().split()]
A,B=map(len,L)
for c in range(2,A+B-1):print((" "*abs(c-A)+" ".join(" \/X"[a[i-c]+2*b[i]]for i in range(max(0,c-A),min(c,B))))[1:A+B-2])
```
The expressions are quite long so I think there's a fair amount of room for improvement, but anyway...
Takes input space-separated via STDIN, e.g.
```
21 32
\ /
X /
\ / X /
\ X / X
X X / \ /
/ X X X /
/ X \ / X
/ \ X / \
X X
/ X \
/ \
```
There's a possible trailing space on some lines, but the `A+B-2` ensures that all of the trailing spaces are within the bounding box.
[Answer]
# Pyth - 79 bytes
A translation of @AlexeyBurdin's answer. Can probably be golfed a lot more.
```
AzHmu++Gm1sH]Zd]Z,_zwK+lzlHJmm\ KK .e.eX@J+kY+-Yklz@" \/x"+byZHzjbmjk:d2_1:J1_2
```
Takes input as two numbers, newline separated. Explanation coming soon.
[Try it online here](http://pyth.herokuapp.com/?code=AzHmu%2B%2BGm1sH%5DZd%5DZ%2C_zwK%2BlzlHJmm%5C+KK+.e.eX%40J%2BkY%2B-Yklz%40%22+%5C%2Fx%22%2BbyZHzjbmjk%3Ad2_1%3AJ1_2&input=21001%0A209&debug=1).
[Answer]
# C#, 451 bytes
```
void d(string s){var S=s.Split('*');int X=S[1].Select(c=>c-47).Sum(),Y=S[0].Select(c=>c-47).Sum(),L=9*(X+Y),A=1,B=L/3,i,j;var a=Range(0,L).Select(_=>new int[L]).ToArray();foreach(var c in S[1]){for(i=48;i<c;++i){for(j=-1;j<Y;++j)a[B-j][A+j]=1;A++;B++;}A++;B++;}A=1;B=L/3;foreach(var c in S[0]){for(i=48;i<c;++i){for(j=-1;j<X;++j)a[B+j][A+j]|=2;A++;B--;}A++;B--;}Write(Join("\n",a.Select(r=>Concat(r.Select(n=>@" /\X"[n]))).Where(r=>r.Trim().Any())));}
```
Formatted for readability, the function in context:
```
using System.Linq;
using static System.Console;
using static System.Linq.Enumerable;
using static System.String;
class VisualMultiply
{
static void Main(string[] args)
{
new VisualMultiply().d("21001*209");
WriteLine();
}
void d(string s)
{
var S = s.Split('*');
int X = S[1].Select(c => c - 47).Sum(),
Y = S[0].Select(c => c - 47).Sum(),
L = 9 * (X + Y),
A = 1,
B = L / 3,
i,
j;
var a = Range(0, L).Select(_ => new int[L]).ToArray();
foreach (var c in S[1])
{
for (i = 48; i < c; ++i)
{
for (j = -1; j < Y; ++j)
a[B - j][A + j] = 1;
A++;
B++;
}
A++;
B++;
}
A = 1;
B = L / 3;
foreach (var c in S[0])
{
for (i = 48; i < c; ++i)
{
for (j = -1; j < X; ++j)
a[B + j][A + j] |= 2;
A++;
B--;
}
A++;
B--;
}
Write(Join("\n", a.Select(r => Concat(r.Select(n => @" /\X"[n]))).Where(r => r.Trim().Any())));
}
}
```
The bitwise OR was just for fun, but addition would work too.
[Answer]
# JavaScript (*ES6*) 271
I'm sure that there is a solution that builds the output row by row, fiddling with math and x,y coordinates (x+y==k, x-y==k ...). But I still can't nail it.
So here is a solution that simply draws the lines one by one.
Run the snippet in Firefox to test.
```
F=(a,b)=>( // string parameters
t=u=0,[for(v of a)t-=~v],[for(v of b)u-=~v],
r=t+u,o=[...' '.repeat(r*r-r)],
L=(x,y,n,z,m,c)=>{
for(i=0;d=n[i++];)
for(j=0;++x,y+=z,j++<d;)
for(l=m+1,p=x+y*r-1-r;l--;p+=r-z,o[p-p%r-1]='\n')
o[p]=o[p]>' '&&o[p]!=c?'X':c
},
L(u,0,a,1,u,'/'),
L(0,u,b,-1,t,'\\'),
o.join('')
)
// TEST
function test()
{
O.innerHTML= F(A.value, B.value);
}
test();
```
```
<input id=A value=21001> * <input id=B value=209> <button onclick='test()'>-></button>
<pre id=O></pre>
```
[Answer]
## VC++ ~~(289)~~280
```
t(char*a){int i,j,k,r,c=1,e,A=0,B=0,*C,G[99],f,u;for(C=&A;c+48|(k=(c=(*(a+=c<1))---48)>0);G[2**(C=!(c+6)?&(B+=A):&(++*C))]=k**C);for(i=0;i<B*B;printf("\n%c"+!!j,32+15*((k=(c<(f=G[(c=i/B)+(j=i%B)+A+2]))*(j<f)*(f>A))+4*(r=(!!e*B>c+(e=G[A+j-c]))*(!!e*c>A-e-2)*(e<A)))+13*k*r),i++);
```
## Usage
```
#include <stdio.h>
#include <conio.h>
int t(char*);
int main(void)
{ char a[]="123*45";
t((char*)a);
getch();
return 0;
}
int
//-------- padded code ------
t(char*a){int i,j,k,r,c=1,e,A=0,B=0,*C,G[99],f,u;memset(G,0,396);for(C=&A;c+48|(k=(c=(*(a+=c<1))---48)>0);G[2**(C=!(c+6)?&(B+=A):&(++*C))]=k**C);for(i=0;i<B*B;printf("\n%c"+!!j,32+15*((k=(c<(f=G[(c=i/B)+(j=i%B)+A+2]))*(j<f)*(f>A))+4*(r=(!!e*B>c+(e=G[A+j-c]))*(!!e*c>A-e-2)*(e<A)))+13*k*r),i++);
//---------------------------
return 0;}
```
## Results
```
\ /
\ x /
\ x x /
x x x /
\ / x x x
\ x / x x \ /
x x / x \ x /
\ / x x / \ x x /
x / x x x x x /
/ x / x \ / x x x /
/ x / \ x / x x x
/ x x x / x x \
/ \ / x x / x \
x / x x / \
/ x / x x
/ x / x \
/ x / \
/ x
/ \
```
>
> * the function iterates one single loop , and use some geometricks and ascii trifling.
>
>
>
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 41 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
(A┬{[1}0}┐)
⁷L├X⁷lYø;{³×?³y³-╵x\╋
⁸⤢↔╶╶⁸n
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjA4JXVGRjIxJXUyNTJDJXVGRjVCJXVGRjNCJXVGRjExJXVGRjVEJXVGRjEwJXVGRjVEJXUyNTEwJXVGRjA5JTBBJXUyMDc3JXVGRjJDJXUyNTFDJXVGRjM4JXUyMDc3JXVGRjRDJXVGRjM5JUY4JXVGRjFCJXVGRjVCJUIzJUQ3JXVGRjFGJUIzJXVGRjU5JUIzJXVGRjBEJXUyNTc1JXVGRjU4JXVGRjNDJXUyNTRCJTBBJXUyMDc4JXUyOTIyJXUyMTk0JXUyNTc2JXUyNTc2JXUyMDc4JXVGRjRF,i=MjEwMDElMEEyMDk_,v=8)
[Answer]
## C (329 b)
```
int f(char*a){int i,j,r,k,c,h,o,e=15,m=99,A=0,B=0,*C,L[m][m],G[m],*g=G;for(C=&A;(c=*a-48)+48;C=!(c+6)?&B:&(*C+=(*g++=c+1)),a++);for(i=B-1,j=0;j<(r=A+B-1);i--,j++)for(k=0,o=4*!!((*(g-=!*g))---1);k<=*(C=(h=i<0)?&B:&A);k++)L[abs(i)+k][j+k-2*k*h]+=o/(3*h+1)*e;for(i=0;i<r*r;i++)printf("\n%c"+!!(i%r),((h=L[i/r][i%r])>e*4)?120:h+32);}
```
## [TRY IT](http://rextester.com/GNQ94710)
[Answer]
# [R](https://www.r-project.org/), 294 bytes
```
d=do.call;r=outer;m=d(r,c(Map(function(y,w)d(c,c(lapply(y%/%10^rev(0:log10(y))%%10,function(z)c(0,rep(w,z))),0)),scan(),1:2),`+`))+1;p=matrix(" ",u<-sum(dim(m)),u);p[d(r,c(lapply(dim(m),seq),function(a,b)nrow(m)-a+b+u*(a+b-2)))]=c(" ","\\","/","X")[m];cat(apply(p,1,paste,collapse=""),sep="\n")
```
[Try it online!](https://tio.run/##RY7RTsMwDEV/ZYo0yaYuS7rxspJP4B1pHVqWBlQpaULaULqfL4EieLAt3Wvf47gsrWz9vVbW1lH6NJpYO9lCJA1PKsBr6vXY@R5mmrAFnWWrQrAzzNvdVvCXaD6AH61/ExxmxG3W6O/ohho4RRNgohsiEs81aNUDkjhWSJfigliIOkinxth9AtswSo/lkBy0nQOX9xPW4bR@9IteHRrMO/6zFF2xj37KTqmKa5HuII@yytiz1D/BrGly2@V6Znhy51qrEdbIQIKCGkZD2tuMGYxk7BsRJGt6houo9puHA98vXw "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 58 bytes
```
ŒDṙLN‘ƊṚị“\/X ”K€
L‘0xż1xⱮ$F
DÇ€Ḥ2¦+þ/µZJUṖ;J’⁶xⱮżÑṖḊẎḊ$€Y
```
[Try it online!](https://tio.run/##y0rNyan8///oJJeHO2f6@D1qmHGs6@HOWQ93dz9qmBOjH6HwqGGu96OmNVw@QCmDiqN7DCsebVyn4sblcrgdKPxwxxKjQ8u0D@/TP7Q1yiv04c5p1l6PGmY@atwGUnZ0z@GJQKGHO7oe7uoDkipAHZEgyx7unPHfyMJYx9TEEgA "Jelly – Try It Online")
### Explanation
A full program that takes the two numbers as a list of two integers and returns a string.
Helper link 1: rotate the matrix
```
ŒD | get the diagonals
ṙ | rotate left by
LN‘Ɗ | minus num columns +1
Ṛ | reverse order
ị“\/X ” | index into \/X
K€ | join each with spaces
```
Helper link 2: generate the row and column templates
```
L‘0x | 0 copied (num digits + 1) times
ż | interleaved with
1xⱮ$ | 1 copied as specified by the digits
F | flattened
```
Main link
```
D | convert to decimal digits
Ç€ | call above link for each number
Ḥ2¦ | double the second one
+þ/ | outer product using +
µ | start a new monadic chain
ZJUṖ;J’ | reversed range counting down
| the columns, followed by range
counting up the rows (without
duplicating 0 in the middle)
⁶xⱮ | that many spaces (to provide indents)
ż | interleaved with
Ñ | rotated matrix
ṖḊẎḊ$€ Y | remove blank rows and columns and join with newlines
```
] |
[Question]
[
Write a program or function that takes two inputs:
1. A text message
2. The dictionary of English language, as it appears in [this](https://raw.githubusercontent.com/kevina/wordlist/master/alt12dicts/2of4brif.txt) Github file (containing about 60000 words)
and outputs the number of spelling errors in the message (see below for definition and test cases).
You can receive the dictionary as a parameter to your function, as a pre-defined file that your program expects to find, as hard-coded data in your code, or in any other sensible manner.
---
Your code should itself look like a text message, with a minimal number of spelling errors. So, you will calculate the **score** of your code by feeding it to itself as input.
The winner is code that has the lowest score (minimal possible score is 0). If there are several answers with the same score, the winner is decided by code size (in characters). If two answers are still tied, the winner is the earlier one.
---
If required, you can assume the input message to be ASCII (bytes 32...126) with newlines encoded in a conventional manner (1 byte "10" or 2 bytes "13 10"), and non-empty. However, if your code has non-ASCII characters, it should also support non-ASCII input (so it can calculate its own score).
Characters are subdivided into the following classes:
* *Letters* a...z and A...Z
* *Whitespace* (defined here as either the space character or the newline character)
* *Punctuation* `.` `,` `;` `:` `!` `?`
+ *Sentence-ending* `.` `!` `?`
* *Garbage* (all the rest)
A *word* is defined as a sequence of letters, which is maximal (i.e. neither preceded nor followed by a letter).
A *sentence* is defined as a maximal sequence of characters that are not sentence-ending.
A character is a *spelling error* if it violates any of the spelling rules:
1. A letter must belong to a dictionary word (or, in other words: each word of length N that doesn't appear in the dictionary counts as N spelling errors)
2. The first character in a sentence, ignoring any initial whitespace characters, must be an uppercase letter
3. All letters must be lowercase, except those specified by the previous rule
4. A punctuation character is only allowed after a letter or garbage
5. A newline character is only allowed after a sentence-ending character
6. Whitespace characters are not allowed in the beginning of the message and after whitespace characters
7. There should be no garbage (or, in other words: each garbage character counts is a spelling error)
In addition, the last sentence must be either empty or consist of exactly one newline character (i.e. the message should end with a sentence-ending character and an optional newline - let's call it rule 8).
Test cases (below each character is a rule that it violates; after `=>` is the required answer):
```
Here is my 1st test case!!
711 4 => 4
main(){puts("Hello World!");}
2 777 883 3 77 78 => 12
This message starts with two spaces
66 8 => 3
What ? No apostrophe's??
4 71 4 => 4
Extra whitespace is BAD!
66 661111111111 66 66333 => 21
Several
lines?
Must be used only to separate sentences.
=> 1 (first linebreak is en error: rule 5)
"Come here," he said.
73 7 => 3 (sentence starts with '"', not 'C')
```
[Answer]
# [Perl 6](http://perl6.org/), 134 spelling errors
```
my token punctuation {<[.,;:!?]>}
my \text = slurp; my \mistakes=[]; for split /\.|\!|\?/, text { for .trim.match: :g, /<:letter>+/ -> \word { (append mistakes, .comb when none words slurp pi given lc word) or (push mistakes, $_ if ((.from or word.from) xor m/<[a..z]>/) for word.match: :g, /./) }}
append mistakes, comb / <after \s | <punctuation>> <punctuation> | <!before <punctuation> | <:letter> | \s> . | <!after \.|\!|\?> \n | [<before ^> | <after \s>] \s /, text; say mistakes.Numeric
```
With extra whitespace for readability:
```
my token punctuation {<[.,;:!?]>}
my \text = slurp;
my \mistakes=[];
for split /\.|\!|\?/, text {
for .trim.match: :g, /<:letter>+/ -> \word {
(append mistakes, .comb when none words slurp pi given lc word)
or
(push mistakes, $_ if ((.from or word.from) xor m/<[a..z]>/) for word.match: :g, /./)
}
}
append mistakes, comb /
<after \s | <punctuation>> <punctuation>
| <!before <punctuation> | <:letter> | \s> .
| <!after \.|\!|\?> \n
| [<before ^> | <after \s>] \s
/, text;
say mistakes.Numeric
```
Notes:
* Expects the dictionary in a file called `3.14159265358979` in the current working directory.
* The only inspired part is the line
`append mistakes, .comb when none words slurp pi given lc word`,
the rest is pretty bad. But maybe it can at least serve as a baseline for better solutions... :)
[Answer]
# [Python 3](https://docs.python.org/3/), 287 spelling errors
```
import re
def function(message):file = open("dictionary", "r");dictionary = file.read().split();words = re.findall("[a-zA-Z]+", message);sentences = re.findall("[^.!?]+", message);return sum(len(word) if word.lower() not in dictionary else 0 for word in words)+sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)+sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)+len(re.findall("[\s.,;:!?][.,;:!?]", message))+len(re.findall("[^.!?]\n", message))+len(re.findall("^\s", message))+len(re.findall("\s\s", message))+len(re.findall("[^a-zA-Z\s.,;:!?]", message))+int(not sentences[-1] and count(sentences[-1], '\n') != 1)
```
[Try it online!](https://tio.run/##hZLRaoMwGIXv9xR/vWlC21DZXaWMvcbUQtDfNRCTkERK9/IuSVenrHRXSs7HOSdHzdWftXodR9EbbT1YfGmxg25QjRdakR6d459ID52QCEfQBhXJWpFUbq/ZFjKb0eL3JECRZRZ5SyhzRgpPaHHRtnVBs8g6oVouJclKvvt6333Um@ByDyocKo@qwT/wia3elqhFP1gFbuiJDLViBAXRQXxhUl/QEgpKexAKZgVROoQ9dNomMqqpHd1Epzw63Esw560whJb7mgnHpTnzYMlVm2wfU4MxKXgWcwdj1HS/W9wU2Zy55Y1H@9hikuceU3B@qOmzpDjPYszKsW1xCIOWP8/Zrg/wtH2lnkKnyj3VK/cPUJ5u/8PUbUEL5cl8dFfu8jp9ikYPQVucb2FdqTWF1RFyOo7f "Python 3 – Try It Online")
Definitely not the best, but I gave it a solid shot, I think!
Here it is in an actually readable format. Assumes there is a file called "dictionary" (no extension) in the cwd.
```
import re
def function(message):
file = open("dictionary", "r")
dictionary = file.read().split()
words = re.findall("[a-zA-Z]+", message)
sentences = re.findall("[^.!?]+", message)
errors = 0
errors += sum(len(word) if word.lower() not in dictionary else 0 for word in words)
errors += sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)
errors += sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)
errors += len(re.findall("[\s.,;:!?][.,;:!?]", message))
errors += len(re.findall("[^.!?]\n", message))
errors += len(re.findall("^\s", message))
errors += len(re.findall("\s\s", message))
errors += len(re.findall("[^a-zA-Z\s.,;:!?]", message))
errors += int(not sentences[-1] and count(sentences[-1], '\n') != 1)
return errors
```
[Answer]
# Python, 32 spelling errors
```
import re;be = open('be').read().split();exec(''.join(chr(be.index(it)) for it in 'aboriginal abominable aborting aborting abolishing abominate abominable abbreviated abetting abbreviated abominates aboriginals aborigines abortionist abortion abdicating abdication abets abortions aborigine aborted abolitionists aborting abbreviated abetting abbreviated aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolishing abdominal abound abhorrent abdominal abnormally abodes abdomen abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abets aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abbreviated abetting abbreviated aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abduct abbreviates abhorred abodes abdomen abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abets aborigines aborted abominates aboriginals abortion abdicating aborting abortionist aboriginal abdicating abominations abominable aboriginals abdicating abortions aborigine aborted abolitionists abdication abbreviated abominates abominably abbreviated abortions aborigine aborted abolitionists abduct abominations aborigine abortions abominable aborted abdicating abdication abbreviated aboriginals aborigine abortion abbreviated abominates aboriginals abbreviated abolition abominable abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated abortions aborigine aborted abolitionists abbreviated abominates aboriginals abbreviated abortions aborigine aborted abolitionists aborting abdication abdomen aborting abortionist aboriginal abdicating abduction abbreviated abominates abominably abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abducting abodes abduct abominates aborting abolishing abominations aborigines abominated abolishing abdicating abdication abbreviated abolishing aboriginals abolitionists abbreviated aboriginals aborigine abortion abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abducting abodes abduct abominates aborting abortionist aborigines aborigines abominable aborted abdicating abdication abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abdication abdomen aborting abortionist aboriginal abdicating aborting abortionist aboriginal abdicating abduction abbreviated abominates abominably abbreviated abolitionist abominated abolishing aborted abolishing abolitionist abortion abominable aborted abduct abominates aborting abortionist aborigines aborigines abominable aborted abdicating abdication abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated abolitionist abominated abolishing aborted abolishing abolitionist abortion abominable aborted abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abduction abet abodes abdication abbreviated abominably aborigine aborted abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abode aborting abduct abdomens abets abet abbreviates abhorred abodes aboard abduct abdomens abets abet abbreviates abhorred abodes abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abduct abbreviates abhorred abodes abode aboriginals abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating abolish abode aborting abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating abode aborting abode aborting abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abolishing abdominal abound abhorrent abdominal abnormally abode aborting abduct abdomens abets abet abbreviates abhorred abodes abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominates aboriginals abortion abdicating aboriginals aborigine abortion abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting aboard abdominal abduction abodes abbreviated abolishing aboriginals abolitionists abbreviated abolitionist aborigine abortionist aboriginals abortion abdicating aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting aboard abdominal abduction abodes abdomens abbreviated abdicates abode aboriginals abdicates abdication abbreviated abbreviates abetting abbreviated abduction abdication abdication'.split()))
```
Takes in input from standard in and outputs to standard out. This requires a dictionary in a file called `be` the same directory as the code.
I took [the Python answer from GotCubes](https://codegolf.stackexchange.com/a/252865/113573) and encoded each character as an index into the dictionary, interpreted as an ASCII code point.
Here's the code that I used to generate my code:
```
be=open("be").read().split()
code="""message = input();words = re.findall("[a-zA-Z]+", message);sentences = re.findall("[^.!?]+", message);print(sum(len(word) if word.lower() not in be else 0 for word in words)+sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)+sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)+len(re.findall("[\s.,;:!?][.,;:!?]", message))+len(re.findall("[^.!?]\\n", message))+len(re.findall("^\s", message))+len(re.findall("\s\s", message))+len(re.findall("[^a-zA-Z\s.,;:!?]", message))+int(not sentences[-1] and count(sentences[-1], '\\n') != 1))"""
words=" ".join(be[ord(c)] for c in code)
print(f"""import re;be=open('be').read().split();exec(''.join(chr(be.index(it))for it in '{words}'.split()))""")
```
*You can definitely lower the score even more, but I will try that when it's not past midnight in my time zone.*
] |
[Question]
[
This challenge is a tribute to our Legendary Challenge Writer™,
[Calvin's Hobbies](https://codegolf.stackexchange.com/users/26997/calvins-hobbies) — now renamed to [Helka Homba](https://codegolf.stackexchange.com/users/26997/calvins-hobbies) —, in the same spirit as
[Generate Dennis Numbers](https://codegolf.stackexchange.com/q/57719/3808).
Calvin is a pretty impressive contributor to PPCG, with the 6th most reputation
overall and probably indisputibly the best challenge writing skills out of all
of us. However, of course, for this challenge, we will focus on his user ID.
26997 might not look very interesting at first. In fact, it's *almost*
interesting in a few ways. For example, here's a chart of `26997 mod <n>` for
certain values of `n`:
```
n | 26997 % n
----+-----------
3 | 0
4 | 1
5 | 2
6 | 3
7 | 5 :(
8 | 5
9 | 6
10 | 7
```
However, 26997 is one of the few numbers that can be represented by `(n * 10)n - n`, where `n` is an integer > 0.
Here are the first few numbers which can be expressed in this way, which we
will henceforth call *Calvin Numbers*:
```
9
398
26997
2559996
312499995
46655999994
8235429999993
1677721599999992
387420488999999991
99999999999999999990
28531167061099999999989
8916100448255999999999988
3028751065922529999999999987
1111200682555801599999999999986
437893890380859374999999999999985
184467440737095516159999999999999984
82724026188633676417699999999999999983
39346408075296537575423999999999999999982
19784196556603135891239789999999999999999981
10485759999999999999999999999999999999999999980
```
These *Calvin Numbers* have some interesting properties. More patterns emerge
when we right-align them and highlight all the `9`s:
[](https://i.stack.imgur.com/dcuHR.png)
The ones that we're interested in for this challenge are:
* Regardless of `n`, every *Calvin Number* ends with
`10n - n`.
So, Calvin(1) ends with `9`, Calvin(2) ends with `98`, and the pattern
continues `997`, `9996`, `99995`, etc., with each successive *Calvin
Number* counting down and adding an extra `9` to the beginning.
* For values of `n` where `n % 10 == 0` (i.e. `n` is divisble by 10), Calvin(n)
ends with `102n - n`.
That is, the pattern extends for twice as many digits as normal, with an
extra number of `9`s at the beginning equal to `n`.
* When `n` is a power of `10` (`10`, `100`, `1000`, etc.), the pattern extends
even further—every single digit is either a `9` or a `0`.
This pattern is the following:
`(n + 1) * 10n - n`
nines, and
`n` zeroes. This is easier to understand in a chart (your solution will
only have to handle numbers up to 10000 anyway, so this is all you need):
```
n | Calvin(n)
-------+-----------------------
10 | 19 nines, 1 zero
100 | 298 nines, 2 zeroes
1000 | 3997 nines, 3 zeroes
10000 | 49998 nines, 4 zeroes
```
The number of nines even exhibits several properties of *Calvin Numbers*
itself, but that's too much detail for this challenge.
## Challenge
*Calvin Numbers* get far too big, far too quickly, for a "get the nth *Calvin
Number* challenge to be feasible in languages without arbitrary-precision
integers. Therefore, the challenge is to determine whether a number fits the
above patterns—that is, whether a number is a "candidate Calvin Number" or not.
Here are the criteria for a number to be considered a *candidate Calvin Number*
(hereafter referred to as a CCN for short):
* It ends with a number that fits the pattern
`10n - n` for an integer `n`.
So, to be a CCN, a number must end with 9, or 98, or 997, 9996, 99995, etc.
* If the last digit is `0`, it must also end with
`102n - n`, for the same `n` as in the
previous point.
This means that `12312312399999999999999999999999999999999999980` is not a
CCN, but `10485759999999999999999999999999999999999999980` is (it's the
correct one, in fact).
* If the value of `n` in the previous two steps is a power of 10, the entire
number must fit the third pattern described above.
## Input / Output
The input will be provided as a string, and it will always represent a number
that is less than `Calvin(10000) + 10000` (which can also be expressed as
`1050000`). (To clarify, the greatest possible input is
50000 nines, and the least possible input is `1`.)
The output should be a truthy value if the input represents a number which is a
CCN, and a falsy value otherwise. For the [definitions of these terms, see
meta](http://meta.codegolf.stackexchange.com/q/2190/3808).
## Test cases
Inputs that should result in a truthy value:
```
9
26997
99999999999999999990
437893890380859374999999999999985
10485759999999999999999999999999999999999999980
999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999900
259232147948794494594485446818048254863271026096382337884099237269509380022108148908589797968903058274437782549758243999867043174477180579595714249308002763427793979644775390624999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999850
1027092382693614216458468213549848274267264533712122209400214436472662418869004625362768700557725707157332451380426829473630485959339004149867738722096608953864534215649211386152032635755501464142277508289403434891444020975243742942368836579910208098242623061684967794815600266752580663281483595687307649904776800899000484103534573979334062832465904049046104660220505973505050538180250643437654409375728443182380726453925959886901573523090619465866810938078629561306599174923972607310649219442207992951278588892681161967770532314854195892941913447519131828356181219857012229150315613569162930098836696593474888020746503116685472977764615483225628639443918309216648893055765917642528801571387940219884056021782642758517893124803355573565644666880920219871370649806723296262307899148031362558110611562055614190049332906933360406981359187305353360484377948591528385990255894034369523166777375785900198782250651053530165824984161319460372145229568890321167955690544235365954748429659526071133879976348254667755220636244075595290123987745560038255541751251200827018722242010925729483977388235141539109139120069464709993781356334885359200734157439642935779132120725231008699003342908280056975158266782782304550273268246184659474285971272532354920744956064671379745219778013465792544241259691493098443741845166419905920702654683993902052727208789915748213660571390107102976665776293366616518962323688316843422737162297255648351087284877987537325761187239807598009767936409247247417410607537333841650998421607775989879490006136112078031237742552602618996017404602674987181629319060214150458746352191115606789019875790921190573561400752476956787515392210098071407806221412149732955903681690377998882038499470092453400748916257640501488510563314141992573250882286817352407459053866180642034662845694338400386823496563185664221362457851894843439705365082614359220653285052800751906334000698723288454227654466240011140570190301931122357632719033275258503935182047714841766010764632214069382579660602964184231995352310981811428980530707871661256260926759509418970021224649566130995825802676411575264295689037775857674060557127369881379685432291930869072749065675720647595081516460449973211035071920099349836074945813885239767788449030051892470053308048906746273036871919251738920141071153777908913021898541658119513188402271468288293408246833819954990709460114510017598873554406350044072275643892449218394225569069468466660333869360644718801813500285081977089623921689922204185138003164149106921903053243405307546841149889662566529697217181329051855403329741409045760789280950603184354320839342588593832348459938736210265795978675460906504449491132656307256451707333439200130425932724262464823848348296787445624028385464112471408499986690593095395244034885421580844176161027627954578726208600199909963055422192706751708210693468639072881081717288837393188012794669089175022406897622823484220002211676520484520241135615999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999028
```
Inputs that should result in a falsy value:
```
1
26897
79999999999999999990
437893890380859374299999999999985
12312312399999999999999999999999999999999999980
999998999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999900
259232147948794494594485446818048254863271026096382337884099237269509380022108148908589797968903058274437782549758243999867043174477180579595714249308002763427793979644775390624999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999911111
1027092382693614216458468213549848274267264533712122209400214436472662418869004625362768700557725707157332451380426829473630485959339004149867738722096608953864534215649211386152032635755501464142277508289403434891444020975243742942368836579910208098242623061684967794815600266752580663281483595687307649904776800899000484103534573979334062832465904049046104660220505973505050538180250643437654409375728443182380726453925959886901573523090619465866810938078629561306599174923972607310649219442207992951278588892681161967770532314854195892941913447519131828356181219857012229150315613569162930098836696593474888020746503116685472977764615483225628639443918309216648893055765917642528801571387940219884056021782642758517893124803355573565644666880920219871370649806723296262307899148031362558110611562055614190049332906933360406981359187305353360484377948591528385990255894034369523166777375785900198782250651053530165824984161319460372145229568890321167955690544235365954748429659526071133879976348254667755220636244075595290123987745560038255541751251200827018722242010925729483977388235141539109139120069464709993781356334885359200734157439642935779132120725231008699003342908280056975158266782782304550273268246184659474285971272532354920744956064671379745219778013465792544241259691493098443741845166419905920702654683993902052727208789915748213660571390107102976665776293366616518962323688316843422737162297255648351087284877987537325761187239807598009767936409247247417410607537333841650998421607775989879490006136112078031237742552602618996017404602674987181629319060214150458746352191115606789019875790921190573561400752476956787515392210098071407806221412149732955903681690377998882038499470092453400748916257640501488510563314141992573250882286817352407459053866180642034662845694338400386823496563185664221362457851894843439705365082614359220653285052800751906334000698723288454227654466240011140570190301931122357632719033275258503935182047714841766010764632214069382579660602964184231995352310981811428980530707871661256260926759509418970021224649566130995825802676411575264295689037775857674060557127369881379685432291930869072749065675720647595081516460449973211035071920099349836074945813885239767788449030051892470053308048906746273036871919251738920141071153777908913021898541658119513188402271468288293408246833819954990709460114510017598873554406350044072275643892449218394225569069468466660333869360644718801813500285081977089623921689922204185138003164149106921903053243405307546841149889662566529697217181329051855403329741409045760789280950603184354320839342588593832348459938736210265795978675460906504449491132656307256451707333439200130425932724262464823848348296787445624028385464112471408499986690593095395244034885421580844176161027627954578726208600199909963055422192706751708210693468639072881081717288837393188012794669089175022406897622823484220002211676520484520241135615999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999027
```
## Rules
* You may *not*, at any point in your program, handle integers larger than
`18446744073709551615` (`264`), if your language has
support for arbitrary-precision integers (or number types with a high enough
precision to allow storing numbers greater than this).
This is simply to prevent solutions that loop through all possible *Calvin
Numbers* (or all possible values of `10n - n`).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win.
[Answer]
# Racket, 353
```
(require srfi/13)(let([s(~a(read))])(for/or([n(range 1 999)])(and(let*([y(string-length(~a n))])(string-suffix?(string-append(make-string(-(if(=(modulo n 10)0)(* 2 n)n)y)#\9)(~r #:min-width y #:pad-string"0"(-(expt 10 y)n)))s))(let([n(inexact->exact(/(log n)(log 10)))])(or(not(integer? n))(string-prefix?(make-string(-(*(+ 1 n)(expt 10 n))n)#\9)s))))))
```
Accepts a number from stdin, outputs `#t` or `#f`.
**Ungolfed version:**
```
(require srfi/13)
(define (calvin? str)
(for/or ([n (in-range 1 10001)])
(and (10^n-n$? n str)
(or (not (integer? (/ (log n) (log 10))))
(expt-of-ten-check? n str)))))
(define (10^n-n$? n str)
(let* ([div-by-ten? (zero? (modulo n 10))]
[digits (string-length (~a n))]
[nines (- (if div-by-ten? (* 2 n) n) digits)]
[suffix (string-append (make-string nines #\9)
(~r #:min-width digits #:pad-string "0" (- (expt 10 digits) n)))])
(string-suffix? suffix str)))
(define (expt-of-ten-check? n str)
(let* ([n (inexact->exact (/ (log n) (log 10)))]
[nines (- (* (add1 n) (expt 10 n)) n)]
[prefix (make-string nines #\9)])
(string-prefix? prefix str)))
```
I normally don't do code golf, and Racket certainly isn't the most suitable language for it, but nobody had answered yet, so I figured I'd give it a shot. ;)
] |
[Question]
[
Remember those fun pinwheels that you blow on and they spin round and round? Let's code one!
A pinwheel will have the set of characters `\ | / _` drawing its center and arms. One possible pinwheel could look like this:
```
|
|
|_ ___
___|_|
|
|
|
```
But what's a pinwheel that doesn't spin? No fun! We can make it spin by rearranging the symbols:
```
/
\ /
\ /
\/\
\/\
/ \
/ \
/
```
The challenge is to create a program that takes three integers and outputs a pinwheel as specified below. The first of these is the number of arms it has, the second is the length of the pinwheel's arms, and the third is the number of times it will spin one-eighth of a revolution clockwise.
You can assume the following:
* The number of arms will always be 0, 1, 2, 4, or 8.
* All the arms will be equally spaced apart from each other.
* The initial position of the pinwheel will have its center like this:
```
_
|_|
```
* If the number of arms is 1, you may decide which direction the arm points.
* If the number of arms is 2, you may decide to make the arms point vertically or horizontally.
You can write a full program that takes input through STDIN or command-line argument, or a function that takes input through function arguments. Your program must show a sequence of outputs that shows the pinwheel spinning, each separated by at least one empty line. The center of the pinwheel should not move by more than one space. You may output as many leading and trailing spaces as necessary.
Here are some examples:
0 2 1
```
_
|_|
/\
\/
```
1 3 2
```
|
|
|_
|_|
/
/
/
/\
\/
_ ___
|_|
```
2 2 0
```
_ __
__|_|
```
8 4 1
```
\ | /
\ | /
\ | /
\|_/____
____|_|
/ |\
/ | \
/ | \
/ | \
| /
\ | /
\ | /
\ |/
____\/\____
\/\
/| \
/ | \
/ | \
/ |
```
This is code golf, so shortest code wins. Good luck!
[Answer]
# Python 2 ~~535 517 473~~ 468 bytes
Saved 5 bytes thanks to @Easterly Ink!
Input expected to be comma separated (i.e., numArms,armLength,numRots)
## Golfed Version
```
n,l,t=input()
b=[7,3,1,5,0,4,2,6][:n]
w=5+2*l
h=w-3
X=w/2
Y=h/2-1
z=range
d=[0,1,1,1,0,-1,-1,-1]
for j in z(t+1):
g=[[' 'for _ in[1]*w]for _ in[1]*h];a=j%2;b=[(k+1)%8for k in b];print''
if a:g[Y][X:X+2]='/\\';g[Y+1][X:X+2]='\\/'
else:g[Y][X+1]='_';g[Y+1][X:X+3]='|_|'
for k in b:k=k+8*a;x=[0,2,3,3,2,0,-1,-1,0,1,2,2,1,0,-2,-1][k]+X;y=[0,0,0,2,2,2,1,0,-1,-1,0,1,2,2,0,0][k]+Y;exec"g[y][x]='|/_\\\\'[k%4];x+=d[k%8];y+=d[(k-2)%8];"*l
for k in z(h):print''.join(g[k])
```
## Ungolfed Version
```
numArms, armLength, rotAmount = input()
# Choose which arms to draw
arms = [0,4,2,6,1,5,3,7][:numArms]
for i in xrange(rotAmount+1):
# Set up the grid spacing
maxWidth = 5 + 2 * armLength
maxHeight = 2 + 2 * armLength
grid = [[' ' for x in xrange(maxWidth)] for y in xrange(maxHeight)]
# Add the base square
angle = i%2
startX = len(grid[0])/2
startY = len(grid)/2 - 1
if angle:
grid[startY][startX:startX+2] = '/\\'
grid[startY+1][startX:startX+2] = '\\/'
else:
grid[startY][startX+1] = '_'
grid[startY+1][startX:startX+3] = '|_|'
for armNum in arms:
# Determine where this arm starts
armIdx = armNum + 8*angle;
armX = [0,2,3,3,2,0,-1,-1,0,1,2,2,1,0,-2,-1][armIdx] + startX
armY = [0,0,0,2,2,2,1,0,-1,-1,0,1,2,2,0,0][armIdx] + startY
# Determine the direction it travels
d = [0,1,1,1,0,-1,-1,-1]
dirX = [0,1,1,1,0,-1,-1,-1][armIdx%8]
dirY = [-1,-1,0,1,1,1,0,-1][(armIdx)%8]
sym = '|/_\\'[armIdx%4]
# Draw the arm
for i in xrange(armLength):
grid[armY][armX] = sym
armX += dirX
armY += dirY
# Increment which arms to draw next
arms = [(a+1)%8 for a in arms]
for i in xrange(len(grid)):
print ''.join(grid[i])
print ''
```
## Explanation
Pretty simple when it's broken down. First figure out how big of grid is required, then plot the base square or diamond.
Each arm's starting location, symbol and direction is hardcoded in for each of the 8 possible arms for the square and diamond base. Then, drawing them is easy enough.
To rotate everything, I simply switch between the square and diamond base, then increment each of the arms, rotating them clockwise once.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/4029/edit).
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
>
> Original close reason(s) were not resolved
>
>
>
[Improve this question](/posts/4029/edit)
There have been many "Do \_\_ without *\_*\_" challenges before, but I hope that this is one of the most challenging.
## The Challenge
You are to write a program that takes two natural numbers (whole numbers > 0) from STDIN, and prints the sum of the two numbers to STDOUT. The challenge is that you must use as few `+` and `-` signs as possible. You are not allowed to use any sum-like or negation functions.
**Examples**
input
```
123
468
```
output
```
591
```
input
```
702
720
```
output
```
1422
```
**Tie Breaker:**
If two programs have the same number of `+` and `-` characters, the winner is the person with fewer `/` `*` `(` `)` `=` `.` `,` and `0-9` characters.
**Not Allowed:** Languages in which the standard addition/subtraction and increment/decrement operators are symbols other than `+` or `-` are not allowed. This means that Whitespace the language is not allowed.
[Answer]
# R (24 characters)
```
length(sequence(scan()))
```
What this does:
* `scan` reads input from STDIN (or a file)
* `sequence` generates integer sequences starting from 1 and concatenates the sequences. For example, `sequence(c(2, 3))` results in the vector `1 2 1 2 3`
* `length` calculates the number of elements in the concatenated vector
Example 1:
```
> length(sequence(scan()))
1: 123
2: 468
3:
Read 2 items
[1] 591
```
Example 2:
```
> length(sequence(scan()))
1: 702
2: 720
3:
Read 2 items
[1] 1422
```
[Answer]
## Perl (no +/-, no tie-breakers, 29 chars)
```
s!!xx!;s!x!$"x<>!eg;say y!!!c
```
As a bonus, you can make the code sum more than two numbers by adding more `x`s to the `s!!xx!`.
Alternatively, here are two 21-char solutions with 1 and 3 tie-breakers respectively
```
say length$"x<>.$"x<>
say log exp(<>)*exp<>
```
Note: These solutions use the `say` function, available since Perl 5.10.0 with the `-E` command line switch or with `use 5.010`. See the [edit history of this answer](https://codegolf.stackexchange.com/posts/4047/revisions) for versions that work on older perls.
---
How does the solution with no tie-breakers work?
* `s!!xx!` is a [regexp replacement operator](http://perldoc.perl.org/perlop.html#s/PATTERN/REPLACEMENT/msixpodualgcer), operating by default on the `$_` variable, which replaces the empty string with the string `xx`. (Usually `/` is used as the regexp delimiter in Perl, but really almost any character can be used. I chose `!` since it's not a tie-breaker.) This is just a fancy way of prepending `"xx"` to `$_` — or, since `$_` starts out empty (undefined, actually), it's really a way to write `$_ = "xx"` without using the equals sign (and with one character less, too).
* `s!x!$"x<>!eg` is another regexp replacement, this time replacing each `x` in `$_` with the value of the expression `$" x <>`. (The `g` switch specifies global replacement, `e` specifies that the replacement is to be evaluated as Perl code instead of being used as a literal string.) `$"` is a [special variable](http://perldoc.perl.org/perlvar.html#$LIST_SEPARATOR) whose default value happens to be a single space; using it instead of `" "` saves one char. (Any other variable known to have a one-character value, such as `$&` or `$/`, would work equally well here, except that using `$/` would cost me a tie-breaker.) The `<>` [line input operator](http://perldoc.perl.org/perlop.html#I%2fO-Operators), in scalar context, reads one line from standard input and returns it. The `x` before it is the Perl [string repetition operator](http://perldoc.perl.org/perlop.html#Multiplicative-Operators), and is really the core of this solution: it returns its left operand (a single space character) repeated the number of times given by its right operand (the line we just read as input).
* `y!!!c` is just an obscure way to (ab)use the [transliteration operator](http://perldoc.perl.org/perlop.html#tr/SEARCHLIST/REPLACEMENTLIST/cdsr) to count the characters in a string (`$_` by default, again). I could've just written `say length`, but the obfuscated version is one character shorter. :)
[Answer]
## D
```
main(){
int a,b;
readf("%d %d",&a,&b);
while(b){a^=b;b=((a^b)&b)<<1;}
write(a);
}
```
bit twiddling for the win
as a bonus the compiled code doesn't contain a add operation (can't speak for the readf call though)
[Answer]
# Python 2, 43 bytes
```
print len('%s%s'%(input()*'?',input()*'!'))
```
[Answer]
# [Seed](https://github.com/TryItOnline/seed), ~~3904~~ ~~3846~~ 11 bytes, 0 +/-, 10 tie breakers
```
4 141745954
```
[Answer]
C (32bit only)
```
int main(int ac, char *av) {
scanf("%d\n%d", &ac, &av);
return printf("%d\n", &av[ac]);
}
```
Pointer arithmetic is just as good.
How does it match the requirements?
\* No `+` or `-`
\* No `/`, `=`, `.`, `0`-`9`
\* Only 3 pairs of parenthesis, which seems to me minimal (you need `main`, `scanf`, `printf`).
\* One `*` (the pointer approach requires it).
\* Four `,` (could save one by defining normal variables, not `ac,av`)
[Answer]
## C++ 0 +/-, 3 tie-breakers
```
#include <vector>
#include <iostream>
#define WAX (
#define WANE )
#define SPOT .
int main WAX WANE {
unsigned x;
unsigned y;
std::cin >> x >> y;
std::vector<int> v WAX x WANE;
std::vector<int> u WAX y WANE;
for WAX auto n : u WANE {
v SPOT push_back WAX n WANE;
}
std::cout << v SPOT size WAX WANE;
}
```
[Answer]
### GolfScript
No +/- or tie-breakers:
```
# Twiddle some bits to get a few small integers
[]!~abs:two~abs:three!:zero~:minusone;
~[two base minusone%\two base minusone%]zip
zero:c;
{
# Stack holds [x y] or [x] with implicit y is zero
# Half adder using x y c: want to end up with sum on stack and carry back in c
[~c zero]three<zero$
~^^\
$~;:c;;
}%
[~c]minusone%two base
```
Much simpler version with two tie-breaker characters, using the same list-concatenation trick that other people are using:
```
~[\]{,~}%,
```
I'm assuming that GolfScript isn't disqualified for having `)` as an increment operator, as I'm not actually using it.
[Answer]
# Haskell, 0+2
```
import Monad
main = join $ fmap print $ fmap length $ fmap f $ fmap lines getContents
f x = join $ flip replicate [] `fmap` fmap read x
```
This uses no `+` or `-` characters, and only two `=` from the set of tie breaker characters, one of which is mandatory for binding `main`. The sum is done by concatenating lists of the appropriate lengths.
[Answer]
I didn't see anyone do it the Electrical Engineering way, so here's my take (in ruby):
```
def please_sum(a, b)
return (a&b !=0)? please_sum( ((a&b)<<1) , a^b ):a^b
end
```
It is a little bit ugly, but it gets the job done. The two values are compared by a bitwise `AND`. If they don't have any bits in common, there is no "carry" into the next binary column, so the addition can be completed by bitwise `XOR`ing them. If there is a carry, you have to add the carry to the bitwise `XOR`. Here's a little ruby script I used to make sure my digital logic was not too rusty:
```
100.times do
a=rand 10
b=rand 10
c=please_sum(a,b)
puts "#{a}+#{b}=#{c}"
end
```
Cheers!
[Answer]
**EDIT** This was posted BEFORE the rules changed to disallow `sum`...
The R language: No calls to `+` or `-`... And 9 tie-breaker characters!
```
sum(as.numeric(readLines(n=2)))
```
Example:
```
> sum(as.numeric(readLines(n=2)))
123
456
[1] 579
```
The `[1] 579` is the answer 579 (the `[1]` is to keep track of where in the result vector your are since in R all values are vectors - in this case of length 1)
Note that R has `+` operators just like most languages - it just so happens that it has `sum` too that sums up a bunch of vectors.
In this case, `readLines` returns a string vector of length 2. I then coerce it to numeric (doubles) and sum it up...
Just to show some other features of R:
```
> 11:20 # Generate a sequence
[1] 11 12 13 14 15 16 17 18 19 20
> sum(1:10, 101:110, pi)
[1] 1113.142
```
[Answer]
# The R language
New rules, new answer, same language. No calls to `+` or `-`
**UPDATE** Using `scan`, it drops to 11 tie-breaker characters (and 27 characters in all).
```
as.numeric(scan())%*%c(1,1)
```
Original: 13 tie-breaker characters!
```
as.numeric(readLines(n=2)) %*% c(1,1)
```
Example:
```
> as.numeric(readLines(n=2)) %*% c(1,1)
123
456
[,1]
[1,] 579
```
This time the result is achieved by matrix multiplication. The answer is displayed as a 1x1 matrix.
[Answer]
# Haskell, 0 `+`/`-`, ~~6~~ 2 tie-breakers (`=`)
## (does not use the string/list concatenation trick)
```
main = interact f
f x = show $ log $ product $ map exp $ map read $ lines x
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 4 bytes, 0 `+`/`-`
```
F>
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fze7/f3MjAy4gBgA "05AB1E – Try It Online")
Apologies if I misunderstood this challenge, but I was
surprised there was no 05AB1E answer. Shortest answer in
this language I could come up with that doesn't use + or
the built in sum function.
Explanation:
```
F #Loop A many times
> #Increment B
#(Implicit output)
```
*-2 Bytes thanks to Grimy.*
[Answer]
# Excel, ~~(25, 8) (22, 6)~~ 13, 4 tie-breakers
Inputs are `A1`, `A2`.
```
=2*MEDIAN(A:A
^^^ ^
```
Because `MEDIAN` is shorter than `AVERAGE` and `AGGREGATE`.
[Answer]
# [Python 3](https://docs.python.org/3/), 64 62 bytes
Without relying on hidden summations in other functions.
```
x=int(input());y=int(input())
while y:x,y=x^y,(x&y)*2
print(x)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8I2M69EIzOvoLREQ1PTuhKFy1WekZmTqlBpVaFTaVsRV6mjUaFWqallxFVQBFJWofn/v7ERl4kJAA "Python 3 – Try It Online")
[Answer]
**Javascript, 56**
```
p=prompt;alert(Array(~~p()).concat(Array(~~p())).length)
```
Thanks to @JiminP on the ~~ tip! I'm going for least bytes, so the 1 byte saving on the p=prompt; is still worth it. I understand your argument about tie-breaker chars, but to be honest wouldn't you rather the least bytes :-p
**Version, 69**
```
i=parseInt;p=prompt;alert(Array(i(p())).concat(Array(i(p()))).length)
```
Thanks to some feedback from @Ilmari and @JiminP, I've shaved 13 bytes off my original solution.
*Originally, 82*
```
i=parseInt;p=prompt;a=Array(i(p()));a.push.apply(a, Array(i(p())));alert(a.length)
```
[Answer]
## C
```
b[500];i;j;main(){scanf("%d%d",&i,&j);printf("%d\n",sprintf(b,"%*s%*s",i,"",j,""));
```
[Answer]
## Javascript (17 tie-breaker characters)
```
eval('걢갽거걲걯걭거건갨걡갽거걲걯걭거건갨걹갽걦걵걮걣건걩걯걮갨걡갩걻걣갽걮걥걷갠걕걩걮건갸걁걲걲걡걹갨걡갩갻걦걯걲갨걩갠걩걮갠걣갩걩걦갨걩갽갽걾걾걩갩걸갮거걵걳걨갨갱갩걽갬걸갽걛걝갩갩갻걹갨걡갩갻걹갨걢갩갻걡걬걥걲건갨걸갮걬걥걮걧건걨갩갻'['split']('')['map'](function(_){return String['fromCharCode'](_['charCodeAt'](~~[])^0xac00)})['join'](''))
```
:P ("Obfuscated" to reduce number of tie-breaker characters. Internally, it's
`b=prompt(a=prompt(y=function(a){c=new Uint8Array(a);for(i in c)if(i==~~i)x.push(1)},x=[]));y(a);y(b);alert(x.length);`
.)
[Answer]
## APL (no +/-, no tie breakers, 8 or 10 characters)
This entry is similar to the other ones that concatenate sequences generated from the input and find the length... but it's in APL, which can appear confusing even for a small problem like this. I used [Dyalog APL](http://www.dyalog.com), which offers a free educational license.
Code:
```
⍴⊃⍪⌿⍳¨⎕⎕
```
From right to left:
* Each quote-quad ( `⎕` ) requests input from the user and evaluates it.
* The each operator ( `¨` ) applies the index generator function ( `⍳` ) to each of the items in the array to its right.
* This flattens the resulting array of arrays into one array. The input array is reduced to a flat list by the reduction operator ( `/` ), which folds the array using the concatenation function ( `,` ). For the sake of this challenge, the one-dimensional reduction operator ( `⌿` ) is used, along with the concatenation operator along the first axis ( `⍪` ).
* As a result of using the reduction operator, the array is *enclosed*, which is like placing it in the bag; all we see on the outside is a bag, not its contents. The disclose operator ( `⊃` ) gives us the contents of the enclosed array (the bag).
* Finally, the shape-of function ( `⍴` ) gives us the lengths of the dimensions of an array. In this case, we have a one-dimensional array, so we obtain the number of items in the array, which is our result.
If we need to explicitly output the result, we can do so like this:
```
⎕←⍴⊃⍪⌿⍳¨⎕⎕
```
Comparable Python code, with corresponding APL symbols above:
```
import operator
⎕← ⍴ ⌿ ⍪ ¨ ⍳ ⎕ ⎕ ⊃
print (len (reduce (operator.__add__, [map (lambda n: range (1, n+1), [input(), input()])][0])))
```
I'd like to know if there's a shorter version possible in APL - another, simpler version I came up with that has more tie breakers (although still at 8 characters) is: `⍴(⍳⎕),⍳⎕`.
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 0 `+-` characters, 0 tiebreakers, 33 bytes
```
"e:"%"X:"%::%p"h:"%"Y:"%::%p&& @
```
[Try it online!](https://tio.run/##S0pNK81LT/3/XynVSklVKQJIWFmpFihlgHiRUJ6amoKCw///5gZGCuZGBgA)
### Explanation
Like @negative seven's Befunge answer, we generate `+` and `.` at runtime and put them onto the field to be executed. However, Befunge-93 does not include the `y` instruction, so we abuse the `%` modulo operator instead.
```
"e:"% # Calculate 101 ('e') mod 58 (':') to get 43 ('+')
"X:"% # Calculate 88 ('X') mod 58 to get 30
::% # Calculate 30 mod 30 to get 0
p # Put character 43 ('+') at position (30, 0)
"h:"% # Calculate 104 ('h') mod 58 to get 46 ('.')
"Y:"% # Calculate 89 ('Y') mod 58 to get 31
::% # Calculate 31 mod 31 to get 0
p # Put character 46 ('.') at position (31, 0)
&& # Get two numbers from STDIN
(changed to '+') # Add the numbers together
(changed to '.') # Output the result
@ # End the program
```
[Answer]
# Scala 2.12, 20 bytes, 0 +/- signs
```
readInt\u002breadInt
```
The unicode literal is just turned into a `+` before compilation
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `as`, 0 bytes
[Try it Online!](http://lyxal.pythonanywhere.com?flags=as&code=&inputs=12%0A24&header=&footer=)
The `a` flag takes newline separated inputs as a list, and the `s` flag sums the top of the stack.
# Non-trivial `a`, ~~4~~ 2 bytes
*-2 bytes because I realized the challenge guarantees 2 number input.*
```
ṁd
```
[Try it Online!](http://lyxal.pythonanywhere.com/?flags=a&code=%E1%B9%81d&inputs=12%0A24&header=&footer=)
Explanation:
```
# 'a' flag - take newline separated inputs as a list
ṁ # Mean of inputs
d # Multiply by 2
# Implicit output
```
Effectively calculates `((a + b) / 2) * 2`, which is equivalent to `a + b`. The previous version worked for any amount of numbers, but it turns out the challenge specifies taking 2 numbers as input, so this works fine.
[Answer]
## Shell, 52
```
read a
read b
(seq 1 $a;seq 1 $b)|wc|awk '{print$1}'
```
This is basically the [same answer](https://stackoverflow.com/a/4765078/149391) I gave for another problem.
[Answer]
## C
```
a,b;A(int a,int b){return a&b?A(a^b,(a&b)<<1):a^b;}
main(){scanf("%d%d",&a,&b);printf("%d\n",A(a,b));}
```
[Answer]
**C#**
It's not the shortest by any stretch:
```
private static int getIntFromBitArray(BitArray bitArray)
{
int[] array = new int[1];
bitArray.CopyTo(array, 0);
return array[0];
}
private static BitArray getBitArrayFromInt32(Int32 a)
{
byte[] bytes = BitConverter.GetBytes(a);
return new BitArray(bytes);
}
static void Main(string[] args)
{
BitArray first = getBitArrayFromInt32(int.Parse(Console.ReadLine()));
BitArray second = getBitArrayFromInt32(int.Parse(Console.ReadLine()));
BitArray result = new BitArray(32);
bool carry = false;
for (int i = 0; i < result.Length; i++)
{
if (first[i] && second[i] && carry)
{
result[i] = true;
}
else if (first[i] && second[i])
{
result[i] = false;
carry = true;
}
else if (carry && (first[i] || second[i]))
{
result[i] = false;
carry = true;
}
else
{
result[i] = carry || first[i] || second[i];
carry = false;
}
}
Console.WriteLine(getIntFromBitArray(result));
}
```
[Answer]
# J, ~~15~~ 7 chars, 1 tie breaker, incomplete program
This is my J attempt. It is not a full program, because I have not yet figured out how to write one. Just put that line in a script to get the function `p` that can be used for adding an arbitrary amount of numbers. It is a monad and takes a list of numbers to add (such as `p 1 2 3 4`):
```
p=:#@#~
```
The idea is very simple. The function is written in tacit aka pointless style. Here is a pointed definition:
```
p=:3 :'##~y'
```
Read from right to left. In the tacit version, `@` composes the parts of the function. (like a ∘ in mathematics [(f∘g)(x) = f(g(x)])
* `y` is the parameter of `p`.
* `~` makes a verb reflexive. For some verb `m`, `m~ a` is equal to `a m a`.
* `#` (copy, `a#b`): Each element in `a` is replicated `i` times, where `i` is the element at the same index as the current element of `a` of `b`. Thus, `#~` replicates an item `n` `n` times.
* `#` (count, `#b`): Counts the number of elements in `b`.
Conclusion: J is awsome and less readable than Perl (that makes it even more awsome)
## Edits
* 15 -> 7 using `#` instead of `i.`. Yeah! Less chars than golfscript.
## More of a program
This one queries for input, but it still isn't a full program: (13 chars, 3 breakers)
```
##~".1!:1<#a:
```
[Answer]
# C#,
Program works on 1 line; separated on multiple lines to avoid horizontal scrolling.
```
using C=System.Console;
class A{
static void Main(){
int a,b,x,y;
a=int.Parse(C.ReadLine());
b=int.Parse(C.ReadLine());
do{x=a&b;y=a^b;a=x<<1;b=y;}while(x>0);
C.WriteLine(y);
}}
```
[Answer]
# C++, () only for `main`
```
#include <iostream>
int main()
{
unsigned int a, b;
std::cin >> a;
std::cin >> b;
unsigned int p = a ^ b;
unsigned int g = a & b;
unsigned int gg {g | p & g << 1};
unsigned int pp {p & p << 1};
unsigned int ggg {gg | pp & gg << 2};
unsigned int ppp {pp | pp << 2};
unsigned int gggg {ggg | ppp & ggg << 4};
unsigned int pppp {ppp & ppp << 4};
unsigned int ggggg {gggg | pppp & gggg << 8};
unsigned int ppppp {pppp | pppp << 8};
unsigned int gggggg {ggggg | ppppp & ggggg << 16};
unsigned int result {a ^ b ^ gggggg << 1};
std::cout << result;
}
```
Assumes 32-bit unsigned ints. Very ugly code to remove tiebreak characters. Emulates a Kogge-Stone adder.
[Answer]
# Octave/MATLAB, 37 bytes
```
f=@()e^(input(''));disp(log(f()*f()))
```
[Try it online!](https://tio.run/##y08uSSxL/f8/zdZBQzM1TiMzr6C0RENdXVPTOiWzuEAjJz9dI01DUwuINTX//zcx4jI2BgA "Octave – Try It Online")
] |
[Question]
[
# Your task
In your language of choice: create a program that outputs `1`
This `1` may either be a string or value equivalent to the number one.
# The shifting catch
If you take the **unicode codepoint** (or whatever codepoint encoding your languages uses if not UTF) for each character in your program, and shift each of those values by the **same non-zero amount**, then the result will be another program (potentially executable in different language) that also outputs `1`.
**Find the unicode codepoint of a character:** [here](https://www.fileformat.info/info/unicode/char/search.htm).
**E.g;**
If your program looked like: `X?$A`, and somehow output `1`, and it also miraculously outputs `1` after shifting all of it's Unicode indices up by, say, 10; then that process of shifting looks like this:
```
original program: X?$A
letter codepoint shift new-codepoint new-letter
X 88 +10 98 b
? 63 73 I
$ 36 46 .
A 65 75 K
new program: BI.K
```
**Note:** The Unicode codepoint will often be represented in the form similar to `U+0058`. `58` is the **hexadecimal** codepoint . In **decimal**, that's `88`. The link above will list `88` under the `UTF (decimal)` encoding section. That is the number you want to increment or decrement!
# Examples of valid outputs
```
1
"1"
'1'
[1]
(1)
1.0
00000001
one
```
**Note:** If your language only supports the output of `true` as an equivalent to `1`, that is acceptable. Exit-codes are also valid outputs.
# Scoring
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **lowest bytes wins**!
* Brownie points for creativity & if the two programs are in separate languages.
[Answer]
# Java, 62 bytes
```
interface M{static void main(String[]a){System.out.print(1);}}
```
[Try it online.](https://tio.run/##y0osS9TNSsn@/z8zryS1KC0xOVXBt7q4JLEkM1mhLD8zRSE3MTNPI7ikKDMvPTo2UbM6uLK4JDVXL7@0RK8AKFiiYahpXVv7/z8A)
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 62 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
\agXeYTVXι@nfgTg\Vιib\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp
```
Uses the 05AB1E encoding, with the codepoints all decreased by 13:
* `interface M{static void main(String[]a){System.out.print(1);}}` has the codepoints `[105,110,116,101,114,102,97,99,101,32,77,123,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,97,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,49,41,59,125,125]`
* `\agXeYTVXι@nfgTg\Vιib\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp` has the codepoints `[92,97,103,88,101,89,84,86,88,19,64,110,102,103,84,103,92,86,19,105,98,92,87,19,96,84,92,97,27,70,103,101,92,97,90,78,80,84,28,110,70,108,102,103,88,96,33,98,104,103,33,99,101,92,97,103,27,36,28,46,112,112]`.
[Try it online.](https://tio.run/##yy9OTMpM/f8/JjE9IjUyJCzi3E6HvLT0kPSYsHM7M5Niws/tTAiJSXzU1OSWnhqTGOUXEPKoqTnPLSctPSJBMSkjXTEZKJwOlFcBiusVFPz/DwA)
### Explanation:
**Java:**
```
interface M{ // Full program:
static void main(String[]a){ // Mandatory main-method:
System.out.print( // Print without trailing newline:
1);}} // Print 1
```
**05AB1E:**
```
\ # Discard the top of the stack (no-op, since it's already empty)
# STACK: []
a # Check if it only consists of letters (resulting in falsey/0
# for an empty string "", which is used implicitly without input)
# STACK: [0]
g # Push and push its length, which is 1
# STACK: [1]
X # Push variable `X`, which is 1 by default
# STACK: [1,1]
e # Push the number of permutations n!/(n-r)! with both 1s, which is 1
# STACK: [1]
Y # Push variable `Y`, which is 2 by default
# STACK: [1,2]
T # Push builtin 10
# STACK: [1,2,10]
V # Pop and store it in variable `Y`
# STACK: [1,2]
X # Push variable `X` again, which is 1 by default
# STACK: [1,2,1]
ι # Uninterleave using the 2 and 1, resulting in ["2"]
# STACK: [1,["2"]]
@ # Check whether 1 is >= ["2"], resulting in [0]
# STACK: [[0]]
n # Square it
# STACK: [[0]]
f # Get a list of all prime factors (none for 0), which results in []
# STACK: [[[]]]
g # Pop and push its length
# STACK: [1]
T # Push builtin 10
# STACK: [1,10]
g # Pop and push its length
# STACK: [1,2]
\ # Discard it
# STACK: [1]
V # Pop and store it in variable `Y`
# STACK: []
```
From here on out I can't really explain it anymore, since it does things I wasn't expecting:
```
ι # Uninterleave (would take either one or two arguments, but since the
# stack is empty, it somehow remembered the 1 that was previously on
# the stack and results in ["1"] -
# A program `ι` without input would result in an error instead..)
# STACK: [["1"]]
i # If-statement, which will be entered if the top is 1;
# since it's ["1"] instead of 1, it won't enter
# STACK: []
b\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp
# No-ops within the if-statement
# It again somehow remembers the previous ["1"] that was on the stack,
# which is output implicitly as result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
1*1
```
(Works in Japt too.)
[Try it online!](https://tio.run/##yy9OTMpM/f/fUMvw/38A "05AB1E – Try It Online")
# [Japt](https://github.com/ETHproductions/japt), 3 bytes
```
6/6
```
[Try it online!](https://tio.run/##y0osKPn/30zf7P9/AA "Japt – Try It Online")
Derived from the 05AB1E program by shifting by 5 *Unicode* codepoints.
The Japt program performs division, but don't be fooled into thinking that the 05AB1E program is performing multiplication. The `*` (square) operator acts only on the first `1`; the output is actually just an implicit print of the second `1`.
The same idea works with the 05AB1E/Japt program pairs `1-1` and `3/3` (shift 2) and `1+1` and `5/5` (shift 4).
[Answer]
# Python 3, ~~19~~ 17 bytes
**-2 bytes thanks to Jonathan Allan**
```
#]pal )!‚êõ
exit(1)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Xzm2IDFHQVNRmiu1IrNEw1Dz/38A "Python 3 – Try It Online")
## Shifted +8
```
+exit(1)#␒m␣q|091
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Xzu1IrNEw1BTWSj3UENhjYGl4f//AA "Python 3 – Try It Online")
where ␛, ␒ and ␣ are literal `\x1b`, `\x12` and `\x80` bytes respectively.
Not much by the way of trickery going on here except prepending the print in the shift version with a `+` so that when we shift it the first character of the second program to the `#` character it doesn't send any characters into a negative codepoint (if we naiÃàvely shifted `e` back to `#`, `(` would be sent to `\x-` which doesn't exist). Outputs by exit code.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2x 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Without an input, any of these single characters will output `1`, so just pick two you like. :)
* `1` (self explanatory): [Try it online.](https://tio.run/##yy9OTMpM/f/f8P9/AA)
* `X` (variable, which is 1 by default): [Try it online.](https://tio.run/##yy9OTMpM/f8/4v9/AA)
* `≠` (`!= 1` check; without input it will do `"" != 1`, resulting in truthy/1): [Try it online.](https://tio.run/##yy9OTMpM/f//UeeC//8B)
* `@` (`>=` check; without input it will do `"" >= ""`, resulting in truthy/1): [Try it online.](https://tio.run/##yy9OTMpM/f/f4f9/AA)
* `Q` (`==` check; without input it will do `"" == ""`, resulting in truthy/1): [Try it online.](https://tio.run/##yy9OTMpM/f8/8P9/AA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 2x2 bytes
```
*0
+1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@WAZe2IYj5P43rUd/UUOdgBXUtbQNDdQA "APL (Dyalog Unicode) – Try It Online")
`*0` computes `e^0`, and `+1` computes complex conjugate of 1. `*0` has Unicode codepoint 42 and 48, and `+1` has 43 and 49, so the two are different by exactly one.
Also works in many different flavors of APL, including... (copied from [Ad√°m's APL bounty](https://codegolf.meta.stackexchange.com/a/17363/78410))
>
> [Dyalog APL](https://www.dyalog.com/) Classic/Unicode/[Extended](https://github.com/abrudz/dyalog-apl-extended)/[Prime](https://github.com/abrudz/dyalog-apl-prime), [APL2](https://www.ibm.com/uk-en/marketplace/apl2/details), [APL+](http://apl2000.com/), [APLSE](https://play.google.com/store/apps/details?id=org.gemesys.android.aplse), [GNU/APL](https://www.gnu.org/software/apl/), [Sharp APL](http://www.sigapl.org/Archives/waterloo_archive/apl/sharp.apl/index.html), [sAPL](https://play.google.com/store/apps/details?id=org.gemesys.android.sapl), [SAX](https://github.com/tobia/luit-sax), [NARS](http://www.nars2000.org/), [APLX](https://www.dyalog.com/aplx.htm), [A+](http://www.aplusdev.org/index.html), [dzaima/APL](https://github.com/dzaima/apl), [ngn/APL](https://gitlab.com/n9n/apl), [APL\iv](https://github.com/ktye/iv), [Watcom APL](https://play.google.com/store/apps/details?id=org.gemesys.android.watapl), or [APL\360](http://wotho.ethz.ch/mvt4apl-2.00/).
>
>
>
... which makes this a polyglot of at least 19 languages!
[Answer]
# Unary, 84 bytes
```
000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
Outputs the character with codepoint 1 (equivalent brainfuck: `+.`). Since Unary cares only about the length of the program, a shift of any number will not change the output.
[Answer]
# HTML, 8 bytes
```
<ol><li>
```
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
!TQ#!QN#
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fMSRQWTHQT/n/fwA "05AB1E – Try It Online")
---
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
([X*(XU*
```
[Try it online!](https://tio.run/##y0rNyan8/18jOkJLIyJU6/9/AA "Jelly – Try It Online")
---
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
5he75eb7
```
[Try it online!](https://tio.run/##y0rNyan8/980I9XcNDXJ/P9/AA "Jelly – Try It Online")
---
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
;nk=;kh=
```
[Try it online!](https://tio.run/##y0rNyan8/986L9vWOjvD9v9/AA "Jelly – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
@spB@pmB
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fobjAyaEg1@n/fwA "05AB1E – Try It Online")
---
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
H{xJHxuJ
```
[Try it online!](https://tio.run/##y0rNyan8/9@jusLLo6LU6/9/AA "Jelly – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Outputs `["1"]`.
```
Q„ÅSQÅ~S
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/8FDLocbgwEONdcH//wMA "05AB1E – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
V‰†XV†ƒX
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/7FDnobaIsENth5oj/v8HAA "05AB1E – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
X‹ˆZXˆ…Z
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/4lD3oY6oiEMdh1qj/v8HAA "05AB1E – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
]êç_]çŠ_
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/9tCEQ73xsYd6D3XF//8PAA "05AB1E – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
a”‘ca‘Žc
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/8dCUQxOTEw9NPNSX/P8/AA "05AB1E – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
e˜•ge•’g
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/9dCMQ1PTUw9NPTQp/f9/AA "05AB1E – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
kž›mk›˜m
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/@9C8Q7Nzsw/NPjQj9/9/AA "05AB1E – Try It Online")
---
("Pffffft! Of *course* I know how 05AB1E and Jelly work! I *totally* didn't just brute-force a bunch of combinations on TIO. That would be [crazy](https://tio.run/##LYyxCsMgFEX3fMUjkyJ5QylZqkLJJziWDGKT9BXjC0b6@8ahFw5nOHC//ufPkOkoQ@L3UqszveZodSTbdytnQWBguI8PINAw3pqVkh20BU4nxwUjb8KVTGnDNfM@fXye2pdAxFfDzbj7QwRjA4Z/exYhFUkpa70A)! It would *never* work!")
[Answer]
# CSS, 48 bytes
```
body:after{content:"1"}z|ancx9`esdqzbnmsdms9!0!|
```
```
cpez;bgufs|dpoufou;#2#~{}body:after{content:"1"}
```
[Answer]
# [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 4 bytes
```
1@/>
```
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P/f0EHf7v9/AA "!@#$%^&*()_+ – Try It Online")
## Explanation
```
1 # Pushes 1
@ # Prints top of the stack (1)
/> # Pushes some meaningless stuff
```
# Shifted +2
```
3B1@
```
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P/f2MnQ4f9/AA "!@#$%^&*()_+ – Try It Online")
## Explanation
```
3B # Pushes some meaningless stuff
1 # Pushes 1
@ # Prints top of the stack (1)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 2 bytes
```
s1
```
[Try it online!](https://tio.run/##K6gsyfj/v9jw/38A "Pyth – Try It Online")
# [Pyth](https://github.com/isaacg1/pyth), 2 bytes, Shifted +1
```
t2
```
[Try it online!](https://tio.run/##K6gsyfj/v8To/38A "Pyth – Try It Online")
---
First Program translates to `floor(1)`
Second Program translates to `2 - 1`
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 2 x 18 bytes
```
" " " ‚êã ‚êå
‚êã ‚êå
" ‚êã
```
[Try it online.](https://tio.run/##K8/ILEktLkhMTv3/X0kBBLk5ebhAGMT6/x8A).
All codepoints decreased by 2 will result in:
```
‚êü ‚êü ‚êü ‚êá
‚êà ‚êá
‚êà ‚êü ‚êá
```
[Try it online.](https://tio.run/##K8/ILEktLkhMTv3/X0EOBDnZuThAGMT6/x8A)
Both programs contain unprintables. The first program contains characters with the codepoints: `[34,32,34,32,34,32,11,9,12,10,11,9,12,10,34,32,11,9]`. The second program with codepoints: `[32,30,32,30,32,30,9,7,10,8,9,7,10,8,32,30,9,7]`. In Whitespace, all characters except for spaces (codepoint 32), tabs (codepoint 9), and newlines (codepoint 10) are ignored, so both programs are actually the following:
```
SSSTN
TN
ST
```
Where `S`, `T`, and `N` are spaces, tabs, and newlines respectively.
This program will:
* `SSSTN`: Push 1
* `TNST`: Print it as integer to STDOUT
It's actually possible to create 3 x 27 bytes, 4 x 36 bytes, and even 5 x 45 bytes programs by having the codepoints apart by 2, still resulting in the same basic program above after all non-whitespace characters are ignored.
[Answer]
# J, ~~3~~ 2 bytes
```
=0
```
Monadic `=` means self-classify. It compares each item with each other item to see if it's the same. 0 is 0. It returns 1.
# Shifted +1
```
>1
```
Unboxes 1, which does nothing, because it wasn't in a box in the first place.
## Alternate 2-byters:
`!1` (1 factorial) shifted by 2 is `#3` (amount of items in 3)
`!0` (0 factorial) shifted by 2 is `#2` (amount of items in 2) shifted by 7 is `*9` (sign of 9)
[Answer]
# JavaScript (web), 19 bytes
## Form #1
```
`kdqs_0_:`;alert`1`
```
## Form #2 (#1 shifted by +1)
```
alert`1`;a<bmfsua2a
```
This took me longer than what I'd like to admit, but it was a fun challenge. üòÅ
Form #2 throws a `ReferenceError`, but [that seems to be allowed](https://codegolf.meta.stackexchange.com/a/4781/95061).
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 3 bytes
Outputs the character with the codepoint 1. [This is allowed by default.](https://codegolf.meta.stackexchange.com/a/18027/92069)
```
(+.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fQ1vv/38A "brainfuck – Try It Online")
# Shifted +3
```
+.1
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fW8/w/38A "brainfuck – Try It Online")
## Explanation
The `+` character increments the current item of the tape, and `.` outputs that value as a character. All other characters are ignored.
[Answer]
# Polyglot, 3 bytes
Shift of 2. Works in R, Octave, Japt, and probably others.
```
1+0
3-2
```
[Try it online (Octave)](https://tio.run/##y08uSSxL/f/fUNuAy1jX6P9/AA "Octave – Try It Online")
[Try it online (R)](https://tio.run/##K/r/31DbgMtY1@j/fwA "R – Try It Online")
[Try it online (Japt)](https://tio.run/##y0osKPn/31jX6P9/AA "Japt – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Among many others:
```
1
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MQ)
```
Ä
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xA)
```
l
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bA)
[Answer]
# [R](https://www.r-project.org/), 4 bytes
```
\061\043\030\077
```
(octal bytes, equivalent to: `'1' '#' CAN '?'`)
Shifted -14:
```
\043\025\012\061
```
(octal bytes, equivalent to `'#' NAK LF '1'`)
Unshifted program consists of number 1 (which is outputted unchanged), followed by `#` (comment character) and 'comments' of CAN (ASCII code \030) and '?'.
Shifted +14 program consists of `#` (comment character) and 'comment' of NAK (ASCII code \025), followed by a new line. On the next line is the number 1 (which is outputted unchanged).
Test at bash command-line using `echo` (or `gecho`):
```
echo -e '\061\043\030\077' >prog1.r
echo -e '\043\025\012\061' >prog2.r
Rscript prog1.r
# [1] 1
Rscript prog2.r
# [1] 1
```
[Answer]
# [naz](https://github.com/sporeball/naz), 4 bytes
```
1a1o
```
**Explanation**
```
1a # Add 1 to the register
1o # Output once
```
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 bytes
```
2b2p
```
A shift of 1 Unicode codepoint forward from the original.
**Explanation**
```
2 # Push 2
b # Convert to binary
2 # Push 2
p # Push isPrime(2)
# ...after which the result is output implicitly
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page)
`¬` (logical NOT) vs `‘` (increment)
**[Try `¬` online!](https://tio.run/##y0rNyan8///Qmv//AQ "Jelly – Try It Online")** or **[Try `‘` online!](https://tio.run/##y0rNyan8//9Rw4z//wE "Jelly – Try It Online")**
This works because given no input a Jelly program has a default argument of `0`.
There are \$\binom{21}{2}=210\$ different pairs of single-byte programs to choose from since there are \$21\$ single bytes on Jelly's [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page) which yield `1` with no input:
[Answer]
# [Io](http://iolanguage.org/), 6 bytes
```
1print
```
[Try it online!](https://tio.run/##y8z//9@woCgzr@T/fwA "Io – Try It Online")
# [Commentator](https://github.com/cairdcoinheringaahing/Commentator), (Shifted -17)
```
_aX]c
```
[Try it online!](https://tio.run/##S87PzU3NK0ksyS/6/18hPjEiNvn/fwA "Commentator – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 1 byte (SBCS)
```
1
```
[Try it online!](https://tio.run/##y05N///f8P9/AA "Keg – Try It Online")
Implicitly outputs 1
## Shifted +198
```
üÑÇ
```
[Try it online!](https://tio.run/##y05N////w/yWpv//AQ "Keg – Try It Online")
Uses the push'n'print to print 1
[Answer]
## Batch, ~~27~~ 17 bytes
```
:_]biÔøΩ+ÔøΩ4
@echo 1
```
The `:` introduces a label of unprintables, so the line is ignored, and the second line prints `1`. Shifted by 6:
```
@echo 1
:ÔøΩFkinu&7
```
Much the same, except this time the second line is ignored.
Unfortunately I've mangled the unprintables. Sorry about that. Feel free to fix it.
[Answer]
# [;#+](https://github.com/ConorOBrien-Foxx/shp), 4 bytes
```
9n;p
```
[Try it online!](https://tio.run/##K84o@P/fMs8aSAIA ";#+ – Try It Online")
# [;#+](https://github.com/ConorOBrien-Foxx/shp), 4 bytes, Shift +2
```
;p=r
```
[Try it online!](https://tio.run/##K84o@P/fusC26P9/AA ";#+ – Try It Online")
---
## Explanation
`;` - increments the counter
`p` - outputs the counter as a number
`9`, `n`, `=` and `r` are not commands in [;#+](https://github.com/ConorOBrien-Foxx/shp) so they can be ignored.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 6 bytes
```
i1<esc><nul>h0
```
* Original: [Try it online!](https://tio.run/##K/v/P9NQmiHD4P9/AA "V (vim) – Try It Online")
* Shifted: [Try it online!](https://tio.run/##K/v/P8tIhjHT8P9/AA "V (vim) – Try It Online")
[Answer]
# bc (?), 3 bytes
```
1+0
```
Shift 2:
```
3-2
```
Use as `echo 1+0 | bc` in bash.
[Answer]
# `pdfTeX -halt-on-error`, 1 byte
```
_
```
and
```
^
```
Both versions will throw an error as `_` and `^` are only allowed in math-mode. Will return a 1 as exit code (due to the error).
[Answer]
# [Perl 5](https://www.perl.org/) -p, 8 bytes + 1 byte/keypress input = 9 bytes
*Edit: -2 bytes and much nicer printable programs thanks to Dom Hastings*
Each program requires input of 1 byte, or a single carriage-return keypress.
I've counted this as +1 byte, but I'm not terribly sure how valid this is...
```
$_++#^**
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXltbOU5L6///RK5/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
Shifted +1:
```
%`,,$_++
```
[Try it online!](https://tio.run/##K0gtyjH9/181QUdHJV5b@///JK5/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
One might (validly) argue that since the extra input/keypress is part of the byte-count, it should also be shifted along with the codepoints of the program. Fortunately, there are inputs for which this works Ok:
```
echo 'a' | perl -pe '$_++#^**'
# 1
echo 'b' | perl -pe '%`,,$_++'
# 1
```
[Answer]
**JavaScript, 3**
`3-2` becomes `2,1` shifted by -1.
`1+0` becomes `2,1` shifted by +1.
Which is cool because `1+0` shifted by one becomes `2,1` shifted by one becomes `3-2` all three produce 1
---
```
let code = '1+0';
console.log (code, eval(code));
code = code.split('').map(c => String.fromCharCode(c.charCodeAt(0) + 1)).join('');
console.log (code, eval(code));
code = code.split('').map(c => String.fromCharCode(c.charCodeAt(0) + 1)).join('');
console.log (code, eval(code));
```
[Answer]
# [CJam](https://esolangs.org/wiki/CJam), 1 byte
```
1
```
```
X
```
For whatever reason, CJam has `X` as a builtin for 1, and since it outputs implicitly, you can just use those two. However, I thought it'd be more interesting to find a 2-byte solution.
```
XR
```
[Try it online!](https://tio.run/##S85KzP3/PyLo/38A "CJam – Try It Online")
Offset by +38:
```
2,
```
[Try it online!](https://tio.run/##S85KzP3/30jn/38A "CJam – Try It Online")
Explanations:
```
X Push 1 to the stack
R Push an empty array to the stack
(implicit) Output the stack
```
```
2 Push 2 to the stack
, Pop and push range from 0 to 1 less than the popped number
(implicit) Output the stack
```
Note that this is not only my first time golfing, but also my first time coding a program (well, programs) in CJam, so let me know how I did!
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 5 bytes
```
=-1!@
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/99W11DR4f9/AA "Hexagony – Try It Online")
# [Hexagony](https://github.com/m-ender/hexagony), 5 bytes, Shifted -12
```
1!%4
```
**Hexdump:**
```
00000000 31 21 25 15 34 |1!%.4|
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/99QUVXU5P9/AA "Hexagony – Try It Online")
# Explanation
Because of the small size and lack of mirrors, the programs are mostly executed linearly.
### Non-shifted Program
```
= Reverse direction of memory pointer
- Sets the current memory edge to the difference of the left and right neighbors (0 - 0 = 0)
1 Multiply current memory edge by 10 then add 1 (0 * 10 + 1 = 1)
! Outputs the value of current memory edge to stdout as an integer
@ Terminate the program
```
### Shifted Program
```
1 Multiply current memory edge by 10 then add 1 (0 * 10 + 1 = 1)
! Outputs the value of current memory edge to stdout as an integer
% Sets the current memory edge to the modulo of the left and right neighbours
(1 % 0) causes program to exit because of division by 0
4 Does not matter since the program as already exited
```
] |
[Question]
[
# For the main cops' challenge, [click here](https://codegolf.stackexchange.com/questions/54464)
>
> **NOTICE** - This challenge is now closed. Any cracks which are posted now will not be counted on the leaderboard and the accepted answer will *not* change.
>
>
>
## Challenge
Given the original program, its output and the output of the changed program, you have to find out which characters need to be changed, removed or added to get the expected output.
When you crack someone's code, leave a comment with a link to your crack on their answer.
## Formatting
```
# [<language>, <username of program owner>](<link to answer>)
## Description
<description of change and how you found it>
## Code
<changed code>
```
## Winning
The person who has cracked the most solutions wins.
## Leaderboard
### 13 cracks:
* Dennis
### 8 cracks:
* Alex Van Liew
### 5 cracks:
* Sp3000
* isaacg
### 3 cracks:
* Luis Mendo
* jimmy23013
* Dom Hastings
### 2 cracks:
* mbomb007
* Sluck49
### 1 crack:
* TheNumberOne
* Jakube
* ProudHaskeller
* David Zhang
* samgak
* paul.oderso
* rayryeng
* mgibsonbr
* n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳
* Stewie Griffin
* abligh
[Answer]
# [Ruby, histocrat](https://codegolf.stackexchange.com/a/54507/16941)
## Description
Changed x to be an array instead of scalar by adding `*`
Changed the last `9` to be a string instead of a number by adding `?`
The result is made of an array with a single element (`[9]`) multipled 9 times then imploded with `"9"` as separator.
## Code
```
x=*9;puts x*9*?9
```
[Answer]
# [Python 2, muddyfish](https://codegolf.stackexchange.com/a/54475/20080)
## Description
Through trials and tribulations involving factorizing large numbers and looking for consequtive factors, I realized that changing the 87654 to 58116 would be enough. Then, I factorized 58116 as 87\*668. Then I realised that 01234 = 668, so I just needed to change 87654 to 87 and remove the 01234 entirely. This is accomplished with a comment.
## Code
```
print (sum(range(054321)*9876)*87)#654)/01234
```
[Answer]
# [Shakespeare, AboveFire](https://codegolf.stackexchange.com/a/54592/6741)
In Scene III, one has to change Claudius into Claudio in the following snippet:
```
[Enter Claudio]
Claudius:
Thou art as stupid as the sum of thee and the product of the
product of me and Helen and Helena
[Exeunt]
```
## Modified code:
```
The Hidden Change.
Helen, a young woman with a remarkable patience.
Helena, a likewise young woman of remarkable grace.
Claudio, a remarkable man much in dispute with Claudius.
Claudius, the flatterer.
The Archbishop of Canterbury, the useless.
Act I: Claudius's insults and flattery.
Scene I: The insulting of Helen.
[Enter Claudius and Helen]
Claudius:
Thou art as hairy as the sum of a disgusting horrible fatherless
dusty old rotten fat-kidneyed cat and a big dirty cursed war.
Thou art as stupid as the product of thee and a fat smelly
half-witted dirty miserable vile weak son.
[Exeunt]
Scene II: The complimenting of Helena.
[Enter Claudio and Helena]
Claudio:
Thou art the sunny amazing proud healthy peaceful sweet joy.
Thou art as amazing as the product of thee and the pretty
lovely young gentle handsome rich Hero. Thou art as great
as the sum of thee and the product of a fair golden prompt good honest
charming loving noble king and a embroidered rich smooth golden angel.
[Exeunt]
Scene III: The insulting of Claudio
[Enter Claudius and Helen]
Helen:
Thou art as stupid as the sum of the sum of thee and a cat and me.
[Exit Helen]
[Enter Claudio]
Claudio:
Thou art as stupid as the sum of thee and the product of the
product of me and Helen and Helena
[Exeunt]
Scene IV: The Final Countdown
[Enter The Archbishop of Canterbury and Claudius]
Claudius:
Thou art the sum of you and a cat.
The Archbishop of Canterbury:
Am I better than a fine road?
Claudius:
If not, let us return to the insulting of Claudio.
[Exit The Archbishop of Canterbury]
[Enter Claudio]
Claudius:
Open your heart!
Open your heart!
[Exeunt]
```
Using the compiler linked by @AboveFire, this prints `11`.
[Answer]
# [CJam, by Mauris](https://codegolf.stackexchange.com/a/54499)
### Description
Mauris' original code does the following:
```
"f~" e# Push that string on the stack.
:i e# Cast each to integer. Pushes [102 126].
:# e# Reduce by exponentiation. Pushes 102^126.
```
No other of CJam's mathematical operators would yield a number that large for small inputs, so `:#` cannot be modified. Since `#`, when used for exponentiation, only takes integers as input, `:i` cannot be removed as well. This leaves only one place to modify the input: the string `"f~"`.
No matter how many characters the string holds, the result will be a left-associative power tower. CJam supports characters in the range from 0 to 65535 (with the exception of surrogates), so we have to express the output as **bn×k×j**, where **b**, **n**, **k** and **j** are integers in that range.
The decimal logarithm of the integer that results from the modified code is slightly smaller than **log10(2.44×10242545) = log10(2.44) + 242545**, so we can divide this value by the logarithms of all possible bases to find proper values for **n×k×j**.
In fact:
```
$ cjam <(echo '65536,2>{2.44AmL242545+1$AmL/i:I#s8<"24399707"=}=SIN')
5 347004
```
Comparing the first 8 digits turned out to be sufficient.
This means that we can express the output as **5347,004 = 1562557,834 = 1259×102×126**, so it suffices to **replace `"f~"` with `"㴉"` or `"} f~"`**.
### Code
```
"㴉":i:#
```
or
```
"} f~":i:#
```
Note that the spaces in the ASCII code should actually be a tabulator.
Attempting to execute this code in the online interpreter is probably a bad idea, but here's how you can verify the results from the command line:
```
$ wget -q https://bpaste.net/raw/f449928d9870
$ cjam <(echo '[15625 57834]:c`":i:#") > mauris.cjam
$ cat mauris.cjam; echo
"㴉":i:#
$ cjam mauris.cjam | diff -s - f449928d9870
Files - and f449928d9870 are identical
$ echo -en '"}\tf~":i:#' > mauris-ascii.cjam
$ cat mauris.cjam; echo
"} f~":i:#
$ cjam mauris-ascii.cjam | diff -s - f449928d9870
Files - and f449928d9870 are identical
```
[Answer]
# [Prolog, Fatalize](https://codegolf.stackexchange.com/a/54487/21487)
## Description
Add two `\`s. `\` is bitwise negation and `\/` is bitwise or.
## Code
```
X is \1\/42.
```
[Answer]
## [MATLAB/OCTAVE, Stewie Griffin](https://codegolf.stackexchange.com/a/54549/21654)
A simple bit of complex arithmetic.
```
acos(i)
```
[Answer]
# [C, LambdaBeta](https://codegolf.stackexchange.com/a/54482/29577)
## Description
Turn `main(a,_)` into `main(_)`. The first argument of main is `argc` which is initialized as `1`.
## Code
```
main(_){puts(_*_-1||_*_*_-1||_*_*_*_-1?"Expected Output":"?");}
```
[Answer]
# [Python 2, rp.belrann](https://codegolf.stackexchange.com/a/54608/19349)
Change the outermost list comprehension into a set comprehension. Partial credit to @mbomb007, who eliminated all of the "boring" solutions (swapping `x` and `y` around, tweaking operators, changing the range).
```
'~'*sum({(x,y)[x%2] for x in[y for y in range(8)]})
```
### Explanation:
In the original, `[(x,y)[x%2]for x in[y for y in range(8)]]` generates the following list:
```
[0, 7, 2, 7, 4, 7, 6, 7]
```
This is because in Python 2.7, the `y` in the inner list comprehension *leaks* into the enclosing scope at it's last known value (which, at the end of a range, is 7). So, in the tuple, `y` is always 7. `x`, however, goes through the list as normal, ranging from 0 to 7. When `x` is even, it chooses the value of `x`, when it's odd, it chooses `y` (which is always 7). I noticed that if I included exactly one 7 and all the rest of the values of `x`, I got 19; then I realized that I could transform the outer comprehension into a set comprehension, which would eliminate all duplicate values and leave me with exactly 19.
This was pretty clever, I don't think I've ever used a set comprehension before. Kudos.
[Answer]
# [Jonas, Matlab/Octave](https://codegolf.stackexchange.com/a/54654/20080)
## Description
I noticed the answer was `i^pi`, so then I justed had to turn `sin` into a nop.
## Code
```
0i+(i^pi)
```
`s` -> `0`, `n` -> `+`
[Answer]
# [Bash, Dennis](https://codegolf.stackexchange.com/a/54524/42620)
Original code:
```
echo {{{1..9}}}
```
Original output:
```
{{1}} {{2}} {{3}} {{4}} {{5}} {{6}} {{7}} {{8}} {{9}}
```
Modified code:
```
echo {,{1..9},}
```
Modified output:
```
1 2 3 4 5 6 7 8 9
```
Explanation:
In Bash you can output a comma separated list of items inside a pair of braces, like this:
```
echo {a,b,c}
```
prints
```
a b c
```
So the modified code is printing out a list of nothing, the numbers 1..9, nothing.
[Answer]
# [MATLAB, Luis Mendo](https://codegolf.stackexchange.com/a/54593/31516)
Original code:
```
-sin(2:.5:3)
ans =
-0.9093 -0.5985 -0.1411
```
New answer:
```
psi(2:.5:3)
ans =
0.4228 0.7032 0.9228
```
# Description:
Changed `-sin` to `psi`, the polygamma function in MATLAB. The `-` sign is substituted by `p` and the `n` is removed.
[Answer]
# [C, LambdaBeta](https://codegolf.stackexchange.com/a/54482/29577)
## Description
Change `-1` into `*0` so that the result of the multiplication is `0` (a falsy value).
## Code
```
main(a,_){puts(_*_*_*_*_*0?"Expected Output":"?");}
```
[Answer]
# [Brainfuck, Kurousagi](https://codegolf.stackexchange.com/a/54478/21487)
## Description
Remove the first `>` and change the first `<` to `.`
Tested at [brainfuck.tk](http://brainfuck.tk/). Note that the output doesn't match Kurousagi's post *exactly*, due to SE eating up unprintable characters.
## Code
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.[>.+<-]
```
[Answer]
# [Fantom, Cain](https://codegolf.stackexchange.com/a/54506/19349)
Security through obscurity is a very poor form of security (especially when the two methods are right next to each other in the Fantom docs and anyone who knows what a float looks like will immediately know what to do).
```
Float.makeBits32(1123581321)
```
[Answer]
# [CJam, by Basset Hound](https://codegolf.stackexchange.com/a/54520)
```
25me
```
Calculates **e25**. [Try it online.](http://cjam.aditsu.net/#code=25me)
The online interpreter gives a slightly different result in my browser, which seems to be a rounding issue.
The Java interpreter prints `7.200489933738588E10`, which is the desired output, but in a different format.
[Answer]
# [Python 2, Sp3000](https://codegolf.stackexchange.com/a/54541/25180)
## Description
Changed `01234` to `0x1234` and `min` to `9in`.
The fact that `4669 = (01234-1)*sum(m<<m in R for m in R)` is misleading.
## Code
```
R=range(0x1234);print sum(m<<9in(m,n)for m in R for n in R)
```
[Answer]
# [MATLAB / Octave, Stewie Griffin](https://codegolf.stackexchange.com/a/54569/42418)
## Description
This required negating the input into the anonymous function `g`, as well as changing the scaling factor of the `g` function to 2 instead of 7:
## Code
```
>> f=@(x)x^.7;g=@(x)2/f(x);g(-7)
ans =
-0.3011 - 0.4144i
```
[Answer]
# [Perl, abligh](https://codegolf.stackexchange.com/a/54596/21487)
## Description
Add in string repetition operator, `x` and insert additional digit!
## Code
```
print sin 95x7
```
[Answer]
# [Java, TheNumberOne](https://codegolf.stackexchange.com/a/54490/19349)
## Description
The program is a one-off implementation of [`Random.next()`](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#setSeed(long)) with a initial seed of `Integer.MAX_INT` and all the hex numbers converted to decimal. Changing the seed to the complement of `MAX_INT` generates the output:
```
class T{public static void main(String[]a){System.out.print(((~Integer.MAX_VALUE^25214903917L)&281474976710655L)*25214903917L+11L&281474976710655L);}}
```
(since there must be exactly two changes, pick any sort of no-op change: adding a space somewhere, an extra semicolon, etc)
[Answer]
# [Brainfuck, AboveFire](https://codegolf.stackexchange.com/a/54476/20370)
this program is a modification of [this](https://codegolf.stackexchange.com/a/54427/20370) code me a cookie answer.
that answer works by first pre-calculating a table of useful ascii codes of useful characters, and then has three conditional statements made up by three loops which are entered to by having a `1` in the correct position.
the start of how i broke the code is that the repeating pattern in the changed output is mostly what is printed if you enter the third loop with the table shifted left.
```
++++++++++[->++++++++<]>>++++++[-<---------->]<-------[----------->>>-<<+<[->->+<<]]>>>+<<>>>+++[->++++++++++<]>(<)++ .<+++++++++[->>>>>>>++++++++++<+++++<++++++++++++++<++++++++++<+++++<++++++++++<<]++++++++++>>+++++...>++>++>-->+>(>)++++<<<<<<<.<<<[->>>>>>.<<>>>>>.<<<<<.>>>>>.<<<<<>>>.<<<<.>>>>>.<<<<.>>>>>.<<<<<.>>>>.<<<<<.>>>>.<<...>.<<<<<<]>[->>>>>.<<...>>>.<<<<.>>>>>.<<<<...>>>>.<<<<<.>>>>.<<...>.<<<<<]>[->>>>.<<>>>>>>.<<<<<<..>>>.<<<<.>>>>>.<<<<>>>>>>.<<<<<<.>>>>>>.<<<<<<>>>>.<<<<<.>>>>.<<...>.<<<<]
```
(the additional characters are marked with parentheses)
[Answer]
# [Python 2, muddyfish](https://codegolf.stackexchange.com/a/54551/21487)
## Description
Change `<<` to `<>` (deprecated version of `!=`) and `0x156` to `0156`, the code point for `"n"` (which appears 3 times in the length 23 string `'<built-in function sum>'`).
## Code
```
print sum((ord(i)<>0156 for i in `sum`))
```
[Answer]
# [JavaScript, by Razvan](https://codegolf.stackexchange.com/a/54562)
### Description
The modified output is clearly Euler's natural number, which can be accessed as `Math['E']`.
By changing `''` to `'3'` and `32` to `36`, `String.fromCharCode` generates the `E`.
### Code
```
a=1,b=a*2,c=a+b,d=[a+b];while(c>b)c-=a;for(i=1;i<=c;i++)d.push(i);i='3'+c*d['length']*d['length'];alert(Math[String.fromCharCode(i.charCodeAt(0) * i.charCodeAt(1) / 36)])
```
[Answer]
# [Fantom, Cain](https://codegolf.stackexchange.com/a/54598/20080)
## Description
The array indexing is set up already, so I just need to make a 55. Honestly, the hardest part was downloading the language.
## Code
```
[7115432d/9,219.or(64),37,55,55][3]
```
(Inserted a comma, `0` -> `3`)
[Answer]
# [Shakespeare, AboveFire](https://codegolf.stackexchange.com/a/54592/42503)
# NOT CORRECT - sorry :(
Will look further into it when i get home from work
In the original Claudio's value is 1132462081
and Claudius' value is 1
In the final Scene Claudio's value is printed twice,
```
[Enter Claudio]
Claudius:
Open your heart!
Open your heart!
```
open your heart x2 = print value of the other person on stage (Claudio).
So if you change Claudius to Claudio(2 chars) - the value of Claudius will be printed - which is 1 - twice
```
The Hidden Change.
Helen, a young woman with a remarkable patience.
Helena, a likewise young woman of remarkable grace.
Claudio, a remarkable man much in dispute with Claudius.
Claudius, the flatterer.
The Archbishop of Canterbury, the useless.
Act I: Claudius's insults and flattery.
Scene I: The insulting of Helen.
[Enter Claudius and Helen]
Claudius:
Thou art as hairy as the sum of a disgusting horrible fatherless
dusty old rotten fat-kidneyed cat and a big dirty cursed war.
Thou art as stupid as the product of thee and a fat smelly
half-witted dirty miserable vile weak son.
[Exeunt]
Scene II: The complimenting of Helena.
[Enter Claudio and Helena]
Claudio:
Thou art the sunny amazing proud healthy peaceful sweet joy.
Thou art as amazing as the product of thee and the pretty
lovely young gentle handsome rich Hero. Thou art as great
as the sum of thee and the product of a fair golden prompt good honest
charming loving noble king and a embroidered rich smooth golden angel.
[Exeunt]
Scene III: The insulting of Claudio
[Enter Claudius and Helen]
Helen:
Thou art as stupid as the sum of the sum of thee and a cat and me.
[Exit Helen]
[Enter Claudio]
Claudius:
Thou art as stupid as the sum of thee and the product of the
product of me and Helen and Helena
[Exeunt]
Scene IV: The Final Countdown
[Enter The Archbishop of Canterbury and Claudius]
Claudius:
Thou art the sum of you and a cat.
The Archbishop of Canterbury:
Am I better than a fine road?
Claudius:
If not, let us return to the insulting of Claudio.
[Exit The Archbishop of Canterbury]
[Enter Claudio]
Claudio: << changed Claudius to Claudio
Open your heart!
Open your heart!
[Exeunt]
```
[Answer]
# [VBA by JimmyJazzx](https://codegolf.stackexchange.com/a/54511/34718)
Changed `IRR` to `MIRR` and changed `5` to a `,` so there are 3 parameters.
I found this while looking for how Excel's `IRR` function works. There was an article: [How Excel's MIRR Function Can Fix the IRR Function](http://exceluser.com/formulas/irr.htm). That tipped me off. Clever attempt, though. I'd never used VBA before, so that was interesting as well.
```
Sub q()
Dim a(2) As Double
a(0)=-5
a(1)=10
msgBox MIRR(a,0.2,3)
End Sub
```
[Answer]
# [Matlab / Octave, Jonas](https://codegolf.stackexchange.com/a/54625/36398)
## Description
In the last line, add `'` to transform `arg'` into the string `'arg'`, which will then be interpreted as ASCII numbers. And then add another `'` at the end to maintain the column format.
The almost unnecessary `'` in the original code was the main clue. Also, in restrospect, the fact that `arg` was defined separately (instead of directly within the `sin` line) should have looked suspicious.
## Code
```
format long
arg = [.1 .2 .3];
sin('arg'*exp(9))'
```
[Answer]
# [bc, abligh](https://codegolf.stackexchange.com/a/54591/34718)
Merely inserted the math operators. Took about 1 minute to solve once I looked up what bc was and what math operations it had. The first thing I thought of was division, but there weren't common factors that looked nice. So I immediately went for exponentiation and modulus. At least 15 digits were necessary for the modulus b/c of the expected output. After that, I guessed twice and found it.
```
4518^574%615489737231532
```
[Answer]
# [Lua, TreFox](https://codegolf.stackexchange.com/a/54595/43004)
## Description
"\_G" is the global table, making "\_G.load" refer to the global function "load". Converting a function to a string results in returning the function's address, which is then made into the length of the string by the length-operator "#".
## Code
```
G={load="lfkjgGsHjkU83fy6dtrg"}
print(#tostring(_G.load))
```
Also, since this is my first post on here, I can't make a comment on the original answer.
[Answer]
# [Python, rp.beltran](https://codegolf.stackexchange.com/a/54694/20080)
## Description
I noticed that the needed letters were always 2 in front of a digit. changing the third `\w` to `\d` got all of the right letters except the spaces. `\D` was the only `\` group I could find that allowed letters and spaces.
## Code
```
import re;''.join(re.findall('\D(?=\w\d)','t74q joh7 jv f9dfij9j bfjtf0e nnjen3j nnjrb6fgam3gtm5tem3hj s3eim7djsd3ye d5dfhg5un7ljmm8nan3nn6n k m2ftm5bsof5bf r5arm4ken8 adcm3nub0 nfrn6sn3jfeb6n d m6jda5 gdif5vh6 gij7fnb2eb0g '))
```
`w` -> `D`, `w` -> `d` in the regex.
[Answer]
# [Pyth, isaacg](https://codegolf.stackexchange.com/a/54529)
### Description
The original code does the following:
```
CG Convert "abcdefghijklmnopqrstuvwxyz" from base 256 to integer, yielding
156490583352162063278528710879425690470022892627113539022649722.
^3y21 Compute 3^(2 * 21).
% Calculate the modulus.
```
Since **156490583352162063278528710879425690470022892627113539022649722 - 58227066** gives **156490583352162063278528710879425690470022892627113538964422656**, which equals **226 × 3 × 7 × 7477 × 381524422711 × 17007550201751761 × 2288745700077000184147**, the desired output can be obtained by replacing `^3y21` with something that evaluates to a divisor of this product and is larger than **58227066**.
The `^` in the original code suggests that we might use it to calculate a power of **2**, the **3** that we could calculate a fitting divisor of the form **3 × 2n**.
Both are misleading. Solutions with a Levenshtein distance of 3 (`%CG^2 26`, `%CG^y2 13`, `%CG^4y13`) or 4 (`%CG.<3y13`) are readily found, but the solution at distance 2 requires a different approach.
The lowercase alphabet (`G`) has 26 letters, so its power set (the set of all strictly increasing sequences of lowercase letters) has **226** elements. By **replacing `y2` with `yG`**, we compute this power set.
We can retrieve the set's length by **replacing `3` with `l`**, which leaves us with `^lyG1`, i.e., **226** raised to the first power.
### Code
```
%CG^lyG1
```
Note that this will only work on a computer with enough available memory (roughly 6.43 GiB, according to `time`), so it will not work with the online interpreter.
Here's how you can verify the results from the command line:
```
$ \time -v pyth -c '%CG^lyG1'
58227066
Command being timed: "pyth/pyth.py -c %CG^lyG1"
User time (seconds): 30.73
System time (seconds): 2.12
Percent of CPU this job got: 100%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:32.85
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 6742564
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 2269338
Voluntary context switches: 1
Involuntary context switches: 58
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
```
] |
[Question]
[
Given a list of digits 1 through 9, output whether each digit is grouped together as a single contiguous block. In other words, no two of the same digit are separated by different digits. It's OK if a digit doesn't appear at all. Fewest bytes wins.
**Input:** A non-empty list of digits 1 through 9. This can be as a decimal number, string, list, or similar sequence.
**Output:** A consistent [Truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value if all the digits are grouped in contiguous blocks, and a consistent [Falsey](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value if they are not.
True cases:
```
3
51
44999911
123456789
222222222222222222222
```
False cases:
```
818
8884443334
4545
554553
1234567891
```
```
var QUESTION_ID=77608,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/77608/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]
# Python 3, ~~38~~ ~~34~~ 33 bytes
```
lambda s:s==sorted(s,key=s.index)
```
This expects a list of digits or singleton strings as argument. Test it on [Ideone](http://ideone.com/lPtREK).
*Thanks to @xsot for golfing off 4 bytes!*
*Thanks to @immibis for golfing off 1 byte!*
[Answer]
## JavaScript (ES6), 27 bytes
```
s=>!/(.)(?!\1).*\1/.test(s)
```
Uses negative lookahead to look for two non-contiguous digits. If at least two such digits exist, then they can be chosen so that the first digit precedes a different digit.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 4 bytes
Code:
```
Ô¹ÙQ
```
Explanation:
```
Ô # Push connected uniquified input. E.g. 111223345565 would give 1234565.
¬π # Push input again.
√ô # Uniquify the input. E.g. 111223345565 would give 123456.
Q # Check if equal, which yields 1 or 0.
```
Uses **CP-1252** encoding.
[Try it online!](http://05ab1e.tryitonline.net/#code=w5TCucOZUQ&input=NDQ5OTk5MTE)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ĠIFPỊ
```
[Try it online!](http://jelly.tryitonline.net/#code=xKBJRlDhu4o&input=&args=NDQ5OTk5MTE)
### How it works
```
ĠIFPỊ Main link. Input: n (list of digits or integer)
Ġ Group the indices of n by their corresponding values, in ascending order.
For 8884443334, this yields [[7, 8, 9], [4, 5, 6, 10], [1, 2, 3]].
I Increments; compute the all differences of consecutive numbers.
For 8884443334, this yields [[1, 1], [1, 1, 4], [1, 1]].
F Flatten the resulting 2D list of increments.
P Product; multiply all increments.
Ị Insignificant; check if the product's absolute value is 1 or smaller.
```
[Answer]
# Pyth, ~~6~~ 5 bytes
*1 bytes thanks to FryAmTheEggman*
```
SIxLQ
```
Inspired by the Python solution [here](https://codegolf.stackexchange.com/a/77624/20080).
[Test suite](https://pyth.herokuapp.com/?code=SIxL&input=%22888444333%22&debug=0)
**Explanation:**
```
SIxLQ
xLQ Map each element in the input to its index in the input. Input is implicit.
SI Check whether this list is sorted.
```
[Answer]
# R, ~~66~~ ~~48~~ ~~46~~ ~~43~~ 38 bytes
```
function(s)!any(duplicated(rle(s)$v))
```
This is a function that accepts the input as a vector of digits and returns a boolean. To call it, assign it to a variable.
Not the shortest but I thought it was a fun approach. We run length encode the input and extract the values. If the list of values contains duplicates then return `FALSE`, otherwise return `TRUE`.
[Verify all test cases online](http://www.r-fiddle.org/#/fiddle?id=R8cXhmZ0&version=5)
Saved 20 bytes thanks to MickyT, 3 thanks to Albert Masclans, and 5 thanks to mnel!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
t!=tXSP=
```
The output is an array containing only ones for truthy, or an array containing at least one zero for falsey.
[**Try it online!**](http://matl.tryitonline.net/#code=dCE9dFhTUD0&input=Jzg4NDQ0MzMzJw)
### Explanation
Consider the input `22331`, which satisfies the condition. Testing if each character equals each other gives the 2D array
```
1 1 0 0 0
1 1 0 0 0
0 0 1 1 0
0 0 1 1 0
0 0 0 0 1
```
The final result should be truthy if *the rows of that array (with rows considered as atomic) are in decreasing lexicographical order*. For comparison, input `22321` gives the array
```
1 1 0 1 0
1 1 0 1 0
0 0 1 0 0
1 1 0 1 0
0 0 0 0 1
```
in which the rows are not in order.
```
t! % Take string input. Duplicate and tranpose
= % Test for equality, element-wise with broadcast: gives a 2D array
% that contains 0 or 1, for all pairs of characters in the input
t % Duplicate
XS % Sort rows (as atomic) in increasing order
P % Flip vertically to obtain decreasing order
= % Test for equality, element-wise
```
[Answer]
## [Retina](https://github.com/mbuettner/retina), 17 bytes
```
M`(.)(?!\1).+\1
0
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYApNYCguKSg_IVwxKS4rXDEKTWAwCilHYA&input=Mwo1MQo0NDk5OTkxMQoxMjM0NTY3ODkKMjIyMjIyMjIyMjIyMjIyMjIyMjIyCjgxOAo4ODg0NDQzMzM0CjQ1NDUKNTU0NTUzCjEyMzQ1Njc4OTEKMTIxMjM0MzQzNDQ1NDU0NTY3Njc4OTg5) (Slightly modified to run all test cases at once.)
The first regex matches digits which *are* separated by other digits, so we get a `0` for valid inputs and anywhere between `1` and `9` for invalid inputs (due to the greediness of the the `.+`, we can't get more than `n-1` matches for `n` different digits).
To invert the truthiness of the result, we count the number of `0`s, which is `1` for valid inputs and `0` for invalid ones.
[Answer]
# J, 8 bytes
```
-:]/:i.~
```
Test it with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%20-%3A%5D%2F%3Ai.~%20)%204%204%209%209%209%209%201%201).
### How it works
```
-:]/:i.~ Monadic verb. Argument: y (list of digits)
i.~ Find the index in y of each d in y.
]/: Sort y by the indices.
-: Match; compare the reordering with the original y.
```
[Answer]
## Java, 161 156 bytes
[Because Java...](http://meta.codegolf.stackexchange.com/a/5829/16043)
Shamelessly stealing borrowing the regex from [this answer](https://codegolf.stackexchange.com/a/77634/16043) because I started out trying to do this with arrays and math manipulation, but it got hideously complex, and regex is as good a tool as any for this problem.
```
import java.util.regex.*;public class a{public static void main(String[] a){System.out.println(!Pattern.compile("(.)(?!\\1).*\\1").matcher(a[0]).find());}}
```
Ungolfed:
```
import java.util.regex.*;
public class a {
public static void main(String[] args) {
System.out.println(!Pattern.compile("(.)(?!\\1).*\\1").matcher(args[0]).find());
}
```
Laid out like a sensible Java person:
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class {
public static void main(String[] args) {
Pattern p = Pattern.compile("(.)(?!\\1).*\\1");
Matcher m = p.matcher(args[0]);
System.out.println(!m.find());
}
}
```
[Answer]
# Regex (Perl / PCRE / Java / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / Ruby), 17 bytes
```
^(?!(.)+\1*+.+\1)
```
[Try it online!](https://tio.run/##bY1NT8JAEIbv8ytGuqFdQcrSXS1dSkOCHj1xJG4qKUmTteAWDqapf71OMagH5zCfz/vOsXBWdW8fyJzGxh52uUUWahrTxXq1WS1b2B9cwMp0qhdLTVXwBss9bXhzdGV1wsG2GugWmcUU6/NrfSLcjO/EWPDivT9i9mc/pQvHBJnRgGSEAQmHwx/CEiF4Vfief30Q9Ej6iSFzYckzf@PORYLoJ/5Tbmtqfa5bMvummdXYGvP4vDamewmym2DCR1txO5pQ5l3nYa/HXV4XNUAESoCUcwohQMwiqe4f4jnM/gsADy8vr@pYxBDHsZQyiiIJUkkFipKKfq3EFw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bZBRS8MwEMff8yluWbGJ1m2xqdbF0henCKJSfbMaaslsIdtK0j2Jn31eJyKIBzkul//97i5d0@0u8q7pIHCQAZ1SmEDnzLt2prNVbVg4nRzmWjeV7XW9WXWtNa5kJVdlMfVhBCGeJSb1uxkE696se8@0vrq5XWjNIxAckXS6bakiy41jQZvNVGCzJRZ49vh0eXPHFf@AdskC@@x7Z80aI34sXrKMlmvKUey3b/iC6WgWHQuu9uqWm7rZDBIFSBWKAOaB/TIODhA5exll4TjEFsEq2@@2qvq6YYGLUKJggHzvbCvfa@McTslH2UOxuNZ393pRFPdFThdDfg50zoJVTp/c1swBb/Sqsh5DiqRPHGBPo4Gl6vPPrzGudq8sH7EJPyrF4dEEPd/txjCwoK688YTEJBFEynM0IYg4iWVyepaek5P/jJAx7Nv/VKciJWmaSinjOJZEJjIhCbok/kWJLw "PHP – Try It Online") - PCRE
[Try it online!](https://tio.run/##bZJbb9owFIDf/SsOQSo2dC4pYaONsqqbqIS0omlUe1m3ySQOmDoOi53ChPjt7ATCtm74wfG5feeWhXgWrxbJ005ly7xwsECZq5y3Q/hbUzqlT@oKOZPryrIsp1rFEGthLdwLZWBTq6wTDj/PuUogQwOduEKZGYhiZr98ZeDmRb6yMFzHculUjoEE4E5pCWlk5Gr/pB6P80RytHssfFemqSxk8kmKRBYw3bu9VNJjZC2mjIV1XnvuwtW84lNqoym2IJIPykjKWCMypdZMpdRy@aMU2lLvot1ue4xtXroeCJS6k4ANEtxvAgIukDBFv6fQdqLWo2lVXxduD7rtR@GcLAwUUf3CbrNllcCeHzXvbyfD76PxZDiejB5Gn4csxDFNYmEMjkCZZekggqrrWkcnP62TGVeG4d6MAxV1Q6gb3/vzubBjuXZYN2wAS1aNqMvqsBztS5yX04ZWgMiv8mHGwxA1JjtADBLqmSADqOZampmbU/a2C2dnoHk8F8Wto12cTqvZYvv9VudeuHiOxWfIKnh2kKhGzr81pDTjqTIJZXAD3kNRymsAD67Bu8MJo4A/xfa/qAq13W5JtcHdN3rToJx1Hv12h@PNdtVadk2oaBALKy0hPdL3SRBc4fF94l/2gv7rN4MrcnnqENKEffpj9MAfkMFgEARBr9cLSNAP@qSPV7/3B@X/Ag "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##bVHBbtswDL3rK1gHaKTEyarY7lw7aYEe9gFDDy3SzHAVxTbm2IIkI2uK/PoySU7WdhgPhEg@8pFPTIhJwdhxUDWs7tYc5i9tq/QXyQv@a1oKcYtYmUvIxHIFC/ju3e92P1@C7un19fGhvN6V@PgD313gKRk/09F4ajw5kn9Bng8jscjEmKbonakyRJLn21tUNRqEND7jUrYSs7ZRGhzxaMuVygtO3pReJwkzAJjP4ZS1T5fnzbpOQXLdyQZoenAjt3nVYAJvCIyJpWGreYMFmdDV4iqFzmCCWaahtZFtKMzDgd1Mg6@awhREp1Pod3LqJImTx9Bh4X9KJUnFcsVJes6qba5ZCbsy1/3kTSsBW669JXU8Bdd11XDcH1g1fk9phuwX9Ly@tWoDeE/A1Kw0ePjcDEn6qeoal1cruLyE8/tiMRwMyV@Y08JqvcEfN88UzyUr@wm@W9g3BxK4A@9BdjwB8CAB71teKxN4H4g3O1lp3ndOWWZkw@R0w1RVe24j6ttbW3uV6zs4f/ovI/rhOABLA1Y@hVCAIorC8MYYpYjOgjC6/hrfoNn/DKEBuL3O3TGNURzHYRgGQRCiMAojFBkXBe@j6G@2qfNCHSe10yFzMvwB "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##bY7BbsIwDEDv/gqTHtoOVjUk2UKmaLd9wW4FpIqGUSlLq6STBj/fJUyICz7YsuX37PE8nQbH5v57HPyE4RxW3nyZX/Co0RNC5n3xviiqcrmlT8sq5nKO04aqZ7p7w4uu4Th4tNi7BFdh6nqnALE/4kXh6Hs3FeV/b40rbImt69A2Edc637pcodW2qZPvwVq9W@g8y28m4zpNPv2PUYgkLV@frYJp/eFU@BVG0NhgkHy0sSgk6fadtWX6mc4ZJgke2mACAANBgfNNDEqBrhkXL69yA@tHAZDhVX6jJZUgpeScM8Y4cMEFiJgEu6voHw "Python 3 – Try It Online") - Python `import regex`
[Try it online!](https://tio.run/##bU1LT4NAGLzvrxiWpA@bblhYdFuyIU2qRw@mtxYJ6lpJVkIWSO3Fv44LtfHiHCaZbx6f7V7OvYXCkz7qr5pV@oTtZrdhVhdvCUoVJDh9lEbDqKNuGwKU7yi94V53bZNAV2OOJ4Nh9kueKUUPFU1cw@wDxpZhNqYuVc8w/Vm35xSTiYsHmaem/tR5QG3LqoWB@oZFCrqznV4DFGvQh8I0TtDr0m/2IvP8/nGb5/3zLPVmbL448JsFczzvex/DCl6LRjeERCTmRIiVA@eEh5GIb@/kioT/gRAf49trW3JJpJRCiCiKBBGxiEnsKI7@pvgP "Ruby – Try It Online") - Ruby
```
^ # Anchor to start of string
(?! # Assert that the following can't match:
(.)+ # Skip any number of characters (minimum zero), then capture
# the next character in \1
\1*+ # Skip all subsequent occurrences of \1, and lock in that match
# using a possessive quantifier.
.+ # Skip at least one character, or as many as necessary to make the
# following match:
\1 # Match the character captured in \1
)
```
## Regex (Perl / PCRE / Java / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / Ruby), 11 bytes
```
(.)\1*+.+\1
```
Returns a match for false, and a non-match for true.
[Try it online!](https://tio.run/##bY09b8IwEIb3@xUnYuG4UIKx3ZqYgJBox06MkawUBSmSG6gDQxWlfz01RbQdesN9Pu97x9I71b99IPEGW3fYFQ5JYsKYLTbr7XrZwf7gY1JlU7NYmlA5a7Hahw1rj76qTzjI64HpkDjMsDm/NqeA2/E9H3NWvl@OuPqzn4YLwxSJNYDBCOMgHA5/CBcIzuqSRvT2IL4g2ScmxCcVW9HnwjVlijSlW38ODVJmumB2pYkz2Fn79LKxto8nLOd3o8ko530f4YXHXdGUDYAAxUHKeQjOgc@EVA@Peg6z/wIgwu@3N7XmGrTWUkohhASppAIVkhK/VvwL "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bZBRS8MwEMff8ynOrNjE1W2xqVZj2YtTBHFS92Yl1JKthWwrSfck@@zzOhFBPEi4/PO/X@7S1u3hdtrWLQQOMqBjCiNonVlpZ1pbVoaF49HZVOu6tJ2utuu2scYVrOCqyMc@jCDEtURRr0xv2HRm03mm9f3j00xrHoHgiKTjXUMVWW4dC5psogKbLbHAs9fF3eMzV/wTmiUL7JvvnDUbzPi5eM8yWmwoR7PffeANytEkOhdcHd0NN1W97S0KkCoUAdSB/TJOTxE5eT/JwkGITwTr7DjbuuyqmgUuQouCHvI9sy19p41z2CU/yV7y2YN@nutZns/zKZ31@g3QGxasp/S@tN70J7pwO0yAImmPDRxpNLBU7f/8GuPqwEa8EGfD0bAQh8MA@lqoSm88ITFJBJHyGkMIIi5imVxepdfk4r8gZADHFn6qU5GSNE2llHEcSyITmZAEtyT@RYkv "PHP – Try It Online") - PCRE
[Try it online!](https://tio.run/##bZJbb9owFIDf/StOQSo2dC5pwpYuyqZuohLSiqZR7WVMk0kccOs4NHYKE@K3sxMI27phKbF9Lt@5@UE8i1cP6eNO5cuidPCAd64K3o3gb0nllD4pK@VcrmvNsppplUCihbVwJ5SBTSOyTjjcnguVQo4KOnGlMnMQ5dx@@87ALcpiZWG4TuTSqQIdCcCt0hKy2MjV/khbPClSyVHfYtGHKstkKdMvUqSyhNne7KWQHj2ba8ZY1MS1Fy5aLWo@pTaeYQki/aSMpIydxabSmqmMWi6fKqEtbV12u90WY5uXpgcCpe4kYIME95uAgEskzNDuMbK9uDM1nXp30fYg234WzsnSQBk3J6w2X9YB7MVR8vFmMvwxGk@G48nofvR1yCJs0yQRxmALlFlWDmKoq25kdPLTOplzZRjOzThQcT@CpvC9PV8IO5Zrh3nDBjBldRb3WeNWoH6J/XLa0BoQe3U8jHhoosZgB4hBQtMTZADVXEszdwvK3vXh/Bw0TxaivHG0j93ptDtsP9963QmXLDD5HFklzw83qpHzbw4ZzXmmTEoZvIfWLXZVvoUW4HdfVngEfBTb/7xq1Ha7JfUEd5Szqdft8d7U29UD2bWh9oVEWGkJ8cnAI0FwjcvziHflB4PXb8JrcnVqEdKGfRJH79ALSRiGQRD4vh@QYBAMyAB/A/8PyvsF "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##bVFtb9owEP7uX3EDqdgQWE2SLk2gk/ZhP2Dqh02AotSYJFpwLNsRKxV/fcx2YG2nnZTT@V6e5@4Jk3JaMnYe1oI13ZbD4qlttfmoeMl/zSopHxCrCgW5XG1gCd8GXw6Hn09h9@P5@ftjdXeo8BnPyJqOJ7PJmp7Jv@VBAGO5zOWEZuiVo7YUihf7B1QLA1JZn3OlWoVZK7QBTznec62LkpMXbbZpymwDLBZwybrQ57nYNhkobjolgGYnD7kvaoEJvCCwJleWreECSzKlm@VtBp3tCee5gda93EBpA9/sMW1/LUpbkJ3JoN/J65KmXhhLh2XwLpWmNSs0J9k1q/eFYRUcqsL0yLtWAXZcR0fqeUpumlpw3B9Yi6CntCDHJb2u76zeAT4SsDUnDR6txYhk76p@cHW7gZsbuMYflqPhiPxt81o4rXf47ea55oViVY8Q@IUDeyCBzzD4WjSapzAA@z2qzoYweEO8O6ja8H5yxnIrGyaXG2a6PnL3ooG7tXVX@bmT95f/ZUU/nYfgoMHJpxEKUUxRFN1boxTReRjFd5@SezT/nyE0BL/jdTqhCUqSJIqiMAwjFMVRjGLr4vAViv5mu6Yo9XnaeB1yL8Mf "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##bY7BboMwEETv@xVbcwCaFLGx3TpUvvYLeiM5oOA0SK5BNpWa/Dy1U0W5ZA8rrWbe7Ezn@TQ6vgzf0@hnDOew9ubL/IJHjZ4xthRVuaPnVbXa0RLvlpoX2r/jRddwHD1aHFzCqjD3g2sAcTjipcHJD24uyv/bGlfYEjvXo20jrnW@c3mDVtu2TnkPbPX@SedZfksyrtfso7PBNMiS@VqzCqbzh1Ph1xhBE1Vkn/4nepCl33fWlqkzLRkmHQ9dMAGAgyQQYhuHCGjDhXx9U1vYPBqADK8NbrQiBUopIQTnXICQQoKMS/J7FP0B "Python 3 – Try It Online") - Python `import regex`
[Try it online!](https://tio.run/##bU1NS8NAEL3vr3hJoFVLl2x2V7eGpRSqRw/SWxNC1LUG1hA2CbUX/3rcpBYvPphhZt7HuP7lNDhoPJuD@WpobY7YbnYb6kz5lqLScYrjR2UNrD6YriVA9Y4qGO9N37UpTD3pWDoSdr9kudZhVoepd9h9TOkyySfV2RpYaj6b7rTGbOblcR7oeTT3HNC4qu5gob/hsEb4WNrW3COEr53r/YjwkvSrPa9F8fC0LYrhil5n7GZBFxkbhgijB69la1pCOJGMCLHyYIywhAt5e6dWJPkPhESYnl/ciimilBJCcM4FEVJIIn2T/C@K/QA "Ruby – Try It Online") - Ruby
This beats the regex in the previous [Java answer](https://codegolf.stackexchange.com/a/77657/17216), [Perl answer](https://codegolf.stackexchange.com/a/77684/17216), and [Ruby answer](https://codegolf.stackexchange.com/a/77634/17216) by 2 bytes.
```
(.) # \1 = a character anywhere in the string
\1*+ # Skip all subsequent occurrences of \1, and lock in that match using a
# possessive quantifier.
.+ # Skip at least one character, or as many as necessary to make the
# following match:
\1 # Match the character captured in \1
```
## Regex (ECMAScript (or better) / Python / .NET), 13 bytes
```
(.)(?!\1).+\1
```
Returns a match for false, and a non-match for true.
**[Try it online!](https://tio.run/##bU3LbsIwELz7KxxFwrsUAiY2NUQup/YD2t5KD1Ew1K1JItv0QdVvTwMS6qVzGO1odmZey/cyVN62cRxauzF@39Rv5qvzujYf9N7sbj9bgKO@mQw7yBBWyZpjdrXm3XByxCw2D9HbegeYBWcrA/PRWOCIMsuw2DYerJ4W4LQ35cbZ2gBiouuDc4XVHL8JpXYLFtu@IwIWvXZ0MKDuafqcaJayk2gPMUQPLtuXsXoBjyt2V7pglpQt2aM/9Adl5@zlE4ufLqUni1ZlMIGQnEhOhFj04JzwWS7k/FotyOw/EJLS88IlrbgiSikhRJ7ngggpJJE9yfyviv8C "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript**
[Try it online!](https://tio.run/##bY3PT8IwFMfv7694soauERmlrZaVQUjQoyeOS5pJRrKkDuzgYJb5r89Og3rwHd7Pz/f7TqV3qn99R@INtu64LxySxIQxW243u82qg8PRx6TKZma5MqFy1mJ1CBvWnnxVn3GU1yPTIXGYYXN5ac4Bt5M7PuGsfBuOuP6zn4ULwxSJNYDBCOMgHI9/CBcIzuqSRvT6IB6Q7AMT4pOKrelT4ZoyRZrSnb@EBikzXTD7pokz2Fn7@Ly1to@nLF7f5JxNb3Pe9xEOCtwXTdkACFAcpFyE4Bz4XEh1/6AXMP8vACL8enxVa65Bay2lFEJIkEoqUCEp8WvFPwE "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bZBRS8MwEMff8yluWbGJ1m2xqVZj6YtTBHFS92Yl1JLZQraVpHsSP/u8TkQQDxIu//zvl7t0Tbe/zrumg8BBBnRKYQKdM@/amc5WtWHhdHKca91Uttf1dt211riSlVyVxdSHEYS4VijqdzMYNr3Z9J5pfXv/MNeaRyA4Iul011JFVlvHgjabqcBmKyzw7Hl5c//IFf@AdsUC@@J7Z80GM34qXrOMlhvK0ex3b3iDcjSLTgVXB3fLTd1sB4sCpApFAHVgv4yjI0TOXkdZOA7xiWCdHWZbV33dsMBFaFEwQL5ntpXvtXEOu@Sj7KmY3@nHhZ4XxaLI6XzQr4BesWCd09vKejOc6NLtMAGKpE9s4ECjgaXq88@vMa72bMJZPioFn5yUYr8fw1ANdeWNJyQmiSBSXmIIQcRZLJPzi/SSnP0XhIzh0MRPdSpSkqaplDKOY0lkIhOS4JbEvyjxBQ "PHP – Try It Online") - PCRE
[Try it online!](https://tio.run/##bZJbb9owFIDf/StOQSo27VxSwpYuyqpuohLSiqal2suYJpM4YOo4LHYKE@K3sxMI27phKbF9Lt@5eSGexatF@rRT@bIoHSzwzlXBuyH8Lamc0idlpZzJda1ZVlOtEki0sBYehDKwaUTWCYfbc6FSyFFBY1cqMwNRzuzXbwzcvCxWFobrRC6dKtCRANwrLSGLjFztj7TFkyKVHPUtFr6vskyWMv0sRSpLmO7NXgrp0bO5ZoyFTVx76cLVvOZTaqMpliDSj8pIythZZCqtmcqo5fJHJbSlratut9tibPPS9ECg1J0EbJDgfhMQcIWEKdo9hfYi6kxMp95duD3Itp@Ec7I0UEbNCavNl3UAe3mUfLiLh99H43g4jkePoy9DFmKb4kQYgy1QZlk5iKCuupHR@Kd1MufKMJybcaCiXghN4Xt7Phd2LNcO84YNYMrqLOqxxq1A/RL75bShNSDy6ngY8dBEjcEOEIOEpifIAKq5lmbm5pS968H5OWiezEV552gPu9Npd9h@vvV6EC6ZY/I5skqeH25UI@ffHDKa80yZlDK4hdY9dlW@hRbg91hWeAR8FNv/vGrUdrsl9QR3lDN6ezbxGL@YeLt6JLs21N6QCCstIX0y8Ijv3@DyPOJd9/3B6zfBDbk@tQhpwz6No3fgBSQIAt/3@/2@T/yBPyAD/A36f1DeLw "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##bVFtb9owEP7uX3EFqdhtYDVJujSBVtqH/YCpH1YBilJjEmvBsexErFT89THbgb5MOymn8708z90TptS4ZOw4FJLV3ZrD7LlpTPtF85L/nlRK3SNWFRpytVjBHH4Mvu12v57D7unl5edjdbur8BFPCH64WFIyuV7SI/m3YRDAlZrn6ppm6J1FWBLNi@09ErIFpa3PudaNxqyRpgVPerXlxhQlJ6@mXacpsw0wm8Ep60Kf53JdZ6B522kJNDt4yG0hJCbwisCaWli2mkusyJiu5jcZdLYnnOYtNO7lBkob@GaPafuFLG1BdW0G/U5emTT10lg6rIJPqTQVrDCcZOes2RYtq2BXFW2PvGk0YMe1d6Sep@RtLSTH/YFCBj2lBdnP6Xl9Z2IDeE/A1pw0eLSUI5J9qvrBxc0KLi/hHF/MR8MReWvzWjitN/jj5rnhhWZVjxD4hQN7IIEHGHwvasNTGID9HnVnQxh8IN7stGh5PzlhuZUNk9MNEyP23L1o4G5t3FV@7uD96X9Z0Q/HIThocPIZhEIUUxRFd9YoRXQaRvHt1@QOTf9nCA3B73ieTmiCkiSJoigMwwhFcRSj2Lo4fIeif9imLkpzHNdeh9zL8Bc "C++ (gcc) – Try It Online") - Boost
**[Try it online!](https://tio.run/##bY7BboMwDIbvfgo3HACtQ7hJupQp2m1PsBv0gEqqImUBJezQvjxLNlW91AdLtv/v/z1fl8vk@Dp@z5NfMFzD1hvwqNEzxtaiKouPTUdl9dLRGjctNa90fMebruE8ebQ4ukRVYRlG1wDieMZbg7Mf3VKU/7M1rrAl9m5A20Zc67xzeYNW27ZOfk9k9XGj8yy/Oxk3aPbZ22AaZEnsTRVM70@Xwm8xUiaekH35nyhAloIfoC3Tw7RmmO546oMJABwkgRCHWERAOy7k/k0dYPesADL8i7/TihQopYQQnHMBQgoJMjbJH1b0Cw "Python 3 – Try It Online") - Python**
[Try it online!](https://tio.run/##bY7BbsIwDIbvfgqTHtpqrMIk2UKnaLc9wW4th4qGUSlLq6STBi/fJUyICz5Ysv1/v//pPJ9Gx5fhexr9jOEc1t58mV/wqNEzxpaiKov3VUtl9dTSEjcN1c@0f8OL3sBx9GhxcAmswtwPrgbE4YiXGic/uLko/2drXGFL7FyPtom41nnr8hqtts0m@T2QbfYrnWf5zcm4XrOPzgZTI0via9AqmM4fToVfYwRNvCL79D9Rgyz9vrO2TJlpyTDd8dAFEwA4SAIhdrGIgLZcyJdXtYPtowLI8JrgRitSoJQSQnDOBQgpJMjYJL9b0R8 "Python 3 – Try It Online") - Python `import regex`
[Try it online!](https://tio.run/##bU1NS8NAEL3vr3hJoB9Il2x3V7eGJRSqRw/SWxNC1LUG1hA2CbUX/3rcpBYvPphhZt7HuP7lPDhoPJuj@WpobU7Ybfdb6kz5lqDScYLTR2UNrD6ariVA9Y4qGO9N37UJTD3pWDIS9rBiudZhVoeJd9hDTOlqnU@qizWw1Hw23TnFbOblcR7oeTT3HNC4qu5gob/hkCJ8LG1r7hHC1971fkR4TfrVXtaieHjaFcWwoMtFGmRsSW8yNgwRRhdey9a0hHAiGRFi48EYYWsu5O2d2pD1fyAkwvT@6lZMEaWUEIJzLoiQQhLpm@R/UewH "Ruby – Try It Online") - Ruby
**[Try it online!](https://tio.run/##bY5NT4QwEIbv/RUVmrRVIXZptQvZuImJN2/eXA@EHaSxAmnZYJbw27G7idHDzmE@Ms/7zvTdCM43YO1C3ObNwQd8v@d5CyPb0oWlnD1e7QRPb3Ziodvb6Kn76o2FfcQLctzcFXXnoKwaRiw2LSam7Q8Dn0zNyJFPozMDJE3nhznAojA1DmBStvuk7YZTa80n0Pia8v8wDtvwgDUt4Iiws8qlL@VQNeCDinM80efSesjpjCHUML@6A@SYzhxHc3HZi9h5ifEJxFXpwSOUISWQlOsQQiCxyqS6f9BrtLoUCMX4fPVXrYVGWmspZZZlEkklFVIhqezPSvwA "PowerShell – Try It Online") - .NET**
## \$\large\textit{Anonymous functions}\$
# [Ruby](https://www.ruby-lang.org/), 21 bytes
```
->s{/(.)\1*+.+\1/!~s}
```
[Try it online!](https://tio.run/##bYxRT4MwFIXf76@4FLOpCx2lrXYjdW/@gr0BMdssSlIJoRAzjP51LOjii@fhJueec762P57HUo/Rg/tYX9ObnN2u6Cpn6@DLfY6DjlN8f62sQatfTOcAsSpxCKZ/03cuRVM/pzholk6BzSJWaE3ymqR@YbOY0igpfltXT7qu7A8isNS8Nd15h4uFn8VFoJfh0meITVvVHZaZLXCHZN/2ZotIcIvk8WCdN2TmwaVpZzuGOFXxdHDGAXCQDITYeDEGLOFC3t2rDST/CSDEmX1ZK6ZAKSWE4JwLEFJIkP5I/odi3w "Ruby – Try It Online")
# JavaScript (ES6), 27 bytes
```
s=>!/(.)(?!\1).+\1/.test(s)
```
[Try it online!](https://tio.run/##dY2xTsMwFEV3f4WbSI0twK1rB9xEbjckdjbCECWOFGQ5wc@Boeq3B6cSgqG9w9Mdzrnvo/6qofH9GB7c0Jq50zPow2pDGCXHVcUpu6v4hgUDgQCdS9Db0pvPqfeGZN7Ure2dyShrYg/mxQXju7ox5NS7cQrF6IfGADAIbe/OlA2OZBfj3urDCWEMeL3G/6hhCuzb9yGuVy6jJQbNy8jZhbNv2/eVztLsptQRS4/Jq59MgXFSJM@1hVgTumxcNSwtz3RO8eLgpgYDCAmUcyTlPoZzxHdC5o9Pao9214JQii9vfm3FFVJKSSmFEBLJXOYojycXf1P8Bw "JavaScript (Node.js) – Try It Online")
Included for completeness; already done in [Neil's answer](https://codegolf.stackexchange.com/a/77622/17216).
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 29 bytes
```
!($args-match'(.)(?!\1).+\1')
```
[Try it online!](https://tio.run/##dY1BbsMgEEX3c4qJjQqochQCtCRR1F1P0F2ThWXh2hK1U3BkKZbP7mJLUTbtLJgB/ntzaXvrQ2Wdm0h5HKYVI7n/Ctl33hUVZWvO3lYnwdfPJ0H5NB7I7bg5lK23eVEx4rBukNTN5drxARDrkpEbH3pfdzar2tCNMS@WD4zpzP5gkmDWeiTuc3Ne7mnCcWZHtC7YZUR8GDBr2sb2rm4sJoTNoidSRj5S9MNf7R6R3ln6nse@jw88mZXwn4k4GKcUZx6LPNgAIEELUGoXSwgQW6n0y6vZwfavAkhx2XWnjTBgjFFKSSkVKK006Hho@VCJXw "PowerShell – Try It Online")
# [Julia](https://julialang.org/) v0.7+, 30 bytes
```
s->!occursin(r"(.)\1*+.+\1",s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bU5LTsMwEN3PKaaJ1NqUVri2wW2UsuME7CiLkNrFyHLATja9ChKqkHoN7tHb4DSq2DCLNxq933we3zpnq8O3KY9da2bqJ87Wo6auuxCtJyEjc7phV9P5dMOy60gH0elrX5rKRV2gaQI6tB6DrrbOeh0JBcSda14qh_vCmgTvwfrWeUIL7bcF7ss2dDqpEum037WvxNH1DY7H6J7Y86ic5JPEIp59xCQW7zF7TKYVYoYrzB769rT7rpQJF62jkM7hy8PpI8fehHUVdQTgIBkIsUzDGLAFF_L2Ti1h8d8A5HhuubgVU6CUEkJwzgUIKSTIBJL_RbGh-Rc "Julia - Attempt This Online") / [Try it online!](https://tio.run/##bU3LTsMwELzvV2wTqbUpVLi2qdso5cYXcGs5mNQpRisH2cklPx@cShUX5jCr1by@B/J2N7X1lJ6Oi65phph8YLFgG34WD@vN@iyKx8SnsW4tJVdh20Uk9AGjsxfywSXGAfFK3aclHCvfZvqJPvQUGK9cuFQ41n0cXHZlkVy49l@M@PEZl0ukk/hY1KtylVXEW461WcVXLN5z6IBY4AGLt3k933krd8LdSxzyO5U4m7GxySUACVqAUvsMIUBspdIvO7OH7X8AKPHWfk8bYcAYo5SSUipQWmnQmbT8qxK/ "Julia 0.7 – Try It Online")
# [Julia](https://julialang.org/) v1.3+, 28 bytes
```
s->count(r"(.)\1*+.+\1",s)<1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVDNTsMwDL77KUwrbQljE1kSyFY6bjzBboxD2ZJRZKXQtJe-ChKakPYWvMjehnRj4oIPtqzvz_LH_rWlsth9uXzfNm5svsN4sa5a37A6YRO-EpejyWglkqvA78SJcvjscldQsBm6qkbC0mNtiw2V3gbGAXFL1XNB2GWli-2tLn1DnvHM-k2GXd7UrY2sCJL12-aFEV9c42CA9CieLvJhOowo4lHHXETxHpNlFM0RE5xj8tCnx9lnRU84c4lDXE9X7g7vKfYiXBfBBgAJWoBSs1hCgJhKpW9uzQym_xVAiseUs9oIA8YYpZSUUoHSSoOOTcs_q9___AA "Julia - Attempt This Online")
*-2 bytes compared to v0.7+, thanks to MarcMush*
# [R](https://www.r-project.org/), 32 bytes
```
\(s)!grepl('(.)\\1*+.+\\1',s,,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY6xTgMxDIZ3P4XbSk1Mj4r0cpD2dCtTRySWW442KZFOaYmvSxFPwlKQeAXepW9DjoJY8GDL1vf_v1_f4vHdVR_7zl2aE9aSabCJdtdKIadU1-piMp2kITLOMkU_3CdXVyUeKudbK4fcrX0YUgluG-USfUDe73bRMt83MfiwYRlts176YFkeiOgZEL1LUaumk6IOgkquVHm-htVjk2wIx-Pk88BdWjKVsgeVGAnCXuOdbdlKl7BM3MW9XSCKTNw26bpAQdR79eCSyhdYtdsEH6g8f388PY2wFyWCLQPkUCjQep5KKVCzXBfXN2YOs_8KYITfOb9qowwYY7TWeZ5r0IUuoEityP-s1Dn5Cw "R - Attempt This Online")
Beaten by [Alex A.'s non-regex answer](https://codegolf.stackexchange.com/a/77633/17216) [by 2 bytes](https://ato.pxeger.com/run?1=bY_BSgMxEIbv8xRpV5oMrGC6WU277FUQeix46WXdTTSwpDXZFaz4JF6q4GsIPkbfxtku4sU5BDL5v28mb-_h8GHLz76z5_prIyJOKv8smn7XurrqTCNCa6h79oQ4ho7fsbwo2L60jl6msWucn2IBdhvEijnPYr_bBRPjbRW88_dRBFM1K-dNFHtEfAHGnCUl6QXfeI5FLGUxdn39UJEG2WxGnrvY0SWVqcRJyROObGCcNW00wgpaR6-3N74jAFO-Dr1ZMsZTfl1RYMk44qAdmBUWr1C3W-L2WIwfORwfEzZAlIgmAmSQS1BqQSUlyHmm8ssrvYD5fwWQsNOcX1pLDVprpVSWZQpUrnLI6cizP5UcJ_8A "R - Attempt This Online"), or [by 6 bytes](https://ato.pxeger.com/run?1=bY_BSgMxEIbv8xSxK00GVjDdrKZd9yoIPRa89JK2iQaWbM1sPVR8Ei9V8CW8-Rh9G7NdxIsDCUzyf98kb-_x8OHqz13nLvTXUhCaphGdWTVWxLQIz5_xZoJD4PhN9WXF9rXz6W5E3caHEVbg2ijmzAdGu-02WqJ7E4MPDySiNZu5D5bEHhFfgDHvknRtOsGXgWNFtayG07B-NEmDbDxOnhV1qcllLvGs5hlH1jPe2YascCI9Ry_au9AlAHO-iDs7Y4zn_NakwIxxxF7bM3OsXmHdtInbYzV85HB8ylgPpQRZAiiglKDUNJWUICeFKq-u9RQm_xVAxk5zfmktNWitlVJFUShQpSqhTFtZ_KnkMPkH "R - Attempt This Online") with pajonk's improvement.
# Java, 33 bytes
```
s->!s.matches("(.)+\\1*+.+\\1.*")
```
[Try it online!](https://tio.run/##bY5BT@MwEIXv/hWvqQR2AashzhIIKWIPnBYu5QZ78AancXGdKHaAatXf3nVT0ErAHDwaz7zvvaV8kSfLp@etXrVN57EMM@@9Nrzqbel1Y/kkx5flJCelkc7hVmqLvwRo@z9Gl3Be@tBeGv2EVdjRue@0XTz8huwWjg2nwM07@3K/Pf7ZNEZJO0OFYutOZiPHV9KXtXI0opwdPT7GkyO@a3wSsW0eIPNSWqs6aNv2HgWsev34o/O182rFtWUhuvXQxTTHa62NAh3ueS3dnXrzlIVE0BXVo2LK3mVN2LchljeW7gBFnA@h91lhgtkeYgPhl7ZquKpADTfKLnxN2WyKgwMYXtayu/Z0ykbF4fiQDZgA@uRDKy7b1qypYbhCdN/16gKIcIHoRhoXhig4fFEZlpPNZrMdY6dAKZ1yhCQkjYkQ56HimMSniUh/nGXn5PS7ImSMweJDncUZybJMCJEkiSAiFSlJw5Mm/1HxPw "Java (JDK) – Try It Online")
# [PHP](https://php.net/), 39 bytes
```
fn($s)=>!preg_match('/(.)\1*+.+\1/',$s)
```
[Try it online!](https://tio.run/##bY9Pb4IwGIfv/RS1Emkn/qkUBbvOy9yyiy7M2zQESRGyqqTF0@JnZ8Vl8bL38Kb59enzvq2KqnlcVEUFnVw0@Qk7hoinTqXlITmmdVZgd4SHZEsf@sP@lo5czwINL09lYmSNUZVpOdyn2VetbUtUeSxr5EHEJhGLprNJFCDCQX7W2CnFmDtK5AdZG/yxeX5bEU6@YZljR32aWitppysyoDsh0PaEiIXNZW9vbOyNvQEl/EaXRGbFuUU4tFbKAbQ5xHdHr2eV411HuF3XjmhxePuSSk2dSK3tPqQj3uPla7JaJ8s4XscLtGzzOURz7LQ7kQXa6IucQ5ugl1QZe7Sfuf7qkKMQvzZd2DIwS400APggoICxyBalgE58FkxnYQQm/xUAXXjT/r0OaQjCMGSM@b7PAAtYAALbAv@uoj8 "PHP – Try It Online")
## \$\large\textit{Full programs}\$
# [Perl](https://www.perl.org/) `-p`, 17 bytes (18 bytes including flag)
```
$_=!/(.)\1*+.+\1/
```
[Try it online!](https://tio.run/##bYzBTsMwEETv/orFsdKEtmlc2@DWCtz4Ao6RIlMcGil1rNg50Kq/TjCVEBfmMLurnXnOjL2YJ29AFCUtFZw@SVv56e1CmsoNTs1x3m2yIq/p/bJY1nQzK9JcFfiggwFyVuScpm7sbMC1xfGqqILDcTg5FVm6Io3q2qw39iMciYY0hUj3YcyIXpUrmluzSBb55UbISLt@io/8Gb@Ok9kD4D1@0b2PK86vtwwQrWCy76YF0swJ/AThoL3xCDEkKOJ8F0UpolvGxcOj3KHtf0IogRv7ty2pRFJKzjljjCMuuEAimmB/KPo1uNAN1s9r9w0 "Perl 5 – Try It Online")
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 17 bytes
```
M`(.)(?!\1).+\1
0
```
[Try it online!](https://tio.run/##bcshDoAwEERRP7dAkJSQNCw7C1uFRHEDBAgEBkG4f6nD8MR3/z6e89pzHeYtL1uITZiqVZrYroIuZ4UJyFSIQHqlDaMn9H/g4nB3kqpK0GiwEtNvlRc "Retina 0.8.2 – Try It Online")
Included for completeness; already done in [Martin Ender's answer](https://codegolf.stackexchange.com/a/77661/17216).
# [Retina 1.0](https://github.com/m-ender/retina/wiki/The-Language), 17 bytes
```
C`(.)(?!\1).+\1
0
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8N85QUNPU8NeMcZQU087xpDL4P9/Yy5TQy4TE0sgMDTkMjQyNjE1M7ew5DLCBrgsDC24LCwsTExMjI2NTbhMTE1MuUyBhKkxQqshAA "Retina – Try It Online")
# [Pip](https://github.com/dloscutoff/pip), ~~19~~ 18 bytes
```
`(.)(?!\1).+\1`NIa
```
[Try it online!](https://tio.run/##K8gs@P8/QUNPU8NeMcZQU087xjDBzzPx////JiaWQGBoCAA "Pip – Try It Online")
Thanks to DLosc.
[Answer]
# Pyth, 7 bytes
```
{IeMrz8
```
[Test Suite](http://pyth.herokuapp.com/?code=%7BIeMrz8&test_suite=1&test_suite_input=3%0A51%0A44999911%0A123456789%0A222222222222222222222%0A818%0A8884443334%0A4545%0A554553%0A1234567891&debug=0).
[Answer]
# Ruby, 23 bytes
Anonymous function. Accepts a string. Regex strat.
```
->n{/(.)(?!\1).*\1/!~n}
```
**Regex breakdown**
```
/(.)(?!\1).*\1/
(.) # Match a character and save it to group 1
(?!\1) # Negative lookahead, match if next character isn't
# the same character from group 1
.* # Any number of matches
\1 # The same sequence as group 1
```
`!~` means if there are no matches of the regex within the string, return `true`, and otherwise return `false`.
[Answer]
# Mathematica, 26 bytes
```
0<##&@@Sort[#&@@@Split@#]&
```
[Answer]
# MATL, ~~13~~ 11 bytes
```
u"G@=fd2<vA
```
Thanks to *Luis Mendo* for saving two bytes!
[**Try it Online!**](http://matl.tryitonline.net/#code=dSJHQD1mZDI8dkE&input=JzEyMzQ1Njc4OTEn)
**Explanation**
```
% Grab the input implicitly
u % Find the unique characters
" % For each of the unique characters
G % Grab the input again
@= % Determine which chars equal the current char
f % Find the locations of these characters
d % Compute the difference between the locations
2< % Find all index differences < 2 (indicating consecutive chars)
v % Vertically concatenate all stack contents
A % Ensure that they are all true
% Implicit end of the for loop
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
i@ÞƑ
```
[Try it online!](https://tio.run/##bYyxDcJAEATrQdpk//bs/cwBTVAAgS03QAXENEAzltzW8SIhYbKVZme77/ujal2O9/mq6/G83KoCppGEbUkRIUh9QEKpBFsop9kdOWYG2j9@GkF6/G1@K31uGR8 "Jelly – Try It Online")
Semi-based on several of [DLosc's 5-byters](https://codegolf.stackexchange.com/a/251235/85334).
```
Ƒ The input is not changed by
√û sorting its elements by
i@ their first indices in the input.
```
Kind of like cutting the `F` out of `¹ƙ`F⁼`, but also kind of like cutting the ``ṢƑ` out of `iⱮ`ṢƑ.`
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
f l=(==)=<<scanl1 min$(<$>l).(==)<$>l
```
[Try it online!](https://tio.run/##bYs7DsMgEET7PcUWFKZBWu@SYMnkLsiyZRQgUbCV4xM7TZq8YjQfzRrqfU6ptQWT77zXfhzrFEoizLGoblS3pM05nK7lEAt6jGWbX2HaUOFeUixzRYM5PLu6Pt5m0Uf6to3BEogMB0RAPYu9XN0A/T/AkQPnnIgws4BYsWAPsfy70gc "Haskell – Try It Online")
Uses the same approach as [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/77665/20260): creates a vector for each entry which indices equal it, and checks that the result is sorted in decreasing order.
`(<$>l).(==)<$>l` is shorter version of `[map(==a)l|a<-l]`. The function `(<$>l).(==)` that takes `a` to `map(==a)l` is mapped onto `l`.
`scanl1 min` takes the cumulative smallest elements of `l`, which equals the original only if `l` is reverse-sorted. `(==)=<<` checks if the list is indeed invariant under this operation.
A recursive strategy also gave **37 bytes**:
```
f(h:t)=t==[]||f t>(elem h t&&h/=t!!0)
```
[Try it online!](https://tio.run/##bYtBCsIwEEX3c4opSEk31TQTTYV4EXERJCHFJIodcdO7x@LGjW/x4X140c03n1KtQcQjd5atPV@WJSCfhE8@Y0Ru27i13DS7rmY3FbQ4FfZPd2Xc4KukqfgZe8zuIeZ4f/ehW@37VgVaAtG4IiXIQZHeH8wIwz/ASAPGGCJSShGQJg16Ha1@qfwA "Haskell – Try It Online")
This checks each suffix to see if its first element doesn't appear in the remainder, excusing cases where the first two elements are equal as part of a contiguous block.
Other approaches:
**42 bytes**
```
f l=and[all(/=a)t|a:b:t<-scanr(:)[]l,a/=b]
```
[Try it online!](https://tio.run/##bYtBDoIwEEX3c4pZuIBEIaVTLcSehLAYECJxqIbWuPHulbhx41v85P3kXTncRpGUJhTH/tKySFY6zuObm76J50MY2K9Zk7ed7Ll0fZcWnj06nH0cVx4i7vDpZfZjwAIXfmThen8VU77Z900ajAKiekMpUJUmczzZGqp/gFUWrLVEpLUmIEMGzDZG/1L1AQ "Haskell – Try It Online")
**43 bytes**
```
import Data.List
((==)<*>nub).map nub.group
```
[Try it online!](https://tio.run/##bYu9DsIwEIP3e4obGFqGSGkukEoNEyMvEVBKI5ofNal4/BCxsPANlm3Zi8kvu661Op/iVvBqimE3lwvMuuu07qfjJez3nnmTsBn23OKeqjcuoEYXit3Mo@AB97C6YDMybMsuL/HN5r6lb1sFSA5EY4Nz4IMgeTqrEYZ/gOIKlFJEJIQgIEkSZBMpflf@AQ "Haskell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
)ġf⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwiKcShZuKBvCIsIiIsIltcIjNcIl1cbltcIjVcIiwgXCIxXCJdXG5bXCI0XCIsIFwiNFwiLCBcIjlcIiwgXCI5XCIsIFwiOVwiLCBcIjlcIiwgXCIxXCIsIFwiMVwiXVxuW1wiMVwiLCBcIjJcIiwgXCIzXCIsIFwiNFwiLCBcIjVcIiwgXCI2XCIsIFwiN1wiLCBcIjhcIiwgXCI5XCJdXG5bXCIyXCIsIFwiMlwiLCBcIjJcIiwgXCIyXCIsIFwiMlwiLCBcIjJcIiwgXCIyXCIsIFwiMlwiLCBcIjJcIiwgXCIyXCIsIFwiMlwiLCBcIjJcIiwgXCIyXCIsIFwiMlwiLCBcIjJcIiwgXCIyXCIsIFwiMlwiLCBcIjJcIiwgXCIyXCIsIFwiMlwiLCBcIjJcIl1cbltcIjhcIiwgXCIxXCIsIFwiOFwiXVxuW1wiOFwiLCBcIjhcIiwgXCI4XCIsIFwiNFwiLCBcIjRcIiwgXCI0XCIsIFwiM1wiLCBcIjNcIiwgXCIzXCIsIFwiNFwiXVxuW1wiNFwiLCBcIjVcIiwgXCI0XCIsIFwiNVwiXVxuW1wiNVwiLCBcIjVcIiwgXCI0XCIsIFwiNVwiLCBcIjVcIiwgXCIzXCJdXG5bXCIxXCIsIFwiMlwiLCBcIjNcIiwgXCI0XCIsIFwiNVwiLCBcIjZcIiwgXCI3XCIsIFwiOFwiLCBcIjlcIiwgXCIxXCJdIl0=)
Takes input as a list of singleton strings. Happens to be a different algorithm to the existing vyxal answer.
## Explained
```
)ġf⁼­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌­
)ƒ° # ‚Äé‚Å°Group by the identity function, by order of first appearance.
f # ‚Äé‚Å¢Flatten the list
⁼ # ‎⁣Does that equal the input?
üíé
```
[Answer]
## Haskell, 44 bytes
```
import Data.List
((==)<*>nub).map head.group
```
Usage example: `((==)<*>nub).map head.group $ "44999911"` -> `True`.
A non-pointfree version:
```
f x = q == nub q -- True if q equals q with duplicates removed
where
q = map head $ group x -- group identical digits and take the first
-- e.g. "44999911" -> ["44","9999","11"] -> "491"
-- e.g "3443311" -> ["3","44","33","11"] -> "3431"
```
[Answer]
# Python, 56 55 bytes
```
a=lambda s:~(s[0]in s.lstrip(s[0]))&a(s[1:])if s else 1
```
[Answer]
# C#, 119 bytes
```
bool m(String s){for(int i=0;i<9;i++){if(new Regex(i.ToString()+"+").Matches(s).Count>1){return false;}}return true;}
```
---
## Ungolfed
```
bool m(String s) {
for(int i=0;i<9;i++) {
if(new Regex(i.ToString() + "+").Matches(s).Count > 1) {
return false;
}
}
return true;
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
vḟÞṠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiduG4n8Oe4bmgIiwiIiwiXCIzXCJcblwiNTFcIlxuXCI0NDk5OTkxMVwiXG5cIjEyMzQ1Njc4OVwiXG5cIjIyMjIyMjIyMjIyMjIyMjIyMjIyMlwiXG5cIjgxOFwiXG5cIjg4ODQ0NDMzMzRcIlxuXCI0NTQ1XCJcblwiNTU0NTUzXCJcblwiMTIzNDU2Nzg5MVwiIl0=)
```
vḟ # Index of B in A, vectorized (B will be each individual character in the
# string / item in the list, and A will be the string/list itself)
√û·π† # Is the result sorted?
```
Answers that use this method, in chronological order:
* [Dennis – Python, 33 bytes](https://codegolf.stackexchange.com/a/77624/17216)
* [isaacg – Pyth, 5 bytes](https://codegolf.stackexchange.com/a/77635/17216)
* [Dennis - Julia, 30 bytes](https://codegolf.stackexchange.com/a/77640/17216)
* [Dennis - J, 8 bytes](https://codegolf.stackexchange.com/a/77705/17216)
* [DLosc – BQN, 5 bytes](https://codegolf.stackexchange.com/a/251233/17216)
* [DLosc – Jelly, 5 bytes](https://codegolf.stackexchange.com/a/251235/17216)
* [Unrelated String – Jelly, 4 bytes](https://codegolf.stackexchange.com/a/251241/17216)
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
‚Çå√û«ìU=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oKMw57Hk1U9IiwiIiwiXCIzXCJcblwiNTFcIlxuXCI0NDk5OTkxMVwiXG5cIjEyMzQ1Njc4OVwiXG5cIjIyMjIyMjIyMjIyMjIyMjIyMjIyMlwiXG5cIjgxOFwiXG5cIjg4ODQ0NDMzMzRcIlxuXCI0NTQ1XCJcblwiNTU0NTUzXCJcblwiMTIzNDU2Nzg5MVwiIl0=)
```
‚Çå # Parallel Apply - apply the following two elements to the input and keep
# both results on the stack.
√û«ì # Connected Uniquify - Remove occurences of adjacent duplicates.
U # Uniquify - Remove all duplicates.
= # Are the two results equal?
```
Turned out to be a port of [Adnan's 05AB1E answer](https://codegolf.stackexchange.com/a/77651/17216).
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~11~~ 10 bytes
-1 byte thanks to @ovs
```
~/,/'='^:\
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rT19FXt1WPs4rh4kpz0FEyVuJKUzI1BJEmJpZAYAhmGxoZm5iamVtYgjhG2IASly5QysLQAqTCwsLCxMTE2NjYBGyQqYkp2FggbWqMYpyhEgDXShno)
`^:` test for spaces - always returns 0s, as the input consists only of digits. The `:` here means monadic.
`^:\` repeat until convergence. This will return a pair of the original argument and a list of 0s of the same length as the argument.
`='` group each. To "group" a list means to make a dictionary that maps each distinct element of the list to the positions where it occurs.
`,/'` raze each, i.e. ignore the keys and concatenate the values. For the list of all 0s this will result in 0,1,...,length-1. For the other list, it will depend on the presence of non-continuous blocks - if there aren't any, the result will be 0,1,...,length-1 too.
`~/` do they match?
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~5~~ 4 bytes
```
≡ᵍc?
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/3DXzupHbRseNTU/6liuVFJUmqqnpPeoY4VSWmJOMZBd@3BXZ@3DrRP@P@pc@HBrb7L9///RxjoWhhY6poY6FhYWJiYmxsbGJjomJpZAYGioY2JqYqpjaGRsYmpmbmGpYwrkmhrrGGEDCGWGOgaGhhZAAywsDMHGWJobmRrHAgA "Brachylog – Try It Online")
*-1 thanks to DLosc*
Takes input as a list of digits through the input variable, and succeeds or fails as output.
```
≡ᵍ The input with identical elements grouped in order of first appearance
c with the groups concatenated
? is the input.
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 40 bytes
```
\[A|S]:-S=[];(S=[A|_];\+member(A,S)),\S.
```
[Try it online!](https://tio.run/##bYzBDoIwEETvfMUeMCmxkNRutWI81A/wwlGIQa1KUgqhGC/@O7bcTJzDvNnd7PRDZ7pH6t7NNJUn9SmqPC32p2pHvKvPudqVy1a3Fz0QRYskoWWRTQu4dwM8a3szjX3AqN0I19ppl0fxEfIUrKFgX@HrfO1u2pEjVQmFtu5N40bSm5cjKUq/UhQOHu@hGbWxJOTykE0xz6IoFiw44taLzZmtOIr1Rm7DsPqncJBMzpASETnnONcIFHOpp@A/ZSz7Ag "Prolog (SWI) – Try It Online")
-3 thanks to Jo King
Similar to xnor's second Haskell answer.
This won't work on TIO because it is too old of a version, and it's longer, but I think it's more interesting:
# [Prolog (SWI)](http://www.swi-prolog.org), 57 bytes
```
\A:-clumped(A,B),maplist([X-_,X]>>!,B,C),list_to_set(A,C).
```
[Answer]
# Julia, 35 bytes
```
s->issorted(s,by=x->findfirst(s,x))
```
For whatever reason, `sort` does not take a string, but `issorted` does...
[Answer]
# Factor, 22 bytes
```
[ dup natural-sort = ]
```
Does what it says on the tin. As an anonymouse function, you should `call` this, or make it a `: word ;`.
[Answer]
## Lua, ~~107~~ ~~94~~ 85 Bytes
**13 bytes saved thanks to @LeakyNun**
At least, it beats Java :D. Lua sucks at manipulating strings, but I think it is good enough :).
It takes its input as a command-line argument, ~~and outputs `1` for truthy cases and `false` for falsy ones.~~ Now outputs using its exit code. Exit code 0 for truthy, and 1 for falsy
```
o=os.exit;(...):gsub("(.)(.+)%1",function(a,b)if 0<#b:gsub(a,"")then o(1)end end)o(0)
```
### Ungolfed
Be care, there's two magic-variables called `...`, the first one contains the argument of the program, the second one is local to the anonymous function and contains its parameters
```
o=os.exit; -- ; mandatory, else it would exit instantly
(...):gsub("(.)(.+)%1", -- iterate over each group of the form x.*x and apply an anonymous
function(a,b) -- function that takes the captured group as parameters
if 0<#b:gsub(a,"") -- if the captured group (.+) contain other character than
then -- the one captured by (.)
o(1) -- exit with falsy
end
end)
o(0) -- exit with truthy, reached only when the string is okay
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 18 bytes
```
Gather@#==Split@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8dJFTkoGxrG1yQk1nioKz2X0HfQaG62rhWR6HaVMcQRJnomOhYQqEhRMhQx0jHGChsqmOmY65joWMJEjTSIRLW6nApgEC1BdA8C5BWCx0QNAFDYzA0gdhsCrIE4hYwEwiNsToA6K7a2P8A "Wolfram Language (Mathematica) – Try It Online")
`Gather` gathers a list into sublists of identical elements, and `Split` splits a list into sublists of consecutive identical elements. They give the same result if and only if each value appears in only one contiguous block.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~9~~ 5 bytes
```
≡⟜∧⊐˜
```
Anonymous tacit function. Takes a string or a list of integers. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4omh4p+c4oin4oqQy5wKCkYg4p+oNCw0LDksOSw5LDksMSwx4p+pCg==)
### Explanation
Inspired by [Dennis's J answer](https://codegolf.stackexchange.com/a/77705/16766), though the details are a bit different.
Given two lists, `‚äê` works as follows: for each element of its right argument, it finds the first index of that value in its left argument.
We're using `⊐˜`, which passes the same list as both left and right arguments. The result is a list, for each digit, of the index of that digit's first occurrence.
If the digits are grouped together, these indices will occur in ascending order. However, if some copies of digit A are separated by digit B, B's (larger) index will come between the copies of A's (smaller) index.
```
≡⟜∧⊐˜
⊐˜ First index of each digit in the argument list
≡⟜ The result is identical to
‚àß The result, sorted ascending
```
] |
[Question]
[
This is different from [My Word can beat up your Word](https://codegolf.stackexchange.com/questions/1128/my-word-can-beat-up-your-word) as it is less complex and only requires you to calculate it, and not compare them.
To find the digital root, take all of the digits of a number, add them, and repeat until you get a one-digit number. For example, if the number was `12345`, you would add `1`, `2`, `3`, `4`, and `5`, getting `15`. You would then add `1` and `5`, giving you `6`.
### Your task
Given an integer ***N*** (0 <= ***N*** <= 10000) through **STDIN**, print the digital root of ***N***.
### Test cases
```
1 -> 1
45 -> 9
341 -> 8
6801 -> 6
59613 -> 6
495106 -> 7
```
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]
## Pyke, 1 byte
```
s
```
[Try it here!](http://pyke.catbus.co.uk/?code=s&input=495106)
Takes the digital root of the input
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7 5 4~~ 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḃ9Ṫ
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=4biDOeG5qg&input=&args=NTk2MTM)** or [all test cases](http://jelly.tryitonline.net/#code=4biDOeG5qgrFvMOH4oKsRw&input=&args=WzEsMTgsNDUsMzQxLDY4MDEsNTk2MTMsNDk1MTA2XQ)
### How?
The [digital root](http://mathworld.wolfram.com/DigitalRoot.html) is known to obey the formula (n-1)%9+1.
This is the same as the last digit in bijective base 9
(and due to implementation that `0ḃ9=[]` and `[]Ṫ=0` this handles the edge-case of zero).
```
ḃ9Ṫ - Main link: n
ḃ9 - convert to bijective base 9 digits (a list)
Ṫ - tail (get the last digit)
```
[Answer]
# JavaScript (ES6), ~~16~~ 10 bytes
```
n=>--n%9+1
```
Test cases
```
let f =
n=>--n%9+1
console.log(f(1)); // -> 1
console.log(f(45)); // -> 9
console.log(f(341)); // -> 8
console.log(f(6801)); // -> 6
console.log(f(59613)); // -> 6
console.log(f(495106)); // -> 7
```
[Answer]
# Python, ~~16~~ 20 bytes
+4 bytes to handle edge case of zero.
```
lambda n:n and~-n%9+1
```
**[repl.it](https://repl.it/EHnu/2)**
[Answer]
# [MATL](http://github.com/lmendo/MATL), 3 bytes
```
9X\
```
[Try it online!](http://matl.tryitonline.net/#code=OVhc&input=WzEgNDUgMzQxIDY4MDEgNTk2MTMgNDk1MTA2XQ)
A lot of (now deleted answers) tried using modulo 9 to get the result. This is a great shortcut, but unfortunately does not work for multiples of 9. MATL has a function for modulo on the interval `[1, n]`. Using this modulo, we have `1 % 3 == 1, 2 % 3 == 2, 3 % 3 == 3, 4 % 3 == 1`, etc. This answer simply takes the input modulo nine using this custom modulo.
[Answer]
## Mathematica, ~~27~~ 11 bytes
```
Mod[#,9,1]&
```
Mathematica's `Mod` takes a third parameter as an offset of the resulting range of the modulo. This avoids decrementing the input and incrementing the output.
[Answer]
## Julia, 12 bytes
```
!n=mod1(n,9)
```
or
```
n->mod1(n,9)
```
`mod1` is an alternative to `mod` which maps to the range `[1, n]` instead of `[0, n)`.
[Answer]
# PHP, 15 Bytes
```
<?=--$argn%9+1;
```
Previous version PHP, 55 Bytes
```
$n=$argn;while($n>9)$n=array_sum(Str_split($n));echo$n;
```
[Answer]
# R, 72 67 29 bytes
Edit: Thanks to @rturnbull for shaving off two bytes.
```
n=scan();`if`(n%%9|!n,n%%9,9)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 7 bytes
```
{`.
*
.
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8L86QY9Li0vv/39DLhNTLmMTQy4zCwNDLlNLM0NjLhNLU0MDMwA "Retina – Try It Online")
I see lots of mathematical solutions, but in Retina the straightforward approach seems to be the best one.
### Explanation
`{`` makes the whole program run in a loop until the string doesn't change anymore. The loop consists of two stages:
```
.
*
```
Convert each digit to unary.
```
.
```
Count the number of characters (=convert the unary number to decimal).
This works because converting each digit to unary with no separator between digits creates a single unary number which is equal to the sum of all digits.
[Answer]
# Haskell, ~~35~~ 34 bytes
```
until(<10)$sum.map(read.pure).show
```
[Try it on Ideone.](http://ideone.com/lm3Tma)
**Explanation:**
```
until(<10)$sum.map(read.pure).show
show -- convert int to string
map( ). -- turn each char (digit) into
pure -- a string
read. -- and then a number
sum. -- sum up the list of numbers
until(<10)$ -- repeat until the result is < 10
```
[Answer]
# Perl, 15 bytes
Includes +2 for `-lp`
Give input on STDIN
```
root.pl <<< 123
```
`root.pl`
```
#!/usr/bin/perl -lp
$_&&=~-$_%9+1
```
This is the boring solution that has already been given in many languages, but at least this version supports `0` too
More interesting doing real repeated additions (though in another order) is in fact only 1 byte longer:
```
#!/usr/bin/perl -p
s%%$_+=chop%reg
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
### Recursive method (4 bytes) (Credit to @ovs)
```
ωoΣd
```
```
# implicit parameter ⁰ (refers to the last parameter)
d # list of digits in base 10
Σd # sum of list
oΣd # compose the two functions
ωoΣd # repeat until the function returns the same result as the previous one
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f/5zvxzi1P@//8fbahjYqpjbGKoY2ZhYKhjamlmaKxjYmlqaGAWCwA)
### Modulus method (4 bytes)
```
→%9←
```
```
# implicit parameter ⁰ (refers to the last parameter)
← # previous number (n - 1)
%9← # modulus by 9
→%9← # next number (n + 1)
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@jtkmqlo/aJvz//z/aUMfEVMfYxFDHzMLAUMfU0szQWMfE0tTQwCwWAA)
[Answer]
## Java 7, 63 bytes
```
int f(int n){int s=0;for(;n>0;n/=10)s+=n%10;return s>9?f(s):s;}
```
Recursive function which just gets digits with mod/div. Nothing fancy.
## Cheap port
of [Jonathan Allan's](https://codegolf.stackexchange.com/a/97730/14215) would be a measly 28 bytes:
```
int f(int n){return~-n%9+1;}
```
[Answer]
## [Labyrinth](https://github.com/m-ender/labyrinth), 8 bytes
```
?(_9%)!@
```
using the equation `(n-1)%9+1`:
* `?` reads the input as decimal and pushes it to the stack
* `(` decrements the top of the stack
* `_` pushes a zero onto the top of the stack
* `9` push the top of the stack popped times 10 the digit (in this case, 9)
* `%` pops y, pops x, pushes x%y
* `)` increments the top of the stack
* `!` pops the top of the stack and out puts it as a decimal string
* `@` terminates the program
[Answer]
## Hexagony, ~~19~~ 15 bytes
```
.?<9{(/>!@!/)%'
```
More Readable:
```
. ? <
9 { ( /
> ! @ ! /
) % ' .
. . .
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/19BQU/BXsFGgUvBUqFaQUNBn8tOQVHBAYj1gWKaCqoK6gp6XCBVQPj/v4mlqaGBGQA)
-3 bytes by taking a different approach, making the 0 edge case trivial.
-1 byte by fixing 0 edge case bug
Using the formula ((n-1) mod 9) + 1 like a lot of other solutions aswell.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Æ=ìx
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=xj3seA&input=NjgwMQ)
```
Æ=ìx :Implicit input of integer U
Æ :Map the range [0,U)
= : Reassign to U
ì : Convert to digit array
x : Reduce by addition
:Implicit output of last element
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 9 bytes
```
#0|@e+:0&
```
[Try it online!](http://brachylog.tryitonline.net/#code=IzB8QGUrOjAm&input=NDk1MTA2&args=Wg)
### Explanation
```
#0 Input = Output = a digit
| OR
@e Split the input into a list of digits
+ Sum
:0& Call this predicate recursively
```
### Alternative approach, 11 bytes
[```
:I:{@e+}i#0
```](http://brachylog.tryitonline.net/#code=Okk6e0BlK31pIzA&input=NDk1MTA2&args=Wg)
This one uses the meta-predicate `i - Iterate` to call `I` times the predicate `{@e+}` on the input. This will try values of `I` from `0` to infinity until one makes it so that the output of `i` is a single digit which makes `#0` true.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes
```
[SODg#
```
[Try it online!](http://05ab1e.tryitonline.net/#code=W1NPRGcj&input=NDk1MTA2)
**Explanation**
```
[ # infinite loop
S # split into digits
O # sum digits
Dg# # if length == 1: break
```
[Answer]
## Ruby, 12 bytes
```
->n{~-n%9+1}
```
[Answer]
## JavaScript (ES6), ~~41~~ 38 bytes
*Saved 3 bytes, thanks to Bassdrop Cumberwubwubwub*
Takes and returns a string.
```
f=s=>s[1]?f(''+eval([...s].join`+`)):s
```
### Test cases
```
f=s=>s[1]?f(''+eval([...s].join`+`)):s
console.log(f("1")); // -> 1
console.log(f("45")); // -> 9
console.log(f("341")); // -> 8
console.log(f("6801")); // -> 6
console.log(f("59613")); // -> 6
console.log(f("495106")); // -> 7
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam/), ~~19~~ 13 bytes
```
r{:~:+_s\9>}g
```
[Interpreter](http://cjam.aditsu.net/#code=r%7B%3A%7E%3A%2B_s%5C9%3E%7Dg&input=12345)
Explanation:
```
r{:~:+_s\9>}g Code
r Get token
{:~:+_s\9>} Block: :~:+_s\9>
~ Eval
: Map
+ Add
: Map
_ Duplicate
s Convert to string
\ Swap
9 9
> Greater than
g Do while (pop)
```
Thanks to 8478 (Martin Ender) for -6 bytes.
---
# CJam, 6 bytes
```
ri(9%)
```
Suggested by 8478 (Martin Ender). [Interpreter](//cjam.aditsu.net#code=ri(9%25)&input=12345)
I was thinking about it, but Martin just got it before me. Explanation:
```
ri(9%) Code
r Get token
i Convert to integer
( Decrement
9 9
% Modulo
) Increment
```
[Answer]
# [Factor](https://factorcode.org), 24
*Smart*, *mathy* answer.
```
[ neg bitnot 9 mod 1 + ]
```
**63** for dumb iterative solution:
```
[ [ dup 9 > ] [ number>string >array [ 48 - ] map sum ] while ]
```
[Answer]
# J, 8 bytes
```
**1+9|<:
```
Uses the formula `d(n) = ((n-1) mod 9) + 1` with the case `d(0) = 0`.
## Usage
```
f =: **1+9|<:
(,.f"0) 0 1 45 341 6801 59613 495106
0 0
1 1
45 9
341 8
6801 6
59613 6
495106 7
```
## Explanation
```
**1+9|<: Input: integer n
<: Decrement n
9| Take it modulo 9
1+ Add 1 to it
* Sign(n) = 0 if n = 0, else 1
* Multiply and return
```
[Answer]
# Pyth - ~~7~~ ~~4~~ ~~6~~ 7 bytes
Not the best one, but still beats a decent amount of answers:
```
|ejQ9 9
```
Like the previous version, but handling also cases of multiples of 9, using logical or.
---
**This version fails the 45 testcase**:
```
ejQ9
```
**Explanation:**
```
jQ9 -> converting the input to base 9
e -> taking the last digit
```
[Try it here](https://pyth.herokuapp.com/?code=%26Qh%25tQ9&input=495106&debug=0)
[Try the previous version here!](https://pyth.herokuapp.com/?code=ejQ9&input=495106&debug=0)
---
**Previous solutions:**
```
&Qh%tQ9
```
**Explanation**:
```
tQ -> tail: Q-1
%tQ9 -> Modulo: (Q-1)%9
h%tQ9 -> head: (Q-1)%9+1
&Qh%tQ9 -> Logical 'and' - takes the first null value. If Q is 0 - returns zero, otherwise returns the (Q-1)%9+1 expression result
```
You're invited to [try it here](https://pyth.herokuapp.com/?code=%26Qh%25tQ9&input=495106&debug=0)!
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~15~~ 9 bytes bytes
```
××1+9|-∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TD0w9PN9S2rNF91DHDECikYMCVpmAIxCamQMLYBMQ0szAAUaaWZobGIBlLU0MDMwA "APL (Dyalog Unicode) – Try It Online")
[Answer]
## Python 2, 54 51 bytes
```
i=input()
while~-len(i):i=`sum(map(int,i))`
print i
```
Thanks to Oliver and Karl Napf for helping me save 3 bytes
[Answer]
# Python, 45 bytes
```
f=lambda x:x[1:]and f(`sum(map(int,x))`)or x
```
Takes the argument as a string.
[Answer]
# C, ~~64~~ 29 bytes
C port from [Jonathan Allan](https://codegolf.stackexchange.com/a/97730/53667)'s answer (with special case 0).
```
f(i){return i>0?~-i%9+1:0;}
```
Previous 64 byte code:
```
q(i){return i>9?i%10+q(i/10):i;}
f(i){i=q(i);return i>9?f(i):i;}
```
`q` takes the cross sum and `f` repeats taking the cross sum until a single digit.
[Answer]
# [Retina](http://github.com/mbuettner/retina), 15 bytes
```
.+
$*
1{9}\B
1
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYAouKwokKgoxezl9XEIKCjE&input=MQo0NQozNDEKNjgwMQ) (The first line enables a linefeed-separated test suite.)
### Explanation
```
.+
$*
```
Convert input to unary.
```
(1{9})*\B
```
Take 1-based modulo by removing nines that have at least one more character after them.
```
1
```
Count the remaining number of 1s to convert back to decimal.
] |
[Question]
[
Inspired by [I'm not the language you're looking for!](https://codegolf.stackexchange.com/questions/55960/im-not-the-language-youre-looking-for)
# Challenge
Choose two different programming languages, and write a program that prints the following line to stdout (or equivalent):
```
This program errors out in <the current language> :P
```
and then generates different kind of error in each of the two languages.
# Rules
Some rules are taken from the original challenge.
* In the output, language names should exactly follow:
+ The name listed on [TIO](https://tio.run/#), optionally excluding the version number and/or the implementation name (e.g. if you use `JavaScript (Node.js)` as one of your languages, you can use `JavaScript` for your language name, but not `JS` or `Javascript`.)
+ The full name on the official website (or GitHub repo) if your language of choice is not available on TIO.
* Neither program should take any input from the user.
* You may use comments in either language.
* Two different versions of the same language count as different languages.
+ If this is done, the program should output the major version number, and if running on two different minor versions, should report the minor version also.
+ You should not use prebuilt version functions (this includes variables that have already been evaluated at runtime).
* **Two different command line flags in the same language also count as different languages** as per [this meta consensus](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends), as long as the flags don't include code fragments (such as `-Dblahblah...` in C).
+ If this is done, the program should also output the flag used.
* Two errors are considered different unless both errors are generated by the same semantics (such as "division by zero", "segmentation fault", or "index out of range").
+ If a language's runtime does not exit after an error, but reports the error in some way to the user, it's a valid error.
+ If a language does not discriminate the error messages but has a known list of reasons that cause error, **you must specify the reason, not the error message.**
An example is `><>`, which has only one error message `something smells fishy...`, but [esolangs wiki page](https://esolangs.org/wiki/Fish#Errors) has a list of error reasons.
* Syntax error is not allowed unless it is generated by calling `eval()` or similar.
* Throwing something manually (via `throw`(JS), `raise`(Python), `die`(Perl) or similar) is allowed, but all of them are considered as one kind of error.
* Error by invalid command in 2D or golflangs is also allowed (and treated as one kind of error).
# Examples
### Python and Ruby
* Python: `This program errors out in Python :P` to stdout, then undefined identifier
* Ruby: `This program errors out in Ruby :P` to stdout, then index out of bounds
### C89 and C99
* C89: `This program errors out in C 89 :P` to stdout, then division by zero
* C99: `This program errors out in C 99 :P` to stdout, then segmentation fault
Note that the version number should *always* be separated from the language name by a space.
### Python 2.7.9 and Python 2.7.10
* Python 2.7.9: `This program errors out in Python 2.7.9 :P` to stdout, then syntax error on eval
* Python 2.7.10: `This program errors out in Python 2.7.10 :P` to stdout, then key error on dict
### Perl and Perl `-n`
* Perl: `This program errors out in Perl :P` to stdout, then invalid time format
* Perl `-n`: `This program errors out in Perl -n :P` to stdout, then try to open a file that doesn't exist
# Winning condition
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. But you're always encouraged to post an answer that is fun or interesting even if it isn't very short.
[Answer]
# [Python 2](https://docs.python.org/2/) / [Python 3](https://docs.python.org/3/), 60 bytes
```
print("This program errors out in Python %d :P"%(3/2*2))*1;a
```
* Python 2 got `NameError: name 'a' is not defined`
* Python 3 got `unsupported operand type(s) for *: 'NoneType' and 'int'`
**Python 2:**
* `/` is integer division, 3 / 2 got 1; int(3 / 2 \* 2) is 2.
* print is a statement, so the first statement read as `print((...)*1)`, here `*1` means repeating the string once.
* second statement referenced a non-existing variable, which caused the error.
* [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQykkI7NYoaAoP70oMVchtagov6hYIb@0RCEzTyEArFRBNUXBKkBJVcNY30jLSFNTy9A68f9/AA "Python 2 – Try It Online")
**Python 3:**
* '/' is floating number division, 3 / 2 got 1.5; int(3 / 2 \* 2) is 3.
* print is a function, so the first statement read as `(print(...))*1`.
* function `print` returns `None`; Multiplication do not work on `None x int`, so it report "unsupported operand".
* [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQykkI7NYoaAoP70oMVchtagov6hYIb@0RCEzTyEArFRBNUXBKkBJVcNY30jLSFNTy9A68f9/AA "Python 3 – Try It Online")
[Answer]
# C and C++, ~~114~~ 101 bytes
*-13 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)!*
```
#include<stdio.h>
main(){auto d=.5;printf("This program errors out in C%s :P",d?"++":"");2[&d]+=1/d;}
```
Segmentation fault in C++, floating point exception in C.
`auto` is defaulted to `int` in C so `(int).5` becomes `0`, so trying to divide by it is basically division by zero.
In C++ `1/d` is 2, adding it to address of `d` and trying to change that address' value throws a segfault.
[Try it in C++!](https://tio.run/##Sy4o0E1PTv7/XzkzLzmnNCXVprgkJTNfL8OOKzcxM09DszqxtCRfIcVWz9S6oCgzryRNQykkI7NYoaAoP70oMVchtagov6hYIb@0RCEzT8FZtVjBKkBJJ8VeSVtbyUpJSdPaKFotJVbb1lA/xbr2/38A)
[Try it in C!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/Djis3MTNPQ7M6sbQkXyHFVs/UuqAoM68kTUMpJCOzWKGgKD@9KDFXIbWoKL@oWCG/tEQhM0/BWbVYwSpASSfFXklbW8lKSUnT2ihaLSVW29ZQP8W69v9/AA)
[Answer]
# JavaScript + HTML / HTML + JavaScript, 160 bytes
```
<!--
document.write`This program errors out in JavaScript + HTML :P`()
--><script>document.write`This program errors out in HTML + JavaScript :P`+X</script>
```
```
<!--
document.write`This program errors out in JavaScript + HTML :P`()
--><script>document.write`This program errors out in HTML + JavaScript :P`+X</script>
```
Not sure if this count two languages, but it is funny.
[Answer]
# [><>](https://esolangs.org/wiki/Fish) and [Foo](https://esolangs.org/wiki/Foo), 42 bytes
```
#o<"This code errors in "p"Foo"'><>'" :P"/
```
[Try it in ><>!](https://tio.run/##S8sszvj/XznfRikkI7NYITk/JVUhtagov6hYITNPQalAyS0/X0ndzsZOXUnBKkBJ//9/AA "><> – Try It Online")
[Try it in Foo!](https://tio.run/##S8vP//9fOd9GKSQjs1ghOT8lVSG1qCi/qFghM09BqUDJLT9fSd3Oxk5dScEqQEn//38A "Foo – Try It Online")
Foo prints everything in `"`, as is well documented, and tries to divide by zero at the end. It ignores the `'><>'`.
`><>` pushes the "Foo" to the stack, but immediately pops it using `p`. After it prints everything to the stack with `#o<` it exits when the the stack is empty with the only error message it knows, `something smells fishy...`
[Answer]
# Java 8 & C99, 172 bytes
```
//\
interface a{static void main(String[]a){System.out.print("This program errors out in Java 8 :P");a[1]=""/*
main(n){{n=puts("This program errors out in C99 :P")/0/**/;}}
```
Based on my answer for the [*'abc' and 'cba'* challenge](https://codegolf.stackexchange.com/a/138416/52210).
[Try it in Java 8 - resulting in *ArrayIndexOutOfBoundsException: 1*.](https://tio.run/##fY29DoIwFEZ3nuKmE5BIdRMJk5uTCW7IcAMVi@lP2guJaXj2SngA1@/knG/CBQ/GCj0Nnxg5fyZSk3Av7AVg8IQke1iMHECh1GlDTuqx7TALzdeTUIWZqbDbSCl7vKUH68zoUIFwzjgPGwap4bbdwBkud5ZV2J66mjGeJ3tSZyHo2s7k/xauZbnr/MjznFfrGuMP)
[Try it in C - resulting in *Floating point exception: division by zero is undefined*.](https://tio.run/##fYyxCoMwFAB3v@KRSYWadqsVp26dCnazDo80tQ80keQplOC3p@IHdL3jTh3UgKaPUcpnQoa1e6PSgMEzMilYLL1gRDJpw45M33aYhebrWY@FnbmYNsipeHzIw@Rs73AE7Zx1HjYNZOCGC8IZLneRVdieuloImSf70mQhmHqa2f89XMtyz@VR5rms1jXGHw)
**Explanation:**
```
//\
interface a{static void main(String[]a){System.out.print("This program errors out in Java 8 :P");a[1]=""/*
main(n){{n=puts("This program errors out in C99 :P")/0/**/;}}
```
As you can see in the Java-highlighted code above, the first line is a comment due to `//`, and the C-code is a comment due to `/* ... */`, resulting in:
```
interface a{static void main(String[]a){System.out.print("This program errors out in Java 8 :P");a[1]="";}}
```
So it prints to STDOUT, and then tries to access the second program-argument (when none given), so it produces the *ArrayIndexOutOfBoundsException*.
---
```
//\
interface a{static void main(String[]a){System.out.print("This program errors out in Java 8 :P");a[1]=""/*
main(n){{n=puts("This program errors out in C99 :P")/0/**/;}}
```
Not sure how to correctly enable C-highlighting, because `lang-c` results in the same highlighting as Java.. But `//\` will comment out the next line, which is the Java-code, resulting in:
```
main(n){{n=puts("This program errors out in C99 :P")/0;}}
```
So it prins to STDOUT, and then gives a division by zero error.
[Answer]
# Java 8 & [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~439~~ ~~431~~ ~~428~~ 408 bytes
```
interface a{static void main(String[]a){System.out.print("This program errors out"+
" in Java 8 :P");a[0]="";}}
```
[Try it in Java 8 - resulting in *ArrayIndexOutOfBoundsException: 0*.](https://tio.run/##XVBBCsIwEDwnr1hyqojFoyh@wJNQb9LDorFGaVLSKEjp2@uabms1OWR2ZjLZ7A2fuHCVtrfzvesARFwyAqAdUU/3UACLfMY6@mDggDkYcuQkgExUiyj3wmiK5PcmcHYvTF7gYkBsHRI49bc9shkbtL/gSQM2dcBgTuLpzFmUaGySBW9sccxx1mSvOugydY@QVkSGRB2upobKu8JjCdp752sgWc2lolTY0QhhBeu9mm3wuMy3Sm3a9tun4L5@ZvQ/FAISxq98eMFjpQ/KrnsD)
[Try it in Whitespace - resulting in *user error (Can't do Infix Plus)*.](https://tio.run/##XVAxDsIwDJyTV1iZWiFVjIiKDzAhlQ0xWBBohjZVEooQ4u3FJG4ppEPOd5er7XttgvYdnvQwAIh4ZARAX0SJTlAAi3zHOvpg5IA5GHPkLIBMVIsoJ2EyRfL7Ejg7CbM/cDEito4JnPrbHtlMG7S70JiATx8wmJPorTmLBk2bVcGZ9no4Yv6sHj7oprC3UHREhkzta@Ohc/bqsAHtnHUeSFYLqSgVttgjrGC9U3mJh@Vxo1T5en37FNzXz47@l0JAwjTKhxe8VhpQDsMb)
### Explanation:
**Java 8:**
```
interface a{static void main(String[]a){System.out.print("This program errors out"+
" in Java 8 :P");a[0]="";}}
```
So it prints to STDOUT, and then tries to access the first program-argument (when none given), so it produces the *ArrayIndexOutOfBoundsException*.
---
**Whitespace:**
```
[S S T T T T T T N
_Push_-31_P][S S T T T S T S T N
_Push_-53_:][S S T T S S T T T T N
_Push_-79_space][S S T T S T S N
_Push_-10_e][S S T T T S S N
_Push_-12_c][S S T T T T S N
_Push_-14_a][S S S T N
_Push_1_p][S S S T S S N
_Push_4_s][S S T T S T S N
_Push_-10_e][S S S T S T N
_Push_5_t][S S T T T S N
_Push_-6_i][S S T T T T N
_Push_-7_h][S S T T T S S S N
_Push_-24_W][S T S S T S T S N
_Copy_0-based_10th_(-79_space)][S S T T N
_Push_-1_n][S S T T T S N
_Push_-6_i][S T S S T S N
_Copy_0-based_2nd_(-79_space)][S S S T S T N
_Push_5_t][S S S T T S N
_Push_6_u][S S S N
_Push_0_o][S T S S T T N
_Copy_0-based_3rd_(-79_space)][S S S T S S N
_Push_4_s][S S S T T N
_Push_3_r][S S S N
_Push_0_o][S S S T T N
_Push_3_r][S N
S _Duplicate_top_(3_r)][S S T T S T S N
_Push_-10_e][S T S S T T S N
_Copy_0-based_6th_(-79_space)][S S T T S N
_Push_-2_m][S S T T T T S N
_Push_-14_a][S S S T T N
_Push_3_r][S S T T S S S N
_Push_-8_g][S S S S (_Note_the_additional_S_here)N
_Push_0_o][S S S T T N
_Push_3_r][S S S T N
_Push_1_p][S T S S T T T N
_Copy_0-based_7th_(-79_space)][S S S T S S N
_Push_4_s][S S T T T S N
_Push_-6_i][S S T T T T N
_Push_-7_h][S S T T T S T T N
_Push_-27_T][N
S S N
_Create_Label_LOOP][S S S T T S T T T T N
_Push_111][T S S S _Add][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try this highlighted version.](https://tio.run/##nVNNa4NAED03v8Jjcgi4mo@2t9KeSjCCgR6CPDa6dIVERVdKf73NRnR3jSahyCL6Zua9NzP7wxPBypxGrK73gRVYuyf1eBP4Vckxdwn8UIPlW54uYOniVQXodbqQ9QsuPHqYPF0AscFMEh10EIWGQB1cgDagLoogVz/1YguUD4joe1xCmOq6nBUSU5ryDN53pOU5C3xJuG1YJ@U9y39hzw@0ZDGILTimXftmqqASjfS2NMXQr@6k8XXxUetty1pghaoF2l82Mp3xUsRgdItRxoERmU5dFCN8I5HeJLDwUeXHJKKCQWQ5pmdodnf@Sv91z1ZjA9Fni9OD6zrgbmBXnvHdpgTWFF4m3XAGGseJSLKUHhGAs4LNHmvM4FXRb27f9HrI9M2b9d87YqDOGrtwL8fYzKFgco4bemBHbLZb39zLfnFCSLhve4m3OJZfTTH4RZIK0BIRpwWNBCsaHm9yzv6sTvl5W3Siuv4D)
Whitespace is a stack-based language that ignores everything except for spaces, tabs and new-lines. Here is the same program in pseudo-code:
```
Push all unicode values of "P: ecapsetihW tuo srorre margorp sihT", minus 111
Start LOOP
Push 111
Add the top two stack values together
Print as character
Go to the next iteration of the LOOP
```
It will error as soon as it's done printing all values and the stack is empty when it tries to do the *Add* (`TSSS`), which requires two items on the stack.
I've generated the constant `111` with [this Java program](https://tio.run/##fVLva9swEP3ev@K4TxJKTQYrY3ZEaWEfDMsYc/YDujJkV3XUObInXQJh5G/35NqOk230i4Tu3T3dvXdPaqcunx5@tm1RKe9hqYz9fQHQbPPKFOBJUbh2tXmATYBYRs7Y8u4eFO/SAPoAOO23FYEEdTe/T54RYwn8RlWV9h2QWtKldtHy5tuPLzfvP7@bQSrfXCWnLGP6p5ENsccfa8c6PiPTxCxeXc0TI8TQwdSDRJzRrJFjVV@X70lDHvcdRqWm2xDwjB/LAUgG8lX9dW0C0qhC3xqr3L7nZfml4ckx10lGkf61VZVnDb/G7MN3m2FMXLgpqZE0Pg7DbR6ZiyptS1ozDovjrCdt/DP@CeOJkhPNBKchbs6/7M9s70lvonpLUROmocoy7MslipFUYBKkRZEKhBhQvKRGyodv/2Zm5@0/Zx0uwjEs0eDSS9ydxXYQZKdc8AWzDAWzi/k1rjDGDPn5QhTxuFdUn1F1KF8qWkcq98xy/j/nSchi8fptMDFwr4at6XVzmrbOhgwM/mI/y6Ft29XaeGhcXTq1Ae1c7TwECcJYMA0F8cc/), which I've also used for previous ASCII-related challenges I've made in Whitespace. In addition, I've used some copies for the spaces to save bytes.
One important thing to note is the trick I've used to place the Java program within the Whitespace answer. Let me start by explaining how a number is pushed in Whitespace:
`S` at the start: Enable Stack Manipulation;
`S`: Push what follows as Number;
`S` or `T`: Positive or Negative respectively;
Some `S` and/or `T`, followed by an `N`: Number as binary, where `T=1` and `S=0`.
Here some examples:
* Pushing the value 1 will be `SSSTN`;
* Pushing the value -1 will be `SSTTN`;
* Pushing the value 111 will be `SSSTTSTTTTN`.
* Pushing the value 0 can be `SSSSN`, `SSTSN`, `SSSN`, `SSTN`, `SSSSSSSSSSSSN`, etc. (When you use `SSSN` (or `SSTN`), we don't have to specify the binary part, because it's implicitly 0 after we've stated its sign.)
So just `SSSN` is enough for pushing the value `0` (used for the letter `o` in this case). But, to place the Java program in this golfed Whitespace program, I needed an additional space, so the first two `o`s are pushed with `SSSN`, but the third one is pushed with `SSSSN`, so we have enough spaces for the sentence of the Java program.
[Answer]
# [CBM BASIC](https://www.c64-wiki.com/wiki/BASIC#CBM_BASIC) and [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 142 144 bytes
*Had to add 2 bytes after realizing a syntax error wasn't allowed ....*
---
Hexdump of `.prg` file:
```
01 08 50 08 00 00 8F 5A 49 52 49 41 A9 17 8D 18 D0 A2 30 BD 30 08 20 D2 FF E8
E0 4B D0 F5 A2 30 BD 05 08 20 D2 FF E8 E0 44 D0 F5 A9 0D 20 D2 FF A2 1A 4C 37
A4 22 36 35 30 32 20 4D 41 43 48 49 4E 45 20 43 4F 44 45 20 3A D0 22 20 20 20
20 20 00 8D 08 01 00 97 35 33 32 37 32 2C 32 33 3A 99 22 D4 48 49 53 20 50 52
4F 47 52 41 4D 20 45 52 52 4F 52 53 20 4F 55 54 20 49 4E 20 C3 C2 CD 2D C2 C1
D3 C9 C3 20 3A D0 22 2C 58 AD 50 00 00 00
```
---
**The CBM BASIC view**, as listed in the C64's editor:
```
0 remziriastepgosubinput#new0exp0 dim.clrsavekinput#stepnew0exp<white> dim.clrsavedinput#stepstep
dim.newl7to"6502 machine code :P"
1 poke53272,23:print"This program errors out in CBM-BASIC :P",x/p
```
[](https://i.stack.imgur.com/s7Ujz.png)
**Attention**: It's impossible to correctly enter this program in the BASIC editor. Don't even **try to *edit*** this program in the BASIC editor, it will crash. Still, it's a runnable BASIC program ;)
---
**The 6502 machine code view**:
```
01 08 ; load address
.C:0801 50 08 BVC $080B ; jump to real start of mc
; line number (00 00), REM (8F) and "ziria"
.C:0803 00 00 8F 5A 49 52 49 41
.C:080b A9 17 LDA #$17
.C:080d 8D 18 D0 STA $D018 ; set upper/lower font
.C:0810 A2 30 LDX #$30
.C:0812 BD 30 08 LDA $0830,X
.C:0815 20 D2 FF JSR $FFD2 ; print "This program errors ..."
.C:0818 E8 INX
.C:0819 E0 4B CPX #$4B
.C:081b D0 F5 BNE $0812
.C:081d A2 30 LDX #$30
.C:081f BD 05 08 LDA $0805,X
.C:0822 20 D2 FF JSR $FFD2 ; print "6502 machine code :P"
.C:0825 E8 INX
.C:0826 E0 44 CPX #$44
.C:0828 D0 F5 BNE $081F
.C:082a A9 0D LDA #$0D
.C:082c 20 D2 FF JSR $FFD2 ; print a newline
.C:082f A2 1A LDX #$1A ; error code for "can't continue"
.C:0831 4C 37 A4 JMP $A437 ; jump to error handling routine
.C:0834 22 ; '"'
; "6502 machine code :P"
.C:0835 36 35 30 32 20 4D 41 43 48 49 4E 45 20 43 4F 44 45 20 3A D0
; '"', some spaces, and next BASIC line
.C:0849 22 20 20 20 20 20 00 8D 08 01 00 97 35 33 32 37 32 2C 32 33 3A 99 22
; "This program errors out in CBM-BASIC :P"
.C:0860 D4 48 49 53 20 50 52 4F 47 52 41 4D 20 45 52 52 4F 52 53 20 4F 55 54
.C:0877 20 49 4E 20 C3 C2 CD 2D C2 C1 D3 C9 C3 20 3A D0
.C:0887 22 2C 58 AD 50 00 00 00
```
---
**[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"perr.prg":"data:;base64,AQhQCAAAj1pJUklBqReNGNCiML0wCCDS/+jgS9D1ojC9BQgg0v/o4ETQ9akNINL/ohpMN6QiNjUwMiBNQUNISU5FIENPREUgOtAiICAgICAAjQgBAJc1MzI3MiwyMzqZItRISVMgUFJPR1JBTSBFUlJPUlMgT1VUIElOIMPCzS3CwdPJwyA60CIsWK1QAAAA"%7D,"vice":%7B"-autostart":"perr.prg"%7D%7D)**, type `run` to run as BASIC, `sys 2049` to run as machine code, `list` to show it interpreted as BASIC code.
Running as BASIC produces a `division by zero error in 1`, running as machine code a `can't continue error`
[](https://i.stack.imgur.com/qjY9i.png)
---
**Explanation:**
The first two bytes of a `.prg` file are the load address in little endian, this is `$0801` (decimal `2049`) here, which is the start address for BASIC programs on the C64. `run` starts this program in the BASIC interpreter, while `sys 2049` is the command to run a machine code program at address `2049`.
As you can see, the first line in the BASIC view is a comment (`rem`) containing "garbage" and part of the required output string. This is the machine code program and some filler bytes. You see some "random" BASIC commands there because CBM-BASIC programs contain the commands "tokenized" as single byte values, and some of these values are the same as opcodes used in the machine code. The machine code reuses the string present in the second line of code for its output.
The first two bytes of a line of a basic program are a pointer to the next line, here `$0850`. This is carefully chosen because `50 08` is also a 6502 branch instruction jumping over the next 8 bytes when the overflow flag is not set -- this is used to jump somewhere in the middle of this "comment" line when executed as machine code. The `50` is the opcode used here, so the second line has to start at `0850` for the trick to work. That's why you see a sequence of 5 `20` bytes (space characters) to fill up. The machine code actively jumps to the ROM error handling routine to give a "can't continue" error.
The BASIC code is pretty straightforward; as a second argument to "print", two uninitialized variables (having a value of `0` in CBM BASIC) are divided, triggering the "division by zero" error.
[Answer]
# C and Python, ~~126~~ 116 bytes
*-10 bytes thanks to @Bubbler!*
```
#1/*
-print("This program errors out in Python :P")
'''*/
main(c){c=puts("This program errors out in C :P")/0;}//'''
```
In Python print() is a None, so trying to get its negative doesn't make sense, so Python throws an error.
In C printf() returns an int, so dividing it by zero gives a floating point exception.
[Try it in C!](https://tio.run/##S9ZNT07@/1/ZUF@LS7egKDOvREMpJCOzWKGgKD@9KDFXIbWoKL@oWCG/tEQhM08hoLIkIz9PwSpASZNLXV1dS58rNzEzTyNZszrZtqC0pBivZmewPn0D61p9faDm//8B)
[Try it in Python!](https://tio.run/##K6gsycjPM/7/X9lQX4tLt6AoM69EQykkI7NYoaAoP70oMVchtagov6hYIb@0RCEzTyEArEHBKkBJk0tdXV1Lnys3MTNPI1mzOtm2oLSkGK9mZ7A@fQPrWn19oOb//wE)
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache) + [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 82 bytes
```
s:="Attache"
s=" Mathematica "
Throw[Print["This program errors out in",s,":P"]-0]
```
[Try Attache online!](https://tio.run/##JccxCoAwDADA3VeEzBWchQ4@QHBwkw5Bis3QVpKIz4@Dtx2Z0Vmyu84Rlz84aERYyUquZHwS4LAX6e@xCTc7cC@scEu/hCpkkS4K/THghkEDzhumcUruHw "Attache – Try It Online") [Try Mathematica online!](https://tio.run/##RckxCoAwDADA3VeEzArOQgcfIDi4SYcgxWSokSTi8@vorVcpuFQKOag1nxLOEXRwwc4TwvIvYLex6buvJlfsuLE43KanUYVipuagT4Bc2HuP04p5GHNrHw "Wolfram Language (Mathematica) – Try It Online")
This pivots upon the meaning of the operator `=` in the two languages. In Attache, it compares for equality, but in Mathematica, it performs variable assignment. `:=` does variable assignment in both languages.
Now, in Attache, `Print` returns an array of strings printed, and subtraction is not possible with strings and integers (namely, `0`). So, a type error is thrown. In Mathematica, `Print` returns `Null`, and Mathematica is just fine subtracting `0` from that. But, we manually throw that null with `Throw`, giving a `nocatch` error.
[Answer]
# [Python (2)](https://docs.python.org/2/) and [QB64](http://qb64.net), 82 bytes
```
1#DEFSTR S
s="QB64"
'';s="Python"
print"This program errors out in "+s+" :P"
CLS-1
```
To test the Python version, you can [Try it online!](https://tio.run/##K6gsycjPM/r/31DZxdUtOCRIIZir2FYp0MnMRIlLXd0ayA4AK1HiKijKzCtRCsnILFYoKMpPL0rMVUgtKsovKlbILy1RyMxTUNIu1lZSsApQ4nL2CdY1/P8fAA "Python 2 – Try It Online") To test the QB64 version, you'll need to download QB64.
### What Python sees
```
1#DEFSTR S
s="QB64"
'';s="Python"
print"This program errors out in "+s+" :P"
CLS-1
```
The first line is just the bare expression `1` (a no-op) followed by a comment.
The second line sets `s` to the string `"QB64"`, but the third line immediately changes it to `"Python"`. The fourth line prints the message accordingly.
The fifth line is another bare expression, but it raises a `NameError` because of the undefined name `CLS`.
### What QB64 sees
```
1#DEFSTR S
s="QB64"
'';s="Python"
print"This program errors out in "+s+" :P"
CLS-1
```
The first line, numbered `1#`, defines every variable whose name starts with `S` (case-insensitive) as a string variable. This means we don't have to use `s$`, which would be a syntax error in Python.
The second line sets `s` to the string `"QB64"`. `'` starts a comment in QB64, so the third line doesn't do anything. The fourth line prints the message accordingly.
The fifth line tries to `CLS` (clear screen) with an argument of `-1`. But since `CLS` only accepts arguments of `0`, `1`, or `2`, this produces the error `Illegal function call`. The error creates a dialog box asking the user if they want to continue execution or abort. Technically, this means the error isn't fatal (in this case, you can pick "continue execution" and the program simply ends without further problems); but the OP has explicitly allowed languages that can continue after an error, so QB64's behavior should be fine.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) and [M](https://github.com/DennisMitchell/m), 39 bytes
```
İ=`ị“¢³ƥ“Ȥ¹»;“ :P”“¢ḅñ⁵ẹḞŀẊịñṙȧṄɱ»;ȮṠṛƓ
```
[Try it in Jelly!](https://tio.run/##y0rNyan8///IBtuEh7u7HzXMObTo0OZjS4GME0sO7Ty02xrIUrAKeNQwFyz3cEfr4Y2PGrc@3LXz4Y55Rxse7uoCaju88eHOmSeWP9zZcnIjUMuJdQ93Lni4c/axyf//AwA "Jelly – Try It Online")
[Try it in M!](https://tio.run/##y/3//8gG24SHu7sfNcw5tOjQ5mNLgYwTSw7tPLTbGshSsAp41DAXLPdwR@vhjY8atz7ctfPhjnlHGx7u6gJqO7zx4c6ZJ5Y/3NlyciNQy4l1D3cueLhz9rHJ//8DAA "M – Try It Online")
Both languages apply inverse `İ` to `0` which results in `inf` for Jelly and `zoo` for M. I don't know why `zoo` represents infinity in M. Ask Dennis.
The important difference is that Jelly's infinity is equal to itself while M's infinity is not. Thus the "is equal to itself" monad `=`` yields `1` in Jelly and `0` in M. From here:
```
İ=`ị“¢³ƥ“Ȥ¹»;“ :P”“¢ḅñ⁵ẹḞŀẊịñṙȧṄɱ»;ȮṠṛƓ
İ=` 0 in M, 1 in Jelly
“¢³ƥ“Ȥ¹» Pair of compressed strings: [' M',' Jelly']
ị Index into this list with 0 or 1
;“ :P” Concatenate with the string ' :P'
“¢ḅñ⁵ẹḞŀẊịñṙȧṄɱ» Compressed string: 'This program errors in'
; Prepend this to ' Jelly/M :P'
Ȯ Print the string and return it
Ṡ Sign. M errors with a string as input and terminates
Jelly returns a list of Nones
ṛ Right argument. This prevents the list of Nones from being printed
Ɠ Read a single line from input. Since input is not allowed, this produces an EOFError
```
Jelly's error is `EOFError: EOF when reading a line`.
M's error is `TypeError: '>' not supported between instances of 'str' and 'int'`.
[Answer]
# [C++ 14 (gcc) / C++ 17 (gcc)](https://gcc.gnu.org/), ~~107~~ 105 bytes
```
#include<cstdio>
int*p,c=*"??/0"/20;int
main(){*p=printf("This program errors out in C++ 1%d :P",4+c)/c;}
```
[Try it online! (C++14)](https://tio.run/##Dc0xDoMgFIDh3VO80DRR0KCNUy116AU69ALkoZREgQBOTa9eyvh/y4/edxox55OxuB1quWFMyrh7ZWyivkVByTzznvBLPxWqdmls3XyoFz6UXmvyepsIPjgd5A5LCC5EcEcCY@HBGAxnBdcnaUeGDcfpm/MP103qmLtyEsjYMP4B "C++ (gcc) – Try It Online")
[Try it online! (C++17)](https://tio.run/##Dc0xDsIgFIDhvad4wZi00IbWmJhYsYMXcPAC5NEiSQsE6GS8usj4f8uP3ncaMeeDsbjuar5hTMq4e2Vsor5FQck08Z7wUz8WqjZpbN18qBc@lF5q8nqbCD44HeQGcwguRHB7AmPhwRgMRwXXJ2nPDBuO4zfnHy6r1DF35SSQseHyBw "C++ (gcc) – Try It Online")
---
Assumes that `<cstdio>` declares `printf` in the global namespace (in addition to `std`) and that the basic execution character set uses ASCII values, which are both true using g++ on Linux.
The basic catch here is that C++17 eliminated trigraphs from the language.
In C++14, `"??/0"` contains a trigraph and is equivalent to `"\0"`. So `*"??/0"` is zero, and `c` is set to zero. The number 4 is passed as an argument to `printf`, then the division by `c` causes undefined behavior. On Linux, this happens before `*p` comes into the picture, and the program gets a `SIGFPE`.
In C++17, `"??/0"` is exactly the length 4 string it appears to be. So `*"??/0"` is `'?'` or 63, and `c` is set to 3. The number 7 is passed as an argument to `printf`, and this time the division by `c` is valid. Since `p` is a namespace member, it gets zero-initialized at the start of the program and has a null pointer value, so `*p` is undefined behavior. On Linux, because the program attempts to modify memory at address zero, the program gets a `SIGSEGV`.
[Answer]
# [Perl 5](https://www.perl.org/) and [JavaScript (Node.js)](https://nodejs.org), 96 bytes
```
eval("printf=console.log");printf("This program errors out in %s :P",("Perl","JavaScript"));$//0
```
This makes use of the fact that `(...)` is a list in Perl that `printf` will use the leftmost element of and the fact that it's the comma operator in JavaScript, which will return the rightmost argument.
Causes a division by zero error in Perl and a ReferenceError because `$` is not defined in JavaScript.
[Try the Perl online!](https://tio.run/##JcxBCsIwEADAryyLQgK1jYdeLP2AIBTqB0KJdSFmwyb2@W4LXucwOUjsVcPmo8EslOprXDgVjqGNvKId/mjw@aYCWXgV/4EgwlKAvxUowbnAbcLG4HRs2ODdb35ehHJFa4dT1znVH@dKR6yXR9@6q9sB "Perl 5 – Try It Online")
[Try the JavaScript online!](https://tio.run/##JcxLCsIwEADQqwyDhQT6W1t6AVeBeoFQpzWSZsJM7PWj6PYt3sufXlcJuXSJH1QrnT4azBJS2eaVk3KkPvKOdvqjwfszKGThXfwBJMKiwO8CIUGjcHXYGnQkEVu8ffvl16O102UYxlo/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/) and MATLAB, 67 bytes
```
v=ver;disp(['This program errors out in ' v(1).Name ' :P']);v(--pi)
```
[Try it online!](https://tio.run/##y08uSSxL/f@/zLYstcg6JbO4QCNaPSQjs1ihoCg/vSgxVyG1qCi/qFghv7REITNPQV2hTMNQU88vMTcVyLYKUI/VtC7T0NUtyNT8/x8A "Octave – Try It Online")
Notes: The code assumes MATLAB is installed with no toolboxes (or that the names of any toolbox that is installed don't start with letters A to M).
How it works:
The code gets the version data for the interpreter and toolboxes using `ver`. Running `v(1).Name` extracts the name of the first product, this will return either `Octave` or `MATLAB` assuming the note above holds true.
The program will then display the required string, complete with `Octave` or `MATLAB` as required.
Finally we do `v(--pi)`.
In Octave, `--` is the pre-decrement operator. As such it attempts to pre-decrement which fails as the variable `pi` doesn't exist (`pi` is actually function, not a variable).
```
This program errors out in Octave :P
error: in x-- or --x, x must be defined first
```
In MATLAB, the pre-decrement operator doesn't exist. As such the statement is interpreted as `v(-(-pi))` which is equal to just `v(pi)`. However `pi` is not an integer, so cannot be used to index into the `v` array, giving an error.
```
This program errors out in MATLAB :P
Subscript indices must either be real positive integers or logicals.
```
[Answer]
# Haskell, Python3, JavaScript(Node.js), 195 Bytes
```
j=1
y="This program errors out in "
--j//1;Error=print
--j;Error(y+"Python :P");eval("console.log(y+`JavaScript :P`);e");j//2;"""
1//0=do print (y++"Haskell :P");putChar$""!!1
main=1//0
--j //"""
```
Error Messages
Python - Syntax Error due to the ` in the EVAL
Haskell - Index too large (""!!1)
JavaScript - Reference Error (e is not defined)
[Answer]
# [Perl 5](https://www.perl.org/) and [Perl 6](https://github.com/nxadm/rakudo-pkg), 55 bytes
```
say('This program errors out in Perl ',5-~-1,' :P').a/0
```
[Try Perl 5 online!](https://tio.run/##K0gtyjH9/784sVJDPSQjs1ihoCg/vSgxVyG1qCi/qFghv7REITNPIQCoTEFdx1S3TtdQR13BKkBdUy9R3@D//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") (Illegal division by zero)
[Try Perl 6 online!](https://tio.run/##K0gtyjH7/784sVJDPSQjs1ihoCg/vSgxVyG1qCi/qFghv7REITNPIQCoTEFdx1S3TtdQR13BKkBdUy9R3@D/fwA "Perl 6 – Try It Online") (No such method)
Prefix `~` is stringification in Perl 6 and essentially a no-op in the program above. In Perl 5, it's bitwise not, converting -1 to 0.
`.` is method call syntax in Perl 6 and concatenation in Perl 5.
[Answer]
# [C (gcc)](https://gcc.gnu.org/)/[Stax](https://github.com/tomtheisen/stax), 109 bytes
```
AA=~1;
char* s;main(){*(int*)(printf("%s C :P",s))=0;}char* s=
"This program errors out in";;;/*dp`UGYC\`Q*/
```
[Try it online! (C (gcc))](https://tio.run/##S9ZNT07@/9/R0bbO0JqLMzkjsUhLodg6NzEzT0OzWksjM69ES1OjoAhIp2koqRYrOCtYBSjpFGtq2hpY10KV23IphWRkFisUFOWnFyXmKqQWFeUXFSvkl5YoZOYpWVtb62ulFCSEukc6xyQEaun//w8A "C (gcc) – Try It Online")
[Try it online! (Stax)](https://tio.run/##Ky5JrPj/39HRts7QmoszOSOxSEuh2Do3MTNPQ7NaSyMzr0RLU6OgCEinaSipFis4K1gFKOkUa2raGljXQpXbcimFZGQWKxQU5acXJeYqpBYV5RcVK@SXlihk5ilZW1vra6UUJIS6RzrHJARq6f//DwA "Stax – Try It Online") or [Run and debug it! (Stax)](https://staxlang.xyz/#c=AA%3D%7E1%3B%0A%09char*+s%3Bmain%28%29%7B*%28int*%29%28printf%28%22%25s+C+%3AP%22,s%29%29%3D0%3B%7Dchar*+s%3D%0A%22This+program+errors+out+in%22%3B%3B%3B%2F*dp%60UGYC%5C%60Q*%2F&a=1)
Segfault in C. Invalid operation in Stax. I love how everything that is not a comment is actually used in Stax.
## C
This is how C sees it. The first line is no-op. The second line prints the message with `printf` and then segfaults due to the `=0`.
```
AA=~1;
char* s;main(){*(int*)(printf("%s C :P\n",s))=0;}char* s=
"This program errors out in";;;/*dp`UGYC\`Q*/
```
## Stax
Stax program terminates whenever it tries to pop or peek from empty stack. This makes it a little bit tricky and we have to prepare a stack that is not empty. `AA=~1;` does this while remaining a valid statement in C.
```
AA=~1;
AA= 10=10, returns a 1
~ Put it on the input stack
1 Pushes a 1 to main stack (*)
; Peek from the input stack (**)
```
What is really useful is the `~`, it prepares a non-empty input stack so that the `;` can be executed without exiting the program. However, the two `1`s on the main stack are also used later.
The second line begins with a tab and starts a line comment in Stax.
```
"...";;;/*dp`UGYC\`Q*/
"..." "This program errors out in"
;;; Peek the stack three times so that we have enough operands for the next two operations
/ Divide, this consumes one element of the main stack
* Multiply, this consumes another element
d Discard the result, now the TOS is the string
p Pop and print without newline
`UGYC\` Compressed string literal for " Stax :P"
Q Print and keep the string as TOS
* Duplicate string specific times
Since the element under the top of stack is `1` that was prepared in (**), this does nothing
/ Invalid operation error
```
The invalid operation is trying to perform `/` operation for a string as the TOS (2nd operand) and the number `1` from (\*) as the 1st operand, which is invalid.
If the two operands are swapped, it would be a valid operation in Stax.
[Answer]
# [Foo](https://esolangs.org/wiki/Foo) / [CJam](https://sourceforge.net/projects/cjam/), ~~51~~ 50 bytes
```
"This program errors out in ""Foo"/'C'J'a'm" :P"Li
```
This exits with a divide-by-zero error in Foo, and a `NumberFormatException` in CJam.
## To CJam:
* A string literal (between quotes) pushes itself to the stack. Items from the stack are automatically printed without a separator when the program terminates.
* `/` tries to split the string `This program errors out in` on the substring `Foo`. Since the string does not contain the substring, this yields a singleton array containing the original string, which displayed in exactly the same way.
* `'x` is a character literal for `x`, which is printed the same way as a one-character string. This way, we can push data for CJam that is ignored by Foo (I haven't figured out how to make a loop not execute in Foo).
* `Li` tries to cast the empty string to an integer, which fails. Everything from the stack is printed.
## To Foo:
* A string literal (between quotes) prints itself.
* `/` tries to divide the current cell by the top stack element (which is an implicit `0`). For some reason, divide-by-0 errors aren't fatal in Foo, so this just prints the message
```
Only Chuck Norris can divide by zero.
```
to STDERR and keeps going.
* Unrecognized characters (`'C'J'a'm` and `Li`) are ignored.
[Answer]
# [Python](https://docs.python.org/3/) and [Lua](https://www.lua.org/manual/5.3/), ~~111~~ ~~110~~ ~~102~~ ~~98~~ ~~95~~ 85 bytes
```
x="This program errors out in ",#[[
print(x[0]+"Python :P")
a#]]z=#print(x.."Lua :P")
```
Errors:
Python 3:
```
Traceback (most recent call last):
File ".code.tio", line 3, in <module>
a#]]z=#print(x.."Lua :P")
NameError: name 'a' is not defined
```
Lua:
```
lua: .code.tio:3: attempt to get length of a nil value
stack traceback:
.code.tio:3: in main chunk
[C]: in ?
```
Clearly distinct.
Abuses multiple differences:
* `<var>=<a>,<b>,...` creates a tuple in Python, but in Lua it creates an argument list, from which only the first member is taken.
* `#` starts a comment in Python, but is the length operator in Lua. Extra props to Python for allowing tuples to end in a comma.
* `[[...]]` is Lua's multiline string syntax, meaning it doesn't even see Python's print function; this is necessary due to Lua using `..` for string concatenation and not `+`.
* Python errors after seeing `a`, an undefined variable; Lua after `z=#print(x.."Lua :P")`. Using just `#print(x.."Lua :P")` for Lua doesn't work, as that raises an error before the code is even executed.
Edits:
* No need to use `"".join` in Python, -1 byte
* Make `x` a string in both languages and place `Python` in a string literal in the print function, -8 bytes
* Using `#[[]]` is shorter than `#""` and `--[[]]`, -4 bytes
* No need to use `#1` as a table key, -3 bytes
* [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) did [this](https://tio.run/##K6gsycjPM/7/v8JWKSQjs1ihoCg/vSgxVyG1qCi/qFghv7REITNPQUlHOTqaq6AoM69EoyLaIFZbKQCsUcEqQEnTOlE5NhYqp6en5FOaCBauslU2/P8fAA), -9 bytes
* Taking the length of the return value of `print(x.."Lua :P")` works, apparently; -1 byte
[Answer]
# Java and C# ~~242~~ 235
```
/**\u002f/*/using System;/**/class G{public static void/**\u002fmain/*/Main/**/(String[]a){String s="This program errors out in ";/**\u002fSystem.out.print(s+"Java :P");/*/Console.Write(s+"C# :P")/**/;s=/**\u002f(1/0)+""/*/a[-1]/**/;}}
```
Abusing different escape handling between java and C# (unicode escapes are parsed before code parsing in java and not in c#) as a sort of preprocessor, thats the job of the `\u0027` magic, rest are some "toggle-comments"
Edit: Golfed off 8 bytes thanks to a pointer of @KevinCruijssen
Edit: Rule derp fixed
[Answer]
# [AutoHotKey](https://autohotkey.com/docs/AutoHotkey.htm) / C#, ~~155~~ ~~133~~ ~~128~~ 122 bytes
Syntax highlighting explains it better than I could:
**C#** RuntimeBinderException: 'Cannot invoke a non-delegate type'
```
;dynamic
i="This program errors out in " ;Console.Write(i+"c# :P");i();/*
i:=SubStr(i,2,27)
send %i%AutoHotkey :P
Throw */
```
**AutoHotkey** Error: An exception was thrown.
```
;dynamic
i="This program errors out in " ;Console.Write(i+"c# :P");i();/*
i:=SubStr(i,2,27)
send %i%AutoHotkey :P
Throw */
```
## Edits:
1. removed a var
2. -5 bytes thanks to [milk](https://codegolf.stackexchange.com/users/58106/milk)
[Answer]
# PHP 7+ / JavaScript, ~~90~~ 89 bytes
This uses 2 languages with very similar syntax, allowing to write this code on both languages.
The language separation is done by a property not present in JavaScript: PHP considers `[]` (empty array) to be a falsy value while it is truthy in JavaScript (because it is an object and objects are **always** truthy, even `new Boolean(false)`).
```
$X='This program errors out in %s :P';([]?console.log($X,'JavaScript'):printf($X,PHP))();
```
---
## Execution:
Will focus on the following piece of code: `([]?console.log($X,'JavaScript'):printf($X,PHP))();`.
The string attribution works the same in both languages.
This code uses the "ternary operator" ([Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator), [PHP](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary)), which works mostly the same way in both languages.
### Javascript
Javascript will run the `console.log($X,'JavaScript')` piece, which returns `undefined`.
Later on, when you try to execute `(...)()`, you get an `Uncaught TypeError: (intermediate value)(intermediate value)(intermediate value) is not a function` (in Google Chrome).
### PHP
PHP will execute the `printf($X,PHP)` piece.
In PHP, the [`printf`](http://php.net/manual/en/function.printf.php) function [returns the length of the output](http://php.net/manual/en/function.printf.php#refsect1-function.printf-returnvalues).
PHP has an interesting functionality: it can execute functions who's name is stored in a variable (or, since PHP7, as the result of an expression), which prevents a syntax error.
PHP then will try to run the function who's name is the result of the expression `[]? ... :printf($X,PHP)` (which is the number `33`).
But that interesting functionality has a caveat: only accepts strings (duh!).
This causes a `Fatal error: Function name must be a string`, because `33` is an `int`.
---
Thanks to [Shieru Asakoto](https://codegolf.stackexchange.com/users/71546/shieru-asakoto) for saving me 1 byte!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) and [Python 3](https://docs.python.org/3/), 89 bytes
```
print("\"}\"This program errors out in Python :P\""[3:-1]);'")н”±¸ :P\”"05AB1E :P":,õι';a
```
[Try it online! (05AB1E)](https://tio.run/##yy9OTMpM/f@/oCgzr0RDKUapNkYpJCOzWKGgKD@9KDFXIbWoKL@oWCG/tEQhM08hoLIkIz9PwSogRkkp2thK1zBW01pdSfPC3kcNcw9tPLQDJANkKhmYOjoZugJ5SlY6h7ee26lunfj/PwA "05AB1E – Try It Online")
[Try it online! (Python 3)](https://tio.run/##K6gsycjPM/7/v6AoM69EQylGqTZGKSQjs1ihoCg/vSgxVyG1qCi/qFghv7REITNPIQCsXsEqIEZJKdrYStcwVtNaXUnzwt5HDXMPbTy0AyQDZCoZmDo6GboCeUpWOoe3ntupbp34/z8A "Python 3 – Try It Online")
## [05AB1E](https://github.com/Adriandmen/05AB1E)
```
print("\"}\"This program errors out in Python :P\""[3:-1]);'")н”±¸ :P\”"05AB1E :P":,õι';a # full program
print("\"}\ # a bunch of nops
"This program errors out in Python :P\" # push literal (in 05AB1E, backslashes are not escape characters)
"[3:-1]);'" # push literal
: # replace all instances of...
”±¸ :P\” # "Python :P\"
: # in...
н # first element of...
) # stack as a list (left of list is bottom of stack)...
: # with...
"05AB1E :P" # literal
, # output explicitly to prevent the error from stopping implicit output
ι # attempt to use...
õ # empty string...
ι # as index "step" value in uninterleave, resulting in an error
```
## Error
```
** (RuntimeError) Could not convert to integer.
(osabie) lib/interp/functions.ex:101: Interp.Functions.to_integer!/1
(osabie) lib/interp/commands/special_interp.ex:113: Interp.SpecialInterp.interp_step/3
(osabie) lib/interp/interpreter.ex:127: Interp.Interpreter.interp/3
(osabie) lib/osabie.ex:62: Osabie.CLI.main/1
(elixir) lib/kernel/cli.ex:105: anonymous fn/3 in Kernel.CLI.exec_fun/2
```
## [Python 3](https://docs.python.org/3/)
```
print("\"}\"This program errors out in Python :P\""[3:-1]);'")н”±¸ :P\”"05AB1E :P":,õι';a # full program
print("\"}\"This program errors out in Python :P\"" # print string "}"This program errors out in Python :P" (including quotes)...
[3:-1]); # not including the first 3 characters and the quote at the end
'")н”±¸ :P\”"05AB1E :P":,õι'; # string literal (nop)
a # references an undefined variable, resulting in an error
```
## Error
```
Traceback (most recent call last):
File ".code.tio", line 1, in <module>
print("\"}\"This program errors out in Python :P\""[3:-1]);'")”±¸ :P\”"05AB1E :P":,õι';a
NameError: name 'a' is not defined
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/) and Vim, 76 bytes
```
.( This program errors out in Forth :P ) <esc>0iThi<esc>:s/F.*/Vim :P<cr>:!a
```
[Try it in Forth!](https://tio.run/##S8svKsnQTU8DUf//62kohGRkFisUFOWnFyXmKqQWFeUXFSvkl5YoZOYpuIEUKVgFKGgq2KQWJ9sZZAIVg1lWxfpuelr6YZm5QGmb5CI7K8XE//8B)
[Try it in Vim!](https://tio.run/##K/v/X09DISQjs1ihoCg/vSgxVyG1qCi/qFghv7REITNPwS2/qCRDwSpAQVPBJrU42c4gE6gYzLIq1nfT09IPy8wFStskF9lZKSb@//9ftwwA "V (vim) – Try It Online")
In Forth, `.( This program errors out in Forth )` prints the necessary message and the rest just makes it blow up because it's an undefined word.
In Vim, that first part writes `s program errors out in Forth :P )` to the buffer, `0iThi` puts `Thi` at the start of the line, and `:s/F.*/Vim` turns that last part into `Vim :P` instead of `Forth :P )`. `:!a` simply tries to run a command named `a` and errors because it doesn't exist.
[Answer]
# Perl 5 and C, 95 bytes
```
//;$_='
main(){puts(puts("This program errors out in C :P"));}//';/T.*n /;print$&,"perl :P";die
```
`//;` is basically a NOP in perl, and is a comment in C.
So the C program is effectively:
```
main(){puts(puts("This program errors out in C :P"));}
```
Which prints the required string, then tries to run `puts(32)`. This is technically undefined behavior in C, but it causes a segmentation fault on TIO and every system I have access to.
The perl program treats the whole C program as a string, uses the regex `/T.*n /` to match `This program errors out in` and then prints that and `perl :P`. `die` causes the program to crash with the error `Died at script_name line 2`.
If you don't like that as an error, `1/0` is the same length and crashes with an `Illegal division by zero` error. I just like `die` more ;)
[Try it online! (C)](https://tio.run/##S9ZNT07@/19f31ol3ladKzcxM09Ds7qgtKRYA0wohWRkFisUFOWnFyXmKqQWFeUXFSvkl5YoZOYpOCtYBShpalrX6uurW@uH6GnlKehbFxRl5pWoqOkoFaQW5YAUWKdkpv7/DwA)
[Try it online! (Perl)](https://tio.run/##K0gtyjH9/19f31ol3ladKzcxM09Ds7qgtKRYA0wohWRkFisUFOWnFyXmKqQWFeUXFSvkl5YoZOYpOCtYBShpalrX6uurW@uH6GnlKehbFxRl5pWoqOkoFQBNBimwTslM/f8fAA)
[Answer]
## VBScript, JScript, 72 bytes
```
x="VB"
'';x='J'
WScript.echo("This program errors out in "+x+"Script")
y
```
VBScript will print "Microsoft VBScript runtime error: Type mismatch: 'y'"
JScript will print "Microsoft JScript runtime error: 'y' is undefined"
[Answer]
# JavaScript & Python 3, ~~105~~ 91 bytes
Errors by `NameError: name 'console' is not defined` in Python 3
```
a="This program errors out in %s :P"
1//2;print(a%"Python 3")
console.log(a,"JavaScript")()
```
[Try it online!](https://tio.run/##HctBCoAgEADAe69YFgSFKKpb0Qc6BfWBJaIEc2W1oNcbNPcJbzrZdznTiOtpIwThQ@iCXYQlAt8JrAcVoZ@xaOq6HYJYnzQpnP8LHZpiYx/Z7ZXjQ1OJEz20bGJDQqNNzh8 "Python 3 – Try It Online")
... and by `TypeError: console.log(...) is not a function` in JavaScript.
```
a="This program errors out in %s :P"
1//2;print(a%"Python 3")
console.log(a,"JavaScript")()
```
[Try it online!](https://tio.run/##HcxRCoMwDADQf08RAkILm6L@bXiBfQnuAkGLdrikJN1gp@/G3gHeg95ki8aUzyxrKIVGvO/RIKlsSk8IqqIG8soQGWqDy4RV17b9NWnk7KjG6ZN3YRjQV4uwyRGaQzZHJ7z99vm/o3e@lC8 "JavaScript (Node.js) – Try It Online")
[Answer]
# Java (JDK)/JavaScript (Node.js), 154 bytes
```
class P{P(){var s="This program errors out in ";try{System.out.printf("%sJava :P",s);}finally{if(1!='1'){var a=0/0;}throw new Error(s+"JavaScript :P");}}}
```
[Try it online! (Java)](https://tio.run/##Lc9Na4NAEAbgs/6K6ULISts0uVY89lIoCPZWcpgaNZPqrsxsDLLsb7cryWlgPh7eueCEr5fT37LUPYpA6Uud@QkZpFDfZxIY2XaMAzTMlgXs1QEZULnj2VezuGbYxd5uZDKu1Wojn5GE91K9SJaHlgz2/eyp1YenYnvY3nEs9m/7PLgz2xuY5gYfq67lWa3XVc00utWIQgiPaF9IxqfJeP3tqQZx6GKZLJ1giBNduZig@zkCcidZXExWN36Tp0lIw/IP "Java (JDK) – Try It Online")
[Try it online! (JavaScript)](https://tio.run/##Jc5BDoIwEAXQvacYmxggKsJW0qUbVyR4gaJFaqAlMxVCSM9eKa4m@Zn/8j9iFPRENdizNi/p/bMTRFAuZZwso0Agzh6tIhjQvFH0IBENEpivBaWBFRbnpZrJyj5ds3RApW0TswPdVxmuJTtRUrhGadF186KaON/zKI/@uODZJSucbdFMoOUEt6DHdGShXW27grEKzvnQqIFvj@u8Ylen4fgf "JavaScript (Node.js) – Try It Online")
Output in Java:
```
This program errors out in Java :P
Exception in thread "main" java.lang.ArithmeticException: / by zero
at P.(Main.java:1)
```
Output in JavaScript (to stderr):
```
Error: This program errors out in JavaScript :P
at P (/home/runner/.code.tio:1:185)
```
This takes advantage of JavaScript's weak typing (`1=='1'`) to detect the language, and the same keywords in Java and JavaScript (`var`,`class`), and the similar error constructors (`new Error()`) to make the polyglot.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) v6 and PowerShell v2, 73 bytes
```
"This errors out in PowerShell v$($PSVersionTable.PSVersion) :P"
1-shl1/0
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XykkI7NYIbWoKL@oWCG/tEQhM08hACQfDJJXKFPRUAkIDgMqz8zPC0lMyknVg3M1FawClLgMdYszcgz1Df7/BwA "PowerShell – Try It Online")
This will throw a parsing error on v2 because `-shl` was introduced in v3. v3+ will then be able to correctly shift the value before attempting to divide it by 0, conveniently throwing a division-by-zero error. Both versions have the $PSVersionTable hashmap which contains the `PSVersion` field
[Answer]
# Python 3 / [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 75 bytes
```
r='=,k1'"This program errors out in Befunge :P"
-print(r[4:31]+"Python :P")
```
Raises a TypeError in Python and a segmentation fault in Befunge.
[Try it online! (Python)](https://tio.run/##K6gsycjPM/7/v8hW3VYn21BdKSQjs1ihoCg/vSgxVyG1qCi/qFghv7REITNPwSk1rTQvPVXBKkCJS7egKDOvRKMo2sTK2DBWWykAbBBISvP/fwA)
[Try it online! (Befunge)](https://tio.run/##S0pNK81LT9W1tPj/v8hW3VYn21BdKSQjs1ihoCg/vSgxVyG1qCi/qFghv7REITNPwQmiXsEqQIlLt6AoM69EoyjaxMrYMFZbKaCyJCM/DySl@f8/AA)
## Python
```
r='=,k1'"This program errors out in Befunge :P"
r= #Declare variable
'=,k1' #String literal
"This program errors out in Befunge-98 (FBBI) :P" #Another string literal
#Concatenating string literals joins the two strings together.
-print(r[4:31]+"Python :P")
r[4:31] #Extract the relevant part of the output
+"Python :P" #Change the language name to "Python"
print( ) #Print the string and return None
- #Unary negation
```
Apparently, consecutive string literals (such as `'1'"2"`) are valid in Python.
The `print` function, after printing its input (`"This program errors out in Python :P"`), returns `None`. The program attempts to negate that with `-`, which raises a TypeError:
```
Traceback (most recent call last):
File ".code.tio", line 2, in <module>
-print(r[4:31]+"Python :P")
TypeError: bad operand type for unary -: 'NoneType'
```
## Befunge
```
r =,k1'"This program errors out in Befunge :P"
r #Reverse direction
"This program errors out in Befunge :P" #String literal (backwards)
1' #Push 49
k #Repeat that many (49) times:
, #Output the last character
= #System-execute the top of the stack ("")
```
After using `'1k,` to print `"This program errors out in Befunge :P"`, the stack is empty. `=` does a system-execute call, passing the string on top of the stack (which is empty) to the interpreter. FBBI implements this using a C `system()` call, so it calls `system("")`, which leads to a segmentation fault:
```
/srv/wrappers/befunge-98: line 3: 6033 Segmentation fault (core dumped) /opt/befunge-98/bin/fbbi .code.tio "$@" < .input.tio
```
] |
[Question]
[
[Give credit to whom credit is due](http://chat.stackexchange.com/transcript/message/29674708#29674708).
**Objective** Given an integer `N > 0`, out the smallest integers `A`, `B`, and `C` so that:
1. All of `A`, `B`, and `C` are strictly greater than `N`;
2. `2` divides `A`;
3. `3` divides `B`;
4. and `4` divides `C`.
This is a code-golf, so the shortest answer in bytes wins.
## Test cases
```
N => A, B, C
1 => 2, 3, 4
4 => 6, 6, 8
43 => 44, 45, 44
123 => 124, 126, 124
420 => 422, 423, 424
31415 => 31416, 31416, 31416
1081177 => 1081178, 1081179, 1081180
```
[Answer]
## Python 2, 32 bytes
```
lambda n:[n+2&-2,n/3*3+3,n+4&-4]
```
Bit arithmetic for 2 and 4, modular arithmetic for 3.
I found four 7-byte expressions for the next multiple of `k` above `n` but none shorter:
```
n-n%k+k
~n%k-~n
n/k*k+k
~n/k*-k
```
Any gives 34 bytes when copies for `k=2,3,4`, and 33 bytes if combined:
```
[n/2*2+2,n/3*3+3,n/4*4+4]
[n/k*k+k for k in 2,3,4]
```
But, 2 and 4 are powers of 2 that allow bit tricks to zero out the last 1 or 2 bytes.
```
n+2&-2
n+4&-4
```
This gives 6 bytes (instead of 7) for getting the next multiple, for 32 bytes overall, beating the `for k in 2,3,4`.
Unfortunately, the promising-looking `n|1+1` and `n|3+1` have the addition done first, so incrementing the output takes parentheses.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
~%2r4¤+‘
```
[Try it online!](http://jelly.tryitonline.net/#code=fiUycjTCpCvigJg&input=&args=MTI) or [verify all test cases](http://jelly.tryitonline.net/#code=fiUycjTCpCvigJgKw4figqxH&input=&args=MSwgNCwgNDMsIDEyMywgNDIwLCAzMTQxNSwgMTA4MTE3Nw).
### How it works
```
~%2r4¤+‘ Main link. Argument: n (integer)
~ Bitwise NOT; yield ~n = -(n + 1).
¤ Combine the three links to the left into a niladic chain:
2 Yield 2.
r4 Yield the range from 2 to 4, i.e., [2, 3, 4].
% Yield the remainder of the division of ~n by 2, 3 and 4.
In Python/Jelly, -(n + 1) % k = k - (n + 1) % k if n, k > 0.
‘ Yield n + 1.
+ Add each modulus to n + 1.
```
[Answer]
# Julia, 16 bytes
```
n->n-n%(r=2:4)+r
```
[Try it online!](http://julia.tryitonline.net/#code=ZiA9IG4tPm4tbiUocj0yOjQpK3IKCmZvciBuID0gKDEsIDQsIDQzLCAxMjMsIDQyMCwgMzE0MTUsIDEwODExNzcpCiAgICBwcmludGxuKGYobikpCmVuZA&input=)
[Answer]
# MATL, ~~15 10~~ 9 bytes
```
2:4+t5M\-
```
[Try it online!](http://matl.tryitonline.net/#code=Mjo0K3QyOjRcLQ&input=MTA)
Explanation:
```
2:4 #The array [2, 3, 4]
+ #Add the input to each element, giving us [12, 13, 14]
t #Duplicate this array
5M #[2, 3, 4] again
\ #Modulus on each element, giving us [0, 1, 2]
- #Subtract each element, giving us [12, 12, 12]
```
[Answer]
# MATL, 8 bytes
```
Qt_2:4\+
```
Uses Denis' Jelly algorithm, I'm surprised it's the same length!
[Try it online](http://matl.tryitonline.net/#code=UXRfMjo0XCs&input=NDIw), or, [verify all test cases](http://matl.tryitonline.net/#code=Mjo0K3QyOjRcLQ&input=MTA).
```
Q % takes implicit input and increments by one
t_ % duplicate, and negate top of stack (so it's -(n+1))
2:4 % push vector [2 3 4]
\ % mod(-(n+1),[2 3 4])
+ % add result to input+1
% implicit display
```
[Answer]
# Matlab, 33 bytes
Another slightly different approach
```
@(a)feval(@(x)a+1+mod(-a-1,x),2:4)
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes
Code:
```
>D(3L>%+
```
[Try it online!](http://05ab1e.tryitonline.net/#code=PkQoM0w-JSs&input=NA).
[Answer]
# Ruby, 27 bytes
Maps 2, 3, and 4 to the next multiple above `n`.
```
->n{(2..4).map{|e|n+e-n%e}}
```
[Answer]
# CJam, 15 bytes
```
5,2>rif{1$/)*N}
```
[Try it online!](http://cjam.tryitonline.net/#code=NSwyPnJpZnsxJC8pKk59&input=MTI) or [verify all test cases](http://cjam.tryitonline.net/#code=cU4vewogICAgNSwyPlJpZnsxJC8pKk59Ck59ZlI&input=MQo0CjQzCjEyMwo0MjAKMzE0MTUKMTA4MTE3Nw).
[Answer]
## Pyth, ~~11~~ 10 bytes
```
m*dh/QdtS4
```
[Test suite.](https://pyth.herokuapp.com/?code=m%2adh%2FQdtS4&input=1%0A4%0A43%0A123%0A420%0A31415%0A1081177%0A&test_suite=1&test_suite_input=1%0A4%0A43%0A123%0A420%0A31415%0A1081177&debug=0)
```
tS4 generate range [2, 3, 4]
m for d in range...
*dh/Qd d*(1+input/d)
```
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for a byte!
[Answer]
## Pyke, ~~11 9~~ 8 bytes
```
3FODQRc+
```
[Try it here!](http://pyke.catbus.co.uk/?code=3FODQRc%2B&input=4)
```
3FODQRc+
- Q = input()
3F - for i in range(3): # for i in [0,1,2]
O - i += 2
Q c - Q-(Q%i)
+ - i+^
```
[Answer]
## Mathematica, 21 bytes
```
Ceiling[#+1,{2,3,4}]&
```
This is an unnamed function which takes a single integer as input and returns a list of the multiples.
The `Ceiling` function takes an optional second parameter which tells it to round up to the next multiple of the given number. Thankfully, it *also* automatically threads over its second argument such that we can give it a list of values and in turn we'll get rounded up multiples for all of those.
[Answer]
# Octave, 20 bytes
```
@(n)n-mod(n,d=2:4)+d
```
Examples:
```
octave:60> f(123)
ans =
124 126 124
octave:61> f(1081177)
ans =
1081178 1081179 1081180
octave:62> f(420)
ans =
422 423 424
```
Worth noting that we can do this up to 9 without adding any extra bytes:
```
@(n)n-mod(n,d=2:9)+d
```
Output (2520 is the smallest positive integer evenly divisible by all the single digit numbers):
```
octave:83> f(2520)
ans =
2522 2523 2524 2525 2526 2527 2528 2529
```
[Answer]
# C, ~~50~~ 46 bytes
```
i;f(int*a,int n){for(i=1;++i<5;*a++=n+i-n%i);}
```
*Thanks to Neil and nwellnhof for saving 4 bytes!*
Disappointingly long. I feel like there's some bit-shifting hack in here that I don't know about, but I can't find it yet. Returns a pointer to an array holding the three elements. Full program:
```
i;f(int*a,int n){for(i=1;++i<5;*a++=n+i-n%i);}
int main()
{
int array[3];
int n=10;
f(array, n);
printf("A:%d\tB:%d\tC:%d\n",array[0],array[1],array[2]);
return 0;
}
```
[Answer]
# Haskell, 27 bytes
```
f n=[div n d*d+d|d<-[2..4]]
```
[Answer]
# Reng, 40 bytes
```
i1+#i2341ø>(1+)31j
i(2[¤, q!^$]æl0eq!~
```
## 1: init
```
i1+#i2341ø
```
`i1+#i` sets the input to `1 + input`; this is because we are to work on the numbers strictly greater than the input. `234` initializes the tape with our iteration values, and `1ø` jumps to the beginning of the next line.
## 2a: loop
```
i(2[¤, q!^$]æl0eq!~
```
`i(` puts the input at the STOS, and `2[` makes a new stack with the top 2 elements. `¤` duplicates the stack, and `,` does modulus. If there is a remainder, `q!^` breaks out of the loop to go to (b). Otherwise, we're fine to print. `$` removes the extra thingy, `]` closes the stack, and `æ` prints it nicely. `l0wq!~` terminates iff the stack contains zero members.
## 2b: that other loop
```
>(1+)31j
q!^
```
`(1+)` adds 1 to the STOS, and `31j` jumps to the part of the loop that doesn't take stuff from the stack. And profit.
---
That extra whitespace is really bothering me. Take a GIF.
[](https://i.stack.imgur.com/jzTxE.gif)
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 19 bytes
```
:?
:
#/)
\ #
!"*@
"
```
[Try it online!](http://labyrinth.tryitonline.net/#code=Oj8KOgojLykKXCAjCiEiKkAKIg&input=NDI)
This outputs the results in the order `C, B, A` separated by linefeeds.
### Explanation
As usual, a short Labyrinth primer:
* Labyrinth has two stacks of arbitrary-precision integers, *main* and *aux*(iliary), which are initially filled with an (implicit) infinite amount of zeros. We'll only be using *main* for this answer.
* The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.
Despite the two no-ops (`"`) which make the layout seem a bit wasteful, I'm quite happy with this solution, because its control flow is actually quite subtle.
The IP starts in the top left corner on the `:` going right. It will immediately hit a dead end on the `?` and turn around, so that the program actually starts with this linear piece of code:
```
: Duplicate top of main stack. This will duplicate one of the implicit zeros
at the bottom. While this may seem like a no-op it actually increases
the stack depth to 1, because the duplicated zero is *explicit*.
? Read n and push it onto main.
: Duplicate.
: Duplicate.
```
That means we've now got three copies of `n` on the main stack, but its depth is `4`. That's convenient because it means we can the stack depth to retrieve the current multiplier while working through the copies of the input.
The IP now enters a (clockwise) 3x3 loop. Note that `#`, which pushes the stack depth, will always push a positive value such that we know the IP will always turn east at this point.
The loop body is this:
```
# Push the stack depth, i.e. the current multiplier k.
/ Compute n / k (rounding down).
) Increment.
# Push the stack depth again (this is still k).
* Multiply. So we've now computed (n/k+1)*k, which is the number
we're looking for. Note that this number is always positive so
we're guaranteed that the IP turns west to continue the loop.
" No-op.
! Print result. If we've still got copies of n left, the top of the
stack is positive, so the IP turns north and does another round.
Otherwise, see below...
\ Print a linefeed.
Then we enter the next loop iteration.
```
After the loop was traversed (up to `!`) three times, all copies of `n` are used up and the zero underneath is revealed. Due to the `"` at the bottom (which otherwise seems pretty useless) this position is a junction. That means with a zero on top of the stack, the IP tries to go straight ahead (west), but because there's a wall it actually makes a 180 degree turn and moves back east as if it had hit a dead end.
As a result, the following bit is now executed:
```
" No-op.
* Multiply two zeros on top of the stack, i.e. also a no-op.
The top of the stack is now still zero, so the IP keeps moving east.
@ Terminate the program.
```
[Answer]
# Matlab, 50 bytes
```
@(a)arrayfun(@(k)find(~rem(a+1:a+k,k))+a,[2 3 4])
```
[Answer]
## JavaScript (ES6), 26 bytes
Interestingly porting either @KevinLau's Ruby answer or @xnor's Python answer results in the same length:
```
n=>[2,3,4].map(d=>n+d-n%d)
n=>[n+2&-2,n+3-n%3,n+4&-4]
```
I have a slight preference for the port of the Ruby answer as it works up to 253-3 while the port of the Python answer only works up to 231-5.
[Answer]
# Retina, ~~62~~ ~~43~~ 26 bytes
17 bytes thanks to [@Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner).
```
^
1111:
M!&`(11+):(\1*)
:
```
(Note the trailing newline.)
[Try it online!](http://retina.tryitonline.net/#code=XgoxMTExOgpNISZgKDExKyk6KFwxKikKOgo&input=MTExMQ)
Input in unary in `1`, output in unary in `1` separated by newlines.
## Previous 43-byte version:
```
.+
11:$&;111:$&;1111:$&
\b(1+):(\1*)1*
$1$2
```
[Try it online!](http://retina.tryitonline.net/#code=LisKMTE6JCY7MTExOiQmOzExMTE6JCYKXGIoMSspOihcMSopMSoKJDEkMg&input=MQ)
Input in unary, output in unary separated by semi-colon (`;`).
## Previous 62-byte version:
```
.+
$&11;$&111;$&1111
((11)+)1*;((111)+)1*;((1111)+)1*
$1;$3;$5
```
[Try it online!](http://retina.tryitonline.net/#code=LisKJCYxMTskJjExMTskJjExMTEKKCgxMSkrKTEqOygoMTExKSspMSo7KCgxMTExKSspMSoKJDE7JDM7JDU&input=MTExMQ)
Input in unary, output in unary separated by semi-colon (`;`).
[Answer]
# Octave, ~~27~~ ~~22~~ 20 bytes
MATLAB and Octave:
```
f=2:4;@(x)f.*ceil((x+1)./f)
```
Better (solutions are equivalent, but one may outperform the other when further golfed), MATLAB and Octave:
```
@(x)x-rem(x,2:4)+(2:4)
f=2:4;@(x)x+f-rem(x,f)
```
Only in Octave:
```
@(x)x-rem(x,h=2:4)+h
```
[Try here](https://ideone.com/gFh8IM).
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 17 bytes
```
n$z3[zi2+$d%-+N].
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=n%24z3%5Bzi2%2B%24d%25-%2BN%5D%2E&input=57)
### Explanation
```
n$z Take number from input and store in register
3[ Open for loop that repeats 3 times
z Push value in register on stack
i2+ Loop counter plus 2
$d Duplicate stack
%-+ Mod, subtract, add
N Output as number
]. Close for loop and stop.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 bytes
-1 thanks to Adam
```
⎕(+-|⍨)1+⍳3
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE4Cktm7No94VhtqPejcb//9vYmQAAA "APL (Dyalog Unicode) – Try It Online")
Explanation:
```
⎕(+-|⍨)1+⍳3
1+⍳3 ⍝ 2 3 4
⎕ ⍝ read n
+-|⍨ ⍝ {⍺ + ⍵ - ⍵ | ⍺}
Let's look at how {⍺ + ⍵ - ⍵ | ⍺} is transformed to +-|⍨:
{⍺ + ⍵ - ⍵ | ⍺}
{⍺} + {⍵ - ⍵ | ⍺}
⊣ + ({⍵} - {⍵ | ⍺})
⊣ + (⊢ - ({⍵} | {⍺}))
⊣ + (⊢ - (⊢ | ⊣))
(⊣ + ⊢ - (⊢ | ⊣))
(+ - (⊢ | ⊣))
(+ - (⊣ |⍨ ⊢))
(+ - (|⍨))
(+-|⍨)
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 31 bytes
```
&2v
:&\&
?!\1+:{:}%
ao\n1+:5=?;
```
Expects `N` to be present on the stack at program start. [Try it online!](http://fish.tryitonline.net/#code=JjJ2CjomXCYKPT9cMSs6ezp9JTAKYW9cbjErOjU9Pzs&input=&args=LXYgMTA4MTE3Nw)
[Answer]
# Mathematica 28 bytes
```
f@n_:=n-n~Mod~#+#&/@{2,3,4}
```
---
```
f[1]
f[4]
f[43]
f[123]
f[420]
f[31415]
f[1081177]
```
{2, 3, 4}
{6, 6, 8}
{44, 45, 44}
{124, 126, 124}
{422, 423, 424}
{31416, 31416, 31416}
{1081178, 1081179, 1081180}
---
[Answer]
# R, ~~30~~ 26 bytes
(Reduced 4 bytes thanks to @Neil)
```
N=scan();cat(N+2:4-N%%2:4)
```
This (similarly to the rest of the answers I guess) adds 2:4 to the input and the reduces the remainder after running modulo on the same numbers.
[Answer]
# [UGL](https://github.com/schas002/Unipants-Golfing-Language), ~~51~~ ~~31~~ ~~25~~ 24 bytes
```
icu$l_u^^/%_u^*ocO$dddd:
```
[Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=aWN1JGxfdV5eLyVfdV4qb2NPJGRkZGQ6&input=MTI)
## Previous 25-byte version:
```
iRcu$l_u$r^/%_u*ocO$dddd:
```
[Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=aVJjdSRsX3Ukcl4vJV91Km9jTyRkZGRkOg&input=MTI)
## Previous 31-byte version:
```
iRcuuulu$cuuuuuu%-r^/%_u*oddcO:
```
[Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=aVJjdXV1bHUkY3V1dXV1dSUtcl4vJV91Km9kZGNPOg&input=MTI)
## Previous 51-byte version:
```
i$$cuuu/%_ucuuu*@cuuuu/%_ucuuuu*@cuu/%_ucuu*ocOocOo
```
[Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=aSQkY3V1dS8lX3VjdXV1KkBjdXV1dS8lX3VjdXV1dSpAY3V1LyVfdWN1dSpvY09vY09v&input=MTI)
[Answer]
# Java ~~70~~ 57
```
a->System.out.print(a/2*2+2+" "+(a/3*3+3)+" "+(a/4*4+4))
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 28 bytes
```
i2&::&::&@%-+nao&1+:&5=?;20.
```
# How it Works
```
i2&::&::&@%-+nao&1+:&5=?;20.
i2& Takes N as input and stores 2 in the register
:: Duplicates N twice
&::& Pushes the register onto the stack and duplicates twice
@ Shifts top the 3 values in the stack to the right
Stack now looks like: N N & N & (& = register)
%-+nao Computes the smallest multiple of k > N: N+k-N%k, where k is the value of the register
nao Outputs answer and a newline.
&1+:&5=?; Increments register by 1, ends the program if the register equals 5
20. Jumps back into the loop, skipping taking input and initializing the register
```
You could save a byte if you are allowed to take input by initializing the stack with N, but TIO doesn't allow for that. The interpreter on <https://fishlanguage.com/> does.
```
2&::&::&@%-+nao&1+:&5=?;10.
```
[Try it online!](https://tio.run/##S8sszvj/30jNygqEHFR1tfMS89UMta3UTG3trY0M9P7/LwIA "><> – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `r`, 8 bytes
```
3ɾ›ƛ⁰/⌈*
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=r&code=3%C9%BE%E2%80%BA%C6%9B%E2%81%B0%2F%E2%8C%88*&inputs=5&header=&footer=)
-1 thanks to lyxal
```
ɾ # Range 1...
3 # Literal
› # Incremented (2...4)
ƛ # Map to...
* # Product of...
# Current item (implicit)
* # And...
⌈ # Floor of
# (Implicit) current item
/ # Divided by...
⁰ # Input
```
] |
[Question]
[
Your network scanning tool is annoyingly picky about input, and immediately crashes if you feed it an IPv4 address that contains improper characters or isn't properly formatted.
>
> An IPv4 address is a **32-bit numeric address** written as four numbers separated by periods. Each number can be **zero to 255**.
>
>
>
We need to write a tool to *pre-validate* the input to avoid those crashes, and our specific tool is picky: A *valid* format will look like `a.b.c.d` where a, b, c and d:
* Can be a `0` or a natural number with **no leading zeros**.
* Should be between 0 - 255 (inclusive).
* Should **not** contain special symbols like `+`, `-`, `,`, and others.
* Should be decimal (base `10`)
**Input**: A string
**Output**: Truthy or Falsey value (arbitrary values also accepted)
**Test Cases**:
```
Input | Output | Reason
| |
- 1.160.10.240 | true |
- 192.001.32.47 | false | (leading zeros present)
- 1.2.3. | false | (only three digits)
- 1.2.3 | false | (only three digits)
- 0.00.10.255 | false | (leading zeros present)
- 1.2.$.4 | false | (only three digits and a special symbol present)
- 255.160.0.34 | true |
- .1.1.1 | false | (only three digits)
- 1..1.1.1 | false | (more than three periods)
- 1.1.1.-0 | false | (special symbol present)
- .1.1.+1 | false | (special symbol present)
- 1 1 1 1 | false | (no periods)
- 1 | false | (only one digit)
- 10.300.4.0 | false | (value over 255)
- 10.4F.10.99 | false | (invalid characters)
- fruit loops | false | (umm...)
- 1.2.3.4.5 | false | (too many periods/numbers)
- 0.0.0.0 | true |
- 0.0 0.0. | false | (periods misplaced)
- 1.23..4 | false | (a typo of 1.2.3.4)
- 1:1:1:1:1:1:1:1| false | (an IPv6 address, not IPv4)
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes will win!
>
> **Note for the users** - if anyone wants to add some test-cases, they're welcomed (by suggesting an edit).
>
>
>
[Answer]
# X86\_64 machine code: ~~18~~ 16 bytes
Edit: This answer doesn't quite work, as
1. I am using `inet_pton` from the standard C libraries, which means I need the extern. I didn't include the extern in my byte count though.
2. I used the red zone as a result for the actual address, but called a function which also could've used the red zone. It fortunately doesn't on my machine, but some odd standard library build might use it which could cause undefined behavior.
And yeah, the whole thing is pretty much being done by an already written function
Anyway, this is what I got: `48 89 fe 6a 02 5f 48 8d 54 24 80 e9 00 00 00 00`
Assembly:
```
section .text
extern inet_pton
global ipIsValid
ipIsValid:
mov rsi, rdi
;mov rdi, 2 ; change to 10 for ipv6
push 2
pop rdi ; thank you peter
lea rdx, [rsp - 128]
jmp inet_pton
```
# Explanation:
Take a look at `inet_pton(3)`. It takes a string IP address and puts it in a buffer you can use with `struct sockaddr`. It takes 3 arguments: the address family (`AF_INET` (ipv4), 2, or `AF_INET6` (ipv6), 10), the ip address's string, and a pointer to the output. It returns 1 on success, 0 for an invalid address, or -1 for when the address family is neither `AF_INET` or `AF_INET6` (which will never occur because I'm passing a constant to it).
So I simply move the string to the register for the second argument, set the first register to 2, and set the third register to the red zone (128 bytes below the stack pointer) since I don't care about the result. Then I can simply `jmp` to `inet_pton` and let that return straight to the caller!
I spun up this quick test program to test your cases:
```
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
extern int ipIsValid(char *);
int main(){
char *addresses[] = {
"1.160.10.240",
"192.001.32.47",
"1.2.3.",
"1.2.3",
"0.00.10.255",
"1.2.$.4",
"255.160.0.34",
".1.1.1",
"1..1.1.1",
"1.1.1.-0",
".1.1.+1",
"1 1 1 1",
"1",
"10.300.4.0",
"10.4F.10.99",
"fruit loops",
"1.2.3.4.5",
NULL
};
for(size_t i = 0; addresses[i] != NULL; ++i){
printf("Address %s:\t%s\n", addresses[i],
ipIsValid(addresses[i]) ? "true" : "false");
}
return 0;
}
```
Assemble with `nasm -felf64 assembly.asm`, compile with `gcc -no-pie test.c assembly.o`, and you'll get:
```
Address 1.160.10.240: true
Address 192.001.32.47: false
Address 1.2.3.: false
Address 1.2.3: false
Address 0.00.10.255: false
Address 1.2.$.4: false
Address 255.160.0.34: true
Address .1.1.1: false
Address 1..1.1.1: false
Address 1.1.1.-0: false
Address .1.1.+1: false
Address 1 1 1 1: false
Address 1: false
Address 10.300.4.0: false
Address 10.4F.10.99: false
Address fruit loops: false
Address 1.2.3.4.5: false
```
I could make this much smaller if the caller was supposed to pass `AF_INET` or `AF_INET6` to the function
[Answer]
# [Java (JDK)](http://jdk.java.net/), 63 bytes
```
s->("."+s).matches("(\\.(25[0-5]|(2[0-4]|1\\d|[1-9])?\\d)){4}")
```
[Try it online!](https://tio.run/##bVJNb9swDL3nVxDGgtlrREiK3dXN0h2GHXoYUKDALkkOiq10yvwRWHKwoclvzyTZTZxtEGSRfI9PpKmt2AuyzX@eVLmrGwNb62NrVIEfZqN/Ypu2yoyqq/@C2jRSlA7atetCZZAVQmv4JlQFryOAPqqNMPbY1yqH0mLhs2lU9bJYgWhedOSpAE@NzFUmjPzUwQ@g9HdRqPzxaR/D/KTJQxhgcKMjLIXJfkgdBuFyiSFPFpQkq0PI7RmvDmy5zA8LRtJV9NmaUfQaH4PoNPO3nK82UpsvQksN874AgIAhu6XIKPKYBhPrp9xG7tDGncuTxBMoTmMPOwA90wVpZzrWYL/pUMpwyjH@2GVynGKf2N3YMy3wDgfqaZqeEy5SeE4QuMYMcw/xKZLEYYw7n/zdDkmQ8OQWCb3uh1w31Hf75jh7GL22hlxCL/bNUOPrwLEFDP7dL4@8rxtgc0aIczwKfnlz4tdATZI7einKFuDHd@wGvKmb/n35Ed9fBh2d57yu60KKChqp28LYBzB4aej4oftEs57@/FsbWWLdGtxZYbMJgzFL9D2M9biyhTjypBfrk44jt4@nPw "Java (JDK) – Try It Online")
## Credits
* -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
* [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) for showing the previously-failing case `.1.1.1.1`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 43 bytes
```
x=>x.split`.`.map(t=>[t&255]==t&&[])==`,,,`
```
[Try it online!](https://tio.run/##XVBbboMwEPzvKSxUERB4ZRtIgyrzlxP0EyHh8mhT0YDAqjhBD9Aj9iLUdkhiqhXWzM7s4PWH@BJTNZ4Gic993SwtX2aezTAN3UmWUMKnGDzJs1y6LEkKzqXr5oXPeRmGYbk8P@QOBbonQAmwmDghcmjKVOcAqq@pGjMGAlFsZC0AuUrWdx0mhELEIH662BlEoJGKuPxmdSrhEazINE1vA/couA0IeIUKaiOxCHCiNco0x/93wAlgluwBk@0SeLvFuuKVaGx3t8j2YnLHgZ1xtIi6gPVgM10fQZeGu35ElFOMNTFGZMrA0JQV3OADcQpo@/EoqndvQjxDVX@e@q6Brn/zJhhE/SLFKD2a@ChAO/T7/aPOALXe5Pv@8gc "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 46 bytes
```
x=>x.split`.`.every(t=>k--&&[t&255]==t,k=4)*!k
```
[Try it online!](https://tio.run/##XVBBbsIwELz3FW5UQVKyK9tJKFFlbrygR4REGkJLg3AUW4h@oA/oE/uR1DYEHLSKNbMzO/H6qzgWqmx3jYaD3FTdVnQnMT@havY7vcY1Vseq/Q61mNcAo9FSj3iWrYTQcS3S6Pmx7l4flgFDNqXIKPKUBjEJWM5NZ4amb6kZcQaKSepkKyDtJe/rhyllmHBMX852jglaZCLOv7k4jfCEXmSe59eBWxReBwp8xxI3TuIJQmY1xi2H@x0gQ@DZFIEOl4DhFpcVe2Kx3x0i3wv0hid@xsIj5gLeg53Y5RFsWTiWLWGCAVjijMSVg7ErL7iCGQ1WuJXtoig/Q0XEnJTyoOS@wr38CBU2xeZNF60OWRaRCRmTv59fc07INlRRFHX/ "JavaScript (Node.js) – Try It Online")
used Arnauld's part
# [JavaScript (Node.js)](https://nodejs.org), ~~54~~ ~~53~~ 51 bytes
```
x=>x.split`.`.every(t=>k--*0+t<256&[~~t]==t,k=4)*!k
```
[Try it online!](https://tio.run/##XVBBboMwELz3FS6qGgjsyjaQBrXmlhf0GEUKJaRNQQGBFdFLjn1An9iPUNshiVOtsGZ3ZgePP7ND1uXtrpGwrzfFsBVDL9Ieu6bayTWusTgU7ZcrRVoCTKkvX3g8e1wej3IlhAxKEXnT@3J4vls6DNmMIqPII@oExGEJV5M5qrlueRwbAcUwMrQmkJ4p6zsvU8ow5Bg9neQcQ9RIWZx@MyoV8YCWZZIkl4WrFV4WMnzDHDeG4iFCrDnGdQ//M0CMoAIj0NsQcJtijHhuNLant8jWAr1i3/ZYWI26gPVgPRsfQZeGk7olTDAA3RghMWVgYMoyLmBOnRVu63aR5R9uR0RK8nrf1VWBVf3udthkm1eZtdJlsUd8MiG/3z/q9MnW7TzPG/4A)
-2B for `0+t<256`, -1B from Patrick Stephansen, +1B to avoid input `1.1.1.1e-80`
RegExp solution ~~58~~54 bytes
```
s=>/^((2(?!5?[6-9])|1|(?!0\d))\d\d?\.?\b){4}$/.test(s)
```
Thank Deadcode for 3 bytes
[Answer]
# [PHP](https://php.net/), 39 36 bytes
```
<?=+!!filter_var($argv[1],275,5**9);
```
[Try it online!](https://tio.run/##K8go@P/fxt5WW1ExLTOnJLUoviyxSEMlsSi9LNowVsfI3FTHVEvLUtP6////hkbmegZAaAgA "PHP – Try It Online")
275 resembles the constant `FILTER_VALIDATE_IP`
5\*\*9 is being used instead of the constant `FILTER_FLAG_IPV4`. This is sufficient, because `5**9 & FILTER_FLAG_IPV4` is truthy, which is exactly what PHP does in the background, as Benoit Esnard pointed out.
Here, `filter_var` returns the first argument, if it's a valid IPv4 address, or false if it's not. With `+!!`, we produce the output required by the challenge.
[Answer]
## PHP, 36 Bytes
```
echo(ip2long($argv[1])===false?0:1);
```
`ip2long` is a well-known [built-in function](http://php.net/manual/en/function.ip2long.php).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~22~~ ~~21~~ 20 bytes
*-1 byte thanks to Phil H.*
```
{?/^@(^256)**4%\.$/}
```
[Try it online!](https://tio.run/##TYzNDgExFIX3nqKL0pnBmdtfRIQHkZFZ6IqQsZqIZ6@2UuRuvnPynXs/DxcXriObebYLz33bHapOWVc3jZkewdtXePQj8xU/1czfhomQkI4gCcqQWMS8USCS0ApmlQsoaHwpAUUjT6wtE@nWiK@KxmESRiG/J@ick1Kkf063pB/PPz3LJ7bhDQ "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous Block
/ / # Regex match
^ $ # Anchor to start/end
@( ) # Interpolate
^256 # range 0..255,
# effectively like (0|1|2|...|255)
**4 # Repeated four times
%\. # Separated by dot
? # Convert match result to Bool
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ ~~24~~ ~~23~~ ~~22~~ ~~23~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'.¡DgsAì₅ÝAìÃg4)Ë
```
-1 byte thanks to *@Emigna*.
+1 byte for bugfixing test case `1.1.1.1E1` incorrectly returning a truthy result.
[Try it online](https://tio.run/##yy9OTMpM/f9fXe/QQpf0YsfDax41tR6eC6QPN6ebaB7u/v/fQM/AQM/QQM/I1BQA) or [verify all test cases](https://tio.run/##XVDBagIxFPyVEApLcd/wkt3o7kGkUL9CelAr0pOgIHpV9OKt9x5671d0/8Qf2SZvV82WEDLzZt4kL6vNdPaxqLf7kVbX86fSo32d4Pf7dbl5qX6uh1P15c/quMyfq0ud1hNtYPoMw7A561RpU1pfKeDrgVrnxMDIcpGDAHGGIjcwuKJ9y2E2yCzyQdNpkaFtbG5snV54QpReluW94RGFe8MUM8zxLpLNQC5oxgZO/8chB7KuD@LuPNQdqJ32RgKOq10Ue4kfuBdnjCPiHxD93U6UZLVWZmiIAhFVyRKYyorSFlSwfvsD).
**Explanation:**
```
'.¡ '# Split the (implicit) input-string on "."
D # Duplicate this list
g # Pop and push the length of this copy
s # Swap so the list is at the top again
Aì # Prepend the alphabet before each item
₅Ý # Push a list in the range [0,255]
Aì # Prepend the alphabet before each integer here as well
à # Only keep those items from the first list
g # Pop and push its length as well
4 # Push a 4
) # Wrap all three values on the stack into a list
Ë # Check that all three are the same (aka all three are 4s)
# (after which the result is output implicitly)
```
Prepending the alphabet is necessary, because in 05AB1E, `"0"`, `"00"`, `"0e0"`, `"5E0"`, `"-0"` etc. are all the same 'integer' `0`.
[Answer]
# Python 3: ~~81~~ ~~78~~ ~~70~~ ~~69~~ 66 bytes
```
['%d.%d.%d.%d'%(*x.to_bytes(4,'big'),)for x in range(16**8)].count
```
Loop over all possible IPv4 addresses, get the string representation and compare it to the input. It uh... takes a while to run.
EDIT: Removed 3 bytes by switching from full program to anonymous function.
EDIT2: Removed 8 bytes with help from xnor
EDIT3: Removed 1 byte by using an unpacked map instead of list comprehension
EDIT4: Removed 3 bytes by using list comprehension instead of the `ipaddress` module
[Answer]
# PowerShell, ~~59~~ ~~51~~ 49 bytes
*-8 bytes, thanks @AdmBorkBork*
*-2 bytes, `true` or `false` allowed by author*
```
try{"$args"-eq[IPAddress]::Parse($args)}catch{!1}
```
Test script:
```
$f = {
try{"$args"-eq[IPAddress]::Parse($args)}catch{!1}
}
@(
,("1.160.10.240" , $true)
,("192.001.32.47" , $false)
,("1.2.3." , $false)
,("1.2.3" , $false)
,("0.00.10.255" , $false)
,("192.168.1.1" , $true)
,("1.2.$.4" , $false)
,("255.160.0.34" , $true)
,(".1.1.1" , $false)
,("1..1.1.1" , $false)
,("1.1.1.-0" , $false)
,("1.1.1.+1" , $false)
,("1 1 1 1" , $false)
,("1" ,$false)
,("10.300.4.0" ,$false)
,("10.4F.10.99" ,$false)
,("fruit loops" ,$false)
,("1.2.3.4.5" ,$false)
) | % {
$s,$expected = $_
$result = &$f $s
"$($result-eq$expected): $result : $s"
}
```
Output:
```
True: True : 1.160.10.240
True: False : 192.001.32.47
True: False : 1.2.3.
True: False : 1.2.3
True: False : 0.00.10.255
True: True : 192.168.1.1
True: False : 1.2.$.4
True: True : 255.160.0.34
True: False : .1.1.1
True: False : 1..1.1.1
True: False : 1.1.1.-0
True: False : 1.1.1.+1
True: False : 1 1 1 1
True: False : 1
True: False : 10.300.4.0
True: False : 10.4F.10.99
True: False : fruit loops
True: False : 1.2.3.4.5
```
Explanation:
The script tries to parse an argument string, to construct a .NET object, [IPAddress](https://docs.microsoft.com/en-us/dotnet/api/system.net.ipaddress.parse).
* return `$true` if `object` created and the argument string is equal to a string representation of the `object` (normalized address by `object.toString()`)
* return `$false` otherwise
## PowerShell, ~~59~~ ~~56~~ 54 bytes, 'don't use a .NET lib' alternative
*-3 bytes, `true` or `false` allowed by author*
*-2 bytes, thanks to @[Deadcode](https://codegolf.stackexchange.com/a/179141/80745) for the cool regexp.*
```
".$args"-match'^(\.(2(?!5?[6-9])|1|(?!0\B))\d\d?){4}$'
```
[Try it online!](https://tio.run/##fZLRToMwFIbveYraVEcjnBQoKCYG44UvIWrIKM4EA1KIJsCz4xlbyNw625vyf/3/c2hbV9@q0RtVlhMryD3pJwosa941dT@zdr1Zvdop2L6dXITJc@TGL3zwBvwS6SPnaZ7mCe/lyFbTaFkPtkVwODb1wIsEeAJ8KShxCGubTvGFxj4I4UHgg7yZcZGV@oCDDwGcAwZdYNxcLQxNLiznRbeATRl6wUgG0mDDsPkvBATy1LdN2@cd9/gP2k5XnEXXRheZp4lQcjCcY4qN47FIENRM5dP2zOKYntKi6T5aUlZVrQ10dz8SQvqnrsXJQC5JP29j2mHqp1brVuX4rNjbTm2U7soWhSt8bUzPImX2XnfV12Lid8tuXGlqjdMv "PowerShell – Try It Online")
Thanks @[Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire) for the original regular expression.
[Answer]
# [C (gcc)](https://gcc.gnu.org/) / POSIX, 26 bytes
```
f(s){s=inet_pton(2,s,&s);}
```
[Try it online!](https://tio.run/##TY9fT4MwFMWf6ae4QWfaAdfyZ1PHtq/hw1wMKbA1YYXQ7sWFry62KGruQ3/n5JyTVEQnIcaxpprd9E6qyrx3plU0CXX4oFk@jHdSieZaVrDVppQtnvdEKgOXQirK4EY8cS56WJrDEXZW@jHGa44xxyTjfmj1S4Kcx5gmmD1NBiaY4i854DYxVVaruRKvn9FOzbF7zBzawDTPMZ20i8yh/@wu4n8cfPswncPNhvvEG3Li1W0P1P1I7ngOcqvlR9XW1LDHH1oaZv0gYMTzut4ma@ovNER7WJRvyg/BHOQxBFuxL2N2sq/MtVfAczKMn6JuipMeo1fVRvLSNVJIE9mVLw "C (gcc) – Try It Online")
Works as 64-bit code on TIO but probably requires that `sizeof(int) == sizeof(char*)` on other platforms.
[Answer]
# PHP 7+, ~~37~~ ~~35~~ 32 bytes
This uses the builtin function [`filter_var`](http://php.net/manual/en/function.filter-var.php), to [validate that it is an IPv4 address](http://php.net/manual/en/filter.filters.validate.php).
For it to work, you need to pass the key `i` over a GET request.
```
<?=filter_var($_GET[i],275,5**9);
```
Will output nothing (for a `falsy` result) or the IP (for a `truthy` result), depending on the result.
You can try this on:
~~<http://sandbox.onlinephpfunctions.com/code/639c22281ea3ba753cf7431281486d8e6e66f68e>~~
<http://sandbox.onlinephpfunctions.com/code/ff6aaeb2b2d0e0ac43f48125de0549320bc071b4>
---
This uses the following values directly:
* 275 = FILTER\_VALIDATE\_IP
* ~~1<<20 = 1048576 = FILTER\_FLAG\_IPV4~~
* 5\*\*9 = 1953125 (which has the required bit as "1", for 1048576)
Thank you to [Benoit Esnard](https://codegolf.stackexchange.com/users/38454/benoit-esnard) for this tip that saved me 1 byte!
Thank you to [Titus](https://codegolf.stackexchange.com/users/55735/titus) for reminding me of the changes to the challenge.
---
I've looked into using the function [`ip2long`](http://php.net/manual/en/function.ip2long.php), but it works with non-complete IP addresses.
Non-complete IPv4 addresses are considered invalid in this challenge.
If they were allowed, this would be the final code (only for PHP 5.2.10):
```
<?=ip2long($_GET[i]);
```
Currently, it isn't explicit in the documentation that this will stop working (when passed an incomplete ip) with newer PHP versions.
After testing, confirmed that that was the case.
Thanks to [nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof) for the tip!
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~84~~ ~~79~~ 65 bytes
```
s=>s.Split('.').Sum(t=>byte.TryParse(t,out var b)&t==b+""?1:5)==4
```
[Try it online!](https://tio.run/##dZFBS8QwFITv/opQZDdhdx9Jm1aLpiDCnjwICp63oZVAaJYkFfbX17Te7Ctzex/zYGZ0OOlgpvM46OcQvRm@j6R1zjakV1NQTYBXNw6RatVopWTFlCp2AT6u1kS6hz2DF2tpVE17ix18@tv7xYeOxqMbI/m5eNKyXVSqPWQZm57uvryJ3ZsZOtrTTNQ5cC6gyEE@ZIz9x5BDARv39ZmnXyA45GWJe@5BrgGIWZhhm8w68S1ywDxkEQKQE4ciJZHAUSbPc8i6XsPejyYS69w1bJUpoUSLm7WVB6@g@utaYrY0q6gecWtaZzGnkMsa0y8 "C# (Visual C# Interactive Compiler) – Try It Online")
-5 and -14 bytes saved thanks to @dana!
~~# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 61 bytes~~
```
s=>s.Count(c=>c==46)==3&IPAddress.TryParse(s,out IPAddress i)
```
[Try it online!](https://tio.run/##PcmxCsIwEADQvV8ROkgC9Ui1dKkXEEEQRAoKzpqmEtAEcpehXx@dXN@ztLbkSyYfXuK6ELsPXBwP1TEHuyNOP2/EM8a3ETMWQkNwiDmwtGgsYtcrxO3qNO6nKTkiuKVlfCRykpqYWfxDeFWG6p48u7MPTs6ybqHtNbQaNp2ulSpf "C# (Visual C# Interactive Compiler) – Try It Online")
This is a work in progress. The code use `System.Net` (+17 bytes if you count it). if you wonder why I count and parse:
>
> The limitation with IPAddress.TryParse method is that it verifies if a string could be converted to IP address, thus if it is supplied with a string value like "5", it consider it as "0.0.0.5".
>
>
>
[source](https://stackoverflow.com/questions/11412956/what-is-the-best-way-of-validating-an-ip-address)
As @milk said in comment, it will indeed fail on leading zeroes. So, the 61 bytes one is not working.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~85 82~~ 81 bytes
-1 byte thanks to Kevin Cruijssen
```
from ipaddress import*
I=input()
try:r=I==str(IPv4Address(I))
except:r=0
print~~r
```
[Try it online!](https://tio.run/##XVDLboMwELz7K6yoEpDWK9sYGipx6KEHbv2FFFyVQ8AyTpVc8uvUDxJMZVma3Zmdfair@RkHPrdjJ3GNd7vd/K3HE@7Vseu0nCbcn9SozR41dT@os0kzZPT1TddNXU9Gp83nr3gP0rTJMiQvrVTG8hQp3Q/mdtOzdUWWkC32bfY4L@dzwoCVFBgFLmiCbFxxmzmAzbuQF4UXUMiFpx0BXumSNECniv7dh1IGOQfxGio55LAUho6L0hJPELlXVfUoWK3gUXCEL2ih8xTPgRSOY9zF5P86pADCixII3e5Dtgst294Dh@PsFsVaQlf8HHt8RIEdILrdxTOjxqxmhDjsSeyfhy/@RWaSHOg6U@gP4aBiva2A5A8 "Python 2 – Try It Online")
[113 byte answer](https://tio.run/##PU/basMwDH3XV4gwsD0yYbtJtwS8x0G@YRs061zmkjrGM6P9@kzNLgiko8uRjtKlfMzRLsu7P@CTHFQPWPKlz@55dxrPUtenEKVt29p/jZMMSqndYc4YMEQc6DNNoUhBQr0C@vPep8JUIQBTDrHIwTlu0nHmJVmpWzn5K3CuUUuICR1WVWXIbDUZTbbRYDrL6QNxccVaG9pYau7BkKUN/YTV31ADmgdWatty7Wpd18H4tgde/CfvJQoF8C@bD/e/AjHU4u5R1MC/B7V8Aw) is deleted as it fails for `1.1.1.1e-80`
[Answer]
# Japt, ~~17~~ 15 bytes
```
q.
ʶ4«Uk#ÿòs)Ê
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=cS4KyrY0q1VrI//ycynK&input=IjEuMTYwLjEwLjI0MCI=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=cS4KyrY0q1VrI//ycynK&input=WwoiMS4xNjAuMTAuMjQwIgoiMTkyLjAwMS4zMi40NyIKIjEuMi4zLiIKIjEuMi4zIgoiMC4wMC4xMC4yNTUiCiIxLjIuJC40IgoiMjU1LjE2MC4wLjM0IgoiLjEuMS4xIgoiMS4uMS4xLjEiCiIxLjEuMS4tMCIKIi4xLjEuKzEiCiIxIDEgMSAxIgoiMSIKXQotbVI=) or [verify additional test cases from challenge comments](https://ethproductions.github.io/japt/?v=1.4.6&code=cS4KyrY0q1VrI//ycynK&input=WwoiMS4xNjAuMTAuMjQwIgoiMTkyLjE2OC4xLjEiCiIyNTUuMTYwLjAuMzQiCiIxLjEuMS4wIgoiMC4wLjAuMCIKIjI1NS4yNTUuMjU1LjI1NSIKIjE5Mi4wMDEuMzIuNDciCiIxLjIuMy4iCiIwLjAwLjEwLjI1NSIKIjEuMi4kLjQiCiIxLjEuMS45OTkiCiIxLjIuMyIKIjE5Mi4wMC4wLjI1NSIKImEuYi5jLmQiCiIxMjMuLTUwLjAuMTIiCiItMS4xNjAuMTAuMjQwIgoiLTUuLTI1Ni4tMC4xIgoiMjU1LjE2MC4tMC4zNCIKIjEuMS4xLjEuMSIKIjEuMS4xLjEuIgoiLjEuMS4xIgoiMS4uMS4xIgoiMS4uMS4xLjEiCiIxLjEuMS4tMCIKIjEuMS4xLisxIgoiMS4xLjEuMUUxIgoiMS4xLjEuMjU2IgoiMS4xLjEuMHgxIgoiJ29yIDE9MS0tIgoiIgoiMSAxIDEgMSIKIjEsMSwxLDEiCiIxLjEuMS4xZS04MCIKXQotbVI=)
---
## Explanation
We split to an array on `.`, check that the length of that array is equal to `4` AND that the length when all elements in the range `["0","255"]` are removed from it is falsey (`0`).
```
:Implicit input of string U
q. :Split on "."
\n :Reassign resulting array to U
Ê :Length of U
¶4 :Equals 4?
« :&&!
Uk :Remove from U
#ÿ : 255
ò : Range [0,255]
s : Convert each to a string
) :End removal
Ê :Length of resulting array
```
[Answer]
# ECMAScript pure regex, 41 bytes
`^((2(?!5?[6-9])|1|(?!0\B))\d\d?\.?\b){4}$`
[Try it online!](https://tio.run/##PY3dToNAEIXv9ylo0oSdKtNdWGooQRKT@gBVr0QTLEtFt0AW6k9/nh13WzXfxZyZM2fmLf/Iu5Wu2t7r2qqQetPU7/J70EktP52lXC@@Wkp3yfV0MjxT6tN0FKaPMy96ggM/mI5lNwBZkRVphmn2AntxHA@T6Q6wb@56XdVrCtipaiXp7NITAHHZaFomPKYq0TIvVFVLCjBK6q1ScZkw2FclHZXQmnBPISbttu96TRVu8n71SjWk7v3yYTF3HHfulrnq5NxxIf5bg/g4cOQzhpyhLxjhkY@McQx8FFeEo48BngthxjitheFpMkZBjD6lGQaCILcY719YPHY2LszAOUEMJmCuCWRWilt7N4pIqbdV76imabvf3wJD@9hiq2OVtQJE8QM "JavaScript (SpiderMonkey) – Try It Online")
[Try it on regex101](https://regex101.com/r/xFKpgH/1)
I think the logic in this regex speaks for itself, so I will merely pretty-print but not comment it:
```
^
(
(
2(?!5?[6-9])
|
1
|
(?!0\B)
)
\d\d?
\.?\b
){4}
$
```
This can be used to shave 2 bytes off the following other answers:
* [Olivier Grégoire](https://codegolf.stackexchange.com/a/174478/17216) (Java (JDK))
* [l4m2](https://codegolf.stackexchange.com/a/174456/17216) (JavaScript (Node.js))
* [mazzy](https://codegolf.stackexchange.com/a/174483/17216) (PowerShell)
* [Kevin Cruijssen](https://codegolf.stackexchange.com/a/174485/17216) (Retina)
Some alternative 41 byte versions:
`^((2(?!5?[6-9])|1|(?!0\d))\d\d?\.?\b){4}$`
`^(((2(?!5?[6-9])|1|(?!0))\d)?\d\.?\b){4}$`
`^(((2(?!5?[6-9])|1)\d|[1-9]?)\d\.?\b){4}$`
Here is an alternative version that allows leading zeros, but does so consistently (octets may be represented by a maximum of 3 decimal digits):
`^((2(?!5?[6-9])|1|0?)\d\d?\.?\b){4}$`
Or allow any number of leading zeros:
`^(0*(2(?!5?[6-9])|1?)\d\d?\.?\b){4}$`
Or if allowed to have undefined behavior regarding leading zeros (as it so happens, a leading zero is only allowed only in 2-digit octets):
`^((2(?!5?[6-9])|1?)\d\d?\.?\b){4}$`
[Answer]
# Mathematica, ~~39~~ 31 bytes
Original version:
```
¬FailureQ[Interpreter["IPAddress"][#]]&
```
Modified version (thanks to Misha Lavrov)
```
AtomQ@*Interpreter["IPAddress"]
```
which returns `True` if the input is a valid IP address ([try it](https://tio.run/##TY5ND4IwDIb/Clk8@VG7MTTc4GLCDc@EA5EZSeQjY56Mv322U4x50@192q5d37ib6RvXXRpf2m5wlc/d2J@zdTE4Yydr6KxEUeZta808i9rvs@gpJMgDgkRQGsVWyFQBooRYgT4yg4IYFkM3Ujm0J8k3uwJNjjhMQogZQbJCx59l7XApb0IyCmLHQc9pvgb8gD7xrjQlutpH56L7OE7z718aEvGq/Rs)).
In case you insist on getting `1` and `0` instead, then an additional 7 bytes would be necessary:
```
Boole/@AtomQ@*Interpreter["IPAddress"]
```
[Answer]
# JavaScript (ES6), 49 bytes
Returns a Boolean value.
```
s=>[0,1,2,3].map(i=>s.split`.`[i]&255).join`.`==s
```
[Try it online!](https://tio.run/##jZJfa8IwFMXf9ymCyGhZvd78c/QhPu5LiGBxrUSypjR1X79LIjLnaGrOU@DHyT335Fx9V@7Y625YtfazHhs1OrXdYUELVvA9fFVdptXWgeuMHg5w2On9K5Myh7PVrb8r5cajbZ01NRh7yppsQYFuECgCE7jIc0LWazL0l/rlkSsZIFLgDMR7AD3XVMb9B4EBh2h1PUnwjpsE0T8cJ5TyiqcclyB@PadA7xRjI3CRCg006KksD@g0GLTCWTByb3Q@CyVRT4D3u06Cfi1@4wJuUyZA8RGaKct0MU1/0QMx1nZuvkHuX5a3WRN/IuhP6tDg@AM "JavaScript (Node.js) – Try It Online")
[Answer]
# Python 2, ~~93~~ ~~89~~ ~~67~~ 53 bytes
```
[i==`int(i)&255`for i in input().split('.')]!=[1]*4>_
```
[Try it online!](https://tio.run/##TU5dT8MgFH0evwITI63GG6Cg6ZL6tr764tuyuFlZRmwKoTS6X18vzC7m8HHOPede8Od4coOcO/dpaEMZY/PWNs3eDrGw5Z3Uen90gVpqB1x@ikUJo@9tLBiwcnfTbMXuXr28z9hJyPfJ9oa@hcmsySqGM54r82O6Io0vUfiAg3OAoNEZH@nmtd2E4ELKfgRz@Fqc9TXfHvrRzEyAeOIgOEjFGWGilsC5gEqCek4aJFSwELw52jmu9V/1FhQy1HkShypJEAk58Y8mPPLFfshFmpFY2tiO8xXwi1BtequuUR3DZCPtnfPj9V8K9OVLCYz8Ag "Python 2 – Try It Online")
Thanks to Dennis for shaving *another* 14 bytes on the internal comparisons and exit code.
Special thanks to Jonathan Allan for shaving 22 bytes & a logic fix! Pesky try/except begone!
Taking properly formatted strings instead of raw bytes shaves off 4 bytes, thanks Jo King.
[Answer]
# [sfk](http://stahlworks.com/dev/swiss-file-knife.html), 176 bytes
\* was originally Bash + SFK but TIO has since added a proper SFK wrapper
```
xex -i "_[lstart][1.3 digits].[1.3 digits].[1.3 digits].[1.3 digits][lend]_[part2]\n[part4]\n[part6]\n[part8]_" +xed _[lstart]0[digit]_999_ +hex +linelen +filt -+1 -+2 +linelen
```
[Try it online!](https://tio.run/##jY7BCsMgEER/Zcl1iagJpX6LXZaCppWKlOrBv7dLIDnnMPB2YGembp8xeuwwJ5jY59qev0beqAVCeqVWSV07fI4lEPuv/Ft6lB3WA24H3IknwB4DnGXa7xHEzjkGfMsYzKlECQTcUm4woxHZ0x7DOKu0lnqrVv0H "sfk – Try It Online")
[Answer]
# ~~Python3~~ Bash\* 60
\*Also other shells. Any one for which the [truthy/falsy](https://codegolf.meta.stackexchange.com/a/2194/25088) test passes on a program exit code
```
read I
python3 -c "from ipaddress import*;IPv4Address('$I')"
```
## Explanation
The trouble with a pure Python solutions is that a program crashing is considered indeterminate. We could use a "lot" of code to convert an exception into a proper truthy/fasly value. However, at some point the Python interpreter handles this uncaught exception and returns a non-zero exit code. For the low-low cost of changing languages to your favourite Unix shell, we can save quite a bit of code!
Of course, this is vulnerable to injection attacks... Inputs such as `1.1.1.1'); print('Doing Something Evil` are an unmitigated threat!
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 15 bytes
```
ipcalc -c `cat`
```
[Try it online!](https://tio.run/##S0oszvj/P7MgOTEnWUE3WSEhObEk4f9/Qz1DMwM9I1NzIDYDAA "Bash – Try It Online")
Outputs exit code 0 for truthy, 1 for falsy.
[Answer]
# [Red](http://www.red-lang.org), 106 bytes
```
func[s][if error? try[t: load s][return off]if 4 <> length? t[return off]s =
form as-ipv4 t/1 t/2 t/3 t/4]
```
[Try it online!](https://tio.run/##XY7JDoMwDETvfIWFeq2bjS6oyz/0GnFAJWmRaIJMqNSvTyMujTjMwW9mbJPp4t10uilsHe3sHnpqdG/BEHm6QaCvDjUMvu0gGWTCTA68tU3KKDhfYTDuGV4pmZsTXArr6Q3ttO3Hj4Kw40kiSSapJo7UuwAWSo58z5AzFIqVxR@fBDLGUQpUh5yjQIlrkM0s1ZZ1VbVax/dHTNdW3Q2qjIhqeYehVGX8AQ "Red – Try It Online")
Returnd `true` or `false`
## Explanation:
```
f: func [ s ] [
if error? try [ ; checks if the execution of the next block result in an error
t: load s ; loading a string separated by '.' gives a tuple
] [ ; each part of which must be in the range 0..255
return off ; if there's an error, return 'false'
]
if 4 <> length? t [ ; if the tuple doesn't have exactly 4 parts
return off ; return 'false'
]
s = form as-ipv4 t/1 t/2 t/3 t/4 ; is the input equal to its parts converted to an IP adress
]
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
∞n·Θ3ª&JH‼∙*~Γ
```
[Run and debug it](https://staxlang.xyz/#p=ec6efae933a6264a4813f92a7ee2&i=%221.160.10.240%22%0A%22192.001.32.47%22%0A%221.2.3.%22%0A%221.2.3%22%0A%220.00.10.255%22%0A%221.2.%24.4%22%0A%22255.160.0.34%22%0A%22.1.1.1%22%0A%221..1.1.1%22%0A%221.1.1.-0%22%0A%22.1.1.%2B1%22%0A%221+1+1+1%22%0A%221%22%0A%2210.300.4.0%22%0A%2210.4F.10.99%22%0A%22fruit+loops%22%0A%221.2.3.4.5%22&a=1&m=2)
Unpacked, ungolfed, and commented, it looks like this.
```
VB constant 256
r [0 .. 255]
'|* coerce and string-join with "|"; i.e. "0|1|2|3 ... 254|255"
:{ parenthesize to "(0|1|2|3 ... 254|255)"
]4* make 4-length array of number pattern
.\.* string join with "\\."; this forms the complete regex
|Q is the input a complete match for the regex?
```
[Run this one](https://staxlang.xyz/#c=VB++%09constant+256%0Ar+++%09[0+..+255]%0A%27%7C*+%09coerce+and+string-join+with+%22%7C%22%3B+i.e.+%220%7C1%7C2%7C3+...+254%7C255%22%0A%3A%7B++%09parenthesize+to+%22%280%7C1%7C2%7C3+...+254%7C255%29%22%0A]4*+%09make+4-length+array+of+number+pattern%0A.%5C.*%09string+join+with+%22%5C%5C.%22%3B+this+forms+the+complete+regex%0A%7CQ++%09is+the+input+a+complete+match+for+the+regex%3F&i=%221.160.10.240%22%0A%22192.001.32.47%22%0A%221.2.3.%22%0A%221.2.3%22%0A%220.00.10.255%22%0A%221.2.%24.4%22%0A%22255.160.0.34%22%0A%22.1.1.1%22%0A%221..1.1.1%22%0A%221.1.1.-0%22%0A%22.1.1.%2B1%22%0A%221+1+1+1%22%0A%221%22%0A%2210.300.4.0%22%0A%2210.4F.10.99%22%0A%22fruit+loops%22%0A%221.2.3.4.5%22&a=1&m=2)
[Answer]
# Python 3, ~~109~~ 93 bytes
```
import re
lambda x:bool(re.match(r'^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(\.(?!$)|$)){4}$',x))
```
**Explanation**
Each octet can be 0 - 255 :
* starts with 25 and having 0-5 as last digit
* start with 2, has 0-4 as second digit and any digit at the end
* starts with 1, and 00 - 99 as rest digits
* has only 2 digits - 1-9 being the first one and any digit thereafter
* or just a single digit
An octet can end with a (.) or just end, with the condition that it cannot do both , the negative lookahead `(?!$)` takes care of this case
Thanks [@Zachary](https://codegolf.stackexchange.com/users/55550/zachar%C3%BD) for making me realize I can discard spaces (since it is code golf)
Thanks [@DLosc](https://codegolf.stackexchange.com/users/16766/dlosc) for the improvements and making me realize my mistake, its been corrected now.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~45~~ 21 bytes
```
I∧⁼№θ.³¬Φ⪪θ.¬№E²⁵⁶Iλι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzEvRcO1sDQxp1jDOb8UKFqoo6Ckp6Spo2AMxH75JRpumTklqUUawQU5mUiyIBmIBt/EAg0jUzMdBbB5OZpAyUxNCLD@/99Az8BAz9BAz8jU9L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 24 bytes by porting @Shaggy's Japt answer. Explanation:
```
θ Input string
№ Count occurrences of
. Literal `.`
⁼ Equal to
³ Literal 3
∧ Logical And
¬ Logical Not
θ Input string
⪪ Split on
. Literal `.`
Φ Filter by
¬ Logical Not
²⁵⁶ Literal 256
E Map over implicit range
λ Map value
I Cast to string
№ Count occurrences of
ι Filter value
I Cast to string
Implicitly print
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki), ~~46~~ 44 bytes
```
^
.
^(\.(25[0-5]|(2[0-4]|1\d|[1-9])?\d)){4}$
```
Port of [*@OlivierGrégoire*'s Java answer](https://codegolf.stackexchange.com/a/174478/52210), so make sure to upvote him!
-2 bytes thanks to *@Neil*.
[Try it online](https://tio.run/##VVDBTsMwDL37K3YYohX4yXaTbTkgToiPWDux0R24MGnigET59pKkS1VkRbGf37Nfcj1/fXwedbyrXt/GA4EOVYvK/F7Yd0Nl8XbdoG0/7JVDVz@3fV3/uN/1OCp0I1CBOSENFssdIkjmfW4JGkeaIAilMkZuLk4Wiigag9tGtqFBIk@TEyFCa5RBIYSJdBNiIh1xwjt6UmvAPqFqxP8csgeb34BlYZEXHpP1ktFcL665z3JLHmbFS8niivLmb6X7y3WlT8pMpKscpI85ivDMO6F5P6YPcH8).
**Explanation:**
```
^
. # Prepend a dot "." before the (implicit) input
^...$ # Check if the entire string matches the following regex
# exactly, resulting in 1/0 as truthy/falsey:
( # Open a capture group
\. # A dot "."
(25[0-5] # Followed by a number in the range [250,255]
|(2[0-4]| ) \d) # or by a number in the range [200,249]
|( |1\d| ) \d) # or by a number in the range [100,199]
|( |[1-9]) \d) # or by a number in the range [10,99]
|( )?\d) # or by a number in the range [0,9]
) # Close capture group
{4} # This capture group should match 4 times after each other
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pF/\./`, 47 bytes
```
$\=@F==4&&!/[^0-9.]/;$\&&=!/^0./&&$_<256for@F}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxtbBzdbWRE1NUT86zkDXUi9W31olRk3NVlE/zkBPX01NJd7GyNQsLb/Iwa22@v9/Qz0DINIz/JdfUJKZn1f8X9fXFChk8F@34L@um36Mnj4A "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁹ḶṾ€ṗ4j€”.ċ
```
A monadic link accepting a list of characters which yields \$1\$ if it's a valid address and \$0\$ otherwise. Builds a list of all \$256^4=4294967296\$ addresses and then counts the number of occurrences of the input therein.
**[Here's similar @ Try it online!](https://tio.run/##y0rNyan8//9R45aHO7Y93LnvUdOahzunm2QB6UcNc/WOdP///1/J0FTPQM9Qz9BACQA "Jelly – Try It Online")** that uses \$16\$ (`⁴`) rather than \$256\$ (`⁹`), since the method is so inefficient!
### How?
```
⁹ḶṾ€ṗ4j€”.ċ - Link: list of characters, S
⁹ - literal 256
Ḷ - lowered range = [0,1,2,...,254,255]
Ṿ€ - unevaluate €ach = ['0','1',...,['2','5','4'],['2','5','5']]
ṗ4 - 4th Cartesian power = ALL 256^4 lists of 4 of them
- (e.g.: ['0',['2','5','5'],'9',['1','0']])
”. - literal '.' character
j€ - join for €ach (e.g. ['0','.','2','5','5','.','9','.','1','0'] = "0.255.9.10")
ċ - count occurrences of right (S) in left (that big list)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~42~~ 41 bytes
```
~(K`
255*
["^(("|'|]")\.?\b){4}$"L$`
$.`
```
[Try it online!](https://tio.run/##VVBNb8IwDL37V6CqiALzk50mQA/TTogD/IOxqXwduICEdpg02F/vkpRUnawo9vN79ktup6/zZafNsFjVzW@xromMcxN6zz6LIruP7h/ZeIu37X78Yx95tslrylE3jUJnAhUYK6SV8eUCHgzq2BKUljRAEAqlj9jsnSgUUZQGdu7ZBiUCuZ0cCB7KkQZVVdWSnkK0pB32OOBIakqwC6ga4n8O2YGNm4GlZ5F7HoP1lFFX966uz/JMpp1imTK/Ir35W2l0vQ30VZmJdBCD9CVGEp54IdTtR/sB9g8 "Retina – Try It Online") Based on a previous version of @nwellnhof's Perl 6 answer, but 1 byte saved by stealing the `\.?\b` trick from @Deadcode's answer. Explanation:
```
K`
```
Clear the work area.
```
255*
```
Insert 255 characters.
```
["^(("|'|]")\.?\b){4}$"L$`
$.`
```
Generate the range 0..255 separated with `|`s, prefixed with `^((`, and suffixed with `)\.?\b){4}$`, thus building the regular expression `^((0|1|...255)\.?\b){4}$`.
```
~(
```
Evaluate that on the original input.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~25~~ 16 bytes
```
a~=X,256RL4J"\."
```
Takes the candidate IP address as a command-line argument. [Try it online!](https://tio.run/##K8gs@P8/sc42QsfI1CzIx8RLKUZP6f///4Z6hmYGeoYGekYmBgA "Pip – Try It Online") or [Verify all test cases](https://tio.run/##TU7LCsIwELz3K8LiTTts0qSlBz16EL14ElTEi1AotPg4if56zKYPy5AwM8zuTlu1/gJS6UoR3v76XR4WxuX7rd3QCeQ/aqeOiSINnTM0w1gm0aUBs0ZmYItowCDDyIRwSMQR5wZ/Bis0OHEfI4saWtCFplyQ8piYd7aKiDR@YUs4ZMG9smu5WpYib/dX9VR107SPf0sLN7SYvL6ygJKz92n9Aw)
### Explanation
Regex solution, essentially a port of [recursive's Stax answer](https://codegolf.stackexchange.com/a/174518/16766).
```
a is 1st cmdline arg (implicit)
,256 Range(256), i.e. [0 1 2 ... 255]
X To regex: creates a regex that matches any item from that list
i.e. essentially `(0|1|2|...|255)`
RL4 Create a list with 4 copies of that regex
J"\." Join on this string
~= Regex full-match
a against the input
```
] |
[Question]
[
This simple challenge is very similar to this one: [How many days in a month?](https://codegolf.stackexchange.com/questions/146555) The only difference is you **yield the number of days in a month given the index of the month** instead of its name.
The reason I ask this near-duplicate is curiosity about mathematical patterns in the sequence of numbers. For example, a simple observation is that even-indexed months have 31 until August and then it flips — but golf that observation and/or make better ones that yield better strokes...
**INPUT**: Integer indicating the month; `1` through `12`. (Optionally, you can accept `0`-indexed month numbers from `0` to `11`.)
**OUTPUT**: Number of days in that month. February can return `28` or `29`.
**Complete I/O table:**
```
INPUT : OUTPUT
1 31
2 28 or 29
3 31
4 30
5 31
6 30
7 31
8 31
9 30
10 31
11 30
12 31
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~13~~ 12 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function. 0-indexed. February is 29.
```
31-1∘=+2|7∘|
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///39hQ1/BRxwxbbaMacyBd8z/tUduER719j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv9PUzBQMFQwUjBWMFEwVTBTMFewULBUMAQKGgIA "APL (Dyalog Unicode) – Try It Online")
`31-` thirty-one minus…
`1∘=` the equal-to-one'ness…
`+` plus…
`2|` the two-mod of…
`7∘|` the seven-mod'ness
>
> The reason I ask this near-duplicate is curiosity about mathematical patterns in the sequence of numbers. For example, a simple observation is that even-indexed months have 31 until August and then it flips — but golf that observation and/or make better ones that yield better strokes...
>
>
>
This solution implements the following mathematical pattern:
$$f(x)=31-[x=1]-\big((x\mod 7)\mod 2\big)$$
or
$$f(x)=31-x-\left[x=1\right]+7\left\lfloor\frac{x}7\right\rfloor+2\left\lfloor x-7\left\lfloor\frac{x}7\right\rfloor\over2\right\rfloor$$
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/index.html), 706 bytes
```
counting a day,one month<t-o>twelve
i got frustrated doing a list
i do say,o,i edited a list,a month&a day count
in twelve(in December)to one(January)i listed a day"s count,then the numeral months
and once i am ready,o,i think i got a number to say
a number,o,i know a count
o,i say i am thirty if one"s short
i am ready,o,i know a count is not a thirty if we switch it
a long,a short,a etc.i switch
i do think i want a count of Febr-u"ry=two n eight:a case of a month"s age as shorter than the others"s
a day"s a day,i reckon
i know,i am clever
o,a date"s count at min=a thirty-day,or affix a one,i think
i do start&i produce threes if ever i am thirty
P.S.note:i index by one,i receive any-format numbers
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?VVJBbuMwDLz7FUQOQQM4OfRYbPe06GFPC@wLGIu2iNjUQqLj@vUtJdnb9GLLJmc4M1QXZlGWARAcrm0QgimI@h96Dj91ofFODcMQFPo4J42o5MCFihg5qVVdgJSxLQM5zg211GLlOhZu6PKohgUq7ZOdflFH05XiSQPY6KffKDPG9cQFX4gMeUgV26onQ3sCmSeKOFb61KA4g3cEDDhBJHRVjXqWG1T5mEE2CrSobfbv0niTsFhHVZh/WEclM4qodu6zPhOSfIjZ87c5j3DgBFLmfUEXgrSwdh5YbfAYZLBsCpW9SbsLbw01zV33gqL/eUMPb3SN5/kQ11ddAggQD15frAET5fqWt8nEgQA3tdmzxxpcsEdMB4tsC7aunc1MdwvSVC9t8deNdKdoceQepX0LgAoTy@tu8FzuTQTse343Pstpj367G4pRjwz/YnCzLUl9JEo5l8z/GHPz5/L3YuHRCwOLo3e4rhuf6SO@mylZz32Ik4mo@0sfzx9XdJ8)
As noted in the final line of the program, this program takes months as 1-based indices, and can take both simple numbers and numbers with a leading 0. (How's *that* for code comments?)
In pseudocode, my approach was basically like this:
```
N = input(); // Poetic doesn't support native numerical input, only input as ASCII codes; I basically have to write myself a number input routine every time
DIGIT = 49 // ASCII value for "1"; I would set it to 3, but that would be slightly longer
if (N>7) N++; // this accounts for the July->August parity shift
if (N!=2) { // if not February...
DIGIT += 2; // now it's "3"
print(DIGIT); // output: "3"
DIGIT -= 3; // and now it's "0"...
if (N%2==1) THREE++; // ...unless N is odd
print(DIGIT); // output: "30" if short month, "31" if long month
} else { // if February...
DIGIT += 1; // now it's "2"
print(DIGIT); // output: "2"
DIGIT += 6; // now it's "8"
print(DIGIT); // output: "28"
}
```
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 4 bytes
```
~%R@
```
I have no idea how does this work (actually, after reading the source, I think I do, but Pyke seems **extremely** weird to me) as I simply used the second half of the Pyke answer by @Blue in the related question OP linked to.
[Try it online!](https://tio.run/##K6jMTv3/v041yOH/f2MA "Pyke – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 27 bytes
0-indexed.
Instead of indexing into a string, I get the day offset (from 28) for the month from a packed bit array. Luckily all the offsets fit in a two-bit representation, so the bit array fits in an integer: I just shift and mask the offset and add 28.
```
f(m){m=0xEEFBB3>>m*2&3|28;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1ezOtfWoMLV1c3JydjOLlfLSM24xsjCuvZ/Zl6JQm5iZp5GWX5miqZCNZeCQlp@kQZIONPWwFoh08bQCEhqa2sqFBQBRdM0lHzz80oyFFRTFGztQGRKYmVxTJ6SjkKmjkKaRqampjVX7f9/yWk5ienF/3XLAQ "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6), 16 bytes
All solutions expect a 0-indexed input and output 29 days for February.
Using a decimal modulo.
```
n=>n%1.7+!~-n^31
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5P1VDPXFuxTjcvztjwf1p@kUaegq2CgbVCnoKNgqERkNbW1lRIzs8rzs9J1cvJT9fI01FI08jT1PwPAA "JavaScript (Node.js) – Try It Online")
---
Using a single integer modulo.
```
n=>30-!~-n|n%7^1
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1s7YQFexTjevJk/VPM7wf1p@kUaegq2CgbVCnoKNgqERkNbW1lRIzs8rzs9J1cvJT9fI01FI08jT1PwPAA "JavaScript (Node.js) – Try It Online")
---
Same approach as [Adám](https://codegolf.stackexchange.com/a/195887/58563) with 2 integer modulos.
```
n=>31-n%7%2-!~-n
```
[Try it online!](https://tio.run/##DcVBDkAwEAXQq4yFpE2NUAsL6i5NqRD5IyqWrl7e5u3@8Slc23kzZF5ydBlu6lpG2ZeWi5eRo1wK5KgZCDRSa/@N0RQESY6lPmRVqCgqaJ0/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 3 bytes
```
∂k=
```
Yep, there's a built-in.
[Try it online!](https://tio.run/##S0/MTPz//1FHU7bt//9GAA "Gaia – Try It Online")
```
∂k List containing days in each month
= Index into it (implicit input)
```
[Answer]
# x86 Machine Code, 14 bytes
```
B8 B3 FB EE 00
01 C9
D3 E8
24 03
04 1C
C3
```
This is a straight port of [ErikF's C answer](https://codegolf.stackexchange.com/a/195904). The above bytes define a function that accepts a zero-indexed month (in the `ECX` register), and outputs the number of days (in the `AL` register, the lower-order bytes of the `EAX` register). The result is calculated by adding 28 to a fix-up parameter obtained from a sequenced vector of 2-bit values.
```
B8 B3 FB EE 00 mov eax, 0x00EEFBB3 ; load bit vector into EAX
01 C9 add ecx, ecx ; \ index into the bit vector
D3 E8 shr eax, cl ; | by shifting it right
24 03 and al, 3 ; / and keeping only the lowest 2 bits
04 1C add al, 28 ; add 28
C3 ret
```
**[Try it online!](https://tio.run/##fZFdT8IwFIavt19xMiXpYMKYkRgBE6NecOG9FyRLbcvWpHSkHwYx/HVn2ykRJfamp@3z9ny85IIILKu2tVLzSjIKpMYKHvCbXsinRpoacWlg7aM0fo/BrQOqmLbCTMNlWWK9LkuULM26eRXu5nx8NZkUeX6ZQa/H8HYpk0B@L0diSj3pnsk267YTlK5VRxHxz1eSvvikIRsWp5MForjukCPgBpI5TgB1LaUAoz401myscV1WXBumgGt4vHuG/uiXkCQAqJsQBCGXXncsvP8r/HlKuykqZqySh8Hu2zMuibCUwUwbypthfRvHwRDMJfKGRKtGAdJ8x0oDHOaQT902g3ExhcGAp3HkmGijnGiFkuAo9IqdhRprF1CgzuqhG1cGPANvdnpkfuoqi/Zx9FVZ7ov6ICuBK91@Ag "C (clang) – Try It Online")**
Note that we can do the `AND` and `ADD` on byte-sized operands, which results in 2-byte instructions, rather than the 3-byte instructions required to operate on double-words.
The big bloat here is that initial 32-bit `MOV` instruction required to load the bit vector, but this implementation is still significantly smaller than a solution implementing the mathematical algorithm cited by [Adam](https://codegolf.stackexchange.com/a/195887/58518): `(31 - ((month % 7) % 2) - (month == 1))`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
7%É31αsΘ-
```
Same formula as [*@Adám*'s APL (Dyalog Unicode) answer](https://codegolf.stackexchange.com/a/195887/52210), which I've also partially used in [this earlier answer of mine](https://codegolf.stackexchange.com/questions/173104/the-work-day-countdown/173126#173126).
[Try it online.](https://tio.run/##yy9OTMpM/W9o5OZnr6TwqG2SgpK9n8t/c9XDncaG5zYWn5uh@1/nPwA)
**Explanation:**
```
7% # Take the (implicit) input-integer modulo-7
É # Check whether it is odd (short for modulo-2)
31α # Take the absolute difference with 31
s # Swap to take the (implicit) input-integer again
Θ # 05AB1E truthify; 1 if n==1; 0 otherwise
- # And subtract this from the earlier number
# (after which the result is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 24 bytes
```
lambda n:31-n%7%2-(n==1)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPythQN0/VXNVIVyPP1tZQ839afpFCnkJmnkJRYl56qoahkaYVl0JBUWZeiUaaRp6m5n8A "Python 3 – Try It Online")
Adaptation of [Adám's APL answer](https://codegolf.stackexchange.com/a/195887/87681)
---
Original answer:
# [Python 3](https://docs.python.org/3/), 29 bytes
```
lambda n:31^n%2^n//7^2*(n==1)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPytgwLk/VKC5PX988zkhLI8/W1lDzf1p@kUKeQmaeQlFiXnqqhqGRphWXQkFRZl6JRppGnqbmfwA "Python 3 – Try It Online")
[Answer]
# [Turing Machine Code](http://morphett.info/turing/turing.html), 197 bytes
```
0 0 _ * j
0 1 _ r F
0 2 _ * j
0 3 2 * F
0 4 _ * j
0 5 2 * F
0 6 _ * j
0 7 _ * j
0 8 2 * F
0 9 _ * j
h * * * halt
j _ 3 r ǰ
ǰ _ 1 * h
F _ 2 r Ƒ
Ƒ _ 8 * h
F 0 2 * F
F 1 _ r j
N _ 0 * h
F 2 3 r N
```
[Try it online!](http://morphett.info/turing/turing.html?8f4d81596dcfd7859a1915b575e5df9d)
[Answer]
# [Python 3](https://docs.python.org/3/), 58 45 bytes
```
lambda x:'312831303130313130313031'[x*2:][:2]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRocJK3djQyMLY0NgAiuEs9egKLSOr2Ggro9j/BUWZeSUaaRqGmpr/AQ "Python 3 – Try It Online")
* A weak solution to get it started with an "unanalyzed" solution space
* Saved a few bytes by functionizing thanks to Jo King
[Answer]
# [PHP](https://php.net/), 31 bytes
```
<?=date(t,mktime(0,0,0,$argn));
```
[Try it online!](https://tio.run/##K8go@P/fxt42JbEkVaNEJze7JDM3VcNABwRVEovS8zQ1rf//N/mXX1CSmZ9X/F/XDQA "PHP – Try It Online")
Just using builtins really. Input month via STDIN, 1-indexed.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 20 bytes
```
x=>"
"[x]
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXogPEdmm2/yts7ZTkZeTlgBBMKEVXxP635krLL9IAqlDItDWwzrQxNLLO1NbWDC/KLEn1ycxL1UjTyNTUtP4PAA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~42~~ ~~39~~ 35 bytes
```
lambda i:(30+(i%2==(i<8)),28)[i==2]
```
[Try it online!](https://tio.run/##Tc29DkAwEADg3VNYJL0wtFc/Je5JMBARl1AiFk9fk5zt277zudfDY1ioD9u4T/MYc6OsThUnSKS4dQAZOuiYCIdwXuzveFEGoo8otMJcWAhLYSV0wlpo9M@/zyCEFw "Python 2 – Try It Online")
Not the shortest Python solution but an alternative approach (1 indexed).
Shorter but not very interesting:
# [Python 2](https://docs.python.org/2/), 34 bytes
```
lambda i:int("303232332323"[i])+28
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHTKjOvREPJ2MDYCAjBhFJ0ZqymtpHF/4IioJxCmoahJheMaYRgGiOYJgimKYJphmCaI5gWCKYlgmlogMRGss/QSPM/AA "Python 2 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~29~~ 28 bytes
```
^o$
x
o{7}|oo
^
31*
__x|_o
```
Explanation:
```
^o$ match input equal to "o"
x replace it with x
o{7}|oo match 7 or 2 "o"s, whichever the regex engine prefers
replace them with nothing (this happens to compute a%7%2)
^ match the beginning of string
31* and replace it with 31 times the default character (_)
__x|_o match __x or _o literally
and erase them (that is, "x" means "erase two _" and "o" means "erase one _")
```
[Try it online!](https://tio.run/##K0otycxLNPyvqpHA9T8uX4Wrgiu/2ry2Jj@fiyuOy9hQiys@vqImPp/r/3@ufK58EAJjCAElYRScRjCQWMjMfAA "Retina – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 46 bytes
```
func[m][b:(a: to now[1 m 1])+ 31 b/4: 1 b - a]
```
[Try it online!](https://tio.run/##DcUxCgIxEAXQ3lN8tlJEQtTGOYbtMEV2M0FhMwmbLOLpo695m8bx1MhySDTSbgtn4ZmOgdALrHzYI8PL6Yybx@zuhH@4IMjYtGroMPgruG5v61xDRPu2rtmtZQmrulysv5ojwwMTTUgwkfED "Red – Try It Online")
A verbose solution that literally calculates the number of days in the given month (28 for february - year 1 AD)
## Explanation:
```
Red[]
f: func[m][
a: to now [1 m 1] ; make a date dd-mm-yyyy (1st of the "month" year 1 AD)
b: a + 31 ; add 31 days to it
b/4: 1 ; and go back to the 1st day of the new month
b - a ; subtract the initial date from the new one
]
```
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
Not in any way clever, but there you go. Pretty much checks all the non-31-day months and if it isn't any of them it falls back on 31.
```
f 2=28;f m|elem m[4,6,9,11]=30;f _=31
```
[Try it online!](https://tio.run/##HchBCsIwEAXQ/T9FFi4UQugktbZITiIig05oMInSVNx49yi@5Zu53iWlljkWH8sqC19XtVGvkmKRajI/t3V@vE0wi/BtZ/7dgrLejseg8keSZJVPvR70pInO3nW/v3hHrREsHHrsMeCAEROoAxHIfgE "Haskell – Try It Online")
[Answer]
## Excel, 29 bytes
```
=DAY(EOMONTH(DATE(0,B1,1),0))
```
Where `B1` is the month number (1-based).
[Answer]
As suggested by @Xcali it can be even shorter:
# [Perl 5](https://www.perl.org/), 35 bytes
```
$_=substr"3128".3130313031x2,$_*2,2
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ra4NKm4pEjJ2NDIQknP2NDYAIIrjHRU4rWMdIz@/zf8l19QkpmfV/xftwAA "Perl 5 – Try It Online")
As suggested by @manatwork this can be shortened substantial:
# [Perl 5](https://www.perl.org/), 39 bytes
```
("3128".3130313031x2)=~/(..){$_}/;$_=$1
```
[Try it online!](https://tio.run/##K0gtyjH9/1/J2NDIwtjQ2ACK4Swl2zp9DT09zWqV@Fp9a5V4WxXD//@N/uUXlGTm5xX/1y0AAA "Perl 5 – Try It Online")
~~Perl (And because I like regex, a first humble attempt):~~
# [Perl 5](https://www.perl.org/), 60 bytes
```
print $1 if "312831303130313130313031" =~ /(..){$ARGV[0]}/g;
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvREHFUCEzTUHJ2NDIwtjQ2ACK4SwlBds6BX0NPT3NahXHIPewaIPYWv106////xsBAA "Perl 5 – Try It Online")
Invoke via `perl -e` and user supplied input, e.g. `2` for the month, at command line argument with index 0.
[Answer]
# z80 Machine Code, 13 bytes
```
47 1F 1F 1F A8 E6 01 05 10 01 3D C6 30
```
Takes input (starting at 1) in the A register and stores output in the same register. This was manually assembled from the ez80 manual and is not yet tested, therefore it might contain some mistakes.
**Explanation:**
```
47 ld b, a ; Copy the value to the B register
1F 1F 1F rra (3 times) ; \ Set A to ((A >> 3) ^ B) & 1, which is
A8 xor a, b ; | equal to 1 on all months with 31 days
E6 01 and a, 1 ; /
05 dec b ; \ Decrement the B register twice and skip the next instruction if
10 01 djnz $+3 ; / the resulting value is not zero (if the month is not february)
3D dec a ; Decrement A (if february)
C6 30 add a, 30 ; Add 30 to A
```
[Answer]
# [C++ (g++)](https://gcc.gnu.org/), ~~60~~ ~~54~~ ~~47~~ 40 bytes
1-indexed. f(2)==29.
```
int f(int n){return(n^n/8)%2-(n==2)+30;}
```
Solution from k-map, which simplified to A=w+x+z and B=zw'+z'w. A was negated and became a subtraction.
```
int f(int n){ //N is a 4-digit binary number wxyz.
return (n^n/8) %2 //Add 1 if (w XOR z)
- (n==2) //Subtract 1 if !(w OR x OR z), which simplifies to (w'x'z'),
//which is only satisfied when N is 0000 or 0010.
//Since n is never 0, this condition is only satisfied when n==2.
+ 30; //Add 30, the base month length.
}
```
At first I tried adding 1 or 2 instead of 1 or 1, but my solution was 87 bytes (if I remember correctly). I tried that with 0-indexing and 1-indexing, but they ended up being the exact same length.
47 bytes: `int f(int n){return(n/8|n/4|n)%2+(n^n/8)%2+29;}`
54 bytes: `int f(int n){return((n>>3|n>>2|n)&1)+((n^n>>3)&1)+29;}`
60 bytes: `int f(int n){return(n>>3&1|n>>2&1|n&1)+((n&1)^(n>>3&1))+29;}`
Edit: Thanks to Herman L. for the improvement to 54 bytes, I'm glad someone found my approach interesting even though it's clearly not the shortest!
Edit 2: Thank you to ceilingcat for the improvement to 47 bytes. This uses division instead of bit shifting, which saves one byte in each of three places. It also replaces `&1` with `%2` in two places. Both of these functionally return the last byte of the integer, but the modulo operator has precedence over addition. This means that two pairs of parentheses can be removed, saving four bytes. In total, by mixing arithmetic and bitwise operators, ceilingcat managed to improve the answer by seven bytes!
Edit 3: Another improvement by ceilingcat brings it down six bytes by doing bitwise comparison with 13, `-!(n&13)`. Since this is only true in one case, simplified to an equality check.
[Answer]
# Javascript, 23 bytes
```
n=>15662007>>~-n*2&3|28
```
This is utilizing a binary map 15662007 which is
```
111011101111101110110111
11.10.11.10.11.11.10.11.10.11.01.11
3. 2. 3. 2. 3. 3. 2. 3. 2. 3. 1. 3
```
You just add each item to 28 and see that it provides a proper mapping to each month.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 18 bytes
```
->n{31-n%7%2-2[n]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6v2thQN0/VXNVI1yg6L7b2v6GRXklmbmpxdU1FTYFCdIVOWnRFLFAcAA "Ruby – Try It Online")
0-based, basically the same formula as Adam, adapted to ruby.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
%7Ḃ31__1⁼$
```
[Try it online!](https://tio.run/##y0rNyan8/1/V/OGOJmPD@HjDR417VP4bGj3cse1w@6OmNZH/AQ "Jelly – Try It Online")
Pretty much just a translation of Adám and Kevin Cruijssen's APL and 05ab1e answers, respectively. There's probably some way I could cut out the `$`.
[Answer]
# T-SQL 61 bytes
```
declare @ int set @=2print DAY(EOMONTH(DATEFROMPARTS(1,@,1)))
```
40 bytes if we put the input directly to the query:
```
print DAY(EOMONTH(DATEFROMPARTS(1,2,1)))
```
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
(31-0 2 0,#:330){~]
```
For fun, here's a J translation of Adam's APL answer (also 12 bytes):
```
31-1&=+2|7&|
```
Jonah's comment saves another 4 bytes, due to:
1. better use of J's hook: `({...)` instead of `(...{~])`
2. better choice of starting binary values, adjusting the arithmetic as necessary (`30+1 _1,...` rather than `31-0 2 0,...`):
```
| expr | result |
|---------|----------------------|
| 0,#:330 | 0 1 0 1 0 0 1 0 1 0 |
| #:693 | 1 0 1 0 1 1 0 1 0 1 |
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuo2CgYAXEunoKzkE@bv81jA11DRSMFAx0lK2MjQ00q@ti/2tycaUmZ@QrpCkYwBiGMIYRjJGpZ2j0HwA "J – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-rr`, ~~17~~ ~~16~~ ~~14~~ 13 bytes
```
$:&1=-&7%2%-
```
[Try it online!](https://tio.run/##y05N/@@QZlij/F9exUrN0FZXzVzVSFX3/7FJh/Y7pB2b9N/wv25REQA "Keg – Try It Online")
Simply a port of Adams APL answer.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 8 bytes
0-indexed, February is 29.
```
C@."
"
```
[Try it online!](https://tio.run/##K6gsyfj/39lBT0lW/uPijjal//@NAQ "Pyth – Try It Online") TIO doesn't seem to like the UTF-8 conjoined character, but it works in the official interpreter. Consider TIO a glorified pastebin for this.
Previous version, 10 bytes:
```
C@."
Îï»
```
[Try it online!](https://tio.run/##K6gsyfj/39lBT0lGnvlw3@H1h3Yr/f9vCAA "Pyth – Try It Online")
[Answer]
# [Wren](https://github.com/munificent/wren), 27 bytes
-3 bytes thx to Jo King for putting all into a tertiary statement.
```
Fn.new{|x|1==x?28:31-x%7%2}
```
[Try it online!](https://tio.run/##Ky9KzftfllikkKhgq/DfLU8vL7W8uqaixtDWtsLeyMLK2FC3QtVc1aj2f3BlcUlqrl55UWZJqkaiXnJiTo6GgabmfwA "Wren – Try It Online")
# [Wren](https://github.com/munificent/wren), 35 bytes
-4 bytes thx 2 Jo King for noticing that `.bytes[x]` would work.
```
Fn.new{|x|"
".bytes[x]}
```
[Try it online!](https://tio.run/##Ky9KzftfllikkKhgq/DfLU8vL7W8uqaiRklBXkZeDgjBhJJeUmVJanF0RWzt/@DK4pLUXL3yosySVI1EveTEnBwNI03N/wA "Wren – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 22 bytes
```
f(n){n=31-n%7%2-!~-n;}
```
[Try it online!](https://tio.run/##Fcg7DoQgEADQnlOwJCQzURI/xRazHsagmCmcNYgVYa/O6iufd5v3tQYQzDKNvRP7toN7/ZxQqSxJ7zOLBswqfCM8wVNH/OkH4qbBfMT7Ahi7mDYAI9JxpROMQSoqrumKojtSpf4B "C (gcc) – Try It Online")
Stealing from @Arnaulds / @Adám
---
~~29~~ [26 bytes](https://tio.run/##S9ZNT07@/z9No0KzusJWSV5GXg4IwYRSdEWsde3/zLwShdzEzDwFDc1qrrT8Ig2QQKatgXWmjaGRdaa2tmZ1QRFQLE1DSTVFSSdNI1NT07qgtKRYQ0lJ07qWqyi1pLQoT8HAmqv2PwA "C (gcc) – Try It Online")
```
f(x){x="
"[x];}
```
Port of @Embodiment of Ignorance answer
] |
[Question]
[
# Task
Your task is to take a character in:
`AÁÀÃÂBCÇDEÉÊFGHIÍJKLMNOÕÓÔPQRSTUÚVWXYZaáàãâbcçdeéêfghiíjklmnoõóôpqrstuúvwxyz`
and turn it into a characters in:
`AAAAABCCDEEEFGHIIJKLMNOOOOPQRSTUUVWXYZaaaaabccdeeefghiijklmnoooopqrstuuvwxyz`
by the obvious operation: dropping the accents in the letters.
# Input
A character in any sensible format, including but not limited to:
* A string with only one character;
* A unicode codepoint.
# Output
The transformed char in any sensible format, which includes:
* A string with only one char;
* A unicode codepoint.
# Test cases
```
'A' -> 'A'
'Á' -> 'A'
'À' -> 'A'
'Ã' -> 'A'
'Â' -> 'A'
'B' -> 'B'
'C' -> 'C'
'Ç' -> 'C'
'D' -> 'D'
'E' -> 'E'
'É' -> 'E'
'Ê' -> 'E'
'F' -> 'F'
'G' -> 'G'
'H' -> 'H'
'I' -> 'I'
'Í' -> 'I'
'J' -> 'J'
'K' -> 'K'
'L' -> 'L'
'M' -> 'M'
'N' -> 'N'
'O' -> 'O'
'Õ' -> 'O'
'Ó' -> 'O'
'Ô' -> 'O'
'P' -> 'P'
'Q' -> 'Q'
'R' -> 'R'
'S' -> 'S'
'T' -> 'T'
'U' -> 'U'
'Ú' -> 'U'
'V' -> 'V'
'W' -> 'W'
'X' -> 'X'
'Y' -> 'Y'
'Z' -> 'Z'
'a' -> 'a'
'á' -> 'a'
'à' -> 'a'
'ã' -> 'a'
'â' -> 'a'
'b' -> 'b'
'c' -> 'c'
'ç' -> 'c'
'd' -> 'd'
'e' -> 'e'
'é' -> 'e'
'ê' -> 'e'
'f' -> 'f'
'g' -> 'g'
'h' -> 'h'
'i' -> 'i'
'í' -> 'i'
'j' -> 'j'
'k' -> 'k'
'l' -> 'l'
'm' -> 'm'
'n' -> 'n'
'o' -> 'o'
'õ' -> 'o'
'ó' -> 'o'
'ô' -> 'o'
'p' -> 'p'
'q' -> 'q'
'r' -> 'r'
's' -> 's'
't' -> 't'
'u' -> 'u'
'ú' -> 'u'
'v' -> 'v'
'w' -> 'w'
'x' -> 'x'
'y' -> 'y'
'z' -> 'z'
```
You can check [here](https://tio.run/##XY85T8NAFIR7/4rVNmtLJA0NQgIJCOEO9ykKG3sdLyRrs14DSRSJo0AgUQENFUeBQKICGtr5YcZOkBIx5cw3T2@ihg5COZimoh6FSpNECjf0uOdoxzA87hMZqrpTE01uxtawQTIprhMl@8liD2KVcokNkNja7bB/KnKZsyZzYleILGeimnU4@4d5vIPRRPuFIWqlmseajBA6hjOc4gLn4xO4LE3iCtflqekZ3MzOzS9UFnGPW9wtLa@srq3jYWNza3vHwRMe8YLnPRevHscb3v1qIPCxf1CryxDf@MRXdKhineDn6Pik0aSGESkhtUlt26aW4YeKuIGjiJAk/6M7vov4lLXyrM1IYZSwVm9/7lptlvX7j6W/) for a Python reference implementation without regexes.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
A port of [my CP-1610 answer](https://codegolf.stackexchange.com/a/200596/58563).
I/O format: a Unicode code point.
```
n=>n>>7?Buffer("ACEIOOU")[n/4&7]^n&32:n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7Pzs7c3qk0LS21SEPJ0dnV098/VEkzOk/fRM08Ni5PzdjIKu@/dbSenp6S4@HGww2Hmw83OTkfbndxPdx5uMvN3cPzcK@Xt4@vn//hqYcnH54SEBgUHBJ6eFZYeERkVOLhhYcXHF58eFFS8uHlKamHVx5elZaekXl4bVZ2Tm5e/uGthzcf3lJQWFRcUnp4V1l5RWWVUiyXXlp@kWticoZGsoKtnUJyfl5xfk6qXk5@ukaCukp1cq26gq6unQKQGVxSlJmXrpdWlJ/rDPRQQH5mXolGmkayXjKM51iiYaCpqVmrnqCp@R8A "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 44 bytes
I/O format: a string with only one character.
```
c=>'oeaUICuic?OEA'[Buffer(c)[1]*13%59%13]||c
```
[Try it online!](https://tio.run/##AeAAH/9qYXZhc2NyaXB0LW5vZGX/Zj3/Yz0@J29lYVVJQ3VpYz9PRUEnW0J1ZmZlcihjKVsxXSoxMyU1OSUxM118fGP/O1suLi4iQcOBw4DDg8OCQkPDh0RFw4nDikZHSEnDjUpLTE1OT8OVw5PDlFBRUlNUVcOaVldYWVphw6HDoMOjw6JiY8OnZGXDqcOqZmdoacOtamtsbW5vw7XDs8O0cHFyc3R1w7p2d3h5eiJdCi5mb3JFYWNoKGMgPT4gY29uc29sZS5sb2coYCcke2N9JyAtLT4gJyR7ZihjKX0nYCkp/w "JavaScript (Node.js) – Try It Online")
### How?
When passed into `Buffer()`, the accented letters used in the challenge are turned into two bytes \$(b\_0,b\_1)\$, corresponding to their UTF-8 encoding. The non-accented letters are turned into a single byte \$b\_0\$ corresponding to their regular ASCII code (or 1-byte UTF-8 encoding).
*Examples:*
```
Buffer('À') // --> <Buffer c3 80>
Buffer('B') // --> <Buffer 42>
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP13DqTQtLbVIQ/1wg7qmJhc2GSegxP//AA "JavaScript (Node.js) – Try It Online")
We use the following formula to convert the 2nd byte of accented letters to an index \$n\$ into a 13-character lookup string of non-accented letters:
$$n=((b\_1\times13)\bmod 59)\bmod 13$$
This results in `NaN` for non-accented letters, which are simply left unchanged.
```
c | UTF-8 | 2nd byte | * 13 | mod 59 | mod 13 | output
-----+------------+----------+------+--------+--------+--------
'À' | 0xC3, 0x80 | 128 | 1664 | 12 | 12 | 'A'
'Á' | 0xC3, 0x81 | 129 | 1677 | 25 | 12 | 'A'
'Â' | 0xC3, 0x82 | 130 | 1690 | 38 | 12 | 'A'
'Ã' | 0xC3, 0x83 | 131 | 1703 | 51 | 12 | 'A'
'Ç' | 0xC3, 0x87 | 135 | 1755 | 44 | 5 | 'C'
'É' | 0xC3, 0x89 | 137 | 1781 | 11 | 11 | 'E'
'Ê' | 0xC3, 0x8A | 138 | 1794 | 24 | 11 | 'E'
'Í' | 0xC3, 0x8D | 141 | 1833 | 4 | 4 | 'I'
'Ó' | 0xC3, 0x93 | 147 | 1911 | 23 | 10 | 'O'
'Ô' | 0xC3, 0x94 | 148 | 1924 | 36 | 10 | 'O'
'Õ' | 0xC3, 0x95 | 149 | 1937 | 49 | 10 | 'O'
'Ú' | 0xC3, 0x9A | 154 | 2002 | 55 | 3 | 'U'
'à' | 0xC3, 0xA0 | 160 | 2080 | 15 | 2 | 'a'
'á' | 0xC3, 0xA1 | 161 | 2093 | 28 | 2 | 'a'
'â' | 0xC3, 0xA2 | 162 | 2106 | 41 | 2 | 'a'
'ã' | 0xC3, 0xA3 | 163 | 2119 | 54 | 2 | 'a'
'ç' | 0xC3, 0xA7 | 167 | 2171 | 47 | 8 | 'c'
'é' | 0xC3, 0xA9 | 169 | 2197 | 14 | 1 | 'e'
'ê' | 0xC3, 0xAA | 170 | 2210 | 27 | 1 | 'e'
'í' | 0xC3, 0xAD | 173 | 2249 | 7 | 7 | 'i'
'ó' | 0xC3, 0xB3 | 179 | 2327 | 26 | 0 | 'o'
'ô' | 0xC3, 0xB4 | 180 | 2340 | 39 | 0 | 'o'
'õ' | 0xC3, 0xB5 | 181 | 2353 | 52 | 0 | 'o'
'ú' | 0xC3, 0xBA | 186 | 2418 | 58 | 6 | 'u'
```
[Answer]
# [PHP](https://php.net/), 42 39 34 bytes
```
<?=iconv('','us//TRANSLIT',$argn);
```
-3 Bytes thanks to @Neil
[Try it online!](https://tio.run/##AZgAZ/9waHD//zw/PWljb252KCcnLCd1cy8vVFJBTlNMSVQnLCRhcmduKTv//0HDgcOAw4PDgkJDw4dERcOJw4pGR0hJw41KS0xNTk/DlcOTw5RQUVJTVFXDmlZXWFlaYcOhw6DDo8OiYmPDp2Rlw6nDqmZnaGnDrWprbG1ub8O1w7PDtHBxcnN0dcO6dnd4eXr@b3B0aW9uc/8tRg "PHP – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes
```
s=>s.normalize`NFD`[0]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5YLy@/KDcxJ7MqNcHPzSUh2iD2f0lqcUlyYnGqgq1CtJ6enpLj4cbDDYebDzc5OR9ud3E93Hm4y83dw/Nwr5e3j6@f/@GphycfnhIQGBQcEnp4Vlh4RGRU4uGFhxccXnx4UVLy4eUpqYdXHl6Vlp6ReXhtVnZObl7@4a2HNx/eUlBYVFxSenhXWXlFZZVSLBfMWr20/CLXxOQMjWQFWzuFaoXk/Lzi/JxUvZz8dI1kHQV1XTt1HYU0jWRNTYVaTev/AA "JavaScript (Node.js) – Try It Online")
save 2 bytes, thanks Arnauld.
[Answer]
# T-SQL, ~~35~~ 33 bytes
```
SELECT v COLLATE Greek_BIN FROM t
```
Input is taken from a pre-existing table *t* with `CHAR(1)` column *v*, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341).
This code simply displays the input after converting it to a different *SQL collation*.
[SQL collations](https://docs.microsoft.com/en-us/sql/relational-databases/collations/collation-and-unicode-support?view=sql-server-ver15) define sorting rules as well as case and accent sensitivity properties for SQL text data. They can even define the valid code page, which is how this particular trick works. [Code page 1253](https://en.wikipedia.org/wiki/Windows-1253) ("Greek - ANSI") doesn't include any of the accented characters in the question, so the collation conversion maps each to its non-accented version.
I based my version on [this StackOverflow answer](https://stackoverflow.com/a/56791799/21398), which uses a more standard collation with a much longer name: `SQL_Latin1_General_CP1253_CI_AI`.
**EDIT**: Saved 2 bytes by replacing `Greek_CS_AI` with `Greek_BIN`. Both use code page 1253, which is really the part that matters, not the "accent insensitive" property.
SQL supports nearly 4000 collations, run this on your SQL server to return all collations that use code page 1253, ordered by the shortest name:
```
SELECT name, bytes=len(name), description, codepage=COLLATIONPROPERTY(name, 'CodePage')
FROM fn_helpcollations()
WHERE COLLATIONPROPERTY(name, 'CodePage') = 1253
ORDER BY len(name)
```
It is possible to replace characters individually, but that is much longer (**79 Bytes**):
```
SELECT TRANSLATE(v,'ÁÀÃÂÇÉÊÍÕÓÔÚáàãâçéêíõóôú','AAAACEEIOOOUaaaaceeiooou')FROM t
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žy›i•M¦>á•₂вI28&èI96&+
```
-2 bytes thanks to *@Grimmy*.
I/O as unicode codepoint.
[Try it online.](https://tio.run/##AZ8AYP8wNWFiMWX/PXZ5w4fCqUT/xb554oC6aeKAok3Cpj7DoeKAouKCgtCywq4yOCbDqMKuOTYmK/99w6c//0HDgcOAw4PDgkJDw4dERcOJw4pGR0hJw41KS0xNTk/DlcOTw5RQUVJTVFXDmlZXWFlaYcOhw6DDo8OiYmPDp2Rlw6nDqmZnaGnDrWprbG1ub8O1w7PDtHBxcnN0dcO6dnd4eXo)
**Explanation:**
```
žy›i # If the (implicit) input-codepoint is larger than 128:
•M¦>á• # Push compressed integer 3755486693
₂в # Convert it to base-26 as list: [1,5,15,21,3,9,15]
I28& # Push the input-codepoint, and bitwise-AND it with 28
è # Index it into the list (0-based and with wraparound)
I96& # Push the input-codepoint, and bitwise-AND it with 96
+ # And add it to the indexed value
# (after which it is output implicitly as result)
# (implicit else:)
# (take the implicit input-codepoint as implicit output)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•M¦>á•` is `3755486693` and `•M¦>á•₂в` is `[1,5,15,21,3,9,15]`.
[Answer]
# iconv, ~~21~~ 20 bytes
```
iconv -tus//TRANSLIT
```
[Try it online!](https://tio.run/##Tcy3TgNBFIXhnqdY0YxdGIsXQHLOeR3lxvY6Z6@zKAgFAokKaKgIBQKJCmhoebDljE4x031XOvdvNuye43L6relkbXiWK9vrNfO@dCEZMx23cWrYbcs49Iq666juFobnxBD1Y@G1Dh3h4@kTB@LvXPOZ5kvNF8p@0g8GyIBcXCkHySAYIkNyca35RjlMhsEIGQGjZBSMkTH5d6scJ@NggkyASTIJpsgUmCbTYIbMyNqD5jvN98pZMgvmyByYJ/NggSyAJmmCRbIoa4/KJbIElskyWCErYJWsgjWyBjbIhqw9a37S/Kr5RblJNsEW2ZKLN2WLtMA22ZaLd80fyh2yA3bJLtgje2Cf7Mu/T@UBOQCH5BAckSNwTI7BCTkBp@RU1n40f2n@Vp6RM3BOzsEFuQBt0gaX5BJckStZ@1Vek2twQ27ALbkFd@QO3JN78Q8 "Bash – Try It Online") Link includes test suite. Edit: Thanks to @NahuelFouilleul for a 1 byte saving. Port of @Oxgeba's PHP answer, but I used `us` as a synonym for `ASCII` to save a further 3 bytes.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~61~~ 56 bytes
```
lambda s:s[s>'z':]or'EIOOUaaceioou_AAC'[ord(s)*17%67%17]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRodiqOLrYTr1K3So2v0jd1dPfPzQxMTk1Mz@/NN7R0Vk9Or8oRaNYU8vQXNXMXNXQPPZ/SWpxCdAEJcfDjYcbDjcfbnJyPtzu4nq483CXm7uH5@FeL28fXz//w1MPTz48JSAwKDgk9PCssPCIyKjEwwsPLzi8@PCipOTDy1NSD688vCotPSPz8Nqs7JzcvPzDWw9vPryloLCouKT08K6y8orKKiUurrT8IoXkjMQihcw8BZDVVlwKQFBQlJlXopGmpF4NkqtVV9C1U1CvTtMA8TRr1ZU0/wMA "Python 3 – Try It Online")
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~76~~ 74 bytes
```
lambda s:(n:=name(s)*2)[21::-2].title()['SM'in n]
from unicodedata import*
```
[Try it online!](https://tio.run/##FY65TsNAAAV7f8XKje1IQcI0yJKRuM9AINwhxcb24gV716w3QIgicRQIJCqgoeIoEEhUQEP7PszErxtNMS/r6liKkdFMFczfKxKatkNKcs8Wni9oGtm5U3GdpjvseVW3NaS5TiLbaVqNmsUFES2DKZmSjuCBDKOQakp4mkmlK4WOck18Yo7jAue4wuXEJK6npnGD25nZuXncLSwu1ZZX8Ih7PNRX1xrrG3ja3Nre2aV4wTPe8NoO8B5G@MAn2485vg4Ok1RI/OIbP9mRynUHf8cnp90z0zCYVCSIqSKDW2XaM8hgmeJC28y0eqXrW6Q6Rqwes0ty@pbpFP8 "Python 3.8 (pre-release) – Try It Online")
**Examples**
```
s 'À'
name(s) 'LATIN CAPITAL LETTER A WITH GRAVE'
name(s)*2 'LATIN CAPITAL LETTER A WITH GRAVELATIN CAPITAL LETTER A WITH GRAVE'
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
(name(s)*2)[21::-2] 'ARTE AIA IA'
(name(s)*2)[21::-2].title() 'Arte Aia Ia'
'SM' in name(s)*2 == False == 0
(name(s)*2)[21::-2].title()[0] 'A'
s 'À'
name(s) 'LATIN SMALL LETTER C WITH CEDILLA'
name(s)*2 'LATIN SMALL LETTER C WITH CEDILLALATIN SMALL LETTER C WITH CEDILLA'
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
(name(s)*2)[21::-2] 'WCRTE LM IA'
(name(s)*2)[21::-2].title() 'Wcrte Lm Ia'
'SM' in name(s)*2 True == 1
(name(s)*2)[21::-2].title()[1] 'c'
```
---
# [Python 3](https://docs.python.org/3/), 55 bytes
Basically the same as tsh's [JavaScript answer](https://codegolf.stackexchange.com/a/200587/64121).
```
lambda s:normalize('NFD',s)[0]
from unicodedata import*
```
[Try it online!](https://tio.run/##TU85SwNBGO33V3xsM1lREOwCEdQY76jxviCTPdzR3Zl1dqImIeBRiIKV2lh5FKJgpTa274etWSz0le/ivaRlQiWHsqC0nUU8bnic0qJUOuaRaPsFVq2UWX/qbA3uWIFWMTWlcJXne9xwEnGitOnLjJ8aKpE9glOc4Bxno2O4KI/jEleVickpXE/PzM5V53GHG9wuLNaWlldwv7q2vrHJ8YgHPOOp4eLF8/GKt2A3FHjf249iqfCFD3wmBzo1TXwfHh232rZlJVpIU7Dr9brtWIHS5IZck5CU7yha1MOvJbBZJ9e6jAaGiXX@buWs02W9/P@y7Ac "Python 3 – Try It Online")
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code, ~~27 26 22~~ 21 DECLEs1 ≈ 27 bytes
*As per the exception described [in this meta answer](https://codegolf.meta.stackexchange.com/a/10810/58563), the exact score is **26.25 bytes** (210 bits)*
A routine taking a Unicode code point in **R0** and returning another code point in the same register.
```
**081** | MOVR R0, R1
**045** | SWAP R1, 2
**203 009** | BPL @@rtn
**065** | SLR R1, 2
**3B9 007** | ANDI #7, R1
**0F9** | ADDR R7, R1
**2F9 006** | ADDI #6, R1
**3B8 020** | ANDI #32, R0
**3C8** | XOR@ R1, R0
**0AF** | @@rtn JR R5
**041 043 045 049** | STRING "ACEIOOU"
**04F 04F 055** |
```
### How?
All the special characters we're interested in are located in the `0xC0-0xFF` Unicode range.
```
full range relevant letters replacement
| 0123 4567 | 0123 4567 | 0123 4567
---+---------- ---+---------- ---+----------
C0 | ÀÁÂÃ ÄÅÆÇ C0 | ÀÁÂÃ ---Ç C0 | AAAA ---C
C8 | ÈÉÊË ÌÍÎÏ C8 | -ÉÊ- -Í-- C8 | -EE- -I--
D0 | ÐÑÒÓ ÔÕÖ× D0 | ---Ó ÔÕ-- D0 | ---O OO--
D8 | ØÙÚÛ ÜÝÞß D8 | --Ú- ---- D8 | --U- ----
E0 | àáâã äåæç E0 | àáâã ---ç E0 | aaaa ---c
E8 | èéêë ìíîï E8 | -éê- -í-- E8 | -ee- -i--
F0 | ðñòó ôõö÷ F0 | ---ó ôõ-- F0 | ---o oo--
F8 | øùúû üýþÿ F8 | --ú- ---- F8 | --u- ----
```
As shown in the tables above, each group of \$4\$ accented letters is mapped to a single non-accented letter. So, given a code point \$n\$, we compute the index:
$$i=\left\lfloor\frac{n}{4}\right\rfloor\bmod 8$$
We pick the corresponding letter from the lookup string `"ACEIOOU"` and then apply the correct case.
### Full commented test code
```
ROMW 10 ; use 10-bit ROM width
ORG $4800 ; map this program at $4800
;; ------------------------------------------------------------- ;;
;; main code ;;
;; ------------------------------------------------------------- ;;
main PROC
SDBD ; set up an interrupt service routine
MVII #isr, R0 ; to do some minimal STIC initialization
MVO R0, $100
SWAP R0
MVO R0, $101
EIS ; enable interrupts
SDBD ; R4 = pointer into the test case table
MVII #tc, R4
MVII #$200, R3 ; R3 = backtab pointer
MVII #76, R2 ; R2 = number of test cases
@@loop MVI@ R4, R0 ; R0 = character code point
CALL conv ; invoke our routine
SUBI #32, R0 ; turn the result into an Intellivision card
SLL R0, 2
SLL R0
MVO@ R0, R3 ; draw it
INCR R3 ; increment the backtab pointer
DECR R2 ; next test case
BNEQ @@loop
DECR R7 ; done: loop forever
ENDP
;; ------------------------------------------------------------- ;;
;; test cases ;;
;; ------------------------------------------------------------- ;;
tc PROC
DECLE 65 ; A
DECLE 193 ; Á
DECLE 192 ; À
DECLE 195 ; Ã
DECLE 194 ; Â
DECLE 66 ; B
DECLE 67 ; C
DECLE 199 ; Ç
DECLE 68 ; D
DECLE 69 ; E
DECLE 201 ; É
DECLE 202 ; Ê
DECLE 70 ; F
DECLE 71 ; G
DECLE 72 ; H
DECLE 73 ; I
DECLE 205 ; Í
DECLE 74 ; J
DECLE 75 ; K
DECLE 76 ; L
DECLE 77 ; M
DECLE 78 ; N
DECLE 79 ; O
DECLE 213 ; Õ
DECLE 211 ; Ó
DECLE 212 ; Ô
DECLE 80 ; P
DECLE 81 ; Q
DECLE 82 ; R
DECLE 83 ; S
DECLE 84 ; T
DECLE 85 ; U
DECLE 218 ; Ú
DECLE 86 ; V
DECLE 87 ; W
DECLE 88 ; X
DECLE 89 ; Y
DECLE 90 ; Z
DECLE 97 ; a
DECLE 225 ; á
DECLE 224 ; à
DECLE 227 ; ã
DECLE 226 ; â
DECLE 98 ; b
DECLE 99 ; c
DECLE 231 ; ç
DECLE 100 ; d
DECLE 101 ; e
DECLE 233 ; é
DECLE 234 ; ê
DECLE 102 ; f
DECLE 103 ; g
DECLE 104 ; h
DECLE 105 ; i
DECLE 237 ; í
DECLE 106 ; j
DECLE 107 ; k
DECLE 108 ; l
DECLE 109 ; m
DECLE 110 ; n
DECLE 111 ; o
DECLE 245 ; õ
DECLE 243 ; ó
DECLE 244 ; ô
DECLE 112 ; p
DECLE 113 ; q
DECLE 114 ; r
DECLE 115 ; s
DECLE 116 ; t
DECLE 117 ; u
DECLE 250 ; ú
DECLE 118 ; v
DECLE 119 ; w
DECLE 120 ; x
DECLE 121 ; y
DECLE 122 ; z
ENDP
;; ------------------------------------------------------------- ;;
;; ISR ;;
;; ------------------------------------------------------------- ;;
isr PROC
MVO R0, $0020 ; enable display
CLRR R0
MVO R0, $0030 ; no horizontal delay
MVO R0, $0031 ; no vertical delay
MVO R0, $0032 ; no border extension
MVII #$D, R0
MVO R0, $0028 ; light-blue background
MVO R0, $002C ; light-blue border
JR R5 ; return from ISR
ENDP
;; ------------------------------------------------------------- ;;
;; our routine ;;
;; ------------------------------------------------------------- ;;
conv PROC
MOVR R0, R1 ; copy R0 to R1
SWAP R1, 2 ; copy the lower byte of R1 to its upper byte,
; resulting in a negative word for an accented letter
BPL @@rtn ; return right away if it's a regular ASCII character
SLR R1, 2 ; right-shift by 2 positions
ANDI #7, R1 ; isolate the 3 least significant bits
ADDR R7, R1 ; add the address of our lookup string,
ADDI #6, R1 ; computed as PC + 6
ANDI #32, R0 ; isolate the case bit of the original character
XOR@ R1, R0 ; XOR it with the non-accented letter
@@rtn JR R5 ; return
STRING "ACEIOOU" ; lookup string
ENDP
```
### Output
[](https://i.stack.imgur.com/CGv7c.gif)
*screenshot from [jzIntv](http://spatula-city.org/~im14u2c/intv/)*
---
*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 37 bytes
A port of [my CP-1610 answer](https://codegolf.stackexchange.com/a/200596/58563).
I/O format: a Unicode code point.
```
f(n){n=n>>7?"ACEIOOU"[n/4&7]^n&32:n;}
```
[Try it online!](https://tio.run/##bdRLTxNhFMbxPZ9i0kTSJpB2ppdpJWIQURGx3vAaTero1CK8IiAohAR1YTRxpW5ceVkYTVypG7d8L8cNz7OZ//qXc@Y95zmZbHKYZUWRV0NtNxwL09Pp8crM7Nx8v79UuRXqrfH09p0w3kyOhqm9YnUwCtXa7lgUra2PwmZerRzJKhNRXu20o1ptKqrXo5kyxr3mIR48J02k@6Rt6UvSlvQFPKqjR50ATIWz1Lenvq@gtKvSk4A94VwZk0asvq9JvYk3ZU0banwKMBaeBkyEZwCbwnl6kbf/FkpbKj0L6ItYAHQy5wCdzCKgd38e0Lvvwyyxr/ADqZN5R@pk3pe162QuADqZi4BO5hKgk7kM6N1fAfTul2iWrmb5CKVO5iqgk7kG6GSuAzqZG2XseX83Af3NAcyS@D4/k/rv8Ik0lX4l7Ui/wKM8611Az5pB36bv7Bv8dxqNQ71HqNL71NfX/Z3Um/hBjXXdOaEaDwnV9wGhwhnRi7z9n1Sq7S8TqvQhoa57hVC/9VXAWLsPhNr9I5il5Sv8Q@pkfpE6md/0WSWzRqjGjwnVd51QD94g1O43CbX7JzBLWxs8@EulSmaLUMlsAybq@5RQyTwj1P52xvaKf1m@MhhuFJPb/wE "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 45 bytes
I/O format: a Unicode code point.
```
f(n){n=n>>7?"ooieca?UOOIECAu"[n*15%61%15]:n;}
```
[Try it online!](https://tio.run/##bdRLTxNxFMbhPZ9i0qRJayR0pp1eIEIQUfFCFcQLxEUdmVqFKXIRhZB4WRhNXKEbV14WRhNX4sYt34txw/tu5rd@cs78z3lPJhntJ0mep5Wsup@dyyYnW1Ol4XCwmvSmlrrdudmZ6Z3SSnYmjMvNsBzG98eziYN8vTfIKtX9kSDY2Bxk22mlVE5KZ4O00oyDanUiGBsLposYduqnePyKNJK@JI2lb0gb0tfwqKYedR6wJZyhvh31fQulbZVeAOwIZ4sY1UL1fUfqTbwvaqumxhcBQ@ElwEh4GbAunKMXefsfoLSh0iuAvoirgE7mGqCTuQ7o3c8DevddmCX0FX4idTKHpE7mY1HbTuYGoJO5CehkFgCdzCKgd38L0LtfolnamuUzlDqZ24BO5g6gk7kL6GTuFbHj/S0D@ps9mCXyfX4l9d/hC2lL@p20Kf0Gj/KsDwA9awJ9676zH/DfqdVO9SGhSlepr6/7J6k38Ysa67pTQjXuE6rvI0KFM6AXefu/qVTbf0yo0ieEuu41Qv3W1wFD7T4j1O6HMEvDV/iX1Mn8IXUyR/RZJbNBqMZPCdV3k1AP3iLU7rcJtfsdmCXWBo//UamSeUaoZHYBI/V9TqhkXhBqf3sjB/lJkq71@lv56O5/ "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
->c{c<?~?c:"ACEIOOUxaceioou"[c.ord/4%16]}
```
[Try it online!](https://tio.run/##AbIATf9ydWJ5/2Y9/y0@Y3tjPD9@P2M6IkFDRUlPT1V4YWNlaW9vdSJbYy5vcmQvNCUxNl19/yJBw4HDgMODw4JCQ8OHREXDicOKRkdIScONSktMTU5Pw5XDk8OUUFFSU1RVw5pWV1hZWmHDocOgw6PDomJjw6dkZcOpw6pmZ2hpw61qa2xtbm/DtcOzw7RwcXJzdHXDunZ3eHl6Ii5jaGFycy5tYXB7fHh8cCBbeCxmW3hdXX3/ "Ruby – Try It Online")
[Answer]
# PHP 5.4+, 32 bytes
This uses the [`htmlentities()`](https://www.php.net/manual/en/function.htmlentities.php) function to return the HTML entity for the character.
```
<?=htmlentities($argn.$argn)[1];
```
For the `"AÁÀÃÂ"` (Ä is missing from the list), it returns `"AÁÀÃÂ"`.
Do you see a problem? The character I want is on position 0 or 1.
So, I just duplicate the input. Problem solved!
You can try this on <http://sandbox.onlinephpfunctions.com/code/690dbfcff4c6dec4170954333c62b9b472eaaa93>
[Answer]
# Java 8, ~~85~~ ~~70~~ ~~47~~ 39 bytes
```
c->c>122?"ACEIOOU".charAt(c/4&7)^c&32:c
```
-46 bytes by creating a port of [*@Arnauld*'s C answer](https://codegolf.stackexchange.com/a/200597/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##ZVA9TwJBEO35FZsryG3BGdHERCIGERUVUBE/o8myHHBw7J67y5eGxI/CaGKlNlZ@FEYTK7WxnR927nF0NJPMzHvz3rwG6ZBYo9L0qUukRDnisLMIQg5TtqgSaqN80A4HiJq0TgSiWNUF70qU6VHbUw5nCQ0ZRHSRiiiHojxiaA75NJakycl4fN5IpTPZQqFkWMGBlDLpxHR0Bh/T6FR8lvqJgOq1y66mji50uFNBLW3GLCrhsNrhESJjsqGzEICkVjRScAHncAWXC2m4XszADdwuLa9k4W51bT2XL8Aj3MPDxuZWcbsETzu7e/sHBF7gGd7gtUzhvWLDB3xWa3UHvhpNt8U4/MI3/HgnQqo2/HW6vf6pkQhl@1LZLYu3leVpA8plpsThqsrFKKlZaSmeDn4WgvRNjIf7cbI5xGNm6YgxDuMc@P8)
**Original answer (85 bytes):**
```
import java.text.*;c->(char)Normalizer.normalize(c,Normalizer.Form.NFD).getBytes()[0]
```
[Try it online.](https://tio.run/##ZZC7TltBEIZ7P8XI1VnAC5RggcTN3A8J5MJFFOv12l5zzu5hd2xsEBJJiohIVIQmVYAiChJVkibtPJhZY4OQaEb/3P75NA3REoVG5aCr08w6hEbIOao28qEijI7C8PgEoAWsKyh3UBWkbRrMyUR4D@tCm5McgDaoXFVIBXEvBZB14UBGW@i0qYFkWHf2yMNCW6oMtTXFMHWaC8GjQC0hBgNT0JWF6ai3ymLrUpHoY@W4eZKRHHlRLgXJ49I84zWFswHMR2xvbL9b7LlmzXISXAfmLasrkAbUAc/ePohXRH3uAbAPMPkZ@kRn9IU@z87R1/kFOqdvpcWlZbpYWV1bjzfoii7p@5u3m1vv3tOPDx@3d3YFXdNPuqWbsqRfFUW/6a5aq2u6bxwkqbH0j/7Q3@zQeWzS/9ZRu3OcL/bPdjyqlNsm8iwAYGIiz/qtqnXPb5z03GeJxiifZ@yx@3o1MlxGkrH@h0@7Dw)
**Explanation:**
```
c-> // Method with character as both parameter and return-type
c>122? // If the character isn't a regular letter:
"ACEIOOU".charAt( // Get the character in String "ACEIOOU" at index:
c/4&7) // c integer-divided by 4 and then bitwise-ANDed by 7
^c&32 // And convert it to lowercase if the input was lowercase
: // Else (it is a regular letter):
c // Simply return the input as is
import java.text.*; // Required import for both Normalizer
c-> // Method with String as parameter and character as return-type
(char) // Convert the following byte to a character:
Normalizer.normalize(c, // Normalize the input-String,
Normalizer.Form.NFD) // using canonical decomposition
.getBytes()) // Convert that to a byte-array (UTF-8 encoding by default)
[0] // And only leave the first byte
```
[Answer]
# ~~[Perl 6](https://www.theregister.co.uk/2019/10/11/perl_6_raku_larry_wall/)~~ [Raku](https://github.com/nxadm/rakudo-pkg), ~~15~~ 14 bytes
```
*.samemark(~0)
```
[Try it online!](https://tio.run/##AZcAaP9wZXJsNv9teSAmZiA9IP8qLnNhbWVtYXJrKH4wKf87CnNheSB8Z2V0LmNvbWI@Pi4mZv9Bw4HDgMODw4JCQ8OHREXDicOKRkdIScONSktMTU5Pw5XDk8OUUFFSU1RVw5pWV1hZWmHDocOgw6PDomJjw6dkZcOpw6pmZ2hpw61qa2xtbm/DtcOzw7RwcXJzdHXDunZ3eHl6)
Returns the string with the same marks/accents as the number `0`, i.e. remove all marks.
[Answer]
# [Turing Machine Code](http://morphett.info/turing/turing.html), ~~796~~ 286 bytes
```
0 * * r 0
0 Á A r 0
0 À A r 0
0 Ã A r 0
0 Â A r 0
0 Ç C r 0
0 É E r 0
0 Ê E r 0
0 Í I r 0
0 Õ O r 0
0 Ó O r 0
0 Ô O r 0
0 Ú U r 0
0 á a r 0
0 à a r 0
0 ã a r 0
0 â a r 0
0 ç c r 0
0 é e r 0
0 ê e r 0
0 í i r 0
0 õ o r 0
0 ó o r 0
0 ô o r 0
0 ú u r 0
0 _ _ * halt
```
[Try it online!](http://morphett.info/turing/turing.html?f92396d8268dd3e33032ab6844e0c03f)
*Saved an incredible 510 bytes thanks to @ovs! That might be some kind of record here on Code Golf*.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes
Mathematics is not the only field Mathematica has built-ins for...
```
RemoveDiacritics
```
[Try it online!](https://tio.run/##AZEAbv9tYXRoZW1hdGljYf9GPVz/UmVtb3ZlRGlhY3JpdGljc/9QcmludEBGWyJBw4HDgMODw4JCQ8OHREXDicOKRkdIScONSktMTU5Pw5XDk8OUUFFSU1RVw5pWV1hZWmHDocOgw6PDomJjw6dkZcOpw6pmZ2hpw61qa2xtbm/DtcOzw7RwcXJzdHXDunZ3eHl6Il3/ "Wolfram Language (Mathematica) – Try It Online") (all the characters are in a single string in the link, but it obviously works character-by-character)
# [Sledgehammer](https://github.com/tkwa/Sledgehammer), 4 bytes
```
⣕⠬⣠⢹
```
Corresponds to the code `RemoveDiacritics@Input[]`.
[Answer]
# [R](https://www.r-project.org/), ~~34~~ 32 bytes
-2 thanks to Giuseppe
```
iconv(scan(,''),,"us//TRANSLIT")
```
[Try it online!](https://tio.run/##AYkAdv9y//9pY29udihzY2FuKCwnJyksLCJ1cy8vVFJBTlNMSVQiKf9Bw4HDgMODw4JCQ8OHREXDicOKRkdIScONSktMTU5Pw5XDk8OUUFFSU1RVw5pWV1hZWmHDocOgw6PDomJjw6dkZcOpw6pmZ2hpw61qa2xtbm/DtcOzw7RwcXJzdHXDunZ3eHl6/w "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 53 bytes
-1 thanks to Kevin Cruijssen
```
"áéíõúÁÉÍÕÚàêióuÀÊIÓUãeiôuÃEIÔUâeiouÂEIOUÇç"žÀ4ׄCc«‡
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f6fDCwysPrz289fCuw42HOw/3Hp56eNbhBYdXZR7eXHq44XCX5@HJoYcXp2Ye3lJ6uNnV8/CU0MOLUjPzSw83uXr6hx5uP7xc6ei@ww0mh6c/apjnnHxo9aOGhf//U24qAA "05AB1E – Try It Online")
## Explanation
```
"áéíõúÁÉÍÕÚàêióuÀÊIÓUãeiôuÃEIÔUâeiouÂEIOUÇç" A huge lookup table of the unicode characters
žÀ Push "aeiouAEIOU"
4× Repeat it 4 times
„Cc« Concatenate "Cc" to the string
‡ Transliterate input
```
```
[Answer]
# [Python 2](https://docs.python.org/2/), 141 bytes
```
o='';i=input()
for x in'AÁÀÃÂ CÇ EÉÊ IÍ OÕÓÔ UÚ aáàãâ cç eéê ií oõóô uú'.split():
if i in x:o=x[0]
print(o,i)[o=='']
```
[Try it online!](https://tio.run/##Fc6xT8JQEAbw/f0Vlzq0EGuMxsTUdEDERAdZZDCEQWsrLzHvNdgm1UlhIJAwCQuTykAgYRIX1vvD6nfD98t9N1wufc261hyVe@RXfYrsozZPAeVZ4p/KRmETh67rlhae6VCbNM@8ikpsjwrSxq3xB7/zgPtU5yE1eMRjuuIJNXnGnzylFs/pnr/5ixf8QxEvKeYVr0nzhiz/8S9vKeede/CSPmtcDhTphDROUxHYsGgfdlTa0ybz7L6utG2IPzolPlJxEUee/FepHp@UTs1RDg@EPjhH6lKG4AJpSBkJY3ApwwRcIzdIUxYzcIu0pMzBnQwL8IBEUpbCSliDrgwbYBArZQsyJJeyA2@O@gc "Python 2 – Try It Online")
Just a simple lookup without any imports. If it finds a "special" character it prints the first character in the string where it is found otherwise just prints the input.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 30 bytes
```
{{S/W.+//}(.uniname).uniparse}
```
[Try it online!](https://tio.run/##AacAWP9wZXJsNv9teSAmZj3/e3tTL1cuKy8vfSgudW5pbmFtZSkudW5pcGFyc2V9/zsKc2F5ICJBw4HDgMODw4JCQ8OHREXDicOKRkdIScONSktMTU5Pw5XDk8OUUFFSU1RVw5pWV1hZWmHDocOgw6PDomJjw6dkZcOpw6pmZ2hpw61qa2xtbm/DtcOzw7RwcXJzdHXDunZ3eHl6Ii5jb21iLm1hcDogJmYg/w "Perl 6 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ 59 bytes
```
g(char*w){w=*w+61?*w:"oeaUICuic OEA"[(256+w[1])*13%59%13];}
```
[Try it online!](https://tio.run/##dcs9a8JQGIbhPb8iHAg5J@oQRaGGVkQcnJycrEM4aMzQWPzgDBLox1AsdFKXTq0OpYVOrYtrf1iUDnXpvby8cD23LkRaZ1kk9TAce0bNzblnchW/5pmqGPXDTqsxi7XdbtZFVxbLlZzp@j3l@SWnfOb4pV6QZoO/9nocJ9OBFK4zce3ChS3yRgWRPJ7UugrjRKq5ddpo9zIR@eP7cyOUCv6VW5Q7lHuSOiYPJA1MFiiPJE1MnkhamCxRVihrkjYmzyQdTF5QXlE2KFuSEJM3Eo3JO8oHSR@TT5IYky@Ub5QdyQiTPcnsF1IrOwA "C (gcc) – Try It Online")
Uses [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s formula from his [JavaScript answer](https://codegolf.stackexchange.com/a/200584/52210).
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~40~~ 32 bytes
```
iconv -f utf8 -t ascii//TRANSLIT
```
[Try it online!](https://tio.run/##Hca/CwFhHMfx3V/x7YkwXLcqpSTDlSg/Nss59@RZnkfuzoLyYxBlwmLyYxBlwmL1hx3fz/J6vztu0ItlJjuKlWf0kCxJUShzZIXkBp5Stt2sF6uNitOMJwlpBqRIaRLfqaC/MziHC7aIXbIl7Aqu2TJ2wzrYLdzBPVvDHtgW9ghP8AwvrIu9sh72Bu@sj32wCvuEL/hmDfbDRiJPXUP9gdKhJJFOBWmyCsRta0FJRcmM7/UM35jkP9l812g//gE "Bash – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pC -MUnicode::Normalize=NFD`, 17 bytes
```
$_=NFD$_;s/\pM//g
```
[Try it online!](https://tio.run/##AaMAXP9wZXJsNf//JF89TkZEJF87cy9ccE0vL2f//0HDgcOAw4PDgkJDw4dERcOJw4pGR0hJw41KS0xNTk/DlcOTw5RQUVJTVFXDmlZXWFlaYcOhw6DDo8OiYmPDp2Rlw6nDqmZnaGnDrWprbG1ub8O1w7PDtHBxcnN0dcO6dnd4eXr@b3B0aW9uc/8tcEP/LU1Vbmljb2RlOjpOb3JtYWxpemU9TkZE "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
A port of Arnauld's JS solution. I/O as codepoints.
```
Á7?H&U^`aÅ8`u cU/4&7:U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=Yw&code=wTc/SCZVXmBhrcU4YHUgY1UvNCY3OlU&footer=VmQ&input=IkHBwMPCQkPHREXJykZHSEnNSktMTU5P1dPUUFFSU1RV2lZXWFlaYeHg4%2bJiY%2bdkZenqZmdoae1qa2xtbm/18/RwcXJzdHX6dnd4eXoiCi1t)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 39 bytes
```
x=>x.Normalize((NormalizationForm)2)[0]
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrpOckVhkl2b7v8LWrkLPL78oNzEnsypVQwPGTCzJzM9zA3I0jTSjDWL/W3Ol5RelJiZnKGiUJRYpVChk5ikoOR5uPNxwuPlwk5Pz4XYX18Odh7vc3D08D/d6efv4@vkfnnp48uEpAYFBwSGhh2eFhUdERiUeXnh4weHFhxclJR9enpJ6eOXhVWnpGZmH12Zl5@Tm5R/eenjz4S0FhUXFJaWHd5WVV1RWKWlycYYXZZakaqRpVOiF5AeD3a@hqalp/R8A "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 72 bytes (53 characters)
```
T`À-ÃÇÉÊÍÓ-ÕÚà-ãçéêíúó-õ`AAAAC\E\EI\O\O\OUaaaaceeiu\o
```
[Try it online!](https://tio.run/##Jc69UsJAFIbh3nvJRSRhhYgaBeLfpCCEVQMKigSUCqVgdIYKaKhQCgZmqJCG9r2wmHXf0z/facl21AiSpFSmbzBgyCdfjBgbTJkxN1iwZMWaDXu2BruymWb7wheO76rzgrRQyij2m0li0uedDwaWzTAjFHeYzTmMjvLHJ6cuYyZMz84LxZLH7OLy6vomYM43PywqIcuqVGO3d/cRm1r94bHRZMsvu6fn1ks7Zt/pvr71DtQLpmXbGSGE0h2Np2nZ07CqEoZVKaUSIw2maS3@x/4A "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The Transliterate command has some special characters `E`, `O` and `o`, so these need to be quoted. To avoid repetition, the `o`s are processed last as the last character in the replacement string is automatically repeated. The remaining repetition is one byte less than the overhead of the `T` command; compare this 72-byte 58-character alternative (which also corrupts eth and n with tilde):
```
T`ÚÀ-Ã`UA
T`Ç-Ê`C\E
T`Í-Õ`I\O
T`úà-ã`ua
T`ç-ê`ce
T`í-õ`i\o
```
[Answer]
# perl -MText::Unidecode -pC -e, 14 bytes
```
$_=unidecode$_
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 82 bytes / 53 chars
```
`áéíõúÁÉÍÕÚàêióuÀÊIÓUãeiôuÃEIÔUâeiouÂEIOUÇç`k∨4*‛Cc+Ŀ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%C3%A1%C3%A9%C3%AD%C3%B5%C3%BA%C3%81%C3%89%C3%8D%C3%95%C3%9A%C3%A0%C3%AAi%C3%B3u%C3%80%C3%8AI%C3%93U%C3%A3ei%C3%B4u%C3%83EI%C3%94U%C3%A2eiou%C3%82EIOU%C3%87%C3%A7%60k%E2%88%A84*%E2%80%9BCc%2B%C4%BF&inputs=%60%C3%A1%C3%9A%C3%A0%C3%AAi%C3%B3u%C3%80%C3%8AI%60&header=&footer=)
The bad version, I can't figure out how to port any of the good ones.
[Answer]
# [Nim](http://nim-lang.org/), 45 bytes
```
import unidecode
echo stdin.readAll.unidecode
```
[Try it online!](https://tio.run/##Pcm5EsFAAAbg3lPkCbxD3Pd9d5FdsiS7kcNVOQrDjAqNylEYZlRotP@Drc7XfpxZUjLLFo6n@JwRqgtCA1Q3hOJ6hPGgQzWimmbwn1KqmGOGJRahMFaRKNbYxOKJJLapdCaby@OAHfaFYqlcqeJYqzeaLQ1nnHDFpa3jRijueHS6BsOz1zctLvDBC2974Liej@9wNJ5Mfw "Nim – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 17 bytes
```
($args|% N* 2)[0]
```
[Try it online!](https://tio.run/##VY9LT8JAFIXX7a@YNMWACQTdGhKhVMUHIAVfhBgolwIWCp1WUCDxsTCauFI3rnwsjCau1I3b@8Nqh1bEs5uZc853pmP0wKR10PWwapjgiLXYwAmKZVOjwwBJz5L5UDFackY8L1pALcUyG22NxAiTEMdTPMFzPEtIeJGU8RKvlpZXUni9ura@kc7gHd7gbXYzp@QLeL@1vbO7V8ZHfMBnfKqo@FIFfMW3mlZv4HvzQG@1DfzCD/zsdE1q2fh92OsfHQu8CP0OqBZUJ3AhzpSQpKQsy4yY8oCuPFrBgzFVVLUKAIzS8CCuPILtA6KRSHDqdxEd2ppVJ2EyFxoGBjw3fnOxU56iuF/iia/JQOb5P3bs40QTqK2zihmxRoRxj8Bzxawi2dQyWplK082UyKIL4xRbVYFS1uXHwtD9611wLfmpPeyc@633E@7diB85Pw "PowerShell Core – Try It Online")
Inspired by [the C# answer](https://codegolf.stackexchange.com/a/200641/97729), thanks [Gymhgy](https://codegolf.stackexchange.com/users/84206/gymhgy)!
Takes the input as a string.
Could be shorten down to [14 bytes](https://tio.run/##VY9LT8JAFIXX7a@YNCUBEwi6NSZCqYoPQAq@CCFSbqFYKLRTQYHEx8Jo4krduPKxMJq4Ujdu7w@rHVoRz25mzjnfmY7ZA8tugGFEVdMCV9MNChbRyMANi5VhiGRmyFykFC@7I54XKdhUoZberpMFwiQk8BRP8BzPkhJepGS8xKul5ZU0Xq@urW9ksniHN3ib28wrhSLeb23v7O7t4yM@4DM@VVV8qQG@4ptWb@j43jwwWm0Tv/ADPztdy6YOfh/2@kfHAi9CvwMqhdoELiSYkpKUkmWZEdM@0JNPK/owpqqq1gCAUXQf4sknOAEgHouFp34XM6Bdpw0SJbORYWjAc@M3DzvlKYmVMk8CTQYyz/@xYx8nWmA7BqsQxh3CUOO5Uk6RHJuarWy16SXKZNFDcYqjqmDbrCkIRaH71zrvWQpTa9g5/1seJLy7ET9yfwA) using a filter, but I don't think it is allowed?
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 18 bytes
```
»æ₁s≥»₄τ?28⋏i?96⋏+
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%BB%C3%A6%E2%82%81s%E2%89%A5%C2%BB%E2%82%84%CF%84%3F28%E2%8B%8Fi%3F96%E2%8B%8F%2B&inputs=205&header=&footer=)
] |
[Question]
[
A [traditional Western die](https://en.wikipedia.org/wiki/Dice#Construction) is a cube, on which the integers 1 to 6 are marked on the faces. Pairs that add to 7 are placed on opposite faces.
As it is cube, we can only see between 1 and 3 faces (inclusive)1 at any given time. Opposite faces can never be seen at the same time.
Your task is to write a program or function which, given a list of integers representing sides on a die, determines if it is possible to see these faces at the same time.
1Okay, maybe you can see 4 or 5 faces with a pair of eyes, but for the purpose of this challenge we observing the die from a single point.
---
# Rules:
* Your submission may assume the input list:
+ Is non-empty.
+ Only contains values which satisfy `1 ≤ n ≤ 6`.
+ Contains no duplicate elements.
* You may *not* assume that the input is sorted.
* Your submission should output a [truthy / falsy value](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey): truthy is the faces can be seen at the same time, falsy otherwise.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins!
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default.
---
## Test Cases
**Truthy:**
```
[6] (One face)
[6, 2] (Share a side)
[1, 3] (Share a side)
[2, 1, 3] (Share a vertex)
[3, 2, 6] (Share a vertex)
```
**Falsy:**
```
[1, 6] (1 and 6 are opposite)
[5, 4, 2] (2 and 5 are opposite)
[3, 1, 4] (3 and 4 are opposite)
[5, 4, 6, 2] (Cannot see 4 faces)
[1, 2, 3, 4, 5, 6] (Cannot see 6 faces)
```
[Answer]
# JavaScript (ES6), ~~38 34 30 29~~ 28 bytes
Takes input as any number of separate parameters. Returns `0` or `1`.
```
(a,b,c,d)=>!(d|(a^b^c)%7)^!c
```
### Test cases
```
let f =
(a,b,c,d)=>!(d|(a^b^c)%7)^!c
console.log('[Truthy]')
console.log(f(6 ))
console.log(f(6, 2 ))
console.log(f(1, 3 ))
console.log(f(2, 1, 3))
console.log(f(3, 2, 6))
console.log('[Falsy]')
console.log(f(1, 6 ))
console.log(f(5, 4, 2 ))
console.log(f(3, 1, 4 ))
console.log(f(5, 4, 6, 2 ))
console.log(f(1, 2, 3, 4, 5, 6))
```
### How?
Below are simplified versions of the main expression according to the number of parameters provided, undefined variables being coerced to either **0** or **false**:
```
# of param. | simplified expression | comment
------------+------------------------------+---------------------------------------------
1 | !(a % 7) ^ 1 | always true
2 | !((a ^ b) % 7) ^ 1 | false for (1,6), (2,5) and (3,4)
3 | !((a ^ b ^ c) % 7) | see the table below
4+ | !(d | (a ^ b ^ c) % 7) | always false
```
*NB*: The order of **(a,b,c)** doesn't matter because they're always XOR'd together.
The trickiest case is the 3rd one. Here is a table showing all possible combinations:
```
a | b | c | a^b^c | %7 | =0? | faces that sum to 7
--+---+---+-------+----+-----+--------------------
1 | 2 | 3 | 0 | 0 | Yes | none
1 | 2 | 4 | 7 | 0 | Yes | none
1 | 2 | 5 | 6 | 6 | No | 2 + 5
1 | 2 | 6 | 5 | 5 | No | 1 + 6
1 | 3 | 4 | 6 | 6 | No | 3 + 4
1 | 3 | 5 | 7 | 0 | Yes | none
1 | 3 | 6 | 4 | 4 | No | 1 + 6
1 | 4 | 5 | 0 | 0 | Yes | none
1 | 4 | 6 | 3 | 3 | No | 1 + 6
1 | 5 | 6 | 2 | 2 | No | 1 + 6
2 | 3 | 4 | 5 | 5 | No | 3 + 4
2 | 3 | 5 | 4 | 4 | No | 2 + 5
2 | 3 | 6 | 7 | 0 | Yes | none
2 | 4 | 5 | 3 | 3 | No | 2 + 5
2 | 4 | 6 | 0 | 0 | Yes | none
2 | 5 | 6 | 1 | 1 | No | 2 + 5
3 | 4 | 5 | 2 | 2 | No | 3 + 4
3 | 4 | 6 | 1 | 1 | No | 3 + 4
3 | 5 | 6 | 0 | 0 | Yes | none
4 | 5 | 6 | 7 | 0 | Yes | none
```
---
# Alt. version #1, 32 bytes
Takes input as an array. Returns a boolean.
```
a=>a.every(x=>a.every(y=>x+y-7))
```
### Test cases
```
let f =
a=>a.every(x=>a.every(y=>x+y-7))
console.log('[Truthy]')
console.log(f([6] ))
console.log(f([6, 2] ))
console.log(f([1, 3] ))
console.log(f([2, 1, 3]))
console.log(f([3, 2, 6]))
console.log('[Falsy]')
console.log(f([1, 6] ))
console.log(f([5, 4, 2] ))
console.log(f([3, 1, 4] ))
console.log(f([5, 4, 6, 2] ))
console.log(f([1, 2, 3, 4, 5, 6]))
```
---
# Alt. version #2, Chrome/Firefox, 34 bytes
This one abuses the sort methods of Chrome and Firefox. It doesn't work with Edge.
Takes input as an array. Returns `0` or `1`.
```
a=>a.sort((a,b)=>k&=a+b!=7,k=1)&&k
```
### Test cases
```
let f =
a=>a.sort((a,b)=>k&=a+b!=7,k=1)&&k
console.log('[Truthy]')
console.log(f([6] ))
console.log(f([6, 2] ))
console.log(f([1, 3] ))
console.log(f([2, 1, 3]))
console.log(f([3, 2, 6]))
console.log('[Falsy]')
console.log(f([1, 6] ))
console.log(f([5, 4, 2] ))
console.log(f([3, 1, 4] ))
console.log(f([5, 4, 6, 2] ))
console.log(f([1, 2, 3, 4, 5, 6]))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 35 bytes
```
lambda a:any(7-i in a for i in a)<1
```
[Try it online!](https://tio.run/##VYy9DsIwEINn7ik8JtIxNGlBqmDtSwDDoRIRCdKq6tKnDyGp@JnO9tnfuMz3IZjojuf4kOe1F0grYVH7rYcPELhhQpH6UMX@5tAp0S1txsmHGcJwyRN16rS76HwYpqiKYYsyjK@xqcB4tylDaO2u@4ZRfxA2D@vfzx8/gWxOm7yPLw "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 24 bytes
*-3 bytes thanks to H.PWiz.*
```
f l=all(/=7)$(+)<$>l<*>l
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hxzYxJ0dD39ZcU0VDW9NGxS7HRssu539uYmaegq1CbmKBr4JGQVFmXomCnkKaJpcCEEQrRJvFglk6QJaOghGcY6ijYAznGOkooPCNgSp1FMyQFSM4pjoKJsgmGYM1m6DJo1sGNM8YLGEKMksh9j8A "Haskell – Try It Online")
## Explanation
```
f l=all(/=7)$(+)<$>l<*>l
f l= -- make a function f that takes a single argument l
(+)<$>l<*>l -- take the sum of each pair in the cartesian product...
all(/=7)$ -- ...and check if they're all inequal to 7
```
[Answer]
# Regex (Perl / Java / PCRE2 v10.34+), ~~30~~ ~~29~~ 27 bytes
```
^(?!.*:(x(\2?+:.*\b)?){7}:)
```
Takes its input in unary, as a concatenation of strings of `x` characters whose lengths represent the numbers, separated and enclosed on both sides by `:` characters. Example: `:x:xxxxxx:` represents `[1, 6]`.
[Try it online!](https://tio.run/##RY7BboMwEETv/oqt5YOdbkOAQCU7hERKc@wpR1QrqYhE5QCFRKJC9Nfp0qjqZe2ZebPaOm9cNF6@QDQGele9Hx0Iz5BMVrvtYbse2LlqpGiThVmtjeqhOJNSfd0U5RV4VnIzUOpTxSXt7dReibb45KOv8s8pT//dBflKC2toC0jhaN2GWrUrrpIjR3IMAxAFJMA1hzl8VEUp6YtwOdY973gn7LBxiiJyJ/h@iCiSb080HqTAD80t1wAcNPD90bUkuPnjnGHDYO3L687a8U2mD/OZlp3MgvRRz2fZSaWqfx60GseYxRgwH0MW4DRDDDAmHeCS0ROzCJcEhBQuCQlpTs699KsxwvgH "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVJRb9owEH7PrzjyUhtctwXKpEQZ6iYqIa1oGtVe2m4yxICp42S2U0CI384uJJ3WrS@277u77@4@31q8iPN1@nxUWZFbD2u0ucp5O4a/kdIr/S5m5VJuK09RzrSaw1wL5@BOKAP7BnJeeLxecpVChg4y9VaZJQi7dA9PFPzK5hsHo@1cFl7lmBgA3CotYZEYuTk9ScjneSo5@kMafyoXC2ll@k2KVFqYncLeguQ1szEXlMZNXcd8vFlV/IS4ZIYjiPSLMpJQ2kpMqTVVC@K4/FUK7Uh40W63Q0r3b0NrBkL8uwR7ZPB/GJDgAhlmGPccu05y9mjOqtvHhxo7fBXeS2vAJs0Lp82KqoBjr8jnm@no53gyHU2m4/vx9xGNUabpXBiDEihTlB4SqKZuMDLdOS8zrgzFfzMeVHIZQzP4KZ6vhJvIrce@YQ/Ysmoll7RJy9FfoF5eG1IRJFdVPaxYi6ixWE1ikKHRBDmAtDRXbpQVfnfivRN@vsIOM0ywPKstEkZhp2bi6xxXAm0GN9aKnePOoygZ0dwVWnkSMtQOEwtizj@G2xDlLqTwZGw87p7lhbBOokEMxTifn1iaHXt4iiKUhNIOFsD@/p2NZHyhTEooDCG8t6WMAEKIILzFj0MDcw7/J2lED4egWozjDzJs8XZEtuSxO@xEvP04o0O6/3CI6LH69@MgGLBucMV6QZdVZ4912QDtLusHeA2Ca9bHgB46@xjSw7NC6qSTza7Z4Dc "Java (JDK) – Try It Online") - Java
[Attempt This Online!](https://ato.pxeger.com/run?1=pVbNbttGEL4WeoqxAli7EuXqx1YN0rTh2goswJYDRUbT2C5BUyuLCLUkyGXtOPWT5JJLj7n20idJn6azP5QoyW0PFSRyd2a--duZWX3-GiRRnsmfdx8EX6-rzSgJUtZp7ldvv41eTdg05AzenIz6He_k8rTvXQ0HY--nwen4DPYrr0IeRPmEwYEC7cwOK8HMT8FLrm_BhVH1x4eHD3fd_OePH9-NZ72HGfk9F9Pm_p-_kKOtnbpNHslN56hh79Rv7ugR_fTDs021xF_f_UHXwVUL6onrJY22U7KciTTk99L0khbGSGX-_HBD7rAScgEJLoXH0jROSRDzTIByuz5nWebfMwqfMjGx7QAl4OAADFkuFZ3xSeRAykSecmg7zxs65T6IJ8yCuziOIHanfpRJtcqMUXfd2evdOhXATzgFojLo3TOjwzNSROsh-giuTs6OR_t1apgWZOETi6dk4fj3BaUkTylVVuSHxHCkgwjiXIANi0CpDK-qYKA8sKG6FrwCV6uIqt7wKl3kY4rlM9ORLJJS0VmZ-yEnGLhiJtd4CBHjJKHN9q3bciBHmW7HE5iillagFOqzgpAnuXBAZ0bmAeopK_ZzXwQzb-ILH89tsXZAWk1ZlkfC0nE4pnzfDt73FWU6zRgyMX705V7MVgTq8a8sEIgy4WAZF_bnSRgxYjL79s14RBPLQN_3R5feuD-6GAyPx_3Tgtx_N-4PT_un8JshXFydjwfng2Hfgm3lnHkbl1p0WQ9bKR6nSWe5ttTTyJVy4G6kxcO9L5g3TeO5l_hCsJSTFGtmeHV-bhSUMdgIgj0KzGaxcl_iG7VkQwtGYCSjcB4KUqixoNmmTklowhLxn0IpC_I0C2P-oqAyO41TUK32JEtJFQ62T4QDi-iqDrmla4g6RQkW2X2igHTZjqR2w2to-sltO4qlEDuyjQh13RYFaTnkOXOWGtAo1o40qwdHtuQtvEriDAVWLBdYzh48xFvAMce-iENjNPCw8rFdGhJMkS3P1b_LCJcbKYyUBhB-UFRKOSaJWTOmOgphRLpZp3hyURQHJMOBYnxApnw2oI0_zqlZtdf0K0XXKNloyMles2ur_GdgOOH-3fpcGy9Z_p82NzIg86IhCtBcA8zZHEuLZGhLx6wAFtQeazLXWATaLePgKhiziyx9TngpTkjNQpSkKs-LEwDXLc8w2-bqWO4w9R8cLe7K8bgZxFqoyzhaS2k92FYbU_V0eSrh6ariaqnvciDg2jRRKdHSba31oAXb28bClmsG2Gh0OfKGlxfH45MzupqP0kwq5q1Ic1bSLUtiBbO8eORtolGHbkveKmOE2gDqcnktb0t8v3jDbOjRt8Sy_1KG_W-8eP6nKecpsWU-NqenFljsafke0kwc0It_AToWvPX035cv3173Kj2rU2lb3UrHks-u1bF6uO9YuxV89Sp71i4KdJG5iyJdfEqKBqm9tWf1tLq_AQ "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
This is an adaptation of the ~~31~~ ~~30~~ 28 byte version below, but it prevents more than one split from occurring in a somewhat more complex manner. Upon matching a split, `\2` captures the intervening elements, including commas – or just a single comma if there are no intervening elements.
How this prevents more than one split would be simple to explain if `(?(2)\2)` were used instead of `\2?+`. Then the mechanism would be that on subsequent attempts to match a splitting after one has already occurred, that would be forced to coincide with matching a duplicate element, or two commas in a row.
But `\2?+` will successfully make an empty match if `\2` is not an exact match at that position. However, note that if this did happen, it could only result in false negatives (returning "False" incorrectly) – never false positives – because it could make the pattern inside the negative lookahead match when it shouldn't, but it can't prevent a match that should have happened.
All lists of 4 or more numbers will return "False", so the addition of false negatives won't matter. And lists of 2 or fewer elements can only match one split anyway (where `\2` captures a single comma alone), so no false negatives could result there.
So we only need to consider lists of 3 elements:
* Only two splits can occur at most, and if that is the case, `\2` will contain exactly one comma. The first split prevents a second split from being matched because `\2?+,` would only match two commas in a row.
* Or if a split matches one intervening element, only one split can occur anyway, so there's no place for a second split to match.
And here is a test harness with all 156 lists of 3 or fewer elements, demonstrating this regex to work correctly:
[Try it online!](https://tio.run/##RVLBbtswDL3rKzTBB7vzkkoiOcBumhbodtypx2BGOqSABzfJnBTIYHi/ntFPHnYw8Ug9UY@PPu76jq9vv23W13boDj@2nc2Wtaaru6fH58f70bwe@jw7rW7ru/u6GGz7qlkxHPt2f7Zus3f1qKder3Sr0/vL6azspvzkS1/sfk3n6//VW60XVdbU2sXmWaftHvTWsWvPuStdqZXaWJu1dmVd5ezC/jy0@1xhad@2x8Fd3CVrxoeu0COtTuQkJGtXf5ZZv7Rr6577911lrbOVdV@33UkTV//jdbUZx6b58u2paa7f8/WHxU2VX/JNWH@sFjebl2JdDJ/HqrhevQkmGjJsxPgy6Bf1I/3YhFJPNQ@ah1JM1DwqJ@pZ1Jw0J81Jc9KcNWfls/JZc9Ez0Vw0F@Vof3QP6B/Ta6gTMAEzOIw3PV73wDGp0b56H5iABZzpDWVAnYe@kNRCNwMzsIAj0Oyh3gOHNA3mYmAGFnAmPkMPQw9DD0MPQw@XyQMBJ80cMH0AjskN7SOYVzCvYF7BvDr2NNAknvTJqc1E87As2SewLNknsAzrAmaYyMACLDgV8CUtdI4CK5OtDCuxZmCGuYxKWgPPRntEhsXJboHFhAjdMJpgMc2VtAD8NmAKOIIZJ0MJfQhmEfoQzCVYRlBIZZwXg98NTAFH5pUExGkBAcsIyT@sKqAewYmoEDDNq/KI8HqOEZEQGSv0iIwVekTCCj1iWqFHDH8B "Perl 5 – Try It Online") - Perl
# Regex (Perl / Java / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby / PCRE), ~~31~~ ~~30~~ 28 bytes
```
^(?!.*:(x\2?+(:).*\b|x){7}:)
```
[Try it online!](https://tio.run/##RY7NTsMwEITvforF8sEuS9r8NEh207RS4cipxwirRakU5CYhaaWgEF49bKgQl7Vn5pvV1nnjluP5E0RjoHfV28GBmBuSyWq33W/XAztVjRRtsjCrtVE9FCdSqq@borwAz0puBkp9qrikvR7bC9EWH3z0Vf4x5em/uyBfaWENbQEpHK3bUKt2xUVy5EiOYQCigAS45uDBe1WUkr4I50Pd8453wg4bpygid4Jvh4gi@Z6LZg4p8H1zzTUABw38@eBaEtz8cc6wYbD26WVn7fgq0ztvpmWXBem91MqbZcevTvWPg1bjGLMYA@ZjyAKcZogBxqQDjBg9MVtiREBIYURISHNybqVfjUuMfwA "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVJRT9swEH7Pr7jmBbs1BlropEQZYlORKkE1LWgvwCa3camL42S2Q1t1/e3dpQnT2Hixfd/dfXf3@ZbiRRwvs@e9ysvCeliizVXBuzH8jVRe6XcxK5/kuvaU1VSrGcy0cA5uhTKwbSHnhcfrpVAZ5OggqbfKPIGwT@7@kYJf2GLlYLSeydKrAhMDgGulJcwTI1eHJwn5rMgkR39I40/VfC6tzL5KkUkL00PYW5C8ZrbmnNK4reuYj1eLmp8Ql0xxBJHdKCMJpZ3EVFpTNSeOy5@V0I6EJ91uN6R0@za0YSDEv0uwRQb/hwEJTpBhinHPseslRw/mqL59vGuw3RfhvbQGbNK@cNq8rAs49op8vkpHP8aTdDRJx3fjbyMao0zpTBiDEihTVh4SqKduMZJunJc5V4bivxkPKjmNoR38EM8Xwk3k2mPfsAVsWXWSU9qmFegvUS@vDakJkrO6HlZsRNRYrCExyNBqghxAOporN8pLvznw3go/W2CHOSZYnjcWCaOw1zDxZYErgTaDK2vFxnHnUZScaO5KrTwJGWqHiSUxxx/DdYhyl1J4MjYed8/yUlgn0SCGYpwvDiztjt0/RhFKQmkPC2B//85Gcj5XJiMULiG8s5WMAEKIILzGj0MDc3b/J2lEd7ugXoz9d3LZ4d2IrB/6lz0SUd59mP5a0@2HXUT39cfvh8GQ9YMzNgj6rD4HrM@GaPfZeYDXMLhg5xgwQOc5hgzwrJEm6WCzCzb8DQ "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##TU/LTsMwELz7KxZfbKfGah4NkpHVG1/ALQEpEJcaGSeyg5QW@PZgN0L0MqvZndmdHU/TcXDlYj7GwU8QToF7/aZn5EGBxxgvz3R/IzJJ57bYb6hkImtfvmf2dfcj2RIFTS5v86d7OKstOgweLBiX9ogw9cZJBGAOcJYweuMmylZutaOWQed6sE20K0VaRyRYZZtt2nct@/Nq1yv86D@1BMBpfEkqgu7865F6DkQS2CQU74NxlMwkSz7DIAUzKZgVYbRmooQTxlYxA22DBvzQxSIBp4j/By1Lr@VLjWpeoJyXqOAJS17wOvKCVyiWGu14FQVlHFZRUkZMndV04XzH618 "Python 3 – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=TU9LTsMwFNz7FA9vbKdu1HwakFHUXU_ALgEpEIcaGSdyUiktcBI23cAdkLhIj8AtajdCsJmn8ZsZz3v_7HbDpjWHL_XctXaAftdzKx_liCzkYDHGH9uhmV9939HVRRgIOpbxakYFC4Py_nVkL5dvgk2S449TF5GYR7fXsM8XqGktaFDGh4b9UCsjEIBqYC-gs8oMlE1cS0M1g8rUoAtnz3NSGiJA57pY-Lz_sl-vNHWOb-xWCgDs1-faYS8r-7ChlgMRBGYew6dWGUpGEnifYuCLKV9Mh32n1UAJJ4xNYgZS9xLwunJDAPYV_z7UzJ8WTQcfjusMZTxGEU9QzD0mPOaZ4zFPkRsZWvLUCRK3TJ0kcehfJtOZ8yXPprgT "Python - Attempt This Online") - **Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`)**
[Try it online!](https://tio.run/##NU5Lb4MwDL7nVxguSWga8SqTQBGq1O24w9Rb6RDV0i5TShEPlap0f50Fth1s63vZrrvDbaxBwJs8yb7ipbzCZr1d81oWHwko4SZw/VRaghYn2TYIQB1B75beXgg7K@3ECHrncr709wnIcgodQVlTsOra5p8T3ixYmstz1d5SswigqlXZAiE4xrAAzZtKq5Zghik/F9V9aAa7t52Gt5dcEc@lD/51UeVkp8Y/D/ENNYUU8LbuZAyAIQb8UujGAJz8XdDmmnkDTZXnz6@bPB/fSWpxJyZ95qcLElPuZIehp/enR0zHMUIR85HHAuSzqQfMZ5HBPguRGRFasdAYAiOGxhKYPjG/oRmzFYt@AA "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##pVZtb@JGEP7Or5hwUtgFk/KS0MiOE6WBKkgJOXFEvV6SWo5ZwDqztux1k8td/nrT2ReDgbT9UAT27rzPszOzBEnSnAfB24cpm4WcwceL8aDjXdz0B97taDjxfhv2J5dwXPkQ8iDKpwxOkiBlnYPFaSVY@Cl4yd0DuDCu/vL09PWxm//@7dvnyaL3tCBvf5CzvYO6TZ7vO2cNYtOD@v3jj2f6/edXm77RbfmqBfXE9ZJG2yk5y0Qa8rn0tqaFMVKZvzzdkTuthFxAgkvhsTSNUxLEPBOgIq0vWZb5c0bheyamth2gBJycgCHLpaIzPo0cSJnIUw5t53XHptwH8ZRZ8BjHEcTuzI8yaVa5MebuOke9B6cC@AlnQBRo3pwZG56RItoO0ajfXlyej4/r1DAtyMIXFs/IKvCfCkpJnlKqvMgPieFMJxHEuQAbVolSmV5VqYGKwIbqVvJKuVpFreo9r9IVHrMozxY6kxUoFY3K0g85wcQVM7nDQ4gYJwltth/clgM5ynQ7nkCIWtqAMqjPCkKe5MIBjYzEAeopK/ZLXwQLb@oLH89ttXZAek1ZlkfC0nk4pmI/Db8MFGU2yxgyMX@MZS4WGwL1@E8WCNQy6WDlFv6XSRgxYpD99HEypollVL8MxjfeZDC@Ho7OJ4N@QR58ngxG/UEffhjC9e3VZHg1HA0s2FfBmbcJqUXX9bCX4nEaOMu1pZ5GroSBuwOLh3tfMG@Wxksv8YVgKScp1szo9urKGCjrYCMI9iwQzWLlvsc3ZsmOFczASEbhMhSkMGNBs02dktCUJeI/hVIW5GkWxvxdQeV2FqegWu1FlpIqHGyfCGcU0VUdckvXEHWKEizQfaGAdNmOpHbPa@j6xW07iqU0DmQbEeq6LQrSc8hz5qwtoFOsHelWD45szVtFlcQZCmx4LnQ5e/JQ3wKOGPsiDo3TwMPKx3ZpSGWKbHmu/mNGuNxIYaQ0gPCTolLKOUmdLWeqo1CNyDDrFE8uiuKAZDhQTAzIlM8GtPHHOTWr9pZ9ZegOJRsNOcxrdm2T/woMJ9y/e19q5yXP/9PnDgISF62iFJpbCku2xNIiGfrSOSsFC2rPNYk1FoEOywS4qYzoIkufE96DU1KzUEtSVeTFCYDrlmeYbXN1LI8I/VdHi7tyPO4msZXqOo/WWloPts3GVD1dnkp4uqq4Wuq7Hgi4Nk1UAlqGra2etGB/33jYc80AG49vxt7o5vp8cnFJN/EozaRi3oo0ZyXbsiQ2dNYXj7xNtNap25K3ygRVbQB1ufwqb0t8v3vD7NjRt8S6/1KG/W@ieP2nKecpsTUeu9NTC6z2tHwPaSYO6NW/AJ0L3npvvUrP6lTaVrfSseSza3WsHu471mEFX73KkXWIAl1kHqJIF5@SopXU3jqyen8Fs8ifZ2/NSHltHv8N "C++ (gcc) – Try It Online") - **PCRE**
This is an adaptation of the ~~33~~ ~~32~~ ~~31~~ 29 byte version below, but it prevents more than one split from occurring with `\2?+(,)`, which forces a split to coincide with matching two commas in a row (which can never happen in the input specification) if a split has already occurred.
# Regex (Perl / Boost / Python / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby / PCRE / .NET), ~~33~~ ~~32~~ ~~31~~ 29 bytes
```
^(?!.*:(?(1)x|x(:.*\b)?){7}:)
```
[Try it online!](https://tio.run/##RY7NbsIwEITvfoqt5YONtkB@K9mEgER75MQR1QpVkFwZSBOQUqXpq6eboqqXtWfmm9VWZe2T4fQJojbQ@ctb4UHMDMlssVnv1sueHS@1FE02N4ulUR24IynVVbU7X4Hvz9z0lAZU8VlzOzRXoi0@Bhio8mPM8393Tr7SwhraAlJ4WreiVuXdVXLkSI5hAMJBBlxzmML7xZ0lfRFORdXxlrfC9iuvKCJ3hO@HCJd9z0Q9gxz4rr6VGoCDBv5S@IYEN3@cN6zvrX3ebqwdXmX@MJ1omctAtV@t1NPJ/qBy1T31Wg1DylIMWYARC3GcEYaYkg4xZvSkLMGYgIjCmJCI5ujcS78aE0x/AA "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##pVPbjtowEH3PV0zpQ2wwLIFdKiVkkfrQD6j2odXuNgrGJNYGJ4odwbLLr5eOHVgulfpSS7l4Zs6cMzM2r6p@xvn@s1S8aBYCpvOy1OamFpnYDPKquveuXWLDRWVkqW4WMs0UmiRPpFqW9Sq15hbF87SGpHp8hhi@d76u1y/zcfPz9fXHQz5Z52T/i8w@DbohmZGAbt43JBx0n@Z0Rt@@7EK6p9eADoNuFSdVL4jOBEkkr0W6uvekMrBKpSIU3jzAVT2iqxCKVLQfPMfDCBqMGY8SA6XdWUBmf7RZhCHGSpWhsWpM5PC8VNqAqzgMXTegFpgsOto0VstzWOfpAYENAGLTbj/SZsIUUgniNlwq1jLQ6KjSLrkEsqWAdtsz4j8pH1m2cRA5l0MMtNwKQuN4SK0yI1UjolMGJMVSLa1re1effB@qqlJjwAXzEavEOkE8A4XDSk0pD6Q8wb5gR3sWTNGdWv9cE2U3NhgtPSBqOqTRZVYUbjFXZHZphBErs0txdEVRcqIZ5mg1oNO@exDgoxQ9/AVX@V2iR4zs9ewB80P/0r8DUWjxb/ZVS37G/J@cf3XA9qWFOED/CrASKy0M0cjV1uwADPyNb3uNh6CVdRB4Ccbuoqud01KqBfEZoqzVKT9OAOL4/ISHoXJjmWPrX6I2HOs@pT4VcVXqqY7hKbo912VjYDoFcn5ZEi3SmufkjBvHjBmwPntlGN4mCjPoPNSNCAE6EELnW4pDwy@16c7uYiuqFqaplaXf7SfehI28gI29EbPvMRuxCe5H7NbDz8S7Y7cYMEbnLYaM8W0tLcjt2R2b/ObLIs30vl846YlT/gc "C++ (gcc) – Try It Online") - **Boost**
[Try it online!](https://tio.run/##TU/LTsQwDLznK0wuSYqJto8tUlDUG1/ArQtSoVltUEirtEjdBb69JFQILmONPWOPx/N8Gny52rdxCDNM5wmDIQE0BErp@sSbK5kp3vBcLJ8LVzI7PItGfNx@KbFGRZurm/zxDi56R45DAAfWpy1ymnvrFQGwR7goGIP1Mxcbd8ZzJ6DzPbg22rVmB88UOO3aXdr3X/brNb7X9CG8GwVA0zgYOZkuvJx4QGCKwXVC@TpYz9nCsmSyAlIqm1I5OY3OzpwhE2ITCzBuMkDvu1gU0JTv75oT6a98rUmNBcmxJAUmLLHAOvICKxJLTfZYRUEZh1WUlBFTZzP9cNxj/Q0 "Python 3 – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=TU9LTsMwFNz7FA9vbKdu1HwakFHUXU_ALgUpEEc1Mk7kuFJa4CRsuoEjsOIivQDnqE2EYDNP4zcznvf20e_dtjPHT_XUd9bBsB-4lchCCRZj_L5z7fzq646uLuJI0HGTrmZUsDja3L-M7PnyVbBJcvr26ioR8-T2Gg7lArWdBQ3KhMR4cI0yAgGoFg4CequMo2ziWhqqGdSmAV15e1mSjSECdKmrRcj7L_v1StOU-MbupADAYW1lPMjaPmyp5UAEgVnA-LFThpKRRMGkGIRWKrTS8dBr5SjhhLFJzEDqQQJe134IwKHf32-ahbuS6drjaV2ggqco4RlKecCMp7zwPOU58qNAS557QeaXuZdkHsPLZPrhfMmLKe4M "Python - Attempt This Online") - **Python**
[Try it online!](https://tio.run/##TU/LTsMwELz7KxZfbIfFah4NkpGVG1/ALQWpEJcaGSdygpQW@PZgN0JwmdXszuzODqfp2Ptyse9DHyYYTyMG82pmEkBDoJQuT7y5kpniDc/F/DVzJbPds2jE5@23EktUtLm6yR/v4Kw35NAHcGB9WiTHqbNeEQB7gLOCIVg/cbFyZzx3Ava@A9dGu9Zs55kCp127Sfv@y369xneaPoQPowBoGl@iytHsw8uRBwSmGFwnlG@99ZzNLEs@KyAFsymYk@Pg7MQZMiFWsQDjRgP0fh@LApoi/h10Ir2WLzWpsSA5lqTAhCUWWEdeYEViqckWqygo47CKkjJi6qymC8ct1j8 "Python 3 – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=TU9LTsMwFNz7FA9vbKdu1HwakFHUXU_ALgEpEIcaGSdyUiktcBI23cAdkLhIj8AtajdCsJmn8ZsZz3v_7HbDpjWHL_XctXaAftdzKx_liCzkYDHGH9uhmV9939HVRRgIOpbxakYFC4Py_nVkL5dvgk2S449TF5GYR7fXsM8XqGktaFDGh4b9UCsjEIBqYC-gs8oMlE1cS0M1g8rUoAtnz3NSGiJA57pY-Lz_sl-vNHWOb-xWCgDs1-faYS8r-7ChlgMRBGYew6dWGUpGEnifYuCLKV9Mh32n1UAJJ4xNYgZS9xLwunJDAPYV_z7UzJ8WTQcfjusMZTxGEU9QzD0mPOaZ4zFPkRsZWvLUCRK3TJ0kcehfJtOZ8yXPprgT "Python - Attempt This Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`)
[Try it online!](https://tio.run/##NU7db4IwEH/vX3Hw0tbVhi9ZAmmIidvjHhbf1BHMqutSkVCIGHH/Oiu4Pdxdfl93V7f761CDgHd5lF3FS3mB1XK95LUsPlNQwkvh8qW0BC2OsjEIQB1Ab@b@Tgh3W7qpFfTG43we7FKQ5Rg6gHLGYNU25p8T/iQ4mstT1VwzuwigqlXZACE4wfAEmptKq4Zghik/FdWtN73buTPDm3OuiO/RO/8@q3K0U@ufhviBmkIGeF23MgHAkAB@LbSxAKd/F7S9Zt9AY@X5y9sqz4cPkjl8lpCM@LTrO5Lw2XZPM3p7vid0GGIUswD5LEQBG3vIAhZbHLAI2RGjBYusIbRiZC2h7SPzCE2YLVj8Cw "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##pVZtb@JGEP7Or5hwUtgFk/KS0MiOE6WBKkgJOXFEvV6SWo5ZwDqztux1k8td/nrT2ReDgbT9UAT27sw887YzswRJ0pwHwduHKZuFnMHHi/Gg413c9Afe7Wg48X4b9ieXcFz5EPIgyqcMTpIgZZ2DxWklWPgpeMndA7gwrv7y9PT1sZv//u3b58mi97Qgb3@Qs72Duk3OSJs@/3gm9kH9/pGe0e8/v9r0jW4DqhbUE9dLGm2nZC0Tacjn0tyaFsZIZf7ydEfutBJyAQkuhcfSNE5JEPNMgHK1vmRZ5s8Zhe@ZmNp2gBJwcgKGLJeKzvg0ciBlIk85tJ3XHZ1yH8RTZsFjHEcQuzM/yqRaZcaou@sc9R6cCuAnnAFRWfPmzOjwjBTReohO@@3F5fn4uE4N04IsfGHxjKwc/6mglOQppcqK/JAYznQQQZwLsGEVKJXhVRUMlAc2VLeCV@BqFVHVe16lq3zMojxb6EhWSanorCz9kBMMXDGTOzyEiHGS0Gb7wW05kKNMt@MJTFFLK1AK9VlByJNcOKAzI/MA9ZQV@6UvgoU39YWP57ZaOyCtpizLI2HpOBxTsp@GXwaKMptlDJkYP/oyF4sNgXr8JwsEokw4WLqF/WUSRoyYzH76OBnTxDLQL4PxjTcZjK@Ho/PJoF@QB58ng1F/0IcfhnB9ezUZXg1HAwv2lXPmbVxq0XU97KV4nCad5dpSTyNXyoG7kxYP975g3iyNl17iC8FSTlKsmdHt1ZVRUMZgIwj2LDCbxcp9j2/Ukh0tGIGRjMJlKEihxoJmmzoloSlLxH8KpSzI0yyM@buCyuwsTkG12ossJVU42D4RDimiqzrklq4h6hQlWGT3hQLSZTuS2j2voekXt@0olkIcyDYi1HVbFKTlkOfMWWtAo1g70qweHNmat/IqiTMU2LBcYDl78hBvAccc@yIOjdHAw8rHdmlIMEW2PFf/MSNcbqQwUhpA@ElRKeWYJGbLmOoohBHpZp3iyUVRHJAMB4rxAZny2YA2/jinZtXe0q8U3aFkoyGnec2ubfJfgeGE@3frS228ZPl/2tzJgMyLhihAcwuwZEssLZKhLR2zAlhQe67JXGMRaLeMg5tgzC6y9DnhRTglNQtRkqo8L04AXLc8w2ybq2N5xNR/dbS4K8fjbhBboa7jaK2l9WDbbEzV0@WphKeriqulvuuBgGvTRKVES7e11pMW7O8bC3uuGWDj8c3YG91cn08uLulmPkozqZi3Is1ZSbcsiQ3M@uKRt4lGnboteatMEGoDqMvlV3lb4vvdG2ZHj74l1v2XMux/48XrP005T4mt87E7PbXAak/L95Bm4oBe/QvQseCt99ar9KxOpW11Kx1LPrtWx@rhvmMdVvDVqxxZhyjQReYhinTxKSkapPbWkdX7K5hF/jx7a0bKavP4bw "C++ (gcc) – Try It Online") - PCRE
[Try it online!](https://tio.run/##RU5BTsMwELznFcYyst06EU3aIDmKWgmJGzdupaBQto2RcSLHVaOmfntw6IHLjGZndnbb5gy2q0Hrkdhya@EI/U5KA2e2oeM7W98lM8nWbMH7a89kMnv75Gs@PHrJR7oR@Kn5aZWGL8wLcikfikNjodrXjGikDCLKtCfHB3Vg5MKHs1UO4rrpnA/hRYGmuU40mKOr@UCqkui4a7VyWOACkb7EEs8ZIxW6ons00J7Otsq4HfnwPP5ulAk@nwco0H83ik0T/tfKAMKETTds8lK5fQ0dIz3nA321J5CIegS6g9D7XAWW1HNENPZ@zKNcpNFCZFEqJsxEKvKgU7GMAuXRSixDIAvmMkSygNPktvSnxUrkvw "PowerShell – Try It Online") - **.NET**
This works by asserting that no two numbers add up to exactly 7. It does this by consuming exactly 7 `x` characters – a split is allowed to occur at any point within this, but not more than once.
```
^ # Anchor to start
(?! # Negative lookahead - assert that the following can't match:
.*: # Skip to after any occurrence of a bounding character,
# which denotes the beginning of a number's unary
# representation.
(?(1) # Conditional upon whether \1 is set:
# If \1 is set:
x # tail -= 1
|
# If \1 is unset:
# (This is only allowed to match once within this loop. There is no
# need to verify afterward that it matched exactly once, because the
# input specification allows us to assume there will be no numbers
# greater than 6 – so, 7 will never appear.)
x # tail -= 1
(
:.*\b # Complete the match for the current number, and
# skip to the beginning of any subsequent number's
# unary representation.
)? # Match the above optionally
){7} # Iterate the above exactly 7 times; this can never result in
# the 7th iteration ending in a split, as that would require
# matching 7 x's in a row, but the input is guaranteed not to
# contain a 7.
: # Assert that tail == 0 (i.e, that this is the end of a
# number's unary representation)
)
```
Strangely, this actually works with Python's `re` library, even though `(?(2)`...`)` is a forward-declared conditional, and `re` doesn't support forward-declared or nested backreferences; `\2` in that position would throw an error.
Equally strangely, it works in Boost, even though that regex engine doesn't support nested or forward-declared backreferences either, and a `\2` in that position would cause Boost to throw an error as well.
The previous 33 byte version did not work properly with Python's `re`; it used a nested conditional, and Python silently treated that as a no-op, making the regex return some false negatives. But strangely, that version works in Python[`regex`](https://github.com/mrabarnett/mrab-regex), even though that engine doesn't support nested backreferences either.
# Regex (Perl / Java / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby / PCRE / .NET), ~~34~~ ~~33~~ ~~32~~ 30 bytes
```
^(?!.*:(x(?!\2):.*\b()|x){7}:)
```
[Try it online!](https://tio.run/##RY5Na8JAEIbv@yumyx52Zarms7BrjILt0ZPH0CWWCCmrpkmElDT96@mkUnqZ2ef9GLYqaheN508QtYHeXd9yB2JhCJPVbnvYrgd2utZSNMnSrNZG9VCeiFRf1eWlBZ5duBnI9ajikuZ2bFpKW3z00FPFx@Sn/@qSdKWFNXQFpHB0bkOtypWt5MiRFMMARAkJcM1hDu/X8iLpiXDOq553vBN22DhFFqlT@P4RUSbfC1EvIAV@qG@FBuCggb/kriHg5i/nDBsGa5/3O2vHV5k@zGdadrQzX@n5LDtK9dWp/mnQahxjFqPPPAyYj9MM0MeY2MeQ0YpZhCEFAjJDigQ0J@Ve@mWMMP4B "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVJRb9owEH7PrzjyUhtctwXKpERZ1U1UQmrRNKq9lG4yxBRTx8lsp4AYv51dSDqtW198vu/uvrv77JV4Eaer9PmgsiK3Hlboc5Xzdgx/I6VX@l3Myie5qSJFOdNqDnMtnIM7oQzsGsh54dG85CqFDANk4q0yTyDsk3t4pOCXNl87GG7msvAqx8IA4EZpCYvEyPXxSkI@z1PJMR7S@FO5WEgr069SpNLC7Jj2FiSvlY27oDRu@jrm4/Wy4ifEJTNcQaS3ykhCaSsxpdZULYjj8mcptCPhWbvdDindvU2tGQjx7xLskMH/YUCCM2SYYd5z7DrJydScVNbH@xrbfxHeS2vAJs0Nt82KqoFjr8jn68nwx2g8GY4no/vRtyGNUabJXBiDEihTlB4SqLZuMDLZOi8zrgzFdzMeVHIeQ7P4MZ8vhRvLjce5YQc4smol57QpyzFeoF5eG1IRJBdVP@xYi6ixWU1ikKHRBDmAtDRXbpgVfnvkvRN@vsQJMyywPKs9EkZhp2biqxy/BPoMrq0VW8edR1EyorkrtPIkZKgdFhbEnH4MNyHKXUjhych4/HuWF8I6iQ4xFPN8fmRp/tjDYxShJJR2sAHO9@9uJOMLZVJC4QrCe1vKCCCECMIbfDh0sGb/f5FGdL8Pqo9x@E6uWrwdkQ3aaZdGvD2dEfprQ3cf9hE9VE9/GAQD1g0uWC/osurssS4boN9l/QDNILhkfUzoYbCPKT08K6QuOvrskg1@Aw "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##TU/LTsMwELz7KxZfbIfFah4NkpHFjS/gloBUiEuNjBM5QUoLfHuwGyF6mdF4Z3bHw3E69L5c7MfQhwnG44jBvJmZBNAQKKXLM7@/kpnic@S2EEpm7QsX37P4uv1RYomWJlc3@dMdnPSG7PsADqxPm@Q4ddYrAmD3cFIwBOsnLlbtjOdOwM534JoY15q1nilw2jWbtO/S9pc1vtP0MXwaBUDT@NxVjmYXXg88IDDF4DqhfO@t52xmWcpZAamYTcWcHAdnJ86QCbGaBRg3GqAPu0gKaKr4f9CJ9LV8qUmNBcmxJAUmLLHAOuoCKxKpJlusoqGMwypayojpZQ2dNW6x/gU "Python 3 – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=TU9LTsMwFNz7FA9vbAc3aj4NyChi1xOwS0EKxKFGxokcV0oLnIRNN3AHNtyjR-AWtRsh2Mzo-c2M571_9lu37sz-Sz33nXUwbAdu5aMckYUSLMb4Y-Pa2eX3Hb0-iyNBR8-rlIk4Wt1T9jqyl4s3wSbR4cfrq0TMktsr2JVz1HYWNCgTYuPBNcoIBKBa2AnorTKOsmnW0lDNoDYN6Mrby5KsDBGgS13NQ95_2a9XmqbEN3YjBQAO61PxeJC1fVhTy4EIAucB46dOGUpGEgWfYhCKqVBMx0OvlaOEE8YmMQOpBwl4WXsSgEPFvw81C6cl08H7w7JABU9RwjOU8oAZT3nh55TnyFOBFjz3gswvcy_JPIaXyXSa-YIXU9wR "Python - Attempt This Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`)
[Try it online!](https://tio.run/##NU5Nb4JAEL3vrxi47C5dNwJKE8iGmNgee2i8qSWYrnabFQkfEaP2r9MB28PMy5v33sxU7e7SV6DgXR90V8pCn2G5WC1kpfPPBIyaJnD@MlaDVQfd1ATA7MGuJ/5WKXdTuAkKdj2VchJsE9DFENqDcYZg2Tb1/0z5o@BYqY9lc0lxEUBZmaIBxmhM4QmsrEtrGkYF5fKYl9dbfXM716tlc8oM86f8Lr9PphjsHP0jqB@oOKRAV1WrYwAKMdDX3NZIaPJ3weI1fIMMlWUvb8ss6z9Y6kgvZh3iJuCx9DY7xm8dvz7fY973EYlEQHwRkkAMPRSBiJAHYkYQIjIXMzSEKM7QEmIfJo/QyMVcRL8 "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##pVZtb9pIEP7Or5hQKeyCyfGS0MiOU@UCpyAlpKJE12uSsxyzgFWztuz1JU2bv37p7IvBQO7uwyGwd2fmmbedmSVIkuY8CF7fTdks5Aw@no8HHe/8uj/wbkbDiff7sD@5gOPKu5AHUT5lcJIEKescLE4rwcJPwUtu78GFcfXXx8evD938j2/fPk8WvccFef2TfNg7qNvkCd93HWof1O8eCP3xRL@/f7HpK91GVC2oJ66XNNpOyVwm0pDPpb01LYyRyvzl6Y7caSXkAhJcCo@laZySIOaZAOVrfcmyzJ8zCt8zMbXtACXg5AQMWS4VnfFp5EDKRJ5yaDsvOzrlPoinzIKHOI4gdmd@lEm1yoxRd9s56t07FcBPOAOi0ubNmdHhGSmi9RCd95vzi7PxcZ0apgVZ@MziGVk5/ktBKclTSpUV@SExfNBBBHEuwIZVoFSGV1UwUB7YUN0KXoGrVURV73iVrvIxi/JsoSNZJaWis7L0Q04wcMVMbvEQIsZJQpvte7flQI4y3Y4nMEUtrUAp1GcFIU9y4YDOjMwD1FNW7Je@CBbe1Bc@nttq7YC0mrIsj4Sl43BMzX4afhkoymyWMWRi/OjLXCw2BOrxXywQiDLhYO0W9pdJGDFiMvvp42RME8tAvwzG195kML4ajs4mg35BHnyeDEb9QR9@GMLVzeVkeDkcDSzYV86Zt3GpRdf1sJficZp0lmtLPY1cKQfuTlo83PuCebM0XnqJLwRLOUmxZkY3l5dGQRmDjSDYk8BsFiv3Lb5RS3a0YARGMgqXoSCFGguabeqUhKYsEf8plLIgT7Mw5m8KKrOzOAXVas@ylFThYPtEOKWIruqQW7qGqFOUYJHdZwpIl@1Iane8hqaf3bajWApxINuIUNdtUZCWQ54zZ60BjWLtSLN6cGRr3sqrJM5QYMNygeXs0UO8BRxz7Is4NEYDDysf26UhwRTZ8lz9h4xwuZHCSGkA4SdFpZRjkpgtY6qjEEakm3WKJxdFcUAyHCjGB2TKZwPa@OOcmlV7S79SdIuSjYYc5zW7tsl/AYYT7t@tL7XxkuX/aXMnAzIvGqIAzS3Aki2xtEiGtnTMCmBB7akmc41FoN0yDm6CMbvI0ueEN@GU1CxESaryvDgBcN3yDLNtro7lAVP/1dHirhyPu0FshbqOo7WW1oNtszFVT5enEp6uKq6W@q4HAq5NE5USLd3WWk9asL9vLOy5ZoCNx9djb3R9dTY5v6Cb@SjNpGLeijRnJd2yJDYw64tH3iYadeq25K0yQagNoC6X3@Rtie83b5gdPfqWWPdfyrD/jRcv/zTlPCW2zsfu9NQCqz0t30OaiQN69S9Ax4K33muv0rM6lbbVrXQs@exaHauH@451WMFXr3JkHaJAF5mHKNLFp6RokNpbR1bv72AW@fPstRkpq83jnw "C++ (gcc) – Try It Online") - PCRE
[Try it online!](https://tio.run/##RU9BasMwELz7FapQkZTIprETF2RMA4XeeustSYubbmIVVTayQkwcvd2V00MvM@zM7CzbNmewXQ1aj8SWGwtH6HdSGjizNR3f2dNdMpOsD7xNuUxm20/Grz0fHr3kI10L/Nz8tErDF@YFuZQPxaGxUO1rRjRSBhFl2pPjgzowcuHD2SoHcd10zofwokCTrhMN5uhqPpCqJDruWq0cFrhApC@xxHPGSIWu6B4NtKezjTJuRz48j78bZYLP5wEK9N@NYtOEB7QygDBh0w2bvFZuX0PHSM/5QN/sCSSiHoHuIPS@VIEl9RwRjb0f8ygXabQQWZSKCTORijzMqVhGgfJoJZYhkAVzGSJZwEn5W7rNYiXyXw "PowerShell – Try It Online") - .NET
This adds Java support to the above ~~33~~ ~~32~~ ~~31~~ 29 byte version, by removing the use of the conditional `(?(2)`...`)`. Support for Python and Boost is dropped, due to the use of the nested backreference `\2`.
# Regex (ECMAScript 2018 / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / .NET), ~~41~~ ~~36~~ 34 bytes
```
^(?!(.*:)(\b(?<=^\1x+).*:x|x){7}:)
```
[Try it online!](https://tio.run/##dVA9b9swEN31K5gs4sUMEdmOCohmPbVAlgxtt7pBGJlS2LKUSlEOAUW/3T0pHjLEy32@d3fvfquD6kpv2nDtmr0@VvJGePlN119iS78Hb1zNvXp5PD7Q7QXlVwXQ3RPdbuTDLosLwEJ8jTB8Ggs4PvLOmlLTjF1nAMLrf73xmqZeq701TqfAS4yDvnNB@0ohdDCu7UPR@qbUXce7sDduBN44ms4MZuXn4SAv79xBWbMnb3ByKUxFK3hHa/rAX7wJuG7nUhCVzERCiKkItdxqV4dnGJBEa2l511oTaMpSgFNvk8Hw4bQDiA/rFkZtOz3gDkKqxlMjb1iUaZEKs6lPU4VZLOatprtX91TJVvluUk/rn@YXwPmdEc9/wl/9EeNEh7iYR08uptzrFt9IFYjx1JjPQGS8kOeURP5XhfKZepDS9dZu068KFRQE@T98jwHBv40jOaMXW3DMk5wtk4ytkiWb7IotWY75kq0TdHlyy9YIWGFzjZAV2qnyRppzdsvy/w "JavaScript (Node.js) – Try It Online") - **ECMAScript 2018**
[Try it online!](https://tio.run/##TU/LTsMwELz7KxZfbLdL1DwaJIPVG1/ALaFSIC41Mk7kBCkt8O3BboToZVazO7M725/GY@fy2Xz0nR9hOA3o9ZueiAcFnlI67/nuhicrKXj9wncPal@n01qExvQ9ia@7HynmIKtSeZs@38NZbcih82DBuLgtGcbWOEkAzAHOEnpv3MjFwq123ApoXAu2CnalWO2YBKtstYn7rmV/Xu1aRZ/8p5YANI4veZNBN/71yD0CkwzWEZP3zjjOJraKPiMgBjMxmE2G3pqRM2RCLGIB2g4a6GMTigQaI/4ftCK@ls4lKTEjKeYkw4g5ZlgGnmFBQinJFosgyMOwCJI8YOwspgvHLZa/ "Python 3 – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=TU9BTsMwELz7FYsvtls3apI2IIPVW1_AraVSoA41Mk5kp1Ja4CVceoE_8JQ-ob_AbkBwmdXuzszOvn82u3ZT28OXfm5q14Lfee7Uo-qQAwkOY_yxbavR1RGv6OyCJgPB6PKezm7kapl2QxYG3WvHXi7fBPthnoJokYpRencNezlGVe3AgLbRO_HtWluBAHQFewGN07alrO-NstQwKO0azCLIpSRLSwQYaRbj6Pef9qtVdi3xrdsqAYDj-pw-8ap0DxvqOBBBYBgxeaq1paQjg6jTDGIwHYOZxDdGt5RwwlhPZqCMV4DnZSgCcIz4d9Cw-FraP3w4zgtU8AylPEcZj5jzjBehz_gEhVKgKZ8EQh6Wk0DJA8ZJLzr3fMqL3u4b "Python - Attempt This Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`)
[Try it online!](https://tio.run/##RU/LTsMwELznK4xlZLt1Kpq0QXKIWgmJGzdufaBQto2RcaLEVa2m/vbgwIHLjHZmdlbb1Bdouwq0HkhbbFo4gdtJaeDC1nTYs9Udm00kZ9sPtnoq9tu5m/IguJvj/aOXfKBrgZ/r70Zp@MQ8J9fiIT/WLZSHihGNlEFEmeZsea@OjFx5f2mVhbiqO@tDeJ6jUdczDeZkK96TsiA67hqtLBY4R8QVWOIpY6REN3SPeuroZKOM3ZF3z@OvWpng82mAHP13o9jU4QmtDCBM2Hijnb2W9lBBx4jjvKdv7Rkkoh6B7iD0vpSBJfUcEY29H7IoE0k0F2mUiBFTkYgszIlYRIGyaCkWIZAGcxEiacBR@Vv6ncVSZD8 "PowerShell – Try It Online") - .NET
```
^ # Anchor to start
(?! # Negative lookahead - assert that the following can't match:
(.*:) # Skip to after any occurrence of a bounding character,
# which denotes the beginning of a number's unary
# representation;
# \1 = the entire portion of the string that has been
# skipped, going all the way back to its beginning.
(
\b # Assert that we're on a word boundary
# The below is only allowed to match once within this loop. There is
# no need to verify afterward that it matched exactly once, because
# the input specification allows us to assume there will be no numbers
# greater than 6 (so, 7 will never appear).
(?<= # Lookbehind - evaluated from right to left (so in this
# listing, read it from bottom to top)
^ # Assert this is the start of the string
\1 # Match \1
x+ # Skip back to the beginning of the unary representation
# of the current number
)
.*: # Complete the match for the current number, and skip
# to the beginning of any subsequent number's unary
# representation.
x # tail -= 1
| # or...
x # tail -= 1 (and do nothing else)
){7} # Iterate the above exactly 7 times; this can never result in
# the 7th iteration ending in a split, as that would require
# matching 7 x's in a row, but the input is guaranteed not to
# contain a 7.
: # Assert that tail == 0 (i.e, that this is the end of a
# number's unary representation)
)
```
A previous 41 byte version using lookbehind appears to expose a bug in Python[`regex`](https://github.com/mrabarnett/mrab-regex):
```
^(?!(.*\b)x+(,.*\b)x+\b(?<=^\1(\2?x){7}))
```
[Try it online!](https://tio.run/##dVCxbtswEN31FUwW8mqGiOREBUyznlogS4a2W9UgtEwpbFlKJSlHgKBvd8@Ohw7xQj7cvXfv7v3Sex3rYPt047udOTTqVgb11bSfx559S8H6VgT9@nx4YpsrJj5UWxgXjJ9BtWWbtXqqclYVmxGmjzPA4VlEZ2vDcn6TA8hg/g42GEaD0TtnvaEgasTJPPhkQqOROlnfD2nVh642MYqYdtbPIDrP6EnBnfo07dX1g99rZ3fkjU6upW1YA//JuiGJ12AT2lWegmxULjNCbEOYE874Nr3AhCLWKidi72xilFOAc2@dw/TutD3Id@sOZuOimdCDkKYLzKpbPipKpV2356HSLhYnUxsf9SPTqtchHo9n7Q/7E@Cy5YjbbzGq33I@yjFwhdvK4zdSEUyPKTINcj7ZI2W8UpcuGMUfneoXFkApPzi3oV80br4idEW/hwEBwbzmmVy4E1twKLOSF1nOl1nBj@@SF7zMsFBm9/wOW0ss353wG7HgS8T3vPwH "JavaScript (Node.js) – Try It Online") - ECMAScript 2018 - works
[Attempt This Online!](https://ato.pxeger.com/run?1=TU9LTsMwEN37FIM3scs0aj4NKGCFFSdg11AppS41Mk7kpFJaxEnYdAN34ChdcJfaTRFsZt5o3pt57-Or2Xbr2uy_1WtT2w7abYtWPsueWBBgKaWfm241vj7wOSsuWDgqF7y_ZHgG5YIVt2JeRqyMi56_Xb1zfhb8OO0sysfR4w3sxISsagsalPEvwrZbKpMTALWCXQ6NVaZjfJi1NExzqMwS9MzJhQhKE-SghZ5N_L3_tF-tNEtBH-xG5gDUr08hwlZW9mnNLEKAQfhSK8OCPhh5heLgLSlvSYdto1XHHIlzDlK3Euh95VoO1Nv6e6K5jxMNIfeHu4xkGJMIExKjrwnGmLk5xpS4lpEppo6QuGV6wgM9xsThKWbDoSM "Python - Attempt This Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`) - does not work
[Try it online!](https://tio.run/##RU/BboMwDL3zFRnKlKQL1YCWSTDUTpN22203aCfauSVTFlBIBSrLt7O0m7SL37P9/Gy3TQ@6q0HKCeu80HCEYZOmCnq6JtOWrm7ofFbu2HBH@R8pd3T1mG/LkJbRamDjg2VsImvuPzdfrZDw4bMMn/P77NBoqPY1xRIJhbBQ7cmwURwoPrOx18JAUDedsU4cZuhSl3MJ6mhqNuIqxzLoWimMz/0M4SGnuELf6BaNZCCz4rUytTv0adfRQiizwe/MsuCzEeqq/7dHgWrcO1IoQD6mlzV67qb3NXQUD4yN5E2fIEXEIpAdOP@XymFKLENY@tZOiZfwyAt57EX8EmMe8cTlEV94DhJvyRdOELvm4sp/5RGPHV/y5Ac "PowerShell – Try It Online") - .NET - works
Upon investigation, the bug actually has nothing to do with lookbehind. I [reported it here](https://github.com/mrabarnett/mrab-regex/issues/494) and it is now fixed.
# Regex (ECMAScript or better), ~~73~~ ~~69~~ ~~46~~ ~~41~~ ~~40~~ ~~39~~ 37 bytes
```
^(?!.*:(?=x*(.*))(x(?=\1).+\b|x){7}:)
```
[Try it online!](https://tio.run/##TU/LUuMwELz7KxQunnGEIA@8VRbanHaruHCAvRGoEolstAjHJStBEPzt2bFJLVzm1dM9PX/1Trcrb5tw2jZ2bfzLpn42bwevavPKbkz1KzYA7@rnWXZ4gMVIZAUsVMxAZIgQqV5OUIyXjx8R9z@6Ag/Z2TuKsLkN3tYVoGidXRnI@ekcUe7UyVW9086uma2bbSjYiSw3Hko1keCUN3rtbG0AcaTqrXOyVOe4tyWMSmxIMADKhDFbMnDCmboKTwMMlXKibZwNkPIU8YhdTnBPV9rgYYfyWDnsjGvNnnQY649bdc6jSotU2svqyJR2PB6UbXutr0GrRvvWXJGB6s7eI37XjWT@kaw/y64nYBwPYn2KqfCmMTqARtkdgeEwbcaR@vIXxYsOqyfwqIbPF@lvTS4LRow/fksFS0miY/@/oOaQJzmfJhM@S6a8jzM@5Tn1Uz5PKOXJBZ/TwozAOa3MKPaTT9LQ8wue/wM "JavaScript (SpiderMonkey) – Try It Online") - **ECMAScript** (SpiderMonkey)
[Try it online!](https://tio.run/##dVA9b9swEN31K5gs4tkMEdmOCohhPbVAlgxttzpFGJlS2LKUSlEOAUW/3T0pHjLEy32@d3fvfquD6kpv2nDlmr0@VvJaePlN119iS78Hb1zNvXp5PP6i2wu@KOhWxgXlCwAaMd5lwJe7p9cIw6exgOMj76wpNc3YVQYgvP7XG69p6rXaW@N0CrzEOOg7F7SvFEIH49o@FK1vSt11vAt740bgjaPpzGBWfh4O8vLOHZQ1e/IGJ5fCVLSCd7SmD/zFm4Drdi4FUclMJISYilDLrXZ1eIYBSbSWlnetNYGmLAU49W4zGD6cdgDxYd3CqG2nB9xBSNV4auQ1izItUmFu69NUYZbLeavp7tU9VbJVvpvU0/qneQA4vzPi@U/4qz9inOgQl/PoycWUe93iG6kCMZ4a8xmIjBfynJLI/6pQPlMPUrre2m36VaGCgiD/h@8xIPi3cSRn9GILjnmSs1WSsXWyYpNdsxXLMV@xTYIuT27YBgFrbG4QskY7Vd5Ic85uWP4f "JavaScript (Node.js) – Try It Online") - ECMAScript 2018 (Node.js)
[Try it online!](https://tio.run/##RY5NT4NAEIbv@yvGzR52caQFCiZsKW1SPXrqsXFDTZtgtgUXmmAQ/zoONsbL7Dzvx2Tro7PxeP4E4TT0tnorLIiZJsyW281usxrYqXJSNNlcL1da9VCeiFRfu/LSAt9fuB7IDahis@Z6aFpKG3wIMFDHj8nP/9U56SoVRtMVkMLSuTW1alu2kiNHUjQDECVkwFMOPrxX5UXSinAu6p53vBNmWFtFFqlT@PYRUWbfM@FmkAPfuesxBeCQAn8ubEPA9V/OajYMxjy9bI0ZX2V@53upzLPOk76nlOxo3wfKv98fvjrVPw6pGseEJRiyACMW4jQjDDEhDnHB6ElYjAsKRGQuKBLRnJRb6ZcxxuQH "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVJRT9swEH7Pr7jmBTs1BlropEQZYlORKgGaVrQXYJPbuNTFcTLboUFdf3t3acI0Nl5s33d33919vpV4Foer7Gmn8rKwHlZoc1XwKIG/kcor/S5m5aOsG09ZzbSaw1wL5@BaKAObDnJeeLyeC5VBjg4y9VaZRxD20d09UPBLW6wdjOu5LL0qMDEAuFRawiI1cr1/kpDPi0xy9Ic0@VQtFtLK7KsUmbQw24e9BclrZmcuKE26uo75ZL1s@Alx6QxHENmVMpJQ2ktNpTVVC@K4/FkJ7Uh4FEVRSOnmbWjLQIh/l2CDDP4PAxIcIcMM454S108P7s1Bc/tk22LbL8J7aQ3YtHvhtHnZFHDsFfl8MR3/mNxMxzfTye3k25gmKNN0LoxBCZQpKw8pNFN3GJm@OC9zrgzFfzMeVHqcQDf4Pp4vhbuRtce@YQPYsuqlx7RLK9Bfol5eG9IQpCdNPazYiqixWEtikKHTBDmA9DRXbpyX/mXPey38fIkd5phged5aJIzDfsvEVwWuBNoMLqwVL447j6LkRHNXauVJyFA7TCyJOfwY1iHKXUrhycR43D3LS2GdRIMYinG@2LN0O3b3EMcoCaV9LID9/TsbyflCmYxQOIfw1lYyBgghhvASPw4NzNn@n6QR3W6DZjF238l5j0cxOU/riPCIUlLj@/6E8v797FdNNx@2Md01G7AbBSM2CE7YMBiw5hyyARuhPWCnAV6j4IydYsAQnacYMsSzQdqkvc3O2Og3 "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##pVPbbtswDH33V3DZg6VYSeOkzQA7boE97AOGPmxoO8NRFFuoIxuWjKRp@@vLKDlpLgP2MgG@iOThOSQlXteDnPPdZ6l42S4EzOZVpc1VI3KxGRZ1fetdusSGi9rISl0tZJYrNEmeSrWsmlVmzR2KF1kDaf3wBAl8731dr5/nk/bny8uP@2K6LsjuF7n7NOxH5C7Z9MmwTynZ4P9jSIfB4/xtQ1@/vEd0Ry@BPQb9OknrIIxPhEkU0YhsdetJZWCVSUUovHqAq35AVykUqekgfEpGMbQYMxmnBiq7s4Dc/miziCKMlSpHY92a2OF5pbQBV3kUua5AIzBZfLBprJoXsC6yPQIbAcSm3X6kzYUppRLEbbhUrGOg8UGlXXIJZEsB7bZ3xH9UPrJskzB2LocYarkVhCbJiFplRqpWxMcMSIqlWlrX/r4@@j5U1ZXGgDPmA1aJdYp4BgqHlplK7kl5in3BjgYWTNGdWf9cE2U3NhgtARA1G9H4PCsKt5gLMrs0woiV2ac4urKsONEMc3Qa0GnfAYT4KEX3f@FFfpfoASODwB40P/LP/e8gSi3@zb7qyE@Y/5Pzrw7YvnQQBxhcAFZipYUhGrm6mh2Agb/xba/xEHSy9gLPwdhddHVzWkq1ID5DlLU65YcJQJKcnvAoUm4sc2z9c9yFY93H1MciLko91jE6RnfnumoNzGZATi9LqkXW8IKccOOYMQPWZ68Mw9tE4Q56900rIoAeRND7luHQ8EttupO72IlqhGkbZenfd1NvysZeyCbemNn3hI3ZFPdjdu3hZ@rdsGsMmKDzGkMm@LaWDuT27IZNf/NlmeV6Nyid9NQp/wM "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##TU/LTsMwELz7KxZfbKeL1TwaJCOrN76AWwJSS1zVyDiRE6S0wLcHmwjBZXbHO7OeHS7TufflYt@GPkwwXkYMhgTQECilyzPf38hM8b2eMy4zIfgc@zYXctMeP2fxcfelxBKVTa5u86d7uOotOfUBHFiftslx6qxXBMCe4KpgCNZPXKzcGc@dgIPvwDXRrjVrPVPgtGu2ad9/2a/X@E7Tx/BuFABN42DkaA7h5cwDAlMMNgnla289ZzPLkskKSKlsSuXkODg7cYZMiFUswLjRAH04xKKApnx/vzmR7sqXmtRYkBxLUmDCEgusIy@wIrHUZIdVFJRxWEVJGTG9rKYfjjusvwE "Python 3 – Try It Online") - Python
[Try it online!](https://tio.run/##TU/LTsMwELz7KxZfbKfGah4NkpHVG1/ALQEpEJcaGSeyg5QW@PZgN0L0MrvjnVnPjqfpOLhyMR/j4CcIp8C9ftMz8qDAY4yXZ7q/EZmkezVnVGSM0Tn2bc7Epn35ntnX3Y9kS1Q2ubzNn@7hrLboMHiwYFxaKMLUGycRgDnAWcLojZsoW7nVjloGnevBNtGuFGkdkWCVbbZp37Xsz6tdr/Cj/9QSAKfxJbIIuvOvR@o5EElgk1C8D8ZRMpMs@QyDFMykYFaE0ZqJEk4YW8UMtA0a8EMXiwScIv5/aFk6LV9qVPMC5bxEBU9Y8oLXkRe8QrHUaMerKCjjsIqSMmJ6WU0Xzne8/gU "Python 3 – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=TU9BTsMwELz7FYslZDt1rSZpAzKyeusLuKUgFepQI-NETiqlBV7CpRf4A0_pE_gFdgOCy6zHO7O78_bR7LpN7Q6f5qmpfQftruVeP-geeVDgMcbv264aXx7Pb-n8TCSSzlWfUJEwRvvwXqZMjJZ3Lz17vniV7Ef8FXxlKsfpzRXs1QRVtQcLxsXxou3WxkkEYCrYS2i8cR1lA7faUctg5dZgy2BXiiwdkWCVLSdx3n_Zr1e7tcLXfqslAI7tUwDR6pW_31DPgUgCo4jisTaOkp4k0WcYxMNMPMyKtrGmo4QTxgYxA21bDXixCkUCjif-LbQsRkuHwIfjokAFz1DKc5TxiDnPeBF4xqcolALN-DQI8tCcBkkeMP4MphPnM14M474B "Python - Attempt This Online") - Python (with `[regex](https://github.com/mrabarnett/mrab-regex)`)
[Try it online!](https://tio.run/##NU5Nb4JAEL3vrxi47C6uG/mQJpANMbE99tB4E0s0Xe02KxLAiBH71@lg28N8vHnvzUx93l2HGhS86YPuKlnqCywXq4Ws9fYjBaNmKVw@jdVg1UG3DQEwe7Drqb9Rys1LN0XCrmdSToNNCrocTXswzmiszm3zP1P@g3Cs1MeqvWa4CKCqTdkCYzShMAErm8qallFBuTxuq1vf9G7neo1sT4Vh/ozf5dfJlKOco/5R1DfUHDKgq/qsEwAKCdCXrW0Q0PTvgsVr@AYZoyieX5dFMbyzzJFewjLVeUx6nLMO@9zncpLv@o7fnu4JH4aYxCIgvghJIMYcikDEiAMRESwxmYsIBSGSEUpCzOPk1/TAYi7iHw "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##pVZtb@JGEP7Or5hwUtgFk/KS0AjjRGmgClJCThxRr5ekljELWGfWlr1ucrnLX286@2IwkLYfisDenfd5dmYWP47rC99/@zBj84Az@Hg5HrTcy9v@wL0bDSfub8P@5ApOSx8C7ofZjEEv9hPWOlqelfyll4Ab3z@CA@PyL09PX6ft7Pdv3z5Plp2nJXn7g5wfHFW75Nx5rpKjKqXkGdcPTXpUe5j@eKbff37t0je6q1i2oBo7blxr2gWvqUgCvpBuN7QgQirzVmd7cmelgAuIcSlcliRRQvyIpwJUyNUVS1NvwSh8T8Ws2/VRAno9MGS5VHTGZ6ENCRNZwqFpv@7ZlHs/mjELplEUQuTMvTCVZpUbY@6@ddJ5tEuAn2AORKHnLpix4Ropou0QDf/d5dXF@LRKDdOCNHhh0ZysA/8ppxTkKaXKi/yQCM51En6UCejCOlEq0ysrNVARdKG8k7xSLpdRq/zAy3SNxzzM0qXOZA1KSaOy8gJOMHHFjO/xEELGSUzrzUenYUOGMu2WKxCihjagDOqzgoDHmbBBIyNxgGrC8v3KE/7SnXnCw3Nbr22QXhOWZqGwdB62Kd1Pwy8DRZnPU4ZMzB9jWYjllkA1@pP5ArVMOljCuf9VHISMGGQ/fZyMaWwZ1S@D8a07GYxvhqOLyaCfkwefJ4NRf9CHH4Zwc3c9GV4PRwMLDlVw5m1CatBNPRwkeJwGzmJtqaeRK2Dg7MHi4t4TzJ0n0cqNPSFYwkmCNTO6u742Boo62AiCPQtEM1857/GNWbJnBTMwkmGwCgTJzVhQb1K7IDRjsfhPoYT5WZIGEX9XULmdRwmoVnuRpaQKB9snxGFFdFUH3NI1RO28BHN0XyggXbYjqTzwCrp@cZq2YimNI9lGhDpOg4L0HPCM2RsL6BRrR7rVgyPd8NZRxVGKAluec13OnlzUt4Ajxp6IAuPUd7HysV1qUpkiW56rN00JlxspjJQaEN7LK6WYk9TZcaY6CtWIDLNK8eTCMPJJigPFxIBM@axBE3@cU7Nq7thXhu5RslaTU73SrWzzX4HhhPt37yvtvOD5f/rcQ0DiolWUQn1HYcVWWFokRV86Z6VgQeW5IrHGItBhmQC3lRFdZOlzwgtxRioWakmqijw/AXCc4gzrdrk6lilC/9XW4o4cj/tJ7KS6yaOxkdaDbbsxVU8XpxKeriquhvpuBgKuTRMVgJZha6u9BhweGg8Hjhlg4/Ht2B3d3lxMLq/oNh6FmZTPW5FkrGBblsSWzubikbeJ1jpzGvJWmaBqF0BdLr/K2xLf794we3b0LbHpv4Rh/5soXv9pyrlKbIPH/vTUAus9Ld5DmokDev0vQOeCt95bp9SxWqWm1S61LPlsWy2rg/uWdVzCV6d0Yh2jQBuZxyjSxqekaCW1t06szl/@PPQW6Vs9VF7rp38D "C++ (gcc) – Try It Online") - PCRE
[Try it online!](https://tio.run/##RU9BboMwELzzCtdyZZsY1AChkhFKpEq99dZbklY0dYIr1yDjKFaI305Ne@hlZmdndlfbdxdhhlYoNSFTb404CbfnXIsL2eDpjazv0piTde1iksaUEhfq3ZKmi93HzdHx0XM64Q2DT913L5X4hLRC1/qhOnZGNIeWIAWkBkjq/mzpKI8EXel4MdKKpO0G60N4WYG5r1Il9Mm2dERNjVQy9EpayGAFkKshhwtCUANu4B6M2OF4K7Xdo3dPk69O6uDTRYAK/O8Gie7CH0pqASAi8w2TvjT20IqBIEfpiF/NWXCAPRBqEGHvcxOYY08BUtD7qYxKlkVLlkcZmzFnGSuDzlgRBSqjFStCIA9mESJ5wLnzN/Sr2YqVPw "PowerShell – Try It Online") - .NET
This now ports the ~~33~~ ~~32~~ 31 byte version's algorithm to support ECMAScript:
```
^ # Anchor to start
(?! # Negative lookahead - assert that the following can't match:
.*: # Skip to after any occurrence of a bounding character,
# which denotes the beginning of a number's unary
# representation.
(?=x*(.*)) # \1 = the entire string following the current number's
# unary representation
(
x # tail -= 1
# The below is only allowed to match once within this loop. There is
# no need to verify afterward that it matched exactly once, because
# the input specification allows us to assume there will be no numbers
# greater than 6 (so, 7 will never appear).
(?=\1) # Assert that the entire string following the current
# position matches what was captured in \1, which
# accomplishes two things – it asserts that we
# haven't skipped to another number yet, and that
# we've finished consuming the entire current number,
# i.e. that tail == 0.
.+\b # Skip to the beginning of any subsequent number's
# unary representation (the first character skipped
# will be a comma).
| # or...
x # tail -= 1 (and do nothing else)
){7} # Iterate the above exactly 7 times; this can never result in
# the 7th iteration ending in a split, as that would require
# matching 7 x's in a row, but the input is guaranteed not to
# contain a 7.
\b # Assert that tail == 0 (i.e, that this is the end of a
# number's unary representation)
)
```
The previous ~~73~~ 69 byte version worked by treating every possible pair of numbers that add to 7 as a separate case, like the decimal version below:
```
^(?!(?=.*\bx\b).*x{6}|(?=.*\bxx\b).*\bx{5}\b|(?=.*\bxxx\b).*\bx{4}\b)
```
# ~~Regex (.NET), 46 bytes~~
```
^(?!.*\b(){7}(?<-1>x)+,.*\b(?<-1>x)+(?(1)^)\b)
```
Obsoleted by the ~~33~~ 32 byte version above.
# ~~Regex (Perl / Boost / Python / Ruby / PCRE / .NET), 58 bytes~~
```
^(?!.*\b(x)?(xx)?(xxxx,.*\b|,.*\bxxxx)(?(2)|xx)(?(1)|x)\b)
```
Obsoleted by the versions above. Worked by capturing two numbers in binary, and asserting that the second number has all 3 of its lowermost bits flipped when compared to the first number (and asserting that this doesn't occur anywhere in the input).
# Regex (ECMAScript or better), ~~38~~ 37 bytes
```
^(?!(?=.*1).*6|(?=.*2).*5|(?=.*3).*4)
```
Takes its input in decimal. There is no need for delimiters, because the full range fits into a single digit.
Try it online! - [ECMAScript](https://tio.run/##NcxLU4MwEADgO78icGGXSVN55VAmctIfoJ6dYWhCU9PAhOCj1d@OsR0vu98@j917N/dOT34zT3ov3Wm0b/JrdcLKD/Ikh4fPCeAs7rfZ@gptDK1gWY4s499XFoH1jWVghWu2PSPz47N32g6AbDa6l8DppkJs1OhAibwBI5zs9kZbCYixsIsxjRJ3eNEKYoVTOPaADdGKgGFG2sEf8DItfvYuNObJaA8JTZAdR20hCTh1vj@AQ3H91qaPnZnljqS79MUtASTF5of8vwheecRpEeW0jAr6F0taUB7qglZRSDyqaRUWyjCsrr6tF7QMrin/BQ "JavaScript (SpiderMonkey) – Try It Online") / [Perl](https://tio.run/##VYy9boNAEIT7e4rN6Yo7a2PM3xWcMVhyUqZyGeVEIiwRnYEALiJCXp0sdhG5WX0zszNt2bl4Pn@D6AyMrvkoHAjPkEy3h/1xv5vYqemk6NON2e6MGqE6kVJj21X1APy15mai1KeKS/vLez/Qt8VHH31Vfi159u9uyFeJsIZWQApHczm1WlcNkiNHcgwDuG1/NlUtOcdz0Y7CTrlT6a8nOg8y4MfuUiYAHBLgz4XrSXBz16O1fFmbJmufXg7Wzm8ye5BZul75ar3SP1cMCOMbhoSRmmfNNAbMx5AFuNwQA9SMDM1ijCgKyY6ufHsMMCSOUf8B "Perl 5 – Try It Online") / [Java](https://tio.run/##bVLJbtswEL3rK8a6hFRZJt50iCAYbeEABhojqIJeuoGWaJsORakiFTtw/e3uaEnRtLmQb97MvFnInXgUb3fZw1nlZVE52KHNVcGDCP5maqf0q1wlN/LQeMp6pVUKqRbWwq1QBo49ZZ1weD0WKoMcHSRxlTIbENXGfvlGwW2rYm9hfkhl6VSBiR7AjdIS1rGR@xYSn6dFJjn6fRq9r9drWcnskxSZrGDVhr0kyXNmb64pjfq6lrlov230CbHxCkcQ2UdlJKF0EJtaa6rWxHL5sxbaEv8yCAKf0uPL0E6BEPeqwBEV3B8FFLhEhRXGPUT2TXzx1Vw0t4tOHXe6E87JykAV9winzcumgGXPzId3yfzHYpnMl8nifvF5TiNcU5IKY3AFypS1gxiaqXuOJE/WyZwrQ/HdjAMVX0XQD97G862wS3lw2DccAVtWg/iK9mkF@kvcl9OGNALxsKmHFbslaizWiRhU6HeCGkAGmis7z0v31OreCpduscMcEyqed1b/BfiuwO/g@ww0t6VWjvgMF4VC/zZBcr5WJiMUZuDfV7W8BvDhGvwb3DAa@ClO/ydpZE8nr3nB83cyG5BZzIMh5UH4q4UjhNMOjhFO6Ll5qnPohWzkDdnYG7HmHLMRCz0kQm/KJugaIz1pcRc4YmPEUxb@Bg "Java (JDK) – Try It Online") / [Python](https://tio.run/##TY9BbsMgEEX3nGLKBoimKDY2CyqUXU/QndtKVkMUIootcBeJencXYlXtZuYx8@frM1@X8xTV6j/nKS2QrxmTIwksJErp@s4PD/xg5a4Rcqe/79gW7DdUBTuxFuXQmMfm7Qludk9OU4IAPlY3mZejj4YA@BPcDMzJx4WL7R1c5EHAGI8QhnJuLXuNzECwYdhXv/@y31sXj5a@pC9nAGhdJyezG9PHmScExuRl8pF7qCl8TRFknoNfOEMmhAAXsgP6PJZmgNYkf75B1B80qyYaW9KgIi3WqrBFTcpAkx67slJl3N15E7aoCveofwA "Python 3 – Try It Online") / [.NET](https://tio.run/##RY5Pa4QwEMXvfoo0BEyWKF3/5KDILhR666X0VrogdnYNTKPELMpaP7uNu4deZn7z5vFm@m4EO7SAuDJbfVq4wPRVFAZGfgzXEz888UMV7/Yi3qnfOyYe8wemHjOxhkdJX7qfXiN8U1GyW/VcnjsLddNyhkQbwrTpr07M@szZTcyj1Q6ithvc4s37kmw6xgjm4loxs7piGA09akclLQmbtvkdeqwb4F6S1J8h/ykkMp3/GLUBQhnf0mz8VrumhYGzSYg5/LBXKEi4EMAByBy@1r4X4SIIQ7osqwqUTIK9TINEbjWViVSBF1SQy8yvUi9nd34YE5l6zqX6Aw "PowerShell – Try It Online")
Pure regex is very limited in what math can be done on decimal input, so this version just asserts that no two numbers occur anywhere in the list that add up to 7, by exhaustively listing all the pairs that could do so.
[Answer]
# [Cubically](https://github.com/aaronryank/cubically), ~~41~~ 34 bytes
```
$(7:*-!F-!S-!B'-!B'-!S-!F$):0+>2=%
```
[Try it online!](https://tio.run/##Sy5NykxOzMmp/P9fRcPcSktX0U1XMVhX0UkdgoFMNxVNKwNtOyNb1f//DRWMFIwVTBRMFcwA "Cubically – Try It Online")

Takes input as a space-separated list of integers, printing `1` for true and `0` for false.
Explanation:
```
$(7 ... $)
```
For every integer in the input...
```
:*
```
Place it in the notepad, and multiply it by itself.
Cubically can only use values in one of its nine [memory locations](https://cubically.github.io/docs/memory.html), and the notepad is the only one that can be freely read or written, so I perform the next calculation "scaled up" by the current input value itself, memory location 7--since it's nonzero and doesn't change until we read a new integer (or character) with `$` (or `~`). This is shorter than using a face we don't modify as the scale factor, because the notepad is the implicit argument for `*` and the input is the implicit argument for `-`.
```
-!F
```
Subtract the input from the notepad. If this makes it 0 (the original input was 1), rotate the front face of the memory Rubik's Cube once clockwise.
Doing this once replaces a row of `0`s on face 0 with `1`; doing this again replaces those `1`s with `5`s.
```
-!S-!B'-!B'-!S-!F
```
Repeat for the other five possible values: rotate the front if it's 6, the middle if it's 2 or 5, and the back if it's 3 or 4. (The back rotations have to be clockwise with respect to the front, so they're actually counterclockwise `B'` with respect to the back.)
```
:0+>2
```
After the loop, set the notepad to the sum of face 0, add it to itself, and check if it's strictly greater than the sum of face 2.
Face 0 contains a mix of `0`, `1`, and `5`, and we want to discriminate between cases where it contains any `5`s and cases where it doesn't. The greatest sum it can have without `5`s is 9, and the least sum it can have with `5`s is 15 (since only whole rows at a time are moved without being mixed, it has to be a multiple of 3), so doubling it turns 9 into 18, which is the sum of face 2 (since none of the rotations performed in the loop affected face 2).
```
=%
```
Output whether or not the notepad equals the input buffer.
The input buffer is set to 0 after exhausting the input, and the notepad contains 1 if the faces can't all be seen or 0 if they can, so comparing them for equality inverts that to satisfy the challenge's truthiness requirement.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 7 bytes
```
~7∊∘.+⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Q680cdXY86ZuhpP@pdARRSMOMCYgUjIGmoYAwkjaC0MZBlxgUWBikxVTABKzIG8k2gfGOoNiMgywQoYgYA)
`∘.+⍨` - addition table (every element with every element)
`7∊` - 7 exists?
`~` - negate
---
# [APL (Dyalog)](https://www.dyalog.com/), 7 bytes
```
⍬≡⊢∩7-⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHvWsedS581LXoUcdKc10gDRRWMOMCYgUjIGmoYAwkjaC0MZBlxgUWBikxVTABKzIG8k2gfGOoNiMgywQoYgYA "APL (Dyalog Unicode) – Try It Online")
`7-⊢` - subtract each element from 7
`⊢∩` - intersect with the original array
`⍬≡` - empty?
[Answer]
# Mathematica, 20 bytes
```
xFreeQ[#+x&/@x,7]
```
The `` is `\[Function]`
-12 bytes from Martin Ender
-7 bytes from Misha Lavrov
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7360oNTUwOqRI30G5Lrg0qTi1pLiu2qhWxzxW7X9AUWZeiUNadLVZbSwXgqNjhMw11DFG5hrpoAkY6xjpmKFqQOGa6pigGmgMNMEEXQWGpUY6xkBhU5BZ/wE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 27 bytes
*thanks to [Gregor](https://codegolf.stackexchange.com/users/62252/gregor) for fixing a bug*
```
function(d)!any((7-d)%in%d)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNFUzExr1JDw1w3RVM1M081RfN/mkayhqGOgpGOgrGm5n8A "R – Try It Online")
Port of [Chas Brown's answer](https://codegolf.stackexchange.com/a/149896/67312). Having vectorized operations helps make this much shorter in R.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~21~~ 20 bytes
```
O`.
M`1.*6|2.*5|34
0
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3z9Bj8s3wVBPy6zGSE/LtMbYhMvg//9os1iuaDMdBSMgZaijYAykjHQUoCxjoLiOghlECkSZ6iiYQNQagxWZwMUQRgB1GIOFTEF6AA "Retina – Try It Online") Link includes test cases. Edit: Saved 1 byte thanks to @MartinEnder. Explanation:
```
O`.
```
Sort the input.
```
M`1.*6|2.*5|34
```
Check for a pair of opposite sides (3 and 4 sort next to each other). This returns 1 for an invalid die or 0 for a valid one.
```
0
```
Logically negate the result.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5.5 bytes (11 nibbles)
```
-~+.$?@- 7
```
For each element `x` of input, checks tbat `7-x` is not present in the input.
Outputs `1` (truthy) if faces can be seen at the same time, and negative value (falsy) if they cannot.
```
-~+.$?@- 7
. # map over
$ # input:
? # index of (or 0 if absent)
@ # in input
# of
- 7 # 7 minus
# (implicit) each element
+ # sum the list
-~ # and subtract from 1.
# (0 and negative values are falsy,
# 1 is truthy)
```
[](https://i.stack.imgur.com/dNWGc.png)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 4 bytes
```
ᵒ+7f
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fssebp2kbZ62pDgpuRgqtOBmQrRZLFe0mY6CEZAy1FEwBlJGOgpQljFQXEfBDCIFokx1FEwgao3BikzgYggjgDqMwUKmID0QiwA)
```
ᵒ+ Generate a 2d table with addition
7f Check if the result is free of 7.
```
`-e` prints `True` if the computation has any result, and `False` otherwise.
Let's take `[3,1,4]` as an example. `ᵒ+` returns the 2d array `[[6,4,7],[4,2,5],[7,5,8]]`, which contains `7`. So the result is `False`.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `D`, ~~7~~ \$5\log\_{256}(96)\approx\$ 4.12 bytes
```
7_Gze
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZLzePdq1IhbJhQtJKLUuzKaGMdBUMdBZNYiCgA)
```
7_ # subtract each from 7
G # map each to the input with it removed
ze # all equal?
```
Now ~~beating~~ tied with the language's creator!
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
f x=null[1|7<-(+)<$>x<*>x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjavNCcn2rDG3EZXQ1vTRsWuwkbLriL2f25iZp6CrUJuYoFvvIJGQVFmXomCnkKapkJ0tFmsTrSZjhGQNNQxBpJGOhDaWMdIxwwsCiJNdUzAaoyBsiZQPkyXkY4xkGcKVBf7HwA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
7_f⁸Ṇ
```
[Try it online!](https://tio.run/##y0rNyan8/988Pu1R446HO9v@H91zuP1R05qjkx7unAGkgSgLRDXMUbC1U3jUMDfy///oaLNYHS6FaDMdBSMww1BHwRjMMNJRgLONgbI6CmYwBRCGqY6CCUyXMVixCZI4soFAvcZgQVOQ3lgA "Jelly – Try It Online")
Port of Chas Brown's [answer](https://codegolf.stackexchange.com/a/149896/41024).
### Explanation
```
7_f⁸Ṇ
7_ Subtract each element from 7
f⁸ Filter with the original list
Ṇ Check if empty
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
!@-L7
```
[Try it here.](http://pyth.herokuapp.com/?code=%21%40-L7&test_suite=1&test_suite_input=%5B6%5D%0A%5B6%2C+2%5D%0A%5B1%2C+3%5D%0A%5B2%2C+1%2C+3%5D%0A%5B3%2C+2%2C+6%5D%0A%5B1%2C+6%5D%0A%5B5%2C+4%2C+2%5D%0A%5B3%2C+1%2C+4%5D%0A%5B5%2C+4%2C+6%2C+2%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%5D&debug=0)
[Answer]
# [Actually](https://github.com/Mego/Seriously), 8 bytes
```
;∙♂Σ7@cY
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/6hnwX/rRx0zH81sOrfY3CE5Eiiy0Dfzf3S0WaxOtJmOghGQMtRRMAZSRjoKUJYxUFxHwQwiBaJMdRRMIGqNwYpM4GIII4A6jMFCpiA9sQA "Actually – Try It Online") (runs all the test cases)
Explanation:
```
;∙♂Σ7@cY
;∙ Cartesian product with self
♂Σ sum all pairs
7@c count 7s
Y logical negate
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), 5 bytes
```
Ëo≠7+
```
[Try it online!](https://tio.run/##yygtzv7//3B3/qPOBeba////jzbWMdQxiQUA "Husk – Try It Online")
### Explanation
```
Ëo Check that the following function gives a truthy value for all pairs
from the input.
+ Their sum...
≠7 ...is not equal to 7.
```
[Answer]
# [Perl 6](http://perl6.org/), 18 bytes
```
!(1&6|2&5|3&4∈*)
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfUcNQzazGSM20xljN5FFHh5bmf2uF4sRKBSWVeAVbO4XqNAWV@FolhbT8IgUNDTMdTR0FIGkEogx1jEGUkQ6UYaxjpGMGkQBTpjomEIXGQBUmMBG4ZiMdYyDXFKhW0/o/AA "Perl 6 – Try It Online")
`1 & 6 | 2 & 5 | 3 & 4` is a junction consisting of the numbers 1 and 6, OR the numbers 2 and 5, OR the numbers 3 and 4. This junction is an element of (`∈`) the input list `*` if it contains 1 and 6, or 2 and 5, or 3 and 4. That result is then negated (`!`) to get the required boolean value.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
7ε↔¬
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiN8614oaUwqwiLCIiLCJbNl1cbls2LCAyXVxuWzEsIDNdXG5bMiwgMSwgM11cblszLCAyLCA2XVxuWzEsIDZdXG5bNSwgNCwgMl1cblszLCAxLCA0XVxuWzUsIDQsIDYsIDJdXG5bMSwgMiwgMywgNCwgNSwgNl0iXQ==)
Very simple answer, ports the approach of the 5 byte Jelly.
## Explained
```
7ε↔¬
7ε # Abs difference of 7 with each item in the input
↔ # Remove items in that list that are also in the input
¬ # Logical negation - empty list turns into 1, non-empty turns into 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
7_ḟƑ
```
[Try it online!](https://tio.run/##y0rNyan8/988/uGO@ccm/j/crhn5/390tFmsDpdCtJmOghGYYaijYAxmGOkowNnGQFkdBTOYAgjDVEfBBKbLGKzYBEkc2UCgXmOwoClIbywA "Jelly – Try It Online")
Relatively trivial golf of [Erik's solution](https://codegolf.stackexchange.com/a/149893/85334).
```
7_ For each face, subtract it from 7.
Ƒ Is the list of results unchanged by
ḟ filtering out elements of the original input?
```
Needless to say, a simple `7_f` would win if inverted output were permitted.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `D`, \$ 5 \log\_{256}(96) \approx \$ 4.12 bytes
```
7_cS!
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSi1LsgqWlJWm6FkvN45ODFSFsqNCCldHGOgpGOgpmsRABAA) or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abRSilLsOs9qlygfJQVdOwWlKB-XpaUlaboWS83jk4MVIexFUd4QxoKbCdFmsVzRZjoKRkDKUEfBGEgZ6ShAWcZAcR0FM4gUiDLVUTCBqDUGKzKBiyGMAOowBguZgvRALAIA)
#### Explanation
```
7_cS! # Implicit input
7_ # Subtract each from 7
c # Is each in the input?
S! # All are false?
# Implicit output
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 6 bytes
```
-~,`&.$- 7$
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq3XrdBLU9FR0FcxVICIwiWilaGMdIx2zWKVYqBAA)
Disgusting. Surely there is a better way to do this.
[Answer]
## [Alice](https://github.com/m-ender/alice), 18 bytes
```
/..y1nr@
\iReA6o/
```
[Try it online!](https://tio.run/##S8zJTE79/19fT6/SMK/IQYErJjMo1dEsX///f2NDUwA "Alice – Try It Online")
Prints `Jabberwocky` for valid inputs and nothing otherwise.
### Explanation
Unfolding the zigzag control flow, the program is really just:
```
i.e16r.RyAno
i. Read all input and duplicate it.
e16 Push "16".
r Range expansion to get "123456".
.R Duplicate and reverse.
y Transliterate, replaces each face with its opposite.
A Intersection with input.
n Logical NOT, turns empty strings into "Jabberwocky"
and everything else into an empty string.
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 5 bytes
```
-7sM*
```
**[Test suite.](https://pyth.herokuapp.com/?code=-7sM%2a&test_suite=1&test_suite_input=%5B6%5D%0A%5B6%2C+2%5D%0A%5B1%2C+3%5D%0A%5B2%2C+1%2C+3%5D%0A%5B3%2C+2%2C+6%5D%0A%5B1%2C+6%5D%0A%5B5%2C+4%2C+2%5D%0A%5B3%2C+1%2C+4%5D%0A%5B5%2C+4%2C+6%2C+2%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%5D&debug=0)**
isaacg saved a byte!
[Answer]
## [Retina](https://github.com/m-ender/retina), 20 bytes
```
T`_654`d
M`(.).*\1
0
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyQh3szUJCGFyzdBQ09TTyvGkMvg/38zLjMjLkNjLiMgNjYy4zI04zI1MeIyNjQB0iApI2MTU5CwkamxCQA "Retina – Try It Online")
An alternative to Neil's approach.
### Explanation
```
T`_654`d
```
Turn `6`,`5`, `4` into `1`, `2`, `3`, respectively.
```
M`(.).*\1
```
Try to find repeated characters and count the number of matches.
```
0
```
Make sure the result was zero (effectively a logical negation).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~36 31 24~~ 23 bytes
```
->l{l-l.map{|x|7-x}==l}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkc3Ry83saC6pqLGXLei1tY2p/Z/tJahnp5ZrF5yfm5SZl5iSWZ@noaRZnVNUQ1XgUJ0kY5CWnRRbCxXLRc2hcZYFP4HAA "Ruby – Try It Online")
It was so simple, I was looking for the solution to the wrong problem all the time.
[Answer]
# [Factor](https://factorcode.org/) + `sets.extras`, 24 bytes
```
[ 7 over n-v disjoint? ]
```
[Try it online!](https://tio.run/##RY3BCsIwEETv/Yr5AQs2tYIePEovXsSTeAh1xapNY7IGpfTbYxpLvewbZoadi6y4Nf6wL3fbFe5kFD1giW1KbzbSopF8TR0NLRuC54tURRbaEPNHm1ox1knSJR0K9PFmkXOIyGxSIuhizH5cIB/bInj55P1/ZCHJgzf0e3/EEq0jAzVzONf21ob5DU6@kRqp/wI "Factor – Try It Online")
```
! { 2 1 3 }
7 ! { 2 1 3 } 7
over ! { 2 1 3 } 7 { 2 1 3 }
n-v ! { 2 1 3 } { 5 6 4 }
disjoint? ! t (i.e. is the intersection empty?)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x!`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
fUma7
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXgh&code=ZlVtYTc&input=WzEsIDIsIDNd) or [verify test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZlVtYTc&footer=IVV4&input=WwpbNl0KWzYsIDJdClsxLCAzXQpbMiwgMSwgM10KWzMsIDIsIDZdClsxLCA2XQpbNSwgNCwgMl0KWzMsIDEsIDRdCls1LCA0LCA2LCAyXQpbMSwgMiwgMywgNCwgNSwgNl0KXS1tUg)
-1 byte thanks to Shaggy
This is basically a port of Lyxal's Vyxal answer.
```
fUma7 x!
f # elements in both the input and
Um # the input, with each num mapped to
a7 # its absolute difference with 7
x! # flags: x = sum, ! = logical not
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ï+ ø7
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=7ysg%2bDc&input=WzEgMiAzIDQgNSA2XQ)
[Answer]
# C (GCC), 77 bytes
```
i,j;r;f(v,l)int*v;{for(i=r=-1;++i<l;)for(j=0;j<l;)r*=v[i]+v[j++]-7;return r;}
```
[Try It Online!](https://tio.run/##lZDBToQwEIbvPMVkjUm7lLgF1MTKcaMH48kbciDQagl2N7MsUQnPjrAYGi4k9PZ3Mt83@TPvI8u6TrNCoFCkZiXVptrWolEHJDrCyOPCdfVjKejwU0Q7UQwBt1Ed68St48J1E@9eoKzOaABF213lUmkj4WX/@vT2TFJECuSkf@VBjeEGxgSXGO8S6jhfqTaEOo0D/6@/A9I4gQgazsBnELRiGh6xHyuy2X8fZVbJHCo8V58/D3Cdv5sNg17EJj@l1G7O@XwUDHQG4ZJApeVpxudWwBcM/mi4W3e8b@H@AjyY@rldxw8sP1jgh7P@1zYUWkl4kbTdHw)
Explanation:
```
i,j;r;
f(v,l)int*v;
{
// i and r are both initialized to -1. i is incremented by 1 before the
// loop, making its value equal 0, and for each iteration of the loop,
// until it's out of bounds of v.
for(i=r=-1;++i<l;)
// j also loops through the vector
for(j=0;j<l;)
// If v[i]+v[j] == 7, set r to 0, otherwise multiply it by
// something. If i == j, the sum will never equal 7 since a whole
// number multiplied by 2 is never odd. Otherwise, the numbers
// will equal 7 if they're on opposite sides of the die.
r*=v[i]+v[j++]-7;
return r;
}
```
] |
Subsets and Splits