text
stringlengths 180
608k
|
---|
[Question]
[
## The task
Most Casio calculators featured a variable `M`, which has 3 operators related to it: `M`, `M+`, and `M-`
`M`, as you can expect, returns the value stored in the variable.
`M+` takes the number on the left and add it to `M`.
`M-` does the same thing as `M+`, but subtract instead.
To make the challenge just a bit more difficult, we will add an extra operator: `MR`, which is short for `Memory reset`. As you can guess from the name, it resets the variable `M` back to 0.
Your task is to parse a string of Casio `M` expression, then print the value of `M`.
Here's an example:
```
9M+9M+
```
Here, we add `9` to variable `M` twice, so the output will be `18`.
## Specifications
* `M` will be `0` when first initialized
* For this challenge, you don't need to handle basic arithmetics, just those operators.
* However, you do need to handle implicit multiplications, so `9M` will become `81` for `M = 9`
* If the expression given is invalid, you can return any value of your choice
* `M+` and `M-` must not have an operator behind them (except for `M`), so cases like `MRM+` and `9M+M+` are invalid, but `9M+MM+` is valid.
## Input/Output
The input should be a string and the output is either the variable `M` or an invalid value of your choice.
## Testcases
```
Input -> Output
9M+9M+ -> 18
9MR9M+ -> 9
9M+MM+ -> 18
9M-9M-9M+ -> -9
9M+MMM+ -> 90
81M+81M+56M-35M-12M+ -> 83
9M+MRM+ -> Invalid
9M+M+ -> Invalid
9 -> 0 (Explanation: does not modify M with an operator)
9M+MM -> 9 (Same as the above test case)
2M+2M2MM+ -> 18
```
[Answer]
# Python3, 287 bytes:
```
import re
R=re.findall
V=lambda m,x,k=1:k if[]==x else V(m,x[1:],k*(int(x[0])if x[0].isdigit()else m))
E=lambda x,M=0:M if[]==x else E(x[1:],M+[-1,1][x[0][1][-1]!='-']*V(M,R('\d+|M',x[0][0]))*(x[0][1]!='MR'))
f=lambda x:''.join(map(''.join,k:=R('([M\d]+)(M(?:\-|\+)|MR)',x)))==x and E(k)
```
[Try it online!](https://tio.run/##bY89b4MwEIZ3fgWdfI5tFDdKlSJZnTLewpDFeKACWpdPEQYq8d@pnaRV8yGdddZ7r5/33H@Pn1272fXDstim74YxHIogUUMRlbbNs7oODqrOmvc8Cxs@8UrJuAptqY1SU1jUxyI8gBtoGRtercC2I0x6bagtQ98je8zthx2BnrwNpcH@lzdxVOsYr2l7OLOQaSG5NNpTtOtCmidFBDGrAyBPgKQ5m5Hw09wF0hVcrM6GCXFJ5V9STEj01dkWmqyHy51XsXIY0JjmhlFAeItTMaeMzphQB6aU@rWyNndbVXTpB/@7EsgrMlc@4Z@U3EsM7yRxqmsVz9teP7zx7CQyf7YvKDZbFPL5QVpyC763eGX5AQ)
[Answer]
# [Python](https://www.python.org), ~~172~~ ~~179~~ ~~174~~ ~~169~~ ~~164~~ ~~156~~ 153 bytes
```
def f(x,M=0):
try:exec(s("M(?=\d|M)","M*",s("(\d|M)M","\\1*M",s("R=","*=0M",s("(.*?)(M[-+R])",r"\2=\1;",x))))+"\nprint(M)")
except:0
import re
s=re.sub
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVDBTuMwEBVXf8XIl9iNEyVFoLbI5czBWqkcCUIsdcBScSLbRa3Ej6C99ML-E3wNEzvLdteypXnvzZvxzK_f_T48dfZweN-Gtph9vK11Cy3bCSUrviAQ3H6hd_qBeUYVu5TN-lVxKqiaUIEUi1gh0TT1REVuJRFOZJUQKyeXnKmbIl_dotHRZiqb-oKKHceT08b2ztjAsConoHcPug-LipjnvnMBnCZeOl367c_0wc-T5Sj5vf-TZTpC2s7BxlgNxg5S6cPaWBwAj7G9wMo9SHi-75kPDlVnkBwMpe83JjAKxRIo5yRaxgrdNgi4SwG6TVdeo9E-Xv1glHJxlBZdLcNWPIbJ8FcvH3V4ud9sNeOpOeP_NcL0sRM5qpBdWbSZdQamTZQESkFvvIbv1LTBUcVBRRo5K5aZgDhDJmUWd8DTGg8f73OV4x2mrmdkrlYjmGOcqyOhiDfiYhTHzIrMapUP7-xcFadnqqinSZqdxsRVQuMIkcrhH2YAVSqammOBqZp-90-__QI)
-3 bytes thanks to [@The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu)
---
# [Python](https://www.python.org), ~~148~~ ~~155~~ ~~150~~ ~~145~~ ~~140~~ 137 bytes
```
lambda x,M=0:exec(s("M(?=\d|M)","M*",s("(\d|M)M","\\1*M",s("R=","*=0M",s("(.*?)(M[-+R])",r"\2=\1;",x))))+"\nprint(M)")
import re
s=re.sub
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBLTsMwFBTbnMLyJnbjRE0rUFtkWLOwkMqSIBSoA5ZSJ7JdlEpcgDOwYVPuBKfhxQ6lICxH8cybeb_X93brHhv9tqsQR8Vu46p09vFSl-u7VYk6Jvh4ITt5TyzBgpzzYvUsKGZYjDADingsgCiKfCQ8t-QAR3wcEMlG55SI6zRZ3oDR4GLCi_wUs47CSXChW6O0I5CVRmrdNsYhIyPLjczs5i409HlUDiG7td8q1URR1RhUKy2R0vC3jkA8s26lNF1ECI7SLUOya2G4ddkS6wyEjQKyt2W2rZUjGKVnCFPqHc5sg7U_Q7pm4xi6DQ_IpJrsCpLoh4tLgjFlB7K9syJQmu5hMP7osgfpnsp6IwkNDZGgld29bN3ijy--0CBWq9jzldJlXf_bJWhvDxoJq_U877fAwj7i9CxmyA8Vcx77BdGw6beP3VwkcPuV5LNoLpYDmMM7EQeB1F-P0yE4KMfRLBdJ_x2fiHR6LNJ8EkKzqRcuAxqm8lSCfjE9GIekoTgkmIjJvn7o9gs)
Shorter version which throws an error for invalid expressions.
+7 bytes to both versions due to bug in code.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~52~~ 47 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0U…+-RS©D¶«.:¶¡ε®'Mì„X+…Xs-‚…)\0ª'U«:'M„XP:.V}X
```
[Try it online](https://tio.run/##yy9OTMpM/f/fIPRRwzJt3aDgQytdDm07tFrPCkguPLf10Dp138NrHjXMi9AGKogo1n3UMAvI0IwxOLRKPfTQait1X5BkgJVeWG3E//9GvtpGvka@vtr/dXXz8nVzEqsqAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/g9BHDcu0dYOCD610ObTt0Go9KyC58NzWQ@vUfQ@vedQwL0IbqCCiWPdRwywgQzPG4NAq9dBDq63UfUGSAVZ6YbUR/130Dq9/1Lng8IJMJc@8ssSczBSlWp3/0UqWvtpApKQDZATBGNq@UIYuGMEFwSwLQ19tEDY189U1NvXVNTSCKwiCs8A0TBuQBqox8jUCGRD7X1c3L183J7GqEgA).
**Explanation:**"
```
0U # Set variable `X` to 0 (it's 1 by default)
…+-RSD¶«.:¶¡ # Split the (implicit) input after each "+"/"-"/"R":
…+-RS # Push triplet ["+","-","R"]
© # Store it in variable `®` (without popping)
D # Duplicate it
¶« # Append a newline to the values in the pair
.: # Replace all "+"/"-"/"R" with "+\n"/"-\n"/"R\n" respectively in the
# (implicit) input
¶¡ # Then split on newlines
ε # Map over each substring:
# (used as a foreach, where all will have their own separated stack):
® # Push triplet ["+","-","R"] from variable `®`
'Mì '# Prepend an "M" in front of each
„X+ # Push string "X+"
‚ # Pair it with
…Xs- # String "Xs-"
ª # And also append
…)\0 # String ")\0"
'U« '# Append an "U" after all three: ["X+U","Xs-U",")\0U"]
: # Replace all "M+"/"M-"/"MR" with "X+U"/"Xs-U"/")\0U" respectively
'M„XP: '# Then replace all remaining "M" with "XP"
.V # Execute it as 05AB1E code (see below)
}X # After the map: push value `X`
# (which is output implicitly as result)
```
```
)\0U # MR:
) # Wrap the entire stack into a list
\ # Discard it
0U # Reset `X` to 0
X+U # M+:
X+ # Add `X` to the top value
U # Pop and store it as new value `X`
Xs-U # M-:
X # Push `X`
s # Wrap the top two values on the stack
- # Subtract the value from `X`
U # Pop and store it as new value `X`
XP # Remaining M:
X # Push value `X`
P # Get the product of all values on the stack (for the current group)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 40 bytes
```
⁽±ḊƛǍ[f;f(nw‛MR‛¥⁼½dĿ÷Ė‟n±ß¥£!3=ß*)¥D⌊=*
```
[Test suite](https://vyxal.pythonanywhere.com/#WyJEQSIsIiIsIuKBvcKx4biKxpvHjVtmO2YobnfigJtNUuKAm8Kl4oG8wr1kxL/Dt8SW4oCfbsKxw5/CpcKjITM9w58qKcKlROKMij0qIiwiIiwiJzlNKzlNKydcbic5TVI5TSsnXG4nOU0rTU0rJ1xuJzlNLTlNLTlNKydcbic5TStNTU0rJ1xuJzgxTSs4MU0rNTZNLTM1TS0xMk0rJ1xuJzlNK01STSsnXG4nOU0rTSsnXG4nOSdcbic5TStNTSdcbicyTSsyTTJNTSsnIl0=). Returns blank in the case of an invalid expression.
**Explanation:**
```
⁽±Ḋ # group digits and non-digits together, preserving order
ƛǍ[f; # split into list of chars for non-digit items
f # flattened
( ) # for each item:
nw # item, wrapped in a single list
‛MR # literal "MR"
‛¥⁼½d # list ["¥¥","⁼⁼"] (D flag: do not decompress string)
Ŀ # transliterate
÷Ė # unwrap and execute the item:
# M: push register twice
# R: always 0, also makes stack length to 1
# + & -: add and subtract respectively
# concatenates with input if stack is insufficient
# <number>: push <number> as int
‟ # rotate the item to the back of stack
n±ß¥ # if the current item is numeric, push register
# (preventing the number from being stored)
£ # store to register
!3=ß* # if stack length == 3, multiply
¥ # push register
D⌊=* # multiply depending on being an integer
# implicit output
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 248 bytes
```
\d+|M
¶$&
\d+
*
{`^(.*)¶(_*¶)?MR|^.*¶M[-+](¶.*)*
+`^(.*)(¶-?_*¶?)M(?!.)
$1$2$1
^(.*¶-?)(_*)¶(-?)(_*)(?!.)
$1$3$.2*$4
--
^(.*)¶(.*)¶M([-+])
$1$3$2
\+-
-
--
+
^(_*)\+|^(-_*)-|^-(_*)\+\3|^(-_*?)(_*)\+\5
$1$2$4
)`(_+)-\1(\B)?
$#2*-
L$`^(-?)(_*)
$1$.2
```
[Try it online!](https://tio.run/##PY6xTsQwDIZ3vwUih5xYjpT0irgpEssteOlK6BUJBhaG0230ufoAfbHiNAHJyW/7/2T7@nn7@n4P2wHP05Y/aBZYF/MAmoKDn2lE7@y64MWti00yzKPXTF6Z3nBd1HMAVCmtORUuWcF05y2YYKIJUNziWZ1SZrXsn@mMj84cgRngb9/@C5Y9jYmQiYELRYrpgEzziKwJzyPXRu5qq27Quq9HHMFOeCHLOWB@tgnMfXQML0ZPb@cU0MdtOwlpwEmGKiS78B6tofoUhMrrH4W7XjjEZg5N9a/wLw "Retina – Try It Online") Link includes test cases. Explanation:
```
\d+|M
¶$&
```
Insert newlines before each number or memory operation. The newline before the very first operation serves to set the initial memory to zero.
```
\d+
*
```
Convert all the numbers to unary.
```
{`
)`
```
Repeat until all of the numbers and memory operations have been processed.
```
^(.*)¶(_*¶)?MR|^.*¶M[-+](¶.*)*
```
`MR` will reset just the memory and `M-` or `M+` in an invalid place will clear everything resulting in an output of zero.
```
+`^(.*)(¶-?_*¶?)M(?!.)
$1$2$1
```
`M` either immediately after an `MR`, `M-` or `M+`, or with a number in between, will read the memory.
```
^(.*¶-?)(_*)¶(-?)(_*)(?!.)
$1$3$.2*$4
--
```
Two values (at least one of which will have been the result of a memory read) will multiply together.
```
^(.*)¶(.*)¶M([-+])
$1$3$2
\+-
-
--
+
^(_*)\+|^(-_*)-|^-(_*)\+\3|^(-_*?)(_*)\+\5
$1$2$4
(_+)-\1(\B)?
$#2*-
```
`M+` and `M-` after the value will add it to or subtract it from the memory.
```
L$`^(-?)(_*)
$1$.2
```
Convert the final memory to decimal, ignoring any pending value.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~78~~ 72 bytes
```
≔¹ηF⪪⁺RθM«¿⊙ι№-+Rκ«≡§ι⁰-¿υ≧⁻Πυζ≔⁰η+¿υ≧⁺Πυζ≔⁰η≔⁰ζ≔⟦⟧υ≔Φιλι»⊞υζ¿ι⊞υIι»¿ηIζ
```
[Try it online!](https://tio.run/##jZA9a8MwFEXn@Fc8NOlhGdKM8RQChQ4Ck46lg/BH9IiQU0vqh0t@uyvZbulSKELLPVdHT6q1GupemWk6OEdny@8EaCyzrh@AP14NeV6Z4Dg7MQEvKIBJhgif2YY64Af7wUnAsQ/Wc1bkqXTBhW/cG/lax5J/sE37norbFdXKtcAKtodkCQhSXZf7T3TWnkuywQmohr4JtY8FASOW0Jp4bJ1zu8z57cr/dKXx/6lq2k4F4/e/wDiDW9xr9vQsIMzhGtyT8e2QXmeimxKK9dlfBad5WCVpOsKf7Kic56l9yxLRkQwUf3HOR8RymnaykLu48ql4NV8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔¹η
```
Start by assuming the expression is valid.
```
F⪪⁺RθM«
```
Split the input on `M` and loop over the parts, however prefix an `R` to the first part to get a free memory reset.
```
¿⊙ι№-+Rκ«
```
If this part contains a `-`, `+` or `R`, then:
```
≡§ι⁰
```
Switch over the first character in the part.
```
-¿υ≧⁻Πυζ≔⁰η
```
If it's a `-` then subtract the product of the stack from the memory, but if the stack is empty then mark the expression as invalid.
```
+¿υ≧⁺Πυζ≔⁰η
```
Similarly for `+`.
```
≔⁰ζ
```
Otherwise, this is an `R`, so clear the memory.
```
≔⟦⟧υ
```
Clear the stack.
```
≔Φιλι
```
Remove the leading character from the part.
```
»⊞υζ
```
Otherwise, push the memory to the stack.
```
¿ι⊞υIι
```
If the part isn't empty then push its value to the stack.
```
»¿ηIζ
```
If the expression was valid then output the memory.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 146 bytes
```
s=>eval(s.replace(/\d+|M[-+R]?/g,b=>`_${c?"*":""}=${b<":"?(d=c++,b):d&&b[1]?"m=``//":`m${(d=b[1])||";a"}=_;${c=!d,b>"M-"&&"m=0"}`};`,m=c=d=0)+"m")
```
[Try it online!](https://tio.run/##ZZBNboMwEIX3OYUzQghqE0KiVAnUcAI22VIU82OiVBBHEEWVCDeo1E2X7T16nl6gR6CGVmlorbE0@ua98YwfolNUJeXucDT2IuVtRtuKuvwU5Vo1KfkhjxKumfcpPvuBgdehZ25JTF22UerEgxuwARqq1PGdzDwtpQnGJNbtVFXjwAo9KChjpgk2K5Raljuon8/gRNK2cWQTOk5J7IJvgKpK9RQa1jiMFDShKZ3qGArQ25wfURJVvEIUBSMkTwArH8sAYi1DckHrHq2uCPb/iYw@JDX@CHvv9MKWlo@7u7j1jfnCN6xZJ1jOB6Z1xxgbMIyGCMh0@ND1iLLpzJ/9Thk6o0yUWrdysCNIhEhk38vrqO49XamUP5FpO93pSSL2lcj5JBdbTVYoRQJ5CD5eXz7fnwHZMn17AoJkPzBcmZQy0PhHxzT@eODJkadIqUWjs84AsnXTfgE "JavaScript (Node.js) – Try It Online")
Creates a program based on the input and then evaluates it. Returns the empty string for invalid inputs. My favorite aspect of this solution is using `b<":"` to separate numeric strings from the other kinds of strings that can appear here.
---
# [JavaScript (Node.js)](https://nodejs.org), 138 bytes
```
s=>eval(s.replace(/\d+|M[-+R]?/g,b=>`_${c?"*":""}=${b<":"?(d=c++,b):d&&b[1]||`m${(d=b[1])||";a"}=_;${c=!d,b>"M-"&&"m=0"}`};`,m=c=d=0)+"m")
```
[Try it online!](https://tio.run/##ZZBNbsIwEIX3nGI6QiiuHX5FBaSGE2TDNo1w4hhKFTBKItQqyQ0qddNle4@epxfoEaiTIgqtNZbG37zn8fgh2AepTNa7zN7qSB2W/JDyqdoHsZW2E7WLA6mszl1EC9ez6dyfdVYs5FOxaOZyhtc4QSx5Mw9vTTazIi4pZSGZRK1W6PX8ohCbZm5wdSBFgU5g5AvHmPlVxMIpuja2WrjhXSxF6Qi24ZJHvEsobpAcYpWBDFKVAgevAWZ5OHapCWS9kc9OaF6j8Rmh7j@RXYeh9h9h7e2e2Kjn0moPb1x7MHTtXr8SjAYXpnnFhLhgFC4Rsu5lo/Mnmkv7bv/3lb7TWOrEqkb21gy0D3r5MzyBvPZUpcSp0yx5ghwS8y1La00cKI0yk/eWIkcshIG1VOptqmPVjvXKMhXOQcMM8PPt9evjBWFi0vdnZGB6oj01SWICro46YanHnZKZiqCZ65KIyoDEaZSHbw "JavaScript (Node.js) – Try It Online")
Similar to [@Mukundan314's reasoning](https://codegolf.stackexchange.com/a/254718/31957), this version throws an error instead of returning a specific value.
] |
[Question]
[
In 1988, the International Mathematical Olympiad (IMO) featured this as its final question, Question Six:
>
> Let \$a\$ and \$b\$ be positive integers such that \$ab + 1\$ divides \$a^2 + b^2\$. Show that \$\frac{a^2 + b^2}{ab + 1}\$ is the square of an integer.
>
>
>
([IMO problems](https://www.imo-official.org/problems.aspx))
This can be proven using a technique called [Vieta jumping](https://en.wikipedia.org/wiki/Vieta_jumping). The proof is by contradiction - if a pair did exist with an integer, non-square \$N=\frac{a^2 + b^2}{ab + 1}\$ then there would always be a pair with a smaller \$a+b\$ with both \$a\$ and \$b\$ positive integers, but such an infinite descent is not possible using only positive integers.
The "jumping" in this proof is between the two branches of the hyperbola \$x^2+y^2-Sxy-S=0\$ defined by \$S\$ (our square). These are symmetrical around \$x=y\$ and the implication is that if \$(A,B)\$ is a solution where \$A\ge B\$ then \$(B,SB-A)\$ is either \$(\sqrt S,0)\$ or it is another solution (with a smaller \$A+B\$). Similarly if \$B\ge A\$ then the jump is "down" to \$(SA-B,A)\$.
### Challenge
Given a non-negative integer, \$n\$, determine whether a pair of positive integers \$(a,b)\$ with \$n=|a-b|\$ exists such that \$ab+1\$ divides \$a^2+b^2\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to write the shortest code in bytes that your chosen language allows.
Your output just needs to differentiate between "valid" \$n\$ and "invalid" \$n\$, some possible ways include the below, feel free to ask if unsure:
* Two distinct, consistent values
* Truthy vs Falsey using your language's definition (either way around)
* A solution if valid vs something consistent and distinguishable if not
* Return code (if using this be sure that errors are not due to resource limits being hit - your program would still need to produce the expected error given infinite time/memory/precision/etc)
### Valid inputs
Here are the \$n\lt 10000\$ which should be identified as being possible differences \$|a-b|\$:
```
0 6 22 24 60 82 120 210 213 306 336 504 720 956 990 1142 1320 1716 1893 2184 2730 2995 3360 4080 4262 4896 5814 6840 7554 7980 9240
```
For example \$22\$ is valid because \$30\times 8+1\$ divides \$30^2+8^2\$ and \$|30-8| = 22\$
...that is \$(30, 8)\$ and \$(8, 30)\$ are solutions to Question Six. The first jumps "down" to \$(8, 2)\$ then \$(2, 0)\$ while the second jumps "down" to \$(2, 8)\$ then \$(0, 2)\$.
---
Note: One implementation approach would be to ascend (jump the other way) from each of \$(x, 0) | x \exists [1,n]\$ until the difference is greater than \$n\$ (move to next \$x\$) or equal (found that \$n\$ is valid). Maybe there are other, superior methods though?
[Answer]
# [Python](https://docs.python.org/3/), 49 bytes
```
f=lambda n,a=1:a>n+1or(n*n-2)%~(a*(a+n))*f(n,a+1)
```
[Try it online!](https://tio.run/##DcpBCoMwEAXQq8ymMJMomIobIb1IcTHSxgb0J4Rs3PTq0bd@@ay/hLG14Hc91o8SOvVu1hesS4Vh0D/l8Wc1rBYiJvA9rJOWS0TlNyikQqAIKorty9MwCMVASJXuLIu0Cw "Python 3 – Try It Online")
Outputs Truthy/Falsey reversed.
Checks whether $$\frac{n^2-2}{a(a+n)+1}$$ is ever an integer for any \$a\$ with \$1 \leq a \leq n+1\$. This upper bound suffices because for \$ a \geq n > 1 \$, the denominator is larger than the numerator, and for \$n=0\$ we just need to get a positive on \$a=1\$.
[Answer]
# JavaScript (ES6), 43 bytes
*-4 bytes with the formula used in [@xnor's answer](https://codegolf.stackexchange.com/a/251895/58563)*
Returns either 0 (falsy) or a positive integer (truthy).
```
f=(n,a=n)=>(n*n-2)%~(a*(a+n))?f(n,a-1):a|!n
```
[Try it online!](https://tio.run/##FYrBDoIwEAV/ZT1Adqk1xSNY/ZZNpUZD3hIwnoy/XultMjMv/eiW1ufy9rD7VEqOjKNGSLwyOvizND/WjtVB5JZr9L0M@j2gZFsZFCmMBLpQH0Il54T2T6htKRk2m6fTbI/dlD8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 50 bytes
```
a;f(n){for(a=0;a++<=n&&(n*n-2)%~(a*(a+n)););a-=n;}
```
[Try it online!](https://tio.run/##VVF/T4MwEP1/n@Ik2dLyI0KBQWXVP4yfwi2mYWUStVuAROKCH128wsa2Jr28e713vb7m3i7P@15mBdH0WOwrIoWfScdZCb1YEG1rj9H5L5E2kY6mNKOZ9ITOur7UDXzJUhMKxxngMkSj6uZNgwA/mzjVHlTeqO3rBvmj78LSBcZwRwgxTREHDAELhhC6EPpYE4YYYh@rEnPKY0w5RxQEkZGEhg2SAOkg5aGRpljMktC04TweWiCO/NREtkRVlHLTNQ3M5WmEfBLH5gpuajiL/G6cPN/ruoH8XVY2RpV/qGp8gLVuX9i65c@4Y8uF6zy0Tmo0Eoh5fKm3qh38OMEV1OWP2hfkbAu9PxH2xGR0aDLaOlmLXUZ7sxu@Rr4gDYU7Aez2SBkJCHH5gmGGDTyB4wwQrYOH82eZdahQWBBrvgXvETDO67XGVzYu1O5kRC2E2tCLynGuJ@tmXf@XF59yV/fe9z8 "C (gcc) – Try It Online")
*Port of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python answer](https://codegolf.stackexchange.com/a/251895/9481).*
Returns \$2\$ for invalid and an integer less than \$2\$ for valid.
[Answer]
## [Pyth](https://github.com/isaacg1/pyth), 18 bytes
```
lfsIc-*QQ2h*T+QTSh
```
[Test suite](https://pythtemp.herokuapp.com/?code=lfsIc-%2aQQ2h%2aT%2BQTSh&input=1000&test_suite=1&test_suite_input=0%0A5%0A5%0A6%0A21%0A22%0A23%0A24&debug=0)
A naïve implementation of the algorithm layed out in [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s answer. I'll see if I can get a better score later.
[Answer]
# [R](https://www.r-project.org), 35 bytes
```
\(n,a=1:n)all(n^2%%(a*(a+n)+1)-2)&n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LU9RasMwDP3vKTJGhrU6YMl2YhVyk1IwZaGFYELSMXaW_WSDHWifu82kdAY_P0nvPeGPz3n9Gvrv19vQpN_Hoyk293gokMfRlBPVtcnPJu8L7BEagqfyL_0x88vSv12u54t5WPI0je_GHdDJsQNAg7DbaYaq-rNxtmptRSQ3CJUyCUcSQriBt5V3ovFeIDpRdTrlKCWzMMSgFq9d7FDamNirNYmYOq8xzHGLEB5cUqRWXCGxpibU5SlIv4tRV7BqmIIDuH9sXe_vHw)
Outputs reversed `TRUE`/`FALSE`.
Slight modification of [@xnor's algorithm](https://codegolf.stackexchange.com/a/251895/55372): checks whether
$$ n^2 = 2 \mod a(a+n)+1.$$
This needs handling \$0\$ as a special case (`&n`), so we may check \$a\$ only up to \$n\$.
---
Actually a direct port works for the same byte-count:
### [R](https://www.r-project.org), 35 bytes
```
\(n,a=1:n)all((n^2-2)%%(a*(a+n)+1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NU9bCgIxDPz3FCsipNqFJm3dRtibiFDERWFZxAfiWfxZBQ_kp7cx8VHodJLMTOj1tu_vTf04HZsyvUYL6Gyucd6Z3LYA3ZJKMuMx5AnkaWemaMxP-oT9-lCfN9vVBoaHvNu1F3BzdHJsY0yJZjDQDFXVK3C2mNmCSG4QKmUSjiSE8APeFt6JxnuB6ERV6ZSjlMzCEINavHaxQmljYq_WJGKqvMYwx0-E8OCSIs3EFRJrakJdnoL0qxh1BauGKbj_x_r--74B)
It's because for \$n=0\$ `a=1:n` becomes `[1 0]`, so we actually check \$a\$ up to \$n+1\$ for \$n=0\$, and up to \$n\$ for \$n>0\$, which is sufficient.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 33 bytes
```
n->n*prod(a=1,n,n^2%(1+a*a+=n)-2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNxXzdO3ytAqK8lM0Em0NdfJ08uKMVDUMtRO1ErVt8zR1jTQhCvcWFGXmlWhE59Xk2ehGG-jpGRoYGMTqKKZp5GnGQtUsWAChAQ)
A port of [@pajonk's R port](https://codegolf.stackexchange.com/a/251911/9288) of [@xnor's Python answer](https://codegolf.stackexchange.com/a/251895/9288). Returns falsy when there is a solution.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 40 bytes
```
n->sumdiv(n^2-2,d,d--*issquare(n^2+4*d))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNzXydO2KS3NTMss08uKMdI10UnRSdHW1MouLC0sTi1JBgtomWimamhD1ewuKMvNKNKLzavJsdKMN9PQMDYAgVidNI08zFqpmwQIIDQA)
Longer but faster. Checks if there is a divisor \$d>1\$ of \$n^2-2\$ such that \$n^2+4d-4\$ is a square.
Returns truthy when there is a solution.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
nÍILDI+*>Öà
```
-2 bytes porting [*@xnor*'s formula](https://codegolf.stackexchange.com/a/251895/52210) as well
Outputs `1`/`0` as truthy/falsey respectively.
[Try it online](https://tio.run/##yy9OTMpM/f8/73Cvp4@Lp7aW3eFphxf8/29pZGIAAA) or [verify the range [0,100]](https://tio.run/##yy9OTMpM/X@xyc3PXknhUdskBSV7P5f/eYd7/Xxc/LS17A5PO7zgv85/AA).
**Original 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
L©+®ø.ΔnOyP>Ö
```
Outputs a valid pair as truthy or `-1` as falsey.
If looping indefinitely would have been a valid falsey result, `L©+®` could have been `∞+∞` instead for -1 byte.
[Try it online](https://tio.run/##yy9OTMpM/f/f59BK7UPrDu/QOzclz78ywO7wtP//LY1MDAA) or [verify the range [0,100]](https://tio.run/##AS0A0v9vc2FiaWX/0YJGTj8iIOKGkiAiP05E/0zCqSvCrsO4Ls6Ubk95UD7Dlv99LP8).
**Explanation:**
Uses formula \$n^2-2 = 0 \mod a(a+n)+1\$ on the range \$[1,n]\$.
```
n # Square the (implicit) input-integer n
Í # Decrease it by 2
IL # Push a list in the range [1, input n]
# (note: n=0 will become list [1,0])
D # Duplicate it
I+ # Add input `n` to each value in the copy
* # Multiply the values at the same positions in the lists together
> # Increase each by 1
Ö # Check for each value in the list if it evenly divides the n²-2
à # Check if any is truthy
# (which is output implicitly as result)
```
Creates a list of pairs \$[a,b]\$ where \$a\$ is in the range \$[n+1,2n]\$ and \$b\$ in the range \$[1,n]\$, and does the check defined in the challenge description on each pair: \$(a^2+b^2) = 0 \mod (ab+1)\$.
```
L # Push a list in the range [1, (implicit) input-integer n]
# (note: n=0 will become list [1,0])
© # Store this list in variable `®` (without popping)
+ # Add the (implicit) input to each value in the list
®ø # Pair it with list [1,n] of variable `®`
# (we now have a list of pairs [a,b], where `a` is in the range [n+1,2n] and
# `b` in the range [1,n] and |a-b|==n)
.Δ # Pop and find the first pair of this list which is truthy for,
# resulting in -1 if none are truthy:
n # Square the values in the pair
O # Sum them together
y # Push the pair again
P # Take the product
> # Increase it by 1
Ö # Check if (a²+b²) is divisible by (a*b+1)
# (after which the result is output implicitly)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 43 bytes
```
->n{(0..n).any?{|a|(n*n-2)%~(~a*~a+=n)==0}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNATy9PUy8xr9K@uiaxRiNPK0/XSFO1TqMuUasuUds2T9PW1qC29n@BAkilqYGBpl5xak5qcomGWprmfwA "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
Nθ⊙…·¹⊕θ¬﹪⁻×θθ²⊕×ι⁺ιθ
```
[Try it online!](https://tio.run/##VYy9DsIwEIN3niLjRQoDWTsxdmhVIV4gpCeIlFzIXyWePhxlqhdL/mzbl8k2Gt/7SO9W5xYemCHJ4bRkRxWu9IGRrG/FbXgz9ES4KMFJxoBUceWuVGKOFaa4Nh9hctQK3F3AAkmJxFTL4@QPnRIL//6cP3YNvWvdz5v/Ag "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for valid, nothing if invalid. Explanation: Uses @xnor's algorithm. I tried writing it using vectorisation but that weighed in at 27 bytes:
```
Nθ¬Π﹪⁻×θθ²⊕÷⁻X⁺θ⊗⊕…⁰⊕θ²×θθ⁴
```
[Try it online!](https://tio.run/##VY3BCsIwEETvfkWPG6ggxVuvveTQEoo/kCaLBpKNSZP6@TFWQV0YhmVn3qqbjMpLWwqne05TdgtGCKw/iGgoweQTiOh1VgnGatbDaCivcDEOVwhtE1jbdFWcVESHlFADpzSYzWj8hIV/VKqweW8MPi92T30bs6QrwukfE9hr3viff3U77xfWl9J15bjZJw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ Input `n` as a number
θ Input `n`
× Multiplied by
θ Input `n`
⁻ Minus
² Literal integer `2`
﹪ Vectorised modulo by
θ Input `n`
⁺ Vectorised plus
… Range from
⁰ Literal integer `0` to
θ Input `n`
⊕ Incremented
⊕ Vectorised incremented
⊗ Vectorised doubled
X Vectorised raise to power
² Literal integer `2`
⁻ Vectorised subtract
θ Input `n`
× Multiplied by
θ Input `n`
÷ Vectorised divided by
⁴ Literal integer `4`
⊕ Incremented
Π Take the product
¬ Is zero (i.e. was any remainder zero)
```
[Answer]
# J, 38 bytes
```
3 :'*/0<1|(_2+*:y)%1+(a+y)*a=.1+i.1+y'
```
Uses @xnor's formula, but implements it directly on an array containing a from 1 to n+1.
[Try it here](https://jsoftware.github.io/j-playground/bin/html2/#code=NB.%20Character%20count%0A%23%273%20%3A%27%27*%2F0%3C1%7C%28_2%2B*%3Ay%29%251%2B%28a%2By%29*a%3D.1%2Bi.1%2By%27%27%27%0ANB.%20indices%20for%20numbers%20not%20complying%20%3C%2010000%0AI.-.3%20%3A%27*%2F0%3C1%7C%28_2%2B*%3Ay%29%251%2B%28a%2By%29*a%3D.1%2Bi.1%2By%27%220%20i.%2010000%0ANB.%20note%3A%20I.-.%20just%20converts%20location%20in%20the%20array%20i.%2010000%20back%20to%20the%20number%0ANB.%20and%20%220%20is%20just%20for%20the%20function%20to%20take%20one%20at%20a%20time%0A)
] |
[Question]
[
[Related challenge](https://codegolf.stackexchange.com/questions/243441/bandwidth-of-a-matrix)
A [band matrix](https://en.wikipedia.org/wiki/Band_matrix) is a matrix whose non-zero entries fall within a diagonal *band*, consisting of the main diagonal and zero or more diagonals on either side of it. (The [main diagonal](https://en.wikipedia.org/wiki/Main_diagonal) of a matrix \$A\$ consists of all entries \$A\_{i,j}\$ for which \$i=j\$.) For this challenge, we will only be considering square matrices.
For example, given this matrix:
```
1 2 0 0 0
3 4 5 0 0
0 6 0 7 0
0 0 8 9 1
0 0 0 2 3
```
this is the band:
```
1 2
3 4 5
6 0 7
8 9 1
2 3
```
The main diagonal (`1 4 0 9 3`) and the diagonals above it (`2 5 7 1`) and below it (`3 6 8 2`) are the only places non-zero elements are found; all other elements are zero. (Some of the elements in the band may also be zero.)
One nice feature of band matrices is that they can be stored more efficiently: only the elements in the band need to be stored. For example, our 5-by-5 matrix above can instead be stored as a 5-by-3 matrix, where each column represents one diagonal of the original matrix:
```
0 1 2
3 4 5
6 0 7
8 9 1
2 3 0
```
Note how the shorter diagonals are padded with zeros: diagonals below the main diagonal are padded at the beginning, while diagonals above the main diagonal are padded at the end.
In this challenge, the band to be stored must be symmetrical about the main diagonal. For example, this matrix:
```
2 3 4 0 0 0
1 2 3 4 0 0
0 1 2 3 4 0
0 0 1 2 3 4
0 0 0 1 2 3
0 0 0 0 1 2
```
has this band:
```
2 3 4
1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3
0 1 2
```
and so it is stored as:
```
0 0 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 0
0 1 2 0 0
```
In this case, one of the diagonals to be stored consists entirely of `0`s, but that diagonal must be included because it is symmetric to the nonzero diagonal consisting of `4`s. (This rule means the output matrix will always have an odd number of columns.)
## Challenge
Given an \$N\$-by-\$N\$ band matrix containing nonnegative integers, output/return its rearranged version.
If \$B\$ is the number of diagonals in the band, the resulting matrix will be \$N\$ rows by \$B\$ columns. If you prefer, you may output the result matrix transposed (that is, a matrix of \$B\$ rows by \$N\$ columns).
You may assume that \$B < N\$. In other words, no input that would generate output the same size or larger needs to be handled.
The matrix will always have at least one nonzero entry.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the goal is to make your code (measured in bytes) as short as possible.
## Test cases
```
1 0
0 1
=>
1
1
1 0 0
0 2 0
0 0 3
=>
1
2
3
0 0 0
0 0 0
0 0 42
=>
0
0
42
1 2 0 0
3 4 5 0
0 6 0 7
0 0 8 9
=>
0 1 2
3 4 5
6 0 7
8 9 0
1 2 0 0 0
3 4 5 0 0
0 6 0 7 0
0 0 8 9 1
0 0 0 2 3
=>
0 1 2
3 4 5
6 0 7
8 9 1
2 3 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 1
0 0 0
0 0 0
0 0 0
0 0 0
2 3 4 0 0 0
1 2 3 4 0 0
0 1 2 3 4 0
0 0 1 2 3 4
0 0 0 1 2 3
0 0 0 0 1 2
=>
0 0 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 0
0 1 2 0 0
```
[Answer]
# [R](https://www.r-project.org/), ~~94~~ ~~84~~ ~~83~~ 78 bytes
*Edit: -5 bytes thanks to Giuseppe*
```
function(m,b=max(abs(row(m)-col(m))*!!m))matrix(c(!1:b,m),dim(m)+1)[-b:b+b+1,]
```
[Try it online!](https://tio.run/##TY7RCsIwDEXf@xd7a2wGrXNTB/sS8WGtFApmgzlxf1/j2qkUmntIctop@i765@DmMA6S0HbUL7K3DzmNL0lQuvHOBXZFwTf18xQW6WRhWosEeAvEXWXgUtrWKqsMXiN13zmDe9TrERUesE5RY8PlmKLGE57RpKh5vgKeq0F4NgvxJ@MWO7LuY96QV3@4ejbM0oQZVgT@QpPfiG8 "R – Try It Online")
(of which 38 bytes are shamefully copied from [Giuseppe's method](https://codegolf.stackexchange.com/a/243509/95126) to calculate the bandwidth: upvote that!)
As noticed by @pajonk, there are 2 'rearranged versions' of any square 'band matrix', depending on how 'rows' and 'columns' are assigned: add [+3 bytes](https://tio.run/##TY5BCoMwEEX3uYW7pP5AUqu2Um/RXenCCILQJGAt9fbpaNSWQOY/ZuYlQ@jq0L1dO/becQtT22bijXnxwX@4FbL1TyrikCR022Yc@om3PNGVwTg34K7SxdlUi7s0lUlNqiHdI9h6X9A4Qi2HZTghj1GhoFLGqHDGBTpGRfOZoLkcN8E6sjP2p6MmWVbh7N6Qln@4mDZctRFXWFDQJ4r9lfAF) (corresponding to `t`ransposing the input matrix) to flip this.
**How?**
For an `n`x`n` matrix, we first calculate the bandwidth `b` and prepend `b` zeros to the front of the matrix elements as a 1d-vector. We then split this up again into a matrix with `n+1` rows: this aligns the diagonals, placing the 'bands' in the first `2b+1` rows. The 'rearranged version' is now just the `2b+1`x`n` submatrix of this.
[Answer]
# [J](http://jsoftware.com/), 66 53 bytes
```
#{.#|.-@$(#"1~0{](]#~[-:"2*"2)#\>/#\|@-/#\)@|.]{.~3*$
```
[Try it online!](https://tio.run/##hY47b8IwFIV3/4qrGJHYai6OQ19uiKwidao6dA0RAwJVXTqULVH@enp9cYtCByS/jv2d4/M5JpgeYOUghRsw4GjmCOv315dRdih7zP0sk0kxmK7NWjk0uUusTqySm3ohN73PaVW@x7bDodSzUYm3Z4TGZaTndda4GhdyXittK@e1rKwmvq38tUxx3H8fVyEJ9ruPL5@mv8ewHyDBJ9xawVgobkQBRhgohLq45GvLq4Fy@mwAwpjuSxugSYjlmBKWcMvUHel7DnyAx8sfGT7jZ0PsQBaqyQyx/xoV0X4Crp8mdsqjX08PoUlUHBsVW6OKMaz@IkkJNf4A "J – Try It Online")
### Basic Strategy
We want to avoid special casing the "pad the partial top rows
on the left", and "pad the partial bottom rows on the right". If we extend
the input "offscreen" in both directions, a solution which automatically
handles these cases falls out for free.
### Explanation
Consider:
```
1 2 0 0
3 4 5 0
0 6 0 7
0 0 8 9
```
* `]{.~3*$` Extend the input so its shape is 3 times its original shape:
```
1 2 0 0 0 0 0 0 0 0 0 0
3 4 5 0 0 0 0 0 0 0 0 0
0 6 0 7 0 0 0 0 0 0 0 0
0 0 8 9 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
```
* `-@$(...)@|.` And rotate it so the original is centered:
```
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 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 2 0 0 0 0 0 0
0 0 0 0 3 4 5 0 0 0 0 0
0 0 0 0 0 6 0 7 0 0 0 0
0 0 0 0 0 0 8 9 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
```
* `#\>/#\|@-/#\` Generate all possible bands:
```
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 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 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 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 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 0
0 0 0 0 0 0 0 0 0 0 0 1
1 1 0 0 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 0 0 0 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0
0 0 0 0 0 0 1 1 1 0 0 0
0 0 0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 0 0 1 1
1 1 1 0 0 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0 0
0 0 1 1 1 1 1 0 0 0 0 0
0 0 0 1 1 1 1 1 0 0 0 0
0 0 0 0 1 1 1 1 1 0 0 0
0 0 0 0 0 1 1 1 1 1 0 0
0 0 0 0 0 0 1 1 1 1 1 0
0 0 0 0 0 0 0 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 0 1 1 1
... etc
```
* `](]#~[-:"2*"2)` Filter only those that, when multiplied elementwise with the extended input, return the input unchanged:
```
1 1 0 0 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 0 0 0 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0
0 0 0 0 0 0 1 1 1 0 0 0
0 0 0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 0 0 1 1
1 1 1 0 0 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0 0
0 0 1 1 1 1 1 0 0 0 0 0
0 0 0 1 1 1 1 1 0 0 0 0
0 0 0 0 1 1 1 1 1 0 0 0
0 0 0 0 0 1 1 1 1 1 0 0
0 0 0 0 0 0 1 1 1 1 1 0
0 0 0 0 0 0 0 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 0 1 1 1
...etc
```
* `0{` Take the first:
```
1 1 0 0 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 0 0 0 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0
0 0 0 0 0 0 1 1 1 0 0 0
0 0 0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 0 0 1 1
```
* `#"1~` Use these masks to filter the extended input, row-wise:
```
0 0 0
0 0 0
0 0 0
0 0 0
0 1 2
3 4 5
6 0 7
8 9 0
0 0 0
0 0 0
0 0 0
0 0 0
```
* `#{.#|.` To extract only the middle portion that is our final answer, rotate
left the length of the original input, and then take the length of the original
input:
```
0 1 2
3 4 5
6 0 7
8 9 0
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔⌈Eθ⌈Eι∧λ↔⁻μκηIEθE⁺κ…·±ηη§ιλ
```
[Try it online!](https://tio.run/##TU3LCoMwELz7FXuMsIW@H3iSnjxYpFfJIbVBgzFaE8W/T7cWbJdhZ4fZnS0q0Ret0N7H1qrSsFRMqhka4o69EP6lQojNk2mih2314CRLlRksaxDq8FsIVRgFWa@MY1dh3S@nY5mm3RohMQVNapR3YUrJbrIUFFXNt9Ril5innD7v9JwZeZ/n@QZhi7AmcAwA8h3CHuGwaHKOs39aNOGMcOGc@9Wo3w "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⌈Eθ⌈Eι∧λ↔⁻μκη
```
Calculate the width of the band.
```
IEθE⁺κ…·±ηη§ιλ
```
Output the relevant cyclic diagonals.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ĀDƶsøƶøαàUεNX-._X·>£
```
-4 bytes thanks to *@Neil*.
[Try it online](https://tio.run/##yy9OTMpM/f//SIPLsW3Fh3cc23Z4x7mNhxeEntvqF6GrFx9xaLvdocX//0dHG@oY6RiAYKxOtLGOiY4plG2gYwZkmUPZBjoWOpY6hlC2AVCPcWwsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpRRQlFpSUqlbUJSZV5KaopAJlzu0PCr93JasQ7uBivxLS2DCLv@PNLgc21Z8eMexbYd3nNt4eEHoua1@Ebp68RGHttsdWvy/1hbD0Hy4doShh7bZ/4@OjjbUMYjViTbQMYyN1VEAc6ECRlDaQMcYImUAl0LQJkYwbUZQUWMdEx1TqLwZUMwcqtJCxxJFKbJiZOVwo4EagI6CWgfUA3eFoQ6KS4hmg7UDzQHaCZMEuQXKhwQCjA/VCOXDjQHzkQwF8mNjYwE).
**Explanation:**
Step 1: Get the bandwidth of the input-matrix, using the same exact code as [my answer in the related challenge](https://codegolf.stackexchange.com/a/243498/52210):
```
Ā # Transform each non-0 integer in the (implicit) input-matrix to a 1
D # Duplicate this matrix of 0s/1s
ƶ # Multiply each inner value by its 1-based row-index
s # Swap so the matrix of 0s/1s is at the top again
øƶø # Do the same for the columns
# (where `ø` is a zip/transpose, to swap rows/columns)
α # Take the absolute difference of the values at the same positions
à # Pop and push the flattened maximum
```
Step 2: Leave the actual diagonal band matrix using the \$bandwidth\times2+1\$, and output it as result:
```
U # Pop and store the bandwidth in variable `X`
ε # Map over the rows of the (implicit) input-matrix
NX- # Push N-X, where `N` is the 0-based map-index
._ # Rotate the current row that many times towards the left,
# where negative values will rotate towards the right instead
X·> # Push 2X+1, where `X` is still the bandwidth
£ # Leave that many leading items from the current rotated row
# (after which the mapped matrix is output implicitly as result)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~37~~ ~~26~~ ~~18~~ 17 bytes
```
vT:ẏεfG£¨2Ǔ¥ǔ¥d›Ẏ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ2VDrhuo/OtWZHwqPCqDLHk8Klx5TCpWTigLrhuo4iLCIiLCJbWzEsMiwwLDAsMF0sWzMsNCw1LDAsMF0sWzAsNiwwLDcsMF0sWzAsMCw4LDksMV0sWzAsMCwwLDIsM11dIl0=)
## How?
```
vT:ẏεfG£¨2Ǔ¥ǔ¥d›Ẏ
vT # For each row, get the indices of truthy elements
:ẏ # Duplicate and push a range in [0..length of list)
ε # Vectorizing absolute difference
fG # Get the flattened maximum difference
£ # Store in the register
¨2 # Open dyadic map lambda on (implicit) input, pushing both item and index
Ǔ # Rotate row left by index
¥ǔ # Rotate row right by the contents of the register
¥d› # Push 2*register+1
Ẏ # Leave that many leading items in the current rotated row
```
*-10 bytes thanks to Neil, and another -9 from myself*
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 89 bytes
```
m->a=0;matrix(#m,,i,j,m[i,j]&&a=max(a,abs(i-j)));matrix(#m,2*a+1,i,j,m[i,(i+j-a-2)%#m+1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZBRSgMxEIbxJqGlJXEnmKTVtpTtPWQJMj6sZDES1i3Us_iyIOKZ9DTOJtl23_oymf_PN_OTfP4EbN3TS-i_alZ-H7tabn8fvTxgqfYeu9ad-NwDOGjAV1TtcomlxxNHwOd37mQjhJiQ5hYLfca5KxqJ0ojF3BfaihTwd3OHIbx-cM_kgYXWvXXUzgYxYzX3QgCrKg1qr0Bb6qmNwsSqYDWYKptjXZuEmuisYA338eaB9CYSW9hNkAt0wfIqAkGn1cTmNA2TxOudhYpGKSD5Q2hWw6tGFfms8mxU5z2k7PhvfZ_Ofw)
[Answer]
# [Python](https://www.python.org) NumPy, 126 bytes
```
def f(*a):x=triu(tri(l:=len(a),2*l-1,l-1))[::-1];x[x>0]=r_[a];j=min(where(x+x[:,::-1])[1]);return x[:,j:-j]
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVFLboMwFFS3PsUTKzsliE_apiBH6jlIVKEGFCJjLIeoZNOLdJNNe4kue4r2NH22SVClVoow5o3fvJkBXt_Vodu08nh823fVdP71si4rqOikYGnPO13vKW5UpFyUkhbMjydiGvl4M5an6TRaZX3eL8IV1495scq2vKklfd6UuqT9dZ-nviWxHO9Ml91eSzCn23S6XZFKtw3IfaMOUDeq1d1kSPHp4NArdiAVIVWrQUAtoVWYJWSBLos1ZcFOibqj3lIupcdSAgC13wIHEewwuxoZfOGxsU2lCpqio_2ZpksliqfSSHm-l3mMBQ9gXHvjSnGM2Xmla9khpPidasZ5y4JCCMoAqe7MMN2rHL-vPiIISQgR4QsS4UUQ25PY7iEkrhOThCAGs34_Z7FhIMKFNQrEViKBGdxY0i3iOys2h3tDRj-IHYG4JjaQepodp8f5IY4hRrYyEZP_1TAyJEbTtMNBKbyosprhyeaP3UrPBrbJPCAXxSEn4dCgbdHZx4QenE6k6ILqZIJz7if-AA)
Rather opportunistically takes the splatted array (this saves three bytes) as input.
#### How?
Uses the properties of masked assignment to map *all* diagonals by the deceptively short statement `x[x>0]=r_[a]`. The actual work is in setting up the initial mask `x`. And in trimming excess columns afterwards.
[Answer]
# JavaScript (ES6), ~~118~~ 116 bytes
```
f=(m,k,q=m.map(_=>0),M=m.map((r,y)=>q.concat(r,q[S='slice'](~y),0)[S](y+k,~k)))=>M.some(r=>r[0]|r[S](-1))?M:f(m,-~k)
```
[Try it online!](https://tio.run/##hY9Nc4IwEIbv@RU7XsiOGEHtpwM9tTd74ShOh2KwKARJsDNMW/@6XSKt01MzTHbf3efdDdvkPTGpzvfNSFVreTplAS/dnVsHpSiTPX8JQg/dRa@4dlsMwlqklUqThmS9jALHFHkqnRU/tuh6uIxWvB3u3OMOkeCFMFUpuQ5CvfRWn7prj3zEh8V9RqtGhJ20rA@5ltzJjINCy2T9lBcyalXKPRRNFTU6VxuOwuyLvOGDWMVqgCKr9GOSvnEDQQgfDKCQDZQQgLmAhHUvt8hPeRyb4fhcfz6Ur1IjuuTujpZEAj0M54xK9J@mKqQoqg2nlrXobpQW2ypX3AEHsU9j5SAMwcY5@8KTDx7zwGeMEptO7O3BlFGA7vsbZ5OOnVh6CjO4so1r0jfWdwt3v8AFuUD9eMJoq2WItcv83nIu/p8x8tH0s@g29sqO6pXFe9VbrfodQ@ob "JavaScript (Node.js) – Try It Online")
### How?
Given a matrix \$m\$ of size \$N\times N\$, we build a vector \$q\$ of size \$N\$ filled with \$0\$'s:
```
q = m.map(_ => 0)
```
For each row \$r\$ at position \$y\$ (0-indexed) in \$m\$, we use \$q\$ to append \$N\$ leading \$0\$'s and \$y+2\$ trailing \$0\$'s:
```
q.concat(r, q.slice(~y), 0)
```
For instance:
```
[ 1 2 3 ] --> [ 0 0 0 1 2 3 0 0 ]
[ 4 5 6 ] --> [ 0 0 0 4 5 6 0 0 0 ]
[ 7 8 9 ] --> [ 0 0 0 7 8 9 0 0 0 0 ]
```
Starting with \$k=0\$, we then remove \$y+k\$ leading \$0\$'s and \$k+1\$ trailing \$0\$'s:
```
.slice(y + k, ~k)
```
Which gives a new matrix \$M\_k\$ of width \$2(N-k)+1\$:
```
[ 0 0 0 1 2 3 0 0 ] --> [ 0 0 0 1 2 3 0 ]
[ 0 0 0 4 5 6 0 0 0 ] --> [ 0 0 4 5 6 0 0 ]
[ 0 0 0 7 8 9 0 0 0 0 ] --> [ 0 7 8 9 0 0 0 ]
```
We increment \$k\$ and repeat the whole process on the original matrix until there's at least one non-zero value in either the first or the last column of \$M\_k\$:
```
M.some(r => r[0] | r.slice(-1))
```
NB: `r.slice(-1)` returns an atomic array which is coerced to an integer by the bitwise operator.
[Answer]
# [Python](https://www.python.org), ~~203~~ 193 bytes
*-10 bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)*
```
def f(m):R=range;n=len(m);r=R(n);d=[*map(any,c:=[[m[i][i+d]if i+d in r else 0for i in r]for d in R(-n,n+1)])];k=min(d.index(1),d[::-1].index(1));return[[c[i][j]for i in R(k,n+n-k+1)]for j in r]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rVJBTsMwEJQ4-hWrnGzaVElboCTyJ9qj60PVOOA23kROKrVv4dIL_INnwGuwnbSCG0IkUTw7u-Nde_flrTl1zzWez6-HrowXH--FKqGkhmVLbjf4pHLklUJH5JYvKbK84OLWbBq6wdN4m3EhjNBS6FEhdQluAY1gQVWtgqSsLehASA-Db0ljHOMoZZLJfM-NRlpMNBbqSFM2LkSWxam8Ei6t6g4Whdj6NDt53XJJ924bjPd-K8_u-kT9QT5voLS1gaaxGjvQpqltN1iErHgURSSFKST-JTOYw11ACdy79SGgBBbwCGlAiYudEeJ-LrQXeflguZCrFcIHa5AGa8DBIk4cRAEEOB2ULkkC4L-f6zyIpt_LvRR7KZX85US-nmQITH6F_u0SfA-IaYGDEML1hR4Z-EYeQyMnbVPpjjIZOOu5tucqjaqlDNy82d7beu9qUERrXGPEJCHeZbzLtBkB9_T9p36-GekH5TL5Xw)
[Answer]
# APL+WIN, 64 bytes
Prompts for input matrix. Index origin = 0
```
b←⌈/⌈/¨+/¨^\¨b(⌽b←×0 1↓a←(⍳n←¯1↑r←↑⍴m)⌽m←⎕)⋄((r,-b)↑a),(r,1+b)↑a
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##lU7BasJAEL3vV8zNBA3d7Cax/YSC4g@UwkaJCNEWPfVeoqAGpUh/wVsP9eol/sn8SJzdhJjclGGY9@a9x4z6jJ3Rl4o/xs4wVovFZJhjeuj3MNlJRuh1QIgzXC2jPCSIm9WT7uzYpn5/y46hhZuzli6/HFxMfhRhC7f/M5rZH232cx1M9rg9TW0yTzVNDzauvy1r3nFCm0Rldwi77YLkdJDlERMgKOUCp3JZC1osYhJkteMgyikbKodmeaKUPfBMuIhJ8MA3KKDuGvQML6XXB7/mrbvrfpOA2zuykeaVcmeV6QACSgtzs1D0H48wfmNX "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
The brilliant engineers at <enter company you love to hate> have struck again. This time they've "revolutionised" the generation of random permutations. "Every great invention is simple" they say and their magical new algorithm is as follows:
* Start with a list `1,2,3,...,n` of numbers to permute.
* For each element x in the list draw a random index in the list and swap x and the element at the random index
Then they "prove" that this is unbiased because each element occurs at each position with equal frequency.
Obviously, their reasoning is flawed because their method has `n^n` equally likely outcomes which typically is not a multiple of `n!`
Your task is as follows: Write a program / function that accepts a list / stream / generator / iterator (whatever makes most sense in your language of choice) of permutations and decides whether they are a biased sample as created by the algorithm above or not. If not you may assume that the sample is unbiased.
`n` will be `3` or more. You can set a minimum sample size as you see fit,
Your program may err on small samples but must converge to the correct answer as the sample size increases.
You may output True/False or any two values (but not groups of values: so for example empty list vs. nonempty list is not allowed unless the nonempty list is always the same)
Apart from that standard rules apply.
This is code-golf, smallest function or program in bytes wins. Different languages compete independently.
# [Python 3](https://docs.python.org/3/) Test case generator
```
import random
def f(n,biased=True,repeats=10,one_based=False):
OUT = []
for c in range(repeats):
out = [*range(one_based,n+one_based)]
OUT.append(out)
for i in range(n):
o = random.randint(i-i*biased,n-1)
out[o],out[i] = out[i],out[o]
return OUT
```
[Try it online!](https://tio.run/##RY8xD4IwEIV3fsWNLRYiMS4mrK4uOBFiihzaRK5NaQd/PbYUdbqXu/e@uzNv99R0WBY1GW0dWEmDnrJswBFGRqJXcsahbqxHYdGgdHNd7YUmvPXr5CxfM/JTBnC5NlBD2wU5agt3UBRxD2RbcHUBaO@iL0@zH0nQ7qd5tzoDsZTGIA0shPjai2j1R9MGDdgATdeXsShyTBUqTw8IKir@NXrX6k7EoroQSkKkdvBYdN5SXL4YGzEjO3K@fAA "Python 3 – Try It Online")
### Additional hints
Now that @AndersKaseorg has let the cat out of the bag I see no harm in giving a few more hints.
Even though it may look plausible at first sight it is not true that elements are uniformly distributed over positions.
We do know:
1. Directly after the nth element was swapped with a random position the element at position n is truly uniformly random. In particular, in the final state the last position is uniformly random.
2. Before that the nth element is guaranteed to be equal or smaller than n
3. Whatever is swapped downwards from position n to m can only be returned to n at the nth move. In particular, it can't be if the original move was the nth in the first place.
4. If we rank positions by their expectation after the kth move then positions m and n can overtake each other only at the mth or nth move.
5. Select values:
* The base (i.e. first or zeroth) element's position is uniformly random. This holds after the first swap and remains true from there on.
* The next element is over-represented in the first position: Out of `n^n` possible draws it occurs in `(n-1) x n^(n-2) + (n-1)^(n-1)` instances.
* The last element is under-represented in the first position: Out of `n^n` possible draws it occurs in `2 x (n-1)^(n-1)` instances.
[More demo / test code](https://tio.run/##dVK7bsQgEOz9FVsCx72UItJJriKlTZNUFjoRGydI9oIwSHF@3lk/74qcG5Z9zOwM9n38dvg0DLb1LkQIGivXShtNiM41XZZVpoaaoXRorp@6M1X@qpvO8EsG8PbxDjkUisLaBSjBImyjBx9clcrICPPLMOQyGG90zHGaBXApjtNirm/4EndbzNXUSTwH7b3BitEQn3IjoR0JV/gZlGAJtCysWq8pFk7J8bCKSnMg5zT1BBNTwJEig6wOrgVMre9hMUTMDpgfT3L8Ax9WKTcRsINwLS6ouEAhcFrm8cYp3skr9mdFGx6P5MN82y/nmDK9YWeJ0kqLkRcnJdj@NrTrUjthnBSnbj5ZtSjUIeh@8m@YZJauaUwZrcNuFfviEtLzZZg/Zz4QAROt9mxJy1/rmaB/gdN3XyfS/2qbZ5wPfw)
5 can be used to solve this challenge in a similar but perhaps slightly less golfable way to Anders's answer.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~45~~ 43 bytes
(−2 bytes from xnor)
```
lambda v:sum(r<r[-1:]for r in v)/len(v)>.51
```
[Try it online!](https://tio.run/##dZC9TsUwDIX3PIXH5JKWFsRSUUZWlstUKpTS9BKpdaI0rcTTF6c/FwbIYic@/hwf9xU@Ld4vQY8BSnhbejU0rYK5GKeB@0dfJXlRd9aDB4Mwi9teI5/FU/qQL2Zw1gfwCls7MNbqDjqOsjFq1G159pOWXjutwljmmbSo35u18qz6UYuCAby8nmlqVVMaZ3zEGYS7aL43rioAO8XfVaetdiVJvLnmol6VREyVcxpbTk1ifYto84PGHUpYgm6/T2MwGLhJzGlbQGKSi0M4hcrWMgZTU9OWyO2ZNF6HyWMczhhS/S5j@wJ0yTM6zPmIjz7zaBL8dgkOm46thfhPv3r3V8PyDQ "Python 3 – Try It Online")
### How it works
Computes the fraction of samples where the first entry is less than the last entry. For unbiased input, this converges to \$\frac12\$.
For biased input, the last entry is uniform, but the first entry is less than a uniform one with probability
$$\frac{(3n - 2)(n - 1)^{n - 1}}{2n^n},$$
which is \$\frac{14}{27} ≈ 0.518518\$ at \$n = 3\$, and increases toward \$\frac{3}{2e} ≈ 0.551819\$ as \$n → ∞\$.
This calculation ignores a slight anti-correlation between the first and last entries for \$n ≥ 4\$, but we can bound it and show that it’s much too small to affect correctness. Here are the [exact probabilities](https://tio.run/##hZPdboMgFMfvfYqTXoG1K2zZTRNfYS9gTNNV7FjiAUGXdE2f3QFqdW23cgHknF/@54ODPjYfCl@6TlZamQawrfQRdhZQR1EhStirFhuCdBOBWxpS53n6FkZZQjABpAkUzVGLVL1/in1De4zNObyL8IeIfaxiH6vojLk0YQU8dyzxt2cKcQw4BMn@cfKM3TiCp1QGJEgEI76EsaIgZocH4Ro1dMqv2hdAdCYT2OSw9G1xG89kTmG9HlUnnPf4JgHZ41l/8ru48equR5PLbeHm@NgHXzrJCffqrl9/4dzjLLrwl7RTF2lmHbJzVj6zujco5O6wlVjIvbDb0qiKaJrDKr3JJCjL4DJDicY3ZQKY169nUXkwTBJ2IFziYwlLPwe2rUjNfWWhnlnito@UjpQJVB9/dRXf8hlYsyDX1/Ar3qwBll@ps1v1ABvRtAZHzB2NkS3R/Wu/KRTjqHDfaG/IKY0iP24Yxi1M2UsCr2z8kkb6D5pAuTiNn/W8PmEc43lBu@4H "Python 3 – Try It Online") computed by dynamic programming.
[](https://i.stack.imgur.com/tqJVd.png)
[Answer]
# [R](https://www.r-project.org/), ~~94~~ ~~78~~ ~~74~~ 56 bytes
*Edit: -12 bytes thanks to Giuseppe, and -6 bytes and corrected (I hope) maths thanks to Anders Kaseorg*
```
function(m,n=max(m))var(t<-table(n^(1:n)%*%m))/mean(t)>2
```
[Try it online!](https://tio.run/##jZDBTsMwDIbP9VNEmqbFqBMUiUshvAgaKBuuli7JuiSdhtCevSQKDYgTPsTWZ/vPL7tJ@betkp7exdSNdhfU0XJTW2HkhRvEs3Q8PK2D3Gri9pU3rcXlzTJ2bg1JywM@308LtnMkA7HRZi3mpRk0tTAD4eUw6I@43tylqMtfF8yzsfWACFC0/ij5/dh1mgSUTY2fUHVHxxVTlnk6RZJQ1YtvyczqBiM8CP2iNo/piVWfqn4jDlBdoXIURpcE4Qr/8Jud/BgO5ANblUOu2DzcQoE8J/xF5tvg9AU "R – Try It Online")
Input is a matrix `m` with each row representing a permutation.
If permutations are unbiased, then all permutations should occur with the same observed frequency `t` (with `k` samples, `mean(t)==k/factorial(n)`), and with an expected variance equal to the mean (binomial variance = `k*p*q` = `k*(1/factorial(n))*(1-1/factorial(n))` = `mean(t)*(1-1/factorial(n))` = `mean(t)` after correction for sample size `factorial(n)`).
We guess that sampling is biased if the variance is greater than twice the mean. Simulations indicate that this is sufficient to detect biased samples with `n=3`, and the difference becomes bigger (so, easier to detect) at larger `n`. As `n` increases, though, the number of permutations needs to be quite large for the guess to be reliable.
---
Addendum: Note that a port of [Anders Kaseorg's approach](https://codegolf.stackexchange.com/a/245964/95126), which is much better tailored to detect exactly *this* type of biased permutations (rather than simply any biased set of permutations) is 19 bytes shorter:
`function(m)mean(m[1,]<m[max(m),])<.51` ([try it](https://tio.run/##jZDBasMwDIbP0VMYemgEYcyHXtL6SUIYXqdQp3aS2g60jD57ZuPFLT1VB0l8kn5@ZBflvr6VdPQjlm4ejl6NQ2nQkAyl4VV7MI2R14CqFg8fO75s2NGS9MTmIR0yJ82kqYYVCCenSd9KXvPPGFUWvmLaDaMdIkDWelFyp7nrNAnIlxp/oehGWyqmBuboEkhERS/@JROrOAZ4FrpR7T6m0PWx61txhuIOhSU/2ygId3jDb3LyMOzJebbNX9uydbmGDMtU8Imsv8HlDw)).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
›₂⌈Eθ№θι⊕₂∕LθΠ…·¹L⊟θ
```
[Try it online!](https://tio.run/##7Vc7a8MwEP4rHlVwQY@xYwul0EJIx5DBJCIxJHbj2qH/3lUcCek4LTlPTc9LIvm7t@6sb7Ovuk1bHcZx0dVNL147W/W2E5@noerssm178VH91Mfh6H6/xKksntvB4dyf@sE9ZfHWbDp7tE1vt6nUS32ut1a822bX78XJARddux02vXACh@G7Pttl1eysUGXhQYvWGXgIz9M4rlbClIUsC4fRToPQZWGmlfQred2IK/fOXFZu129cVmqCSa9FTe@M16ICMsjJaSOR0xF5tafjSns56AuykCChFh8OiE/GiFTUogMyiS9kQoa8aL/S0RcZkCba00BOR6SKnsmANNgXZCFBQi0z6kDyk5oX6AuykCChFhgRrBE6rQZkYoY9DeSSzMNok5xBX5AFmN1Eyz84n/c@X6h1IPlJzQs65dBCgkSdY0D9khqh04o6gGpPA7kk8zDaJGe57pdALsluouXe6zdjzlP7ljTPoC/IApz6CsRHrQN17pLyAn1BFmBXyfnfo3n2bv/ezpgTdz1fqOc6N21U9s6HJhjqYh2RCkw@BeJDtwsJ5DSYKDI7I2@qA8lPal5yt9/8NwBNaGofzbCns7c1FK0E9090e1LZGZnTwvyP@R/zP@Z/zP@Y/zH/Y/7H/I/5H/M/5n/M/5j/Mf9j/sf8j/kf8z/mf8z/mP8x/2P@x/yP@R/zvz/P/9br8fF8@AU "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` if it thinks the list of permutations is biased. (Test case consists of 768 biased permutations of four elements.) Explanation:
```
θ Input list
E Map over elements
№ Count of
ι Current element
θ In input list
⌈ Maximum
₂ Square root
› Is greater than
θ Input list
L Length
∕ Divided by
θ Input list
⊟ Last element
L Length
Π…·¹ Factorial
₂ Square root
⊕ Incremented
› Implicitly print
```
A port of @AndersKaesorg's answer would be just 16 bytes:
```
‹·⁵¹∕ΣEθ‹§ι⁰⊟ιLθ
```
[Try it online!](https://tio.run/##5VZNa8MwDP0rObrgDVlmp50Guww2KOwYeihtWQNdv1f277MkTbAe8qXKrctNtqSnD@tFi/X8uNjNN3U9PVbbs3tfnU6OHp@CL16rS7Vcuc@fb/cx37uDL7rLl/Pbdrn6dZUvaOKL6W7vqknztdfbr/PaHVrpua7LsoyNji8aXzzzRcm@iJ1EvUTXgyQ1d7GVmtP@oJVCp0a9l9Ddxd5LGDQHO@oOhB0nzSseJ4l7O4xFIQhN9NKnA/lRyigkLzxoivyGStBQF@4lTrHQoBkTHoMdJ82QIqNBM@pYFILQRC8j@mCK01oXjEUhCE30ghlhj9RrjVCJEXgMdqLymK2oGcaiELC6wss/eJ/3zi/WPpjitNZFvXJEEJpqciL0T/RIvVY1AVY8BjtRecxW1Cw3/QR2orrCy733bwTPW@fWxGcYi0JA1g@Qn7UPVt411QVjUQg4VTT@fzQO7/b/7QieuGt@sb7rHNuE7M6nGExNMSfNAMwXID@1XRDYMTAKZTnypj6Y4rTWJbf95v8BiqGtczQCj7PbmsqWYP9U21PIcqTwMpvVD5fNHw "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` if it thinks the list of permutations is biased. (Test case consists of 256 biased permutations of four elements.)
] |
[Question]
[
You are a historian studying a long forgotten language. You have just discovered a clay tablet which seems to list all known words in the language, in alphabetical order. Your task is to find this alphabet's order, if it exists.
## The Task
Given an ordered list of words, try to output an ordered list of characters such that:
1. Every character of the words in the word list appears exactly once in the character list.
2. The word list as given is sorted "alphabetically" according to the character list.
If (and *only* if) no character list is able to satisfy these requirements, output a falsy/fail value of your choice. You must specify in your answer the value you have chosen.
Notably, it is possible that more than one alphabet ordering is valid for a given list of words; If we have the words Cod, Com, and Dy, all that can be assumed is that C comes before D, and d comes before m. The letters o and y have various valid positions in the generated alphabet. For more clarity, here are some (but not all) valid outputs for that word list:
```
Input: Cod Com Dy
Output: CDdmoy
Output: CDdmyo
Output: CDdomy
Output: CoDdym
Output: dmCDoy
Output: dCmDoy
Output: CdoymD
Output: dyCoDm
Output: yodmCD
```
If there are multiple valid character lists, your code must output either *one* valid answer or *all* valid answers, consistently.
## Rules
* Your input is a list of words, which may be input in any reasonable format. Output only languages are allowed to include this word list in their initial data/program at no additional byte cost.
* The word list will contain at least two words, and no two words will be identical.
* Any alphanumeric character `[A-Za-z0-9]` may be included as a character in the wordlist.
* Words are read from left to right, and are alphabetized first by leftmost character, then by the next character, etc.
* Two words which begin with the same substring are only alphabetized if the shorter of the two comes first (e.g. "CAR" must come before "CARP").
* Uppercase and lowercase forms of the same character are considered to be different characters, i.e. the alphabet is case sensitive.
* You may output each alphabet in any reasonable format, but each must contain every character present in the word list exactly once, and no other characters. (This requirement, of course, does not apply to falsy/fail outputs)
## Examples
Your correct outputs may not match all these, as any given wordlist may have more than one proper alphabet. Some may only have one valid answer.
```
Input: bob cat chat dog hat hot guy
Output: tuybcdaohg
Input: A Aa AA Bb Ba
Output: baAB
Input: 147 172 120 04 07
Output: 14720
```
### Falsy output examples
These *should* all be falsy outputs, and can be used as test cases.
```
Input: GREG HOUSE ROCK AND ROLL
Output: [falsy]
Input: b5OtM bb5O MO Mtt 5
Output: [falsy]
Input: a aa aaa aaaaa aaaa
Output: [falsy]
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins. :)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes
```
∑UṖ'→?µ←:₃[nL|β];?⁼;h
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%88%91U%E1%B9%96%27%E2%86%92%3F%C2%B5%E2%86%90%3A%E2%82%83%5BnL%7C%CE%B2%5D%3B%3F%E2%81%BC%3Bh&inputs=%5B%27147%27%2C%20%27172%27%2C%20%27120%27%2C%20%2704%27%2C%20%2707%27%5D&header=&footer=)
Outputs a single possible alphabet. Times out for inputs with larger alphabets because it checks all permutations of the character set of the input. Exits with an error if falsey.
14 if `a aa aaa aaaaa aaaa` wasn't falsey. Much shorter if base conversion wasn't so janky.
## Explained (in theory if base conversion wasn't so janky)
```
∑UṖ'→?µ←ðpβ;?⁼;h
∑U # Get all unique characters of the input
Ṗ # and then all permutations of that.
' # From that, keep only items (n) where
→?µ←ðp; # the input sorted by conversion to bijective base n with a space prepended to make everything non-zero
?⁼ # equals the original input (⁼ is non-vectorising equals)
;h # and get the first from that
```
I actually got to use [the ghost variable](https://codegolf.stackexchange.com/a/231288/78850) and variable scoping for once.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
Returns all valid alphabets and the empty list as a falsy value.
```
FQŒ!iⱮⱮṢƑ¥Ƈ
```
[Try it online!](https://tio.run/##y0rNyan8/98t8OgkxcxHG9cB0cOdi45NPLT0WPv/hzs2HW6P/P/fUcExUcHRUcEpScEpEQA "Jelly – Try It Online")
```
F -- flatten the word list into a single string
Q -- get the unique characters
Œ! -- get all permutations of those characters
Ƈ -- keep the permutation that return a truthy value for:
¥ -- group the last two links into dyad
-- which is called with the permutation on the left and the word list on the right
iⱮⱮ -- for each character of each word get its index in the permutation
ṢƑ -- is the resulting list invariant under sorting?
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~92~~ 76 bytes
```
WS⊞υι≔⟦⟧θ≔ ηW⌈⁻⪪⪫υω¹θ«⊞θι≔⭆⪪ηLθ⭆κ⭆κ⁺ξ⎇⁼νπιωη»EΦ⪪η⊕Lθ⬤υ⬤υ⁼‹μξ‹⍘◨λLνι⍘◨νLλιΦιμ
```
[Try it online!](https://tio.run/##bVBNa8MgGD7XXyE9vYKDpBRy6KmDDToaCOtuYwdJJcrM2yTqmjH22zNdpIExQfTB5@u1VmKoL8JM01VpIykcsPPu5AaNDTBGK28VeE4125G9tbpBeH3jtF/gmq45VQEng1KMuvUtlBq9hVNntIOni8bocmWc5izKg/UXWf2697P7KvnN2aXoklZxepTYuEBkQbo8v/8BlQl5I6cvckAxfMJD74WxgJx2Qadjelxz2W9SBamDqH3UxslhiTtgPchWopNnWKKDcG9MnCIdyf8orYWW05HFouF@L6xMH1iJ87NulANzGwKjkQ77PxreaGampcapYZihDXg3Tfm2IHmxIfkmI9mWZAWZ7j7MDw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of words (space-terminated works, but it's easy to forget the trailing space) and outputs all orderings (the orderings themselves are output in ASCII order). Even slower now for larger character sets. Explanation:
```
WS⊞υι
```
Input the list of words.
```
≔⟦⟧θ
```
Start with no characters processed.
```
≔ η
```
Start with a space-prefixed list of one element, the empty string.
```
W⌈⁻⪪⪫υω¹θ«
```
Repeat until all distinct characters have been processed.
```
⊞θι
```
Mark this character has having been processed.
```
≔⭆⪪ηLθ⭆κ⭆κ⁺ξ⎇⁼νπιωη
```
Generate all permutations of the characters so far.
```
»EΦ⪪η⊕Lθ⬤υ⬤υ⁼‹μξ‹⍘◨λLνι⍘◨νLλιΦιμ
```
Filter those permutations which are valid orderings, removing the space prefix. Words are compared by padding them to the same length, then performing custom base conversion with the space-prefixed permutation.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
˜ÙœʒIkðýD{Q
```
Port of [*@ovs*'s Jelly answer](https://codegolf.stackexchange.com/a/236456/52210), so make sure to upvote him!
I/O as a list of character-lists. Outputs all possible alphabet-lists.
Should have been **9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** without the `ðý`, but there is [a weird bug when sorting after we've just indexed apparently..](https://github.com/Adriandmen/05AB1E/issues/184)
[Try it online](https://tio.run/##yy9OTMpM/f//9JzDM49OPjXJM/vwhsN7XaoD//@PjlZyVtJRygfiFKVYHQQvF8xzAbIqlWJjAQ) or [verify most test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWjpjXBh1b@Pz3n8Myjk09NOrQu@/CGw3tdqgP/1wKlvHT@R0crOeenKOkAyVwg6VKpFKsTreQIZDomgggQywkk75QIljE0MQdyDM2NQKSRAZA0MAER5mDZJFODEl8gNwnIAFK@/iCipARImoLlQUYmQggoCaeVYmMB) (two of them are removed because they time out).
**Explanation:**
```
˜ # Flatten the (implicit) input-list of character-lists
Ù # Uniquify this list of characters
œ # Get all its permutations
ʒ # Filter this list of lists by:
Ik # Get the index of each character of the input-list of lists
ðý # (Bug workaround: join each inner list by spaces)
D # Duplicate the list
{ # Sort the copy
Q # And check if it's still the same
# (after which the resulting list of character-lists is output implicitly)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Returns `undefined` for inputs without a solution.
```
¬â á æ@eUnX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=rOIg4SDmQGVVblg&input=WyJBIiAiQWEiICJBQSIgIkJiIiAiQmEiXQ)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 146 bytes
```
a=>(g=s=>s[0]?g(s.filter(c=>a.some(w=>s.includes((r=/(.*)(.?).*,\1(.)/.exec([p,p=w]))[2])&&r[3]==c,p='')||!(q+=c))):q)([...new Set(a.join(q=''))])
```
[Try it online!](https://tio.run/##VU/RattAEHy/r5i@RLtperHdBEPNOSitSaFJDQl9UgQ5nc@ygqyT7y6xQ@Jvd6XQFgq7M8vsLMw@6mcdjK/a@KlxC3tYqoNWUypVUNOQDfKLkoJcVnW0noyaahnc2tK2W8qqMfXTwgYir05JHjPJC5bHJ/dDknwq7c4aytqTVm1z5myU89GRzz7nSplOSxJ@e/tAm4/KMPOXDVMmpWzsFnc2kpaPrmpo09s450O0IRodbIDCgyhcAaMjzKqDhSvR88pFlE8vIkWqkaa4LHCpxfBsjOF4hOFogMEZBmNxdTu7wvf5r7sZbudffyD9@a0brq9FcT6PNyg6wk1XMeJcaOi@3vsPigcZfbUmlqGtq0jJfZOwXOuWdlBT7P7K6JJPxL/gcun8TJsVxd71KoDoX94ZMK4JrraydiUtKfZ3wL5/0axAlvH6nyWhmffOc8IT7MWeJ4ff "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/) + [gtools](https://cran.r-project.org/package=gtools), 162 bytes
```
function(w,a=unique(unlist(strsplit(w,""))),l=length(a))for(x in apply(gtools::permutations(l,l,a),1,Reduce,f=paste0))if(!is.unsorted(chartr(x,"a-z",w)))return(x)
```
[Try it online!](https://tio.run/##fY9vS8MwEIff@ynO7k0CUdoxGQz6ovvDBDcHEz/AtU27YJbU5MI2v3xtRSdMJtzlAvfwyxPXVmlbBVOQsoYdBKbBqPcgWTBaeWKenG@0om4VRZxzoVMtTU07hpxX1rEjKAPYNPrEarJW@8mkkW4fCPtEz7TQArlIxFaWoZCiShv0JGPOVcVulb8PxltHsmTFDh11gSLCu49IHLrXnKTgDDvytmJS/8pEM1vCzO5hfopEBL3YzQWRQYaQZTDNYYrXoGQ0hmQ8hGQYQzyCeHwGBxdkbnMokKCTJChtDf3cWYI6nBVgQPgmPSBoa62pgdRe/klabhdLeNy8vixgu5k9QfY87y6r1f8plzoPG1pD3g1Yd0UED9f@iIB9ffX3@YO2nw "R – Try It Online")
Iterates through all permutations (calculated by [gtools](https://cran.r-project.org/package=gtools) package as I didn't have the heart to do it myself) of used alphabet and checks whether sorting by it gives desired result. This is done by translating the characters to `a-z` and using built-in `is.unsorted`.
Returns nothing as falsy.
] |
[Question]
[
The *ball game* is a game in which a number of players sit together in a circle. Each player is first assigned a number \$ n \$, either `1`, `2`, or `3`. The game begins with any starting player, and proceeds *clockwise* around the circle. The *current* player with the ball throws it to the *next* player. Who the *next* player is solely depends on the number \$ n \$ the *current* player was assigned.
If \$ n = 1 \$, the *next* player will be the one sat directly adjacent (one space away), traveling in the current direction.
If \$ n = 2 \$, the *next* player will be the one sat two spaces away, traveling in the current direction.
If \$ n = 3 \$, the direction of play is first switched *(clockwise to counter-clockwise, and vice-versa)*. The *next* player will then be the one sat directly adjacent, traveling in the new direction.
## Task
You are given a list of numbers \$ l \$ all in the range \$ [1 - 3] \$, denoting the numbers each player was assigned. The elements in \$ l \$ are given in clockwise order, and such that the last element of \$ l \$ is adjacent to the first element. Your task is to determine the number of players who have touched the ball, before it reaches a player who previously already touched the ball.
### Example
The starting player is at the first index. `X` represents a visited index, `O` represents an index visited twice.
```
[1, 2, 1, 1, 2, 2, 3] ->
[X, 2, 1, 1, 2, 2, 3] ->
[X, X, 1, 1, 2, 2, 3] ->
[X, X, 1, X, 2, 2, 3] ->
[X, X, 1, X, X, 2, 3] ->
[X, X, 1, X, X, 2, X] ->
[X, X, 1, X, X, X, X] ->
[X, X, 1, O, X, X, X]
The answer is 6.
```
## Clarifications
* \$ l \$ can be inputted in any reasonable format, but the numbers `1`, `2`, and `3` must not change
* The starting player does not have to be at the first index, but please specify where it would start
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
## Test Cases
```
Input (start is index 0) -> Output
[1] -> 1
[2] -> 1
[3] -> 1
[3, 2] -> 2
[2, 1] -> 1
[2, 2, 3] -> 3
[1, 1, 1, 1, 1] -> 5
[2, 2, 2, 2, 2] -> 5
[3, 3, 3, 3, 3] -> 2
[1, 3, 2, 1, 2, 3] -> 2
[1, 2, 1, 1, 2, 2, 3] -> 6
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~67~~ 55 bytes
```
f=lambda x,*l:x and-~f(*l[x%3-1::1-x//3*2],0,*l[x%2:1])
```
[Try it online!](https://tio.run/##VY3BbsMgEETvfMVeqtgWJAWUHJCcH7F8IDVWkTBGhlTk0l93sB2cVprDztvZWfcI36Pl89zXRg63TkLElRERpO3Ib19UpokfnFAhKImnE69Yiz/xSpmgbTnrwY1TAP/wqB8nMNoq0HbxRx86bQUCg0FFp74C1DBIV6gfmdCSPHpndCgO5HooSwST8nezpJa/ybtJ21BsNHfgPVW/SDk3tAVyBYoalge@Dxg2yNIWwzuZOIYtxlFD02rXCs8581KGqfCt3ExXy9Zz9p@zXPv34@UJ "Python 3 – Try It Online")
Use [@Leo's idea](https://codegolf.stackexchange.com/a/205357/92237) of keeping the current player at a fixed index and transforming the list instead. Be sure to check out and upvote his answer!
If the current list is `[x, a, b, c, d]`, where `x` is the move of the current player, then we want to rotate the list appropriately, and replace `x` with `0`:
* If `x == 1`, the new list is `[a, b, c, d, 0]`
* If `x == 2`, the new list is `[b, c, d, 0, a]`
* If `x == 3`, the new list is `[d, c, b, a, 0]`
* If `x == 0`, this player has already been visited, thus we stop the algorithm.
---
# [Python 2](https://docs.python.org/2/), ~~90~~ 85 bytes
```
f=lambda l,d=1,p=0,*t:(p in t)^1and-~f(l,[d,-d][l[p]>2],(-~l[p]%4*d-d+p)%len(l),p,*t)
```
[Try it online!](https://tio.run/##VY7BboMwDIbvPIUvVZPOqZa026ESvEjEJLYELVIIFmTTeumrs0AJ3aT/YH/@/dt0jZ99UNPUlr7p3k0DHk0pkcpnPMQLI3ABIn@TTTDi1jKP2qAwtfaa6krVyMRtLnfngxHmifjO28A8R0rrfHId9UOE8ToWbT@Ad8HOgak/jtG4cCnSPbA/ZD8ilNA1xOx3k9DsPI7kXWR7Ue05L2Cw45efXemL1NLgQlxhjsDNVK5k0rIGUYEstMrFaSsQ7lClKcLDmTjC3XYqtEyjTQt8yZ5VGabAh3KyXFq1rKv/XOXYvxdffwE "Python 2 – Try It Online")
Not every elegant, but does the job.
This recursive function keeps track of the current direction `d`, the position `p`, and the list of seen position `t`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
←LU¡Γ!Moëṙ1ṙ2↔IΘ
```
[Try it online!](https://tio.run/##yygtzv6fqxGsraGtpGunVPyoqbFIU/PQtv@P2ib4hB5aeG6yom/@4dUPd840BGKjR21TPM/N@P//f7RhLFe0ERAbg7AOiGWkAxbTMdIBiRnqQCFUDAzBaqEQrAaoE6gGpsMIrANiAgA "Husk – Try It Online")
Takes a list of numbers where the ball is currently at the first element and keeps rotating/reflecting the list to keep the ball in the first position while setting any visited element to 0. Returns how many different lists were created this way (-1).
For a more detailed explanation of the code (hard to do, but I'll try):
```
←LU¡Γ!Moëṙ1ṙ2↔IΘ
ëṙ1ṙ2↔I List of four functions [rotate by 1, rotate by 2, reflect, do nothing]
Mo Θ Make each of these functions prepend a 0 to the list before doing anything
Γ! Use the first element of the input list as an index into the list
of functions, and apply that function to the rest of the input list.
Note that indexing with a 0 returns the last function (do nothing)
¡ Iterate this process and keep all the results produced
U Discard all results after the first repeated one
←L Return the number of results minus one
```
I'm a bit sad for all the bytes I'm taking to do `←LU`, but I couldn't find a shorter alternative (damn 1-based indexing!)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~94~~ ~~92~~ 91 bytes
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
c;s;i;d;p;f(l,n)int*l,n;{p=1;for(s=i=0;c=l[i];l[i]=!++s,i=(i+p*d+n)%n)d=c>2?p*=-1,1:c;p=s;}
```
[Try it online!](https://tio.run/##vZLBbuIwEIbvPIWLhJSQQW0SEkhdt4fVPkXhEJxk11I3jTAHVMSz0wkxWTZUo2ol2xqwMv5n5v8Sy9kvKU8nyTVXvOANr7w3qH1V76a480MjQl69bz0tlHjgUry9qjVv/8RdEGhQwlNBMy2C2p/UfiHkc/TSTMUshPBR8kZofjz9yVXt@ewwYriwMduVeqfD1zUT7BAe@b/5qMtHw3zc5eNhfm7ywG5KEtMK2M2UtD/CuOm5MN6wsI@hZnndwcRQk/Xe/sZQk/ez4nOT8GtLm14WXSzdmi/3TSl3A/OdHpsn5@iqUlMlf@fbKdt2JePV/me02mc/8JeMgV0/x@PrOah@AKZxm2Xt4qPzGV4U5rUC1Qo4bk9Mq4/yvfK6b@7fm0cU@ZwFgbrci3PrCqvZHZZeZ9vVbLGg8lpPPu9PjqPh@aQYg7ldam2Unar1enEBhClTdGnIZs9sUrCJXtU4XAO@KvOSyyBYC6HbKd9ij5yxRwR7BIQpa@yxM/aYYI@BMGWNfe6MfU6wz4EwZY09ccaeEOwJEKassafO2FOCPQXClDX2hTP2BcG@AMKUNfalM/Ylwb4EwpQ19swZe0awZ0CYssaeO2PPCfYcCFPW2DfO2DcE@wYIU//Ffjx9Ag "C (gcc) – Try It Online")
Inputs an array of `int` along with its length and returns the number of players touched before a repetitive touch.
**How?**
Passes the ball around setting the last place the ball was to \$0\$ and incrementing the counter \$s\$. When we arrive back at a \$0\$ we're done and return \$s\$.
**Commented code**
```
c;s;i;d;p;f(l,n)int*l,n;{
p=1; /* polarity is initialised to 1 forwards.
-1 is backwards */
for(s=i=0; /* initialise counter and index */
c=l[i]; /* stop looping when we hit a zero
and cache the current value in c */
++s, /* after loop bump our count */
l[i]=0, /* and zero last player */
i=(i+p*d+n)%n) /* and move index d places
in polarity p direction
adding n so we never go negative
when we make it all mod n */
d=c>2?p*=-1,1:c; /* if number is 3 reverse polarity p
and set d to 1 otherwise set d to
the number */
p=s; /* return s */
}
```
[Answer]
# JavaScript (ES6), 67 bytes
```
a=>(d=1,g=x=>(n=a[x%=w=a.length])&&!(a[x]=0)+g(x+=n-3?n*d:d=w-d))``
```
[Try it online!](https://tio.run/##lY/dCoIwGIbPu4p1kGz515Q6CL66EBk4nFkhW6Skd7@GZj9aYuM9GB8PL8975jdeJNfTpXSlEqk@gOawwwKok0FtfhJ4VC@gAu7lqczKIyOWNcfmyGBF7AzXNkg33Mul2AqoXEFIHOtEyULlqZerDB9wRBkaPEKQ7yM666HBdDT8A3XQoLhFg4GAgyib6GpaHfSp0aJhH6Wm9Rn2jq6/tz4yjppZr7DRWbSBgkagk/6NBp1rN7FFN/oO "JavaScript (Node.js) – Try It Online")
### Commented
```
a => ( // a[] = input array
d = 1, // d = direction
g = x => // g is a recursive function taking the current position x
( n = // n is the player number at the current position
a[ //
x %= // take the wrap-around into account by computing
w = a.length // x modulo w, where w is the length of a[]
] //
) && // stop the recursion if a[x] is equal to 0
!(a[x] = 0) + // otherwise, set it to 0 and increment the final result
g( // do a recursive call:
x += // update the position:
n - 3 ? n * d // add n * d to x if n is not equal to 3
: d = w - d // otherwise, reverse the direction and add it to x
) // end of recursive call
)`` // initial call to g with a zero'ish value for x
```
[Answer]
# [R](https://www.r-project.org/), ~~97~~ ~~87~~ 85 bytes
```
function(p,i=1)sum(while(m<-p[i]){p[i]=0
i=(i+`if`(m>2,T<--T,m*T)-1)%%sum(p|1)+1},!p)
```
[Try it online!](https://tio.run/##bY3fCoIwFMbv9xSLEM7JM2iTunI9hXcRCKJ4oOlIRxfVsxsKsqLgx3fz/btNYx@qth7s1ISuGrnvwBNbjUNwcG/5WoPLlT/zBR@z2r1gC5yW3JTgToaKXKmC3K5ApTFJ5pp/akz1izYe13moQJOMIMqtPIjoGpKRHzcjGVlcI76Ws6WoF/0bMOu1@cgcxfQG "R – Try It Online")
*Edit: -10 bytes by tracking direction of travel (instead of [flipping list of players](https://tio.run/##bY3RCoJAEEXf9ys2QtjBEdqVeqn5kggEURxwdVG3HsxvtxRki4LLZYZzZ243D63Pq6KnufRNPnDbKIdMGmvqvVXuqQGW4VFxXSh7SdyVbzAuTgfBlHGZKUuU4uioK@7KwbmOdcITcmwTDVH0XifcOdiqVK40yiAAuZdHEahBGfRDU5RBKzXi63O6HurV/wbMVm0@MicxvwA))*
*Edit 2: re-arranged to cull 2 more characters*
```
touches=function(p, # p=player numbers
i=1) # i=current player
sum(
while(m<-p[i]){ # while m=number of current player is non-zero
p[i]=0 # set his number to zero
i=i+ # calculate new player:
`if`(m>2, # if m is 3...
T<--T, # flip the direction of travel T and move by this
m*T) # otherwise move ahead by T*m
-1)%%sum(p|1)+1 # -1, modulo number of players, +1
} # (R indices are 1-based)
!p) # sum of null (the return value of 'while')
# and the final number of zeros
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[ć©_#0š„RÀS¤ºª®è.V¼}¾
```
[Try it online](https://tio.run/##yy9OTMpM/f8/@kj7oZXxygZHFz5qmBd0uCH40JJDuw6tOrTu8Aq9sEN7ag/tA6ox1FEw0lEwBCMjMDKOBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/6CPth1bGKxscXfioYV7Q4YbgQ0sO7Tq06tC6wyv0wg7tqT2077@O3qGt/6OjDWN1FKKNQIQxmNABs410IOI6RjpgYUMdKISJgiFEAxRClAH1A5XBdRmBdUGMiQUA).
**Explanation:**
```
[ # Loop indefintely:
ć # Extract head; pop and push remainder-list and first item separately
© # Store this first item in variable `®` (without popping)
_ # Check if its 0
# # And if it is, stop the infinite loop
0š # Prepend a 0 at the start of the list
„RÀ # Push string "RÀ"
S # Convert it to a list of characters: ["R","À"]
# (NOTE: The `ª` already implicitly converts it to a list of
# characters, so this usually isn't necessary; but without it the
# `„RÀ¤` would act like a dictionary string and become "R cry")
¤ # Push its last item (without popping): "À"
º # Double it by mirroring: "ÀÀ"
ª # Append it to the list: ["R","À","ÀÀ"]
®è # Index `®` into this list (0-based and with wraparound,
# so the 3 will index into the first item "R")
.V # Execute it as 05AB1E code
# "R": Reverse the list
# "À": Rotate the list once towards the left
# "ÀÀ": Rotate the list twice towards the left
¼ # Increase the counter_variable by 1
}¾ # After the infinite loop: push the counter_variable
# (after which it is output implicitly as result)
```
[Answer]
# [J](http://jsoftware.com/), 39 bytes
```
1-~&#[:({.(|.*1*@+2*[)0,}.)^:a:]+_4*=&3
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DXXr1JSjrTSq9TRq9LQMtRy0jbSiNQ10avU046wSrWK14020bNWM/2typSZn5CsYKtgqpCkYInOMkDnGEI4RhKODKmmkA9NpDOMDEVSLKcRkHSSELAFRC0VoliAQsoQhWMgIbBTCGjOYnBHMGqgr/gMA "J – Try It Online")
I solved this independently before looking at other answers, but have stumbled on the same high-level approach used by Leo and Surculose Sputum.
A few details appear to be different:
1. `]+_4*=&3` I start by transforming all `3`s in the list into `-1`s, so that I don't have to special case any code. J automatically treats a negative rotation as the reverse direction.
2. Instead of reversing the list when I hit a -1, I multiply all numbers on the list by -1. I avoid special casing here too by always multiplying all numbers on the list by the following quantity: "double current value, add 1, take sign num" `1*@+2*[`. The quantity will be 1 for all values greater than 0, and -1 when the value is -1.
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 66 bytes
```
while($_=$F[$i]){$F[$i]=0;$.*=-1if/3/;$i+=$.+$.*/2/;$i%=@F;$\++}}{
```
[Try it online!](https://tio.run/##K0gtyjH9/788IzMnVUMl3lbFLVolM1azGkLbGlir6GnZ6hpmpukb61urZGrbquhpA4X0jUA8VVsHN2uVGG3t2trq//8NdRSMdBQMwcgIjIz/5ReUZObnFf/X9TXVMzA0@K9bkJgDAA "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 81 bytes
```
s=>s.map(_=>(t=s[r=p%q])?s[p+=t>2?w*=-1:t*w,r]=!++n:0,q=s.length,n=0,p=3*q,w=1)|n
```
[Try it online!](https://tio.run/##VY1NbsMgEIX3PgVdVMI2JgGrWaQachBiNcglbiKCsUHxpnd3kVPyM3qLmW/evDmrq/LteHKhsv23no8wexCeXpTDXyBwAC9HcO9Dk@@8dCUEwXdTARXbhmIiYwNvZWm3azKAp0bbLvwQC2vioC4GMgHLf@382fbW90ZT03f4kEnWoEoglkmemvreEHSDPG4JejgjJ@hmq2NCXN21wI/k@VeCMfChlMyWkS/n/JXzFPv8cZMd6KidUa3Gq72kxb5ZdQQFEEesr8rgkMea/wA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
W⊟θ≔⁺⎇⁼ι²⟦⊟θ⁰⟧⟦⁰⟧⎇⁼ι³⮌θθθI⊕№θ⁰
```
[Try it online!](https://tio.run/##ZY0xC8IwEIV3f0XGC1SoduwkxcEtiFvIEOphAzE1l6Tir4/XOno8jnePj3fjZGmcra/1PTmPAtT8giilOKXkHgGULwluSMHSB86xWJ/ANeIoG6F/aCNaw0dr2P2DHadXXJASbixXr6vfKXIhw2BThksYCZ8YMt5hmAvHkUslT1@r1h2/23TYtBpj6n7xXw "Charcoal – Try It Online") Link is to verbose version of code. Based on @Leo's idea explained better by @SurculoseSputum. Takes input in reverse order. Explanation:
```
W⊟θ
```
Let the current list be `[e, d, c, b, a]`. Remove the last element `a`, which represents the current player. Then if it is non-zero, meaning that they have not played yet:
```
≔⁺⎇⁼ι²⟦⊟θ⁰⟧⟦⁰⟧⎇⁼ι³⮌θθθ
```
Create two lists depending on the value of `a`:
1. `[0]` and the rest of the list `[e, d, c, b]`
2. `[b, 0]` (obtained by popping `b` from the list) and the rest of the list `[e, d, c]`
3. `[0]` and the reverse of the rest of the list `[b, c, d, e]`
Concatenate them together to create the new state of the list.
```
I⊕№θ⁰
```
Print 1 more than the number of `0`s in the list (because we popped `a` so that's no longer in the list).
[Answer]
# perl -M5.010 -a, 84 bytes
```
$:=1;{($;=$F[$,])?do{$:=-$:,$;=1 if$;==3;$"++;$F[$,]=0;$,=($,+$;*$:)%@F;redo}:say$"}
```
[Try it online!](https://tio.run/##LYvNCoMwEITveYogW9AmKfnBS5bQnrz1CUoPghYEaUR7KeKrN12iDOwyM99M/TzWCYoAMmhM4IPBtQQM0DxAPqtrF1cKFXhJoeHDi15wCIUQuDO0o3EJUgCewVenW4Nz38XNL@0Xii0lwyxzzHHLLDecjuWOGX4o@yxCDlFLOLU7aTOZd784fYb4XpK61xdtdFLtHw "Perl 5 – Try It Online")
This just follows the rule of the game, labelling any visited player as 0, and terminating when it encounters a player labelled 0. Steps are counted and printed at the end.
The code in the header section of TIO is just there to make it work on multiple inputs; leave it off for a single line of input.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 63 bytes
```
f=->a,d=1{x,*a=a;x ?1+f[[p,*a].rotate((2-x%2)*d*=1-x/3*2),d]:0}
```
[Try it online!](https://tio.run/##ZY7BDsIgEETv/Yq9mLRIq2yjBw36IYQDSht7kaapCcb67UhJazEmQzLMG3bpHpenczXPT4pqzl6WEsXV0cKZrWshWn@VRWd61VdpirldYUY04Sy3m5JgRrU8bN9OJABCMEnBn@Ax8mXsKYwI51ogyytPKIz9ckqYh1/5fPfTnBTlfv6iaBELCYY5@IdwXrF8YO@pLCp1vYE2MDQUzODrLdSikcA5mKS6a/cB "Ruby – Try It Online")
] |
[Question]
[
# Challenge:
Read input (within visible ASCII range) and output with a few modifications:
1. In each set of 10 characters of the input randomly (50/50):
* replace one character\* (with a random\*\* one within visible ASCII range) (ex. `lumberjack` becomes `lumbeZjack`)
* or remove one character (ex. `lumberjack` becomes `lmberjack`)
\* If the set is of less than 10 characters, you don't have to modify it, but you can.
\*\* The character can be the same as the one input, as long as it's still random.
# Example:
Input: `Go home cat! You're drunk!`
Output: `Go hom cat! YouLre drunk!`
(just a example, since output could be random, don't use as a test case)
# Rules:
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), least characters wins!
[Answer]
# Pyth, ~~27~~ 25 bytes
```
VczTpXNOT?<JOr\ \ÞKC127JK
```
[Test suite available here.](http://pyth.herokuapp.com/?code=VczTpXNOT%3F%3CJOr%5C+%5C%C3%9EKC127JK&input=Go+home+cat%21+You%27re+drunk%21&test_suite=1&test_suite_input=lumberjack%0AGo+home+cat%21+You%27re+drunk%21%0APerhaps+I+should+not+use+test+cases+from+the+question%2C+as+the+output+can+be+different+from+those+examples+and+still+be+correct%21&debug=0)
Thanks to [Maltysen](https://codegolf.stackexchange.com/questions/103355/this-cat-has-bugs-really/103376#comment251583_103376) for shaving off 2 bytes.
# Explanation
```
VczTpXNOT?<JOr\ \ÞKC127JK z autoinitalizes to input, T autoinitializes to 10
czT chop input into strings of length 10, returned as list of strings
V for each string N in this list:
Or\ \Þ randomly pick a char between ' ' (32) and 'Þ' (222)
J and assign it to variable J
KC127 assign the DEL char to variable K
?<J K if J < K:
XNOT J replace a random character in N with J
?<J K else:
XNOT K replace a random character in N with K
p print this string with no trailing newline
```
As is often the case, I feel that this is a bit of a naive method and may be improved upon. Usually I find something obvious while typing up the explanation but nothing jumped out at me this time.
[Answer]
## [\*><>](https://esolangs.org/wiki/Starfish), ~~44~~ ~~46~~ ~~52~~ 50 bytes
```
rl5(?voooo/!|Ou+1Ox:@=?~o~oooo!
ol5(?v" ":/
o;!?l<
```
[Try it here!](https://starfish.000webhostapp.com/?script=E4GwrAFA-Abg9guB6AhAHwPIFcDUBGDADwC4ABAXigD84bEUAoOcaGAIgAI3ikmBuFFBAAeIA)
This uses any ascii character near/above space for the random characters. This always edits the 6th character, unless it's the end of a string and that string's length isn't a multiple of 10. This has a 50% chance to remove the 7th character instead of editing the 6th.
### Input
>
> The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a
> technical standard for floating-point computation established in 1985
> by the Institute of Electrical and Electronics Engineers (IEEE). The
> standard addressed many problems found in the diverse floating point
> implementations that made them difficult to use reliably and portably.
> Many hardware floating point units now use the IEEE 754 standard.
>
>
>
### Output
>
> The IEE Standardfor Float$ng-Point Aithmetic (EEE 754) i a technicl
> standar! for floa!ing-point!computati#n establised in 1985by the
> Insitute of !lectrical#and Electrnics Engi!eers (IEE%). The st!ndard
> add!essed man! problems#found in !he divers! floating oint
> impl!mentation" that mad# them dif!icult to ue reliabl# and port!bly.
> Many!hardware foating po#nt units %ow use th! IEEE 754"standard.
>
>
>
Edit: ~~This answer probably isn't always in the visible ascii range, editing...~~ Fixed.
Edit2: ~~Didn't see there needs to be a 50/50 chance to remove a character, editing again...~~ I believe everything is in order now :).
[Answer]
# [Perl 6](https://perl6.org), ~~78~~ 67 bytes
```
{[~] map {~S/.**{(^.chars).pick}<(./{(' '..'~').pick x Bool.pick}/},.comb(10)}
```
```
{[~] .comb(10)».&{~S/.**{10.rand}<(./{(' '..'~').pick x 2.rand}/}}
```
[Try it](https://tio.run/nexus/perl6#@19anKpQZqaXbM2VW6mglpyfkqpgq1AdXReroJecn5ukYWigeWi3nlp1XbC@npZWtaGBXlFiXkqtjYaefrWGuoK6np56nbqmXkFmcrZChYIRRFa/tparOLFSAWzc@72L3PMVMvJzUxWSE0sUFSLzS9WLUhVSikrzshXf712skJZfpBBnaPD/PwA "Perl 6 – TIO Nexus")
## Explanation:
```
{
[~] # reduce with string concatenation operator
.comb(10)\ # take input and break it into chunks of up-to 10 chars
».\ # on each of them call the following
&{
~ # Stringify the following
S/ # substituted
. # any char
** # repeated
{ 10.rand } # a random number of times
<( # ignore all of that
. # the char to be removed/replaced
/{
( ' ' .. '~' ).pick # choose a character
x # string repeated
2.rand # zero or one times
}/
}
}
```
[Answer]
# Pyth - 21 bytes
```
smO,XdOTOr;\~.DdOTcQT
```
[Try it online here](http://pyth.herokuapp.com/?code=smO%2CXdOTOr%3B%5C%7E.DdOTcQT&input=%22Go%20home%20cat%21%20You%27re%20drunk%21%22&debug=0).
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
The 75-byte applies the transformation to the first character of each group, and only picks from 2 random characters, such as in [the Jelly answer](https://codegolf.stackexchange.com/a/103394/60919) (which OP allowed):
```
from random import*
f=lambda s:s and choice(['','a','b'])+s[1:10]+f(s[10:])
```
[**Try it online!**](https://tio.run/nexus/python3#DYm7DoQgEAD7@4o9G0AttCW5@j6A0lCsPCK5gzUbLPx6pJjMJNMiUwbG4rtSPonr@IqfP@bdIxhtoC9wByUX5CbELLCzC6sms616XewUZa9FW9VOTqXKKIcvwUE5gMM6w02X4ACer/J7D0q1Bw)
This is a recursive function which, every iteration, prepends either nothing, `'a'`, or `'b'`, and then calls itself with the first 10 characters sliced off. The final iteration short circuits at `s and` (an empty string is falsy), avoiding infinite recursion.
The result of all the separate calls are then concatenated, and returned to the context which called the function.
# 120 bytes
Of course, that feels a bit like cheating, so here's one which is completely random:
```
from random import*;r=randint
def f(S):a=S[:10];R=r(0,len(a)-1);print(end=a[:R]+chr(r(32,126))*r(0,1)+a[R+1:]);f(S[10:])
```
[**Try it online!**](https://tio.run/nexus/python3#JYyxDoMgFEX3fgV16XtKE7FJBwhzdxyJAxGIphXMiw79eovpdE9uzr1HpLwwcsmXmJc101Yr0mcxp@3iQ2QRepRO91aKdlBGE7T8ExI4vAtUKxUPQvLaWWmGZpwICB4dF90TsT5lgY2zphFyQFXOrGgLHf9hhOqV2ZSXwEa3cfbN@40C87Sn97VCPH4)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
₀ẇ⟑ẏ℅kP¤"℅℅Ȧ₴
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoDhuofin5Hhuo/ihIVrUMKkXCLihIXihIXIpuKCtCIsIiIsIlwiR28gaG9tZSBjYXQhIFlvdSdyZSBkcnVuayFcIiJd)
```
₀ẇ # Chunks of length 10...
⟑ # Over each...
Ȧ # Replace at ...
ẏ℅ # random index in the input
℅ # A random item of...
℅ # A random item of...
kP # Printable ascii
¤" # Or the empty string
₴ #
```
[Answer]
**Clojure, ~~135~~ 139 bytes**
Edit: Forgot to use `partition-all` instead of `partition`.
```
(fn[i](apply str(flatten(map #(let[r rand-int [b e](split-at(r 9)%)][b(if(<(rand)0.5)""(char(+(r 25)97)))(rest e)])(partition-all 10 i)))))
```
Ungolfed:
```
(def f (fn[i]
(->> i
(partition-all 10)
(map #(let [[begin end] (split-at (rand-int 9) %)]
[begin (if (< 0.5 (rand)) "" (char (+(rand-int 25)97))) (rest end)]))
flatten
(apply str))))
```
Man those function names are long... Anyway, it splits input into partitions of 10 characters, splits them at random point into two halves, randomly injects an empty string or a random character between them and discards the first character of the 2nd half.
[Answer]
## Mathematica 133 Bytes (129 characters)
```
StringReplacePart[#,Table[If[(r=RandomInteger)[]<1,"",FromCharacterCode@r@128],c=⌊StringLength@#/10⌋],Array[{g=10#-9+r@9,g}&,c]]&
```
76 characters to write the names of 8 functions :/
Using the `⌊..⌋` instead of `Floor[]` saves 5 characters, 1 byte.
[Answer]
# Python 3, 129 bytes
```
def f(s):f=id(s)%9+1;print(''.join(j[0:f-1]+chr(33+id(s)%94)*(id(s)//10%2)+j[f:]for j in [s[i:i+10]for i in range(0,len(s),10)]))
```
In order to save some bytes, instead of importing Python's random module, I just did some modulo operations on the id of the string, which should be different every time. For example the program will decide whether or not to remove a char or replace one based on whether or not `id(string)//10` is even (I integer divide by 10 as the last digit will always be even).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15 14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 13 characters
```
2X
s⁵µ¢1¦ṫ¢µ€
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=MlgKc-KBtcK1wqIxwqbhuavCosK14oKs&input=&args=TG9yZW0gSXBzdW0uIFNlZCB1dCBwZXJzcGljaWF0aXMsIHVuZGUgb21uaXMgaXN0ZSBuYXR1cyBlcnJvciBzaXQgdm9sdXB0YXRlbSBhY2N1c2FudGl1bSBkb2xvcmVtcXVlIGxhdWRhbnRpdW0sIHRvdGFtIHJlbSBhcGVyaWFtIGVhcXVlIGlwc2EsIHF1YWUgYWIgaWxsbyBpbnZlbnRvcmUgdmVyaXRhdGlzIGV0IHF1YXNpIGFyY2hpdGVjdG8gYmVhdGFlIHZpdGFlIGRpY3RhIHN1bnQsIGV4cGxpY2Fiby4gTmVtbyBlbmltIGlwc2FtIHZvbHVwdGF0ZW0sIHF1aWEgdm9sdXB0YXMgc2l0LCBhc3Blcm5hdHVyIGF1dCBvZGl0IGF1dCBmdWdpdCwgc2VkIHF1aWEgY29uc2VxdXVudHVyIG1hZ25pIGRvbG9yZXMgZW9zLCBxdWkgcmF0aW9uZSB2b2x1cHRhdGVtIHNlcXVpIG5lc2NpdW50LCBuZXF1ZSBwb3JybyBxdWlzcXVhbSBlc3QsIHF1aSBkb2xvcmVtIGlwc3VtLCBxdWlhIGRvbG9yIHNpdCBhbWV0IGNvbnNlY3RldHVyIGFkaXBpc2NpW25nXSB2ZWxpdCwgc2VkIHF1aWEgbm9uIG51bXF1YW0gW2RvXSBlaXVzIG1vZGkgdGVtcG9yYSBpbmNpW2RpXWR1bnQsIHV0IGxhYm9yZSBldCBkb2xvcmUgbWFnbmFtIGFsaXF1YW0gcXVhZXJhdCB2b2x1cHRhdGVtLiBVdCBlbmltIGFkIG1pbmltYSB2ZW5pYW0sIHF1aXMgbm9zdHJ1bSBleGVyY2l0YXRpb25lbSB1bGxhbSBjb3Jwb3JpcyBzdXNjaXBpdCBsYWJvcmlvc2FtLCBuaXNpIHV0IGFsaXF1aWQgZXggZWEgY29tbW9kaSBjb25zZXF1YXR1cj8gUXVpcyBhdXRlbSB2ZWwgZXVtIGl1cmUgcmVwcmVoZW5kZXJpdCwgcXVpIGluIGVhIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlLCBxdWFtIG5paGlsIG1vbGVzdGlhZSBjb25zZXF1YXR1ciwgdmVsIGlsbHVtLCBxdWkgZG9sb3JlbSBldW0gZnVnaWF0LCBxdW8gdm9sdXB0YXMgbnVsbGEgcGFyaWF0dXIu)**
Replaces or removes the first of every ten characters including that of the last 1-9 if there is such a chunk. Chooses from the, admittedly small, subset of characters: `1`; `2`.
### How?
```
2X - Link 1, flip a coin: no arguments
X - random choice from
2 - 2 (treated as the integers [1,2])
s⁵µ¢1¦ṫ¢µ€ - Main link: string of printable ASCII
s⁵ - split (s) into chunks of size ten (⁵)
µ µ - monadic chain separation
€ - for each chunk
¢ - last link as a nilad
1¦ - apply to index 1 (replace 1st of the 10 char chunk with the chosen integer)
¢ - last link as a nilad
ṫ - tail - if it was 1 this has no effect (50%)
- if it was 2 this discards the replaced character (50%)
- implicit print
```
---
To choose from all of printable ASCII rather than just `1` and `2` (still replacing or removing the 1st character of each chunk) in 21 bytes:
```
s⁵µ32r126¤ỌX¤1¦ṫ2X¤µ€
```
---
For a [fully random version](http://jelly.tryitonline.net/#code=OTVSKzMx4buMWDsKCnPigbXCteG5meKBtVjCpMKp4bmWMljCpMS_4bmZwq5DwqTCteKCrA&input=&args=TG9yZW0gSXBzdW0uIFNlZCB1dCBwZXJzcGljaWF0aXMsIHVuZGUgb21uaXMgaXN0ZSBuYXR1cyBlcnJvciBzaXQgdm9sdXB0YXRlbSBhY2N1c2FudGl1bSBkb2xvcmVtcXVlIGxhdWRhbnRpdW0sIHRvdGFtIHJlbSBhcGVyaWFtIGVhcXVlIGlwc2EsIHF1YWUgYWIgaWxsbyBpbnZlbnRvcmUgdmVyaXRhdGlzIGV0IHF1YXNpIGFyY2hpdGVjdG8gYmVhdGFlIHZpdGFlIGRpY3RhIHN1bnQsIGV4cGxpY2Fiby4gTmVtbyBlbmltIGlwc2FtIHZvbHVwdGF0ZW0sIHF1aWEgdm9sdXB0YXMgc2l0LCBhc3Blcm5hdHVyIGF1dCBvZGl0IGF1dCBmdWdpdCwgc2VkIHF1aWEgY29uc2VxdXVudHVyIG1hZ25pIGRvbG9yZXMgZW9zLCBxdWkgcmF0aW9uZSB2b2x1cHRhdGVtIHNlcXVpIG5lc2NpdW50LCBuZXF1ZSBwb3JybyBxdWlzcXVhbSBlc3QsIHF1aSBkb2xvcmVtIGlwc3VtLCBxdWlhIGRvbG9yIHNpdCBhbWV0IGNvbnNlY3RldHVyIGFkaXBpc2NpW25nXSB2ZWxpdCwgc2VkIHF1aWEgbm9uIG51bXF1YW0gW2RvXSBlaXVzIG1vZGkgdGVtcG9yYSBpbmNpW2RpXWR1bnQsIHV0IGxhYm9yZSBldCBkb2xvcmUgbWFnbmFtIGFsaXF1YW0gcXVhZXJhdCB2b2x1cHRhdGVtLiBVdCBlbmltIGFkIG1pbmltYSB2ZW5pYW0sIHF1aXMgbm9zdHJ1bSBleGVyY2l0YXRpb25lbSB1bGxhbSBjb3Jwb3JpcyBzdXNjaXBpdCBsYWJvcmlvc2FtLCBuaXNpIHV0IGFsaXF1aWQgZXggZWEgY29tbW9kaSBjb25zZXF1YXR1cj8gUXVpcyBhdXRlbSB2ZWwgZXVtIGl1cmUgcmVwcmVoZW5kZXJpdCwgcXVpIGluIGVhIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlLCBxdWFtIG5paGlsIG1vbGVzdGlhZSBjb25zZXF1YXR1ciwgdmVsIGlsbHVtLCBxdWkgZG9sb3JlbSBldW0gZnVnaWF0LCBxdW8gdm9sdXB0YXMgbnVsbGEgcGFyaWF0dXIu) (50/50 remove/replace, uniform random printable ASCII, and a uniformly random character location within each chunk) I have 30 bytes (probably non-optimal):
```
95R+31ỌX;
s⁵µṙ⁵X¤©Ṗ2X¤Ŀṙ®C¤µ€
```
This rotates each chunk left by a random amount, pops the last character off and then calls a random one of the first two links, one of which is empty and the other which concatenates with a random printable ASCII character; it then rotates the chunk right again.
[Answer]
# Python3, ~~188~~ ~~186~~ ~~184~~ 114 characters
```
from random import*
s=input()
for c in[s[i:i+10]for i in range(0,len(s),10)]:print(end=choice(["","x","y"])+c[1:])
```
~~Seems too long. Could probably be shortened a lot with a lambda.~~
Apparently the OP has allowed choosing the random character from a list of two characters and the index of the character to be replaced can be a constant. After the modifications, my answer would've looked exactly the same as [@FlipTacks](https://codegolf.stackexchange.com/a/105194/41754) Python submission, so this is the form I'm staying with.
[@FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack) saved 5 bytes!
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-pl`, 52 bytes
```
gsub(/.{10}/){_1[rand 0..9]=[*" "..?~,""].sample
_1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5BjlLsgqWlJWm6FjdN0otLkzT09aoNDWr1NavjDaOLEvNSFAz09CxjbaO1lBSU9PTs63SUlGL1ihNzC3JSueINayF6oUYs2OWer5CRn5uqkJxYoqgQmV-qXpSqkFJUmpetCFEBAA)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 46 bytes
```
Fi(a<>t){IRR2YiRARR#iRCPAEL{YiRARR#ix}b:bAEy}b
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGaShhPD50KXtJUlIyWWlSQVJSI2lSQ1BBRUx7WWlSQVJSI2l4fWI6YkFFeX1iIiwiIiwiIiwiXCJHbyBob21lIGNhdCEgWW91J3JlIGRydW5rIVwiIl0=)
How?
```
Fi(a<>t){IRR2YiRARR#iRCPAEL{YiRARR#ix}b:bAEy}b
Fi { } - For each in
t - Var for 10
a<>t - Split input into 10 pieces
I - If truthy
RR2 - 0 or 1
Y - Yank (equivalent to (y:a)):
RA - Replace item in at index
i - First input
RR#i - Random int from 0 to length of input
RCPA - Random Printable ASCII character
EL{ } - Else
Y - Yank:
RA - Replace item in at index
i - First input
RR#i - Random int from 0 to length of input
x - Empty string
b: - Assign b to
bAEy - Append y to b
b - Output b
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
TôεžQΩæΩ9ÝΩǝ?
```
Also (potentially) modifies the last part if it's less than 10 characters.
[Try it online](https://tio.run/##AUQAu/9vc2FiaWX//1TDtM61xb5RzqnDps6pOcOdzqnHnT///0dvIGhvbWUgY2F0ISBZb3UncmUgZHJ1bmsh/y0tbm8tbGF6eQ) or [see 10 example outputs at once](https://tio.run/##AUsAtP9vc2FiaWX/VEb/VMO0zrXFvlHOqcOmzqk5w53OqcedP/99XMK2P/9HbyBob21lIGNhdCEgWW91J3JlIGRydW5rIf8tLW5vLWxhenk).
**Explanation:**
```
Tô # Split the (implicit) input-string into parts of size 10
# (where the trailing part is potentially smaller)
ε # Foreach over the parts:
žQ # Push the printable ASCII string constant
Ω # Pop and push a random character from it
æ # Get the powerset of this character, resulting in a pair of an empty
# string "" and the character
Ω # Pop and push a random item from this pair
9Ý # Push list [0,1,2,3,4,5,6,7,8,9]
Ω # Pop and push a random digit from this list
ǝ # Replace the character at that (0-based) index with the chosen ASCII
# character or the empty string
# (if the index is ≥ the length, it does nothing)
? # Pop and print the modified part
```
] |
[Question]
[
*Inspired by [this](http://www.bradyharanblog.com/blog/2016/3/30/math-in-the-archives) Numberphile entry*
## Background
The ***cube distance numbers*** of an integer *n* are defined here as the set of integers that are *x³* distance away for a given *x*. For a simple example, with `n=100` and `x=2`, the *cube distance numbers* are `{92,108}`.
This can be extended into a larger set simply by varying *x*. With `x ∈ {1,2,3,4}` and the same `n=100`, we have the resultant set `{36,73,92,99,101,108,127,164}`.
Let's define ***CD(n,x)*** as the set of all integers `n ± z³` with `z ∈ {1,2,3,...,x}`.
Now we can focus on some of the special properties of these *cube distance numbers*. Of the many special properties that numbers can have, the two properties we're interested in here are *primality* and *prime divisors*.
For the above example *CD(100,4)*, note that `73, 101, 127` are all prime. If we remove those from the set, we're left with `{36,92,99,108,164}`. All prime divisors of these numbers are (in order) `{2,2,3,3,2,2,23,3,3,11,2,2,3,3,3,2,2,41}`, which means we have 5 distinct prime divisors `{2,3,23,11,41}`. We can therefore define that *CD(100,4)* has ***ravenity***1 of `5`.
The challenge here is to write a function or program, in the fewest bytes, that outputs the *ravenity* of a given input.
### Input
* Two positive integers, `n` and `x`, in any convenient format.
### Output
* A single integer describing the *ravenity* of the two input numbers, when calculated with *CD(n,x)*.
### Rules
* Input/output can be via any [suitable method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* [Standard loophole](http://meta.codegolf.stackexchange.com/q/1061/42963) restrictions apply.
* For ease of calculation, you can assume that the input data will be such that *CD(n,x)* will only have positive numbers in the set (i.e., no *CD(n,x)* will ever have negative numbers or zero).
* The function or program should be able to handle input numbers so that `n + x³` fits in your language's native integer data type. For example, for a 32-bit signed integer type, all input numbers with `n + x³ < 2147483648` are possible.
### Examples
```
n,x - output
2,1 - 0 (since CD(2,1)={1,3}, distinct prime divisors={}, ravenity=0)
5,1 - 2
100,4 - 5
720,6 - 11
```
---
### Footnotes
1 - So named because we're not interested in the [*cardinal*](https://en.wikipedia.org/wiki/Cardinal_(bird))ity of the set, but a different type of bird. Since we're dealing with "common" divisors, I chose to use the [common raven](https://en.wikipedia.org/wiki/Common_raven).
[Answer]
# Jelly, 16 bytes
```
ŒRḟ0*3+µÆfFœ-µQL
```
Takes **x** and **n** as command-line arguments, in that order. [Try it online!](http://jelly.tryitonline.net/#code=xZJS4bifMCozK8K1w4ZmRsWTLcK1UUw&input=&args=Ng+NzIw)
### How it works
```
ŒRḟ0*3+µÆfFœ-µQL Main link. Arguments, x, n
ŒR Range; yield [-x, ..., x].
ḟ0 Filter out 0.
*3 Cube each remaining integer.
+ Add n to all cubes.
µ Begin a new, monadic link. Argument: A (list of sums)
Æf Factorize each k in A.
F Flatten the resulting, nested list.
œ- Perform multiset difference with A.
If k in A is prime, Æf returns [k], adding on k too many to the
flat list. Multiset difference with A removes exactly one k from
the results, thus getting rid of primes.
If k is composite (or 1), it cannot appear in the primes in the
flat list, so subtracting it does nothing.
µ Begin a new, monadic link. Argument: D (list of prime divisors)
Q Unique; deduplicate D.
L Compute the length of the result.
```
[Answer]
# Pyth - ~~21~~ ~~19~~ 18 bytes
I wonder if there's a trick.
```
l{st#mP+Q^d3s_BMSE
```
[Test Suite](http://pyth.herokuapp.com/?code=l%7Bst%23mP%2BQ%5Ed3s_BMSE&test_suite=1&test_suite_input=5%0A1%0A100%0A4%0A720%0A6&debug=0&input_size=2).
```
l Length
{ Uniquify
s Combine divisor lists
t# Filter by if more than one element
PM Take prime factorization of each number
+RQ Add each num in list to input
s_BM Each num in list and its negative (with bifurcate)
^R3 Cube each num in list
SE Inclusive unary range - [1, 2, 3,... n] to input
```
[Answer]
# Julia, 107 bytes
```
f(n,x)=endof(∪(foldl(vcat,map(k->[keys(factor(k))...],filter(i->!isprime(i),[n+z^3for z=[-x:-1;1:x]])))))
```
This is a function that accepts two integers and returns an integer.
Ungolfed:
```
function f(n, x)
# Get all cube distance numbers
cubedist = [n + z^3 for z = [-x:-1; 1:x]]
# Filter out the primes and zeros
noprimes = filter(i -> !isprime(i) && i > 0, cubedist)
# Factor each remaining number
factors = map(k -> [keys(factor(k))...], noprimes)
# Flatten the list of factors
flat = foldl(vcat, factors)
# Return the number of unique elements
return endof(∪(flat))
end
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 19 bytes
Code:
```
L3mD(«-Dp_Ïvyf`})Úg
```
Input in the form `x`, `n`. Uses **CP-1252** encoding.
[Try it online!](http://05ab1e.tryitonline.net/#code=TDNtRCjCqy1EcF_Dj3Z5ZmB9KcOaZw&input=NAoxMDA)
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 21 bytes
```
:3^t_h+tZp~)"@Yf!]vun
```
Input is `x`, `n` separated by a newline.
[**Try it online!**](http://matl.tryitonline.net/#code=OjNedF9oK3RacH4pIkBZZiFddnVu&input=Ngo3MjA)
### Explanation
```
: % take n implicitly. Generate [1,2,...,n]
3^ % raise to 3, element-wise
t_h % duplicate, negate, concatenate horizontally: [1,2,...,n,-1,2,...-n]
+ % take x implicitly. Add to that array
t % duplicate
Zp % array that contains true for primes
~ % logical negate
) % apply index to keep only non-primes
" % for each number in that array
@ % push that number
Yf! % prime factors, as a column array
] % end for each
v % concatenate vertically all factors
u % remove repeated factors
n % number of elements of that array. Implicitly display
```
[Answer]
## J, 30 bytes
```
#@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
```
This is a dyadic verb, used as follows:
```
f =: #@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
100 f 4
5
```
[Try it here.](http://tryj.tk)
## Explanation
```
#@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
i: Range from -x to x
( )@ Apply this verb to the range:
^&3 a) every item cubed
| b) absolute value of every item
# c) every item in a) repeated b) times; this removes 0
and produces some harmless duplication
+ Add n to every element of the resulting list
( )@: Apply this verb to the resulting vector:
0&, a) the vector with 0 appended
,@:q: b) flat list of prime divisors in the vector
(and some extra 0s since we flatten an un-even matrix)
-. c) list b) with elements of a) removed; this gets rid of
the extra 0s and all primes that were in the list
#@~.@ Remove duplicates and take length
```
[Answer]
# Python 3.5, 218 198 bytes:
(*Thanks to @Blue for saving me 20 bytes.)*
```
lambda r,n:len({z for z in{v for f in{t for u in[[r-q**3,r+q**3]for q in range(1,n+1)]for t in u if any(t%g<1 for g in range(2,t))}for v in range(2,f)if f%v<1}if all(z%g>0 for g in range(2,z))})
```
A nice one-lined lambda function, although it may be a bit long. Since I was using Python, I had to come up with my own way of finding the composites for the first step, and then the prime divisors for the last step, so it was not very easy, and this was the shortest I, by myself. could get it to. Nonetheless, it does what it needs to, and I am proud of it. :) However, any tips for golfing this down a bit more are welcome.
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 79 bytes
```
(n,x)->omega(factorback(select(k->!isprime(k),vector(2*x,i,n+(i-(i<=x)-x)^3))))
```
Here is my original straightforward implementation. The optimized version above combines the two vectors into a single, slightly more complicated vector.
```
(n,x)->omega(factorback(select(k->!isprime(k),concat(vector(x,i,n-i^3),vector(x,i,n+i^3)))))
```
[Answer]
## Ruby, 138 bytes
```
->(n,x){require'prime'
v=((-x..x).to_a-[0]).map{|i|n+i**3}.reject{|e|Prime.prime?(e)}
Prime.each(v[-1]).select{|i|v.any?{|e|e%i==0}}.size}
```
It was a *pun*y challenge. :-)
[Answer]
# Ruby, ~~132~~ ~~120~~ 114 bytes
I'm well aware that this solution still needs a lot of golfing. Any golfing tips are welcome.
```
require'prime'
->n,x{(-x..x).map{|i|j=n+i**3;j.prime?||(j==n)?[]:j.prime_division.map{|z|z[0]}}.flatten.uniq.size}
```
**Ungolfing:**
```
require 'prime'
def ravenity(n, x)
z = []
(-x..x).each do |i|
j = n + i**3
m = j.prime_division
if j.prime? || j == n
z << []
else
z << m.map{|q| q[0]}
end
return z.flatten.uniq.size
end
```
[Answer]
# Python 3.5 - ~~177~~ ~~175~~ 159 bytes
Any golfing tips welcome :)
```
a=range
p=lambda n:any(n%x<1for x in a(2,n))
r=lambda n,x:len(set(sum([[x for x in a(2,z+1)if z%x<1&1>p(x)]for z in filter(p,[n+z**3for z in a(-x,x+1)])],[])))
```
### Ungolfed:
```
def is_composite(n):
return any(n % x == 0 for x in range(2, n))
def prime_factors(n):
return {x for x in range(2, n+1) if n % x == 0 and not is_composite(x)}
def ravenity(n, x):
nums = [n + z**3 for z in range(-x, x+1)]
nums = filter(is_composite, nums)
factors = map(prime_factors, nums)
factors = sum(factors, [])
#remove duplicates
factors = set(factors)
return len(factors)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 90 bytes
```
Tr[1^Union[First/@Join@@FactorInteger/@Select[z=Range@#2^3;Join@@{#-z,#+z},Not@*PrimeQ]]]&
```
[Try it online!](https://tio.run/##JY3LCsIwFER/pRDoQm/py9aFVO6qoAvxuSoJhBJqwCYQs2rIt8dQN2fOwMDM3L7FzK0ceeiTLjzNULKXkloNvTRfm@NZS4XY89Fqc1JWTMLk@BAfMdph6e5cTQJJxerDf@hItgDZLh4u2uLmauQsbpTSNERVdiDZsUckNE1yTJyroPTgmpVlUcAu5r4qoF07ayGijh4PCqhY2Xgffg "Wolfram Language (Mathematica) – Try It Online")
un-golfed: the code is read mostly from right to left,
```
F[n_, x_] :=
Length[Union[ (* number of unique elements *)
First /@ (* drop multiplicities *)
Join @@ (* join all prime factor lists *)
FactorInteger /@ (* compute prime factors *)
Select[ (* select those... *)
Join @@ {n - Range[x]^3, n + Range[x]^3}, (* ...candidates... *)
Not@*PrimeQ]]] (* ...that are not prime *)
```
] |
[Question]
[
Your task is to find the length of the coastline of a map of islands provided in
an ASCII map. The input map will consist of 1 or more `#` characters that
indicate land, and spaces which indicate water. The coastline is considered to
be any edge between land and water, including inland lakes and islands.
Your solution should be a complete program that reads in a file, a string or an array of
strings, and outputs a single integer to the screen or stdout. Each input line
may have leading or trailing space, and zero or more hash characters. The borders of the map are assumed to be space (water).
Lines may be of different lengths.
## Examples:
```
Input:
##
##
Output: 8
Input:
### ###
##### #
##
Output: 26
Input:
#####
# #
# # #
# #
#####
Output: 36
```
This is code golf, so the smallest byte count wins.
[Answer]
# [Snails](https://github.com/feresum/PMA), 8 bytes
```
A
\#o!\#
```
The `A` option means to count all matching paths rather which starting points a match succeeds from. `\#` consumes a `#`, `o` turns in a cardinal direction, and `!\#` is a negative assertion which succeeds if there is not a `#` in front of us.
[Answer]
# Pyth - ~~25~~ 23 bytes
First it pads the input to a rect. Then counts the occurrences of `" #"` over the 4 permutations of transpositions and reversals of the input+space.
```
/ssm_B++;j;d;CB.t.zd" #
```
[Try it online here](http://pyth.herokuapp.com/?code=%2Fssm_B%2B%2B%3Bj%3Bd%3BCB.t.zd%22+%23&input=++%23%23%23%23%23%0A++%23+++%23%0A++%23+%23+%23%0A++%23+++%23%0A++%23%23%23%23%23&debug=0).
[Answer]
## ES6, ~~123~~ ~~115~~ 114 bytes
```
a=>a.map((s,i)=>s.replace(/#/g,(h,j)=>r+=(s[j-1]!=h)+(s[j+1]!=h)+((a[i-1]||'')[j]!=h)+((a[i+1]||'')[j]!=h)),r=0)|r
```
Edit: Saved 9 bytes thanks to @edc65.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), [42](https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life.2C_the_Universe.2C_and_Everything_.2842.29) bytes
```
c2\FTFt!*Y+2*qFTFtl-4lhhbvv_2X53$Y+t0>)s2/
```
This accepts the input as a cell array of strings, of the form
```
{'#####', '# #', '# # #', '# #', '#####'}
```
It first converts the input to a 2D char array, padding with spaces, and then to a matrix of zeros and ones. 2D-convolution is then applied twice, with two different masks: first for expanding the matrix, second for detecting edges.
[Try it online!](http://matl.tryitonline.net/#code=YzJcRlRGdCEqWSsyKnFGVEZ0bC00bGhoYnZ2XzJYNTMkWSt0MD4pczIv&input=eycjIyMjIycsICcjICAgIycsICcjICMgIycsICcjICAgIycsICcjIyMjIyd9)
[Answer]
# Japt, ~~22~~ 19 bytes
```
4o £UzX è"#%s|#$} x
```
Assumes the input is padded with spaces to form a rectangle. [Test it online!](http://ethproductions.github.io/japt?v=3c017df05a10332dad3e27109fbdd291ef376837&code=NG8go1V6WCDoIiMlc3wjJH0geA==&input=IiAgIyMjIyMKICAjICAgIwogICMgIyAjCiAgIyAgICMKICAjIyMjIyI=)
### How it works
```
// Implicit: U = input string, S = a space
4o £ } // Create the array [0,1,2,3], and map each item X to:
UzX // Rotate U by 90 degrees X times.
è"#%s|#$ // Count the number of "#"s followed by a space, newline, or end-of-string.
x // Sum the resulting array.
```
] |
[Question]
[
# Confidant Numbers
Let `x` be an integer of an arbitrary base, such that `D` is an array of its digits. `x` is a Confidant Number if, for all `n` between `1` and the length of `D`:
```
D[n+1] = D[n] + D[n-1] + ... + D[1] + n
```
---
Take, for example, the number `349` in base 10. If we label the indices for this number, we have the following.
```
Index Digit
----- -----
1 3
2 4
3 9
```
Starting from the first digit, we have `1 + 3 = 4`, which yields the next digit. Then with the second digit we have `3 + 4 + 2 = 9`, which, again, yields the next digit. Thus, this number is a Confidant Number.
---
Given an integer with a base between 1 and 62, calculate all the Confidant Numbers for that base, and output a list of them, separated by newlines. You can assume that there is a finite amount of Confidant Numbers for a given base.
For digits greater than 9, use the alpha characters `A-Z`, and for digits greater than `Z` use the alpha characters `a-z`. You will not have to worry about digits beyond `z`.
They do not have to be output in any particular order.
---
Sample Input:
```
16
```
Sample Output:
```
0
1
2
3
4
5
6
7
8
9
A
B
C
D
E
F
12
23
34
45
56
67
78
89
9A
AB
BC
CD
DE
EF
125
237
349
45B
56D
67F
125B
237F
```
This is code golf, so the shortest code wins. Good luck!
(Thanks to Zach for helping out with the formatting and pointing out a few problems.)
[Answer]
## Python 2, 104 bytes
```
n=input()
for i in range(n):
s=''
while i<n:s+=chr(48+i+(i>9)*7+i/36*6);print s;i+=n**0**i+i*(s>s[:1])
```
This uses the following observation: in a confidant number, the digit `i` is followed by `2*i+1`, except it's `i+1` instead for the second digit. By trying all possible first digits and adding more digits until they get too big, we can generate all confidant numbers.
We compute the character corresponding the number `i` as `chr(48+i+(i>9)*7+i/36*6)`, which shifts it into the number, uppercase letter, or uppercase letter range for the intervals `0-9, 10-35, 36-61`.
Then, we increase `i` via `i+=i+1` with two adjustments. To make this instead `i+=1` after the first digit, we add `i` conditional on `s` having more than `1` chars. Also, we need to avoid numbers starting with 0 from being printed, while at the same time allowing `0`. To do this, we do a hack that causes `i=0` to fail the condition `i<n` on the next loop by adding `n` to it. This is done by replacing `1` with `n**0**i`, which right-associates to `n**(0**i)`, which equals `n**(i==0)` or `n if i==0 else 1`.
[Answer]
# Python 3, ~~201~~ 200 bytes
```
n=int(input())
X=[[i]for i in range(1,n)]
for x in X:
y=sum(x)+len(x)
if y<n:X.append(x+[y])
X=[[0]]+X
print('\n'.join(''.join(map(lambda x:[str(x),chr(x+55),chr(x+61)][(x>9)+(x>35)],x))for x in X))
```
### Explanation
The key insight here is that given a sequence `x` (like, say, `[1,2,5]`), you can get the next term in the sequence with `sum(x)+len(x)`, which gives `11` in this case (`B`). Check to see if this is less than `n`, and if it is, add the extended sequence to the list of all such sequences (seeded by all single digits).
```
[str(x),chr(x+55),chr(x+61)][(x>9)+(x>35)]
```
This is how I map sequence items to characters. These are `''.join`ed together and then printed, separated by newlines.
[Answer]
## GS2, 44 bytes
```
26 c8 2f 08 4d 08 40 64 45 2e 30 42 67 40 24 d0
75 d3 20 e1 35 09 cb 20 23 78 22 09 34 30 e0 32
08 86 84 30 85 30 92 58 09 34 10
```
It produces the numbers in a different order, but the problem description doesn't specify, so I'm going for it! Here's the output for input of 16.
```
1
12
125
125B
2
23
237
237F
3
34
349
4
45
45B
5
56
56D
6
67
67F
7
78
8
89
9
9A
A
AB
B
BC
C
CD
D
DE
E
EF
F
0
```
Here are the mnemonic equivalents for the bytes:
```
read-num dec save-a
range1
{
itemize
{
dup
sum
over length
add
swap right-cons
dup last push-a le
push-d eval
block2 when
}
save-d eval
init inits tail
} map
+ ' fold
{
ascii-digits
uppercase-alphabet catenate
lowercase-alphabet catenate
select
show-line
} map
0
```
[Answer]
# CJam, ~~46~~ ~~42~~ 40 bytes
```
ri:R,{Q{+_A,s'[,_el^+f=oNo__,+:+_R<}g&}*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri%3AR%2C%7BQ%7B%2B_A%2Cs'%5B%2C_el%5E%7Cf%3DoNo__%2C%2B%3A%2B_R%3C%7Dg%26%7D*&input=16).
### How it works
```
ri:R e# Read an integer from STDIN and save it in R.
, e# Push [0 ... R-1].
{ e# Fold; For each element but the first:
e# Push the element.
Q e# Push an empty array (accumulator for base-R digits).
{ e# Do:
+ e# Concatenate the integer and the array on the stack.
_ e# Push a copy of the result.
A,s'[,_el^+ e# Push "0...0A...Za...z".
e# See: http://codegolf.stackexchange.com/a/54348
f= e# Replace each base-R digit with the corresponding character.
oNo e# Print the resulting string and a linefeed.
_ e# Push another copy of the accumulator.
_,+ e# Append its length to it.
:+ e# Add all digits (including the length).
_R< e# Push a copy of the result and compare it with R.
}g e# If the sum is less than R, it is a valid base-R digit,
e# the comparison pushes 1, and the loop is repeated.
& e# Intersect the accumulator with an integer that is greater
e# or equal to R. This pushes an empty array.
}* e#
```
At the end **0** and a few empty arrays are left on the stack, so the interpreter prints `0`.
[Answer]
# Pyth, 38 bytes
```
0jms@L+s`MT+rG1Gdf<eTQsm.u+N+lNsNQ]dSQ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=0jms%40L%2Bs%60MT%2BrG1Gdf%3CeTQsm.u%2BN%2BlNsNQ%5DdSQ&input=16)
### Explanation:
```
0jms@L+s`MT+rG1Gdf<eTQsm.u+N+lNsNQ]dSQ implicit: Q = input base
0 print 0
m SQ map each d of [1, 2, ..., Q] to:
.u Q]d start with N=[d], apply v Q times
+N+lNsN add (len(N) + sum(N)) to N
gives all intermediate results
s join to one list of candidates
f<eTQ filter those, where every digit < Q
ms@L+s`MT+rG1Gd convert numbers to letters 0-9A-Za-z
j print each on separate line
```
[Answer]
# gawk, 111 bytes
```
{for(n=$0;n>c=++i;)for(j=0;n>$++j=c+=j;print"")for(c=k=0;k++<j;c+=$k)printf"%c",$k+($k>9?$k>35?61:55:48)}$0="0"
```
For every starting digit from `1` to `base-1` it calculates the next digits, and while these are lower than the base we still have a confidant number. Calculating the next digit while printing. Finally prints `0`.
] |
[Question]
[
When students are first taught about the [proof](http://en.wikipedia.org/wiki/Mathematical_proof) technique of [mathematical induction](http://en.wikipedia.org/wiki/Mathematical_induction), a common example is the problem of tiling a 2N×2N grid with L-shaped [trominoes](http://en.wikipedia.org/wiki/Tromino), leaving one predetermined grid space empty. (N is some nonnegative integer.)
I will leave it to you to go over the proof if you do not already know it. [There are many resources that discuss it.](http://goo.gl/83ZxPL)
Your task here is to write a program that takes in a value for N, as well as the coordinates of the grid space to leave empty, and prints an ASCII representation of the resulting tromino tiled grid.
The character `O` will fill the empty space, and the 4 rotations of our tromino will look like this:
```
|
+-
|
-+
-+
|
+-
|
```
(Yes, it can be ambiguous which `+` goes with which `-` and `|` for certain arrangements, but that's ok.)
Your program must work for N = 0 (for a 1×1 grid) up to at least N = 8 (for a 256×256 grid). It will be given x and y values that are the coordinates for the `O`:
* x is the horizontal axis. x = 1 is the left grid edge, x = 2N is the right grid edge.
* y is the vertical axis. y = 1 is the top grid edge, y = 2N is the bottom grid edge.
Both x and y are always in the range [1, 2N].
So for a given N, x, and y, your program must print a 2N×2N grid, tiled completely with L-shaped trominoes, except for the x, y grid coordinate which will be an `O`.
## Examples
If N = 0, then x and y must both be 1. The output is simply
```
O
```
If N = 1, x = 1, and y = 2, the output would be
```
-+
O|
```
N = 2, x = 3, y = 2:
```
+--+
||O|
|+-|
+--+
```
N = 2, x = 4, y = 1:
```
+-|O
||+-
|+-|
+--+
```
N = 3, x = 3, y = 6 (e.g. the image on [this page](https://www.math.hmc.edu/funfacts/ffiles/20002.4.shtml)):
```
+--++--+
|+-||-+|
||+--+||
+-|-+|-+
+--+||-+
||O|-+||
|+-||-+|
+--++--+
```
## Details
* You may write a function that takes the 3 integers instead of writing an entire program. It should print or return the grid string.
* Take input from stdin, command line, (or function args if you write function).
* The output may optionally contain a single training newline.
* You are not *required* to use the tiling method that the proof normally suggests. It only matters that the grid is filled with L-shaped trominoes besides the `O`. (Trominoes may not be cut or go out of the grid bounds.)
**The shortest code in bytes wins. Tiebreaker is earlier post.** ([Handy byte counter.](https://mothereff.in/byte-counter))
[Answer]
# C, 399 bytes
```
char*T=" |-+ | +-| ",*B;w;f(N,x,y,m,n,F,h,k,i,j){w=B?F=0,w:1<<N|1;char b[N?w*w:6];for(k=w;k--;)b[k*w-1]=10;B=!B?F=1,m=0,n=0,x--,y--,b:B;if(N>1){h=1<<N-1;i=x>--h,j=y>h;while(++k<4)if(k%2-i||k/2-j)f(N-1,!(k%2)*h,!(k/2)*h,m+k%2*(h+1),n+k/2*(h+1));f(1,h&i,h&j,m+h,n+h);h++;f(N-1,x-h*i,y-h*j,m+h*i,n+h*j);}else while(++k<4)B[w*(n+k/2)+m+k%2]=T[5*x+2*y+k];if(F)B[y*w+x]=79,B[w*w-w-1]=0,puts(N?B:"O"),B=0;}
```
No one's come forward with anything yet, so I'll offer up a meager solution. Mark my words, this is not the end. This will get shorter.
We define a function `f` that takes 10 arguments, but you need only call it with `f(N, X, Y)`. Output goes to stdout.
Here's a readable version:
```
char*T=" |-+ | +-| ",*B;
w;
f(N,x,y,m,n,F,h,k,i,j){
w=B?F=0,w:1<<N|1;
char b[N?w*w:6];
for(k=w;k--;)
b[k*w-1]=10;
B=!B?F=1,m=0,n=0,x--,y--,b:B;
if(N>1){
h=1<<N-1;
i=x>--h,j=y>h;
while(++k<4)
if(k%2-i||k/2-j)
f(N-1,!(k%2)*h,!(k/2)*h,m+k%2*(h+1),n+k/2*(h+1));
f(1,h&i,h&j,m+h,n+h);
h++;
f(N-1,x-h*i,y-h*j,m+h*i,n+h*j);
}
else
while(++k<4)
B[w*(n+k/2)+m+k%2]=T[5*x+2*y+k];
if(F)B[y*w+x]=79,B[w*w-w-1]=0,puts(N?B:"O"),B=0;
}
```
A taste of output for `f(3, 2, 7)`:
```
+--++--+
|+-||-+|
||+--+||
+-|-+|-+
+--+||-+
|-+|-+||
|O|||-+|
+--++--+
```
It's a fairly simple recursive algorithm to fill the grid. I may upload an animation of the algorithm drawing trominoes since I think it's pretty neat. As usual, feel free to ask questions and shout at me if my code breaks!
Try it [online](http://ideone.com/n6Bb8L)!
[Answer]
# Python 3, ~~276~~ ~~265~~ 237 bytes
My first Python golf so I'm sure there is a lot of room for improvement.
```
def f(n,x,y,c='O'):
if n<1:return c
*t,l,a='x|-+-|',2**~-n;p=(a<x)+(a<y)*2
for i in 0,1,2,3:t+=(p-i and f(n-1,1+~i%2*~-a,1+~-a*(1-i//2),l[p+i])or f(n-1,1+~-x%a,1+~-y%a,c)).split(),
u,v,w,z=t;return'\n'.join(map(''.join,zip(u+w,v+z)))
```
10 bytes saved thanks to @xnor and 6 more bytes thanks to @Sp3000.
The function returns a string. Example usage:
```
>>>print(f(3,3,6))
+--++--+
|+-||-+|
||+--+||
+-|-+|-+
+--+||-+
||O|-+||
|+-||-+|
+--++--+
```
[Answer]
# JavaScript (ES6) 317 ~~414~~
A lot of work to golf, but still quite long.
```
T=(b,x,y)=>
(F=(d,x,y,f,t=[],q=y<=(d>>=1)|0,
b=d?x>d
?q
?F(d,x-d,y,0,F(d,1,1,2))
:F(d,1,d,2,F(d,x-d,y-d))
:F(d,1,d,1-q,F(d,1,1,q)):0,
r=d?(x>d
?F(d,d,d,1-q,F(d,d,1,q))
:q
?F(d,x,y,1,F(d,d,1,2))
:F(d,d,d,2,F(d,x,y-d))
).map((x,i)=>x.concat(b[i])):[[]]
)=>(r[y-1][x-1]='|+-O'[f],r.concat(t))
)(1<<b,x,y,3).join('\n').replace(/,/g,'')
```
Run snippet to test (better looking using Unicode block characters - but even a bit longer)
```
T=(b,x,y)=>
(F=(d,x,y,f,t=[],q=y<=(d>>=1)|0,
b=d?x>d
?q
?F(d,x-d,y,0,F(d,1,1,6))
:F(d,1,d,6,F(d,x-d,y-d))
:F(d,1,d,q,F(d,1,1,q+1)):0,
r=d?(x>d
?F(d,d,d,q+3,F(d,d,1,q+4))
:q
?F(d,x,y,1,F(d,d,1,6))
:F(d,d,d,6,F(d,x,y-d))
).map((x,i)=>x.concat(b[i])):[[]]
)=>(
r[y-1][x-1]='┐│┘┌│└─O'[f],r.concat(t)
))(1<<b,x,y,7).join('\n').replace(/,/g,'')
loop=_=>{
var x=X.value|0, y=Y.value|0, n=N.value|0;
var b=1<<n, cur=1<<(n+n);
(L=_=>{
--cur;
O.innerHTML=T(n,(cur&(b-1))+1,(cur>>n)+1);
cur&&setTimeout(L,100);
})()
}
tile=_=>{
var x=X.value|0, y=Y.value|0, n=N.value|0;
O.innerHTML=T(n,x,y);
}
tile()
```
```
input { width: 3em }
pre { font-size: 10px; line-height: 10px }
```
```
N: <input id=N value=4> X: <input id=X value=5> Y: <input id=Y value=3>
<button onclick="tile()">Tile</button>
<button onclick="loop()">Loop</button>
<pre id=O></pre>
```
[Answer]
# Haskell, 250 240 236 bytes
```
c=cycle
z o(#)(x,y)=zipWith o(1#x)(2#y)
f n x y=unlines$(z(+)(\m w->[c[0,m]!!div(w-1)(2^(n-k))|k<-[1..n]])(x,y),"O")%n
(_,x)%0=[x]
((p:o),x)%k=z(++)(\_ q->((o,x):c[(c[3-q],[" |-+| +--+ |+-|"!!(4*p+q)])])!!abs(p-q)%(k-1))=<<[(0,1),(2,3)]
```
This follows the inductive solution to the problem closely. The point to mark is represented by a sequence of numbers from 0 to 3 which indicate which quadrant holds the point at each zoom level; this is initially calculated by the expression starting with z(+). The operator (%) combines pictures for the four quadrants into a single picture. Pictures for the unmarked quadrants are generated by drawing marked quadrants with the mark somewhere near the middle, drawn with a mark of "+-|" as appropriate to build the central L tile.
Funny business: For golf reasons, the subexpression
```
\m w->[c[0,m]!!div(w-1)(2^(n-k))|k<-[1..n]]
```
(which more or less computes the bit sequence for a number) is hilariously inefficient --- it determines if w / 2^p is odd or even by looking up the (w / 2^p)th element of a list.
*Edit:* Saved 10 bytes by inlining the bit calculation and replacing an if/then/else with an indexing operation.
*Edit2:* Saved four more bytes by switching a function back to an operator.
@randomra, the race is on!
Demo:
```
λ> putStr $ f 4 5 6
+--++--++--++--+
|+-||-+||+-||-+|
||+--+||||+--+||
+-|+-|-++-|-+|-+
+-||-+-++--+||-+
||+-O||||-+|-+||
|+-||-+|-+|||-+|
+--++--+||-++--+
+--++-|-+|-++--+
|+-|||+--+|||-+|
||+-|+-||-+|-+||
+-||+--++--+||-+
+-|+-|-++-|-+|-+
||+--+||||+--+||
|+-||-+||+-||-+|
+--++--++--++--+
```
[Answer]
# IDL 8.3+, 293 bytes
This is too long, I'm trying to cut it down but I haven't gotten there yet.
```
function t,n,x,y
m=2^n
c=['|','+','-']
b=replicate('0',m,m)
if m eq 1 then return,b
h=m/2
g=h-1
k=[1:h]
o=x gt h
p=y gt h
q=o+2*p
if m gt 2then for i=0,1 do for j=0,1 do b[i*h:i*h+g,j*h:j*h+g]=t(n-1,i+2*j eq q?x-i*h:k[i-1],i+2*j eq q?y-j*h:k[j-1])
b[g+[1-o,1-o,o],g+[p,1-p,1-p]]=c
return,b
end
```
Outputs:
```
IDL> print,t(1,1,2)
- +
0 |
IDL> print,t(2,3,2)
+ - - +
| | 0 |
| + - |
+ - - +
IDL> print,t(2,4,1)
+ - | 0
| | + -
| + - |
+ - - +
IDL> print,t(3,3,6)
+ - - + + - - +
| + - | | - + |
| | + - - + | |
+ - | - + | - +
+ - - + | | - +
| | 0 | - + | |
| + - | | - + |
+ - - + + - - +
```
And, uh... just for fun...
```
IDL> print,t(6,8,9)
+ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - +
| + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + |
| | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | |
+ - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - +
+ - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - +
| | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | |
| + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + |
+ - - + + - | - + | - + + - - + + - - + + - | - + | - + + - - + + - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - +
+ - - + + - | 0 | | - + + - - + + - - + + - - + | | - + + - - + + - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - +
| + - | | | + - - + | | | - + | | + - | | - + | - + | | | - + | | + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + |
| | + - | + - | | - + | - + | | | | + - - + | | | - + | - + | | | | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | |
+ - | | + - - + + - - + | | - + + - | - + | - + + - - + | | - + + - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - +
+ - | + - | - + + - | - + | - + + - - + | | - + + - | - + | - + + - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - +
| | + - - + | | | | + - - + | | | - + | - + | | | | + - - + | | | | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | |
| + - | | - + | | + - | | - + | - + | | | - + | | + - | | - + | | + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + |
+ - - + + - - + + - - + + - - + | | - + + - - + + - - + + - - + + - - + + - - + + - - + + - | - + | - + + - - + + - - + + - - +
+ - - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - - +
| + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + | | + - | | - + | | + - | | - + | - + | | | - + | | + - | | - + |
| | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | | | | + - - + | | | | + - - + | | | - + | - + | | | | + - - + | |
+ - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - + + - | + - | - + + - | - + | - + + - - + | | - + + - | - + | - +
+ - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - + + - | | + - - + + - - + | | - + + - | - + | - + + - - + | | - +
| | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | | | | + - | + - | | - + | - + | | | | + - - + | | | - + | - + | |
| + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + | | + - | | | + - - + | | | - + | | + - | | - + | - + | | | - + |
+ - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + | | - + + - - +
+ - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + | | - + + - - + + - - + + - | - + | - + + - - +
| + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | - + | - + | | | - + | | + - | | | + - - + | | | - + |
| | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - - + | | | - + | - + | | | | + - | + - | | - + | - + | |
+ - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | - + | - + + - - + | | - + + - | | + - - + + - - + | | - +
+ - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - - + | | - + + - | - + | - + + - | + - | - + + - | - + | - +
| | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | - + | - + | | | | + - - + | | | | + - - + | | | | + - - + | |
| + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | - + | | | - + | | + - | | - + | | + - | | - + | | + - | | - + |
+ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - - + + - - + + - - + + - - + + - - +
+ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + + - - + + - - + + - - + + - - +
| + - | | - + | | + - | | - + | | + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + | | + - | | - + | | + - | | - + |
| | + - - + | | | | + - - + | | | | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | | | | + - - + | | | | + - - + | |
+ - | + - | - + + - | - + | - + + - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - + + - | + - | - + + - | - + | - +
+ - | | + - - + + - - + | | - + + - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - + + - | | + - - + + - - + | | - +
| | + - | + - | | - + | - + | | | | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | | | | + - | + - | | - + | - + | |
| + - | | | + - - + | | | - + | | + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + | | + - | | | + - - + | | | - + |
+ - - + + - | + - | - + + - - + + - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - | - + | - + + - - +
+ - - + + - | | + - - + + - - + + - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + | | - + + - - +
| + - | | | + - | + - | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | - + | - + | | | - + |
| | + - | + - | | | + - - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - - + | | | - + | - + | |
+ - | | + - - + + - | + - | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | - + | - + + - - + | | - +
+ - | + - | - + + - | | + - - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - - + | | - + + - | - + | - +
| | + - - + | | | | + - | + - | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | - + | - + | | | | + - - + | |
| + - | | - + | | + - | | | + - | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | - + | | | - + | | + - | | - + |
+ - - + + - - + + - - + + - | | + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - - +
+ - - + + - - + + - - + + - | + - | - + + - - + + - - + + - - + + - - + + - - + + - - + + - | - + | - + + - - + + - - + + - - +
| + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + | | + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + |
| | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | | | | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | |
+ - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - + + - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - +
+ - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - + + - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - +
| | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | | | | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | |
| + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + | | + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + |
+ - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - +
+ - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - + + - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - +
| + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + |
| | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | |
+ - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - +
+ - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - +
| | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | |
| + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + |
+ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - +
```
[Answer]
# Ruby Rev 1, 288
As an anonymous lambda literal. Shown in test program (the lambda literal is `->(n,a,b){...}` )
```
g=
->(n,a,b){
$x=a-1
$y=b-1
$a=Array.new(m=2**n){"|"*m}
def t(u,v,m,r,f)
(m/=2)==1?$a[v+1-r/2%2][u,2]='-+-'[r%2,2]:0
if m>1
4.times{|i|i==r ?t(u+m/2,v+m/2,m,r,0):t(u+i%2*m,v+i/2*m,m,3-i,0)}
f>0?t(u+r%2*m,v+r/2*m,m,2*$x/m&1|$y*4/m&2,1):0
end
end
t(0,0,m,2*$x/m|$y*4/m,1)
$a[$y][$x]='O'
$a
}
n=gets.to_i
a=gets.to_i
b=gets.to_i
puts(g.call(n,a,b))
```
# Ruby Rev 0, 330 ungolfed
Currently the only golfing I'm claiming is elimination of comments, unnecessary newlines and indents.
This is my first proper algorithm encoded in Ruby and it's been hard work. I'm sure there's at least 50 characters than can be eliminated, but I've done enough for now. There are some real horrors, for example the input. That can probably be fixed by a function or lambda instead of a program, but the inner function `t` that draws the trominoes still needs access to the global variables. I'll have to figure out the syntax for that.
A feature of my answer which is not present in the others, is that I initialize an array of strings with `|` characters. That means I only have to draw the `+-` or `-+`, which are next to each other on the same line.
```
m=2**gets.to_i #get n and store 2**n in m
$x=gets.to_i-1 #get x and y, and...
$y=gets.to_i-1 #convert from 1-indexed to 0-indexed
$a=Array.new(m){"|"*m} #array of m strings length m, initialized with "|"
def t(u,v,m,r,f) #u,v=top left of current field. r=0..3= quadrant containing O. f=flag to continue surrounding O
m/=2
if m==1 then $a[v+1-r/2%2][u,2] ='-+-'[r%2,2];end #if we are at char level, insert -+ or +- (array already initialized with |'s)
if m>1 then #at higher level, 4 recursive calls to draw trominoes of next size down
4.times{|i| i==r ? t(u+m/2,v+m/2,m,r,0):t(u+i%2*m,v+i/2*m,m,3-i,0)}
f>0?t(u+r%2*m,v+r/2*m,m,2*$x/m&1|$y*4/m&2,1):0 #then one more call to fill in the empty quadrant (this time f=1)
end
end
$a[$y][$x]='O' #fill in O
t(0,0,m,2*$x/m&1|$y*4/m&2,1) #start call. 2*x/m gives 0/1 for left/right quadrant, similarly 4*y/m gives 0/2 for top/bottom
puts $a #dump array to stdout, elements separated by newlines.
```
[Answer]
# Haskell, 170 bytes
```
r=reverse
g n s x y|n<1=[s]|x>k=r<$>g n s(2^n+1-x)y|y>k=r$g n s x$2^n+1-y|0<1=zipWith(++)(h s x y++h"-"k 1)$h"|"1 k++h"+"1 1 where m=n-1;k=2^m;h=g m
f n x=unlines.g n"O"x
```
[Run online at Ideone](http://ideone.com/V1rXjp)
Example run:
```
*Main> putStr(f 3 3 6)
+--++--+
|+-||-+|
||+--+||
+-|-+|-+
+--+||-+
||O|-+||
|+-||-+|
+--++--+
```
] |
[Question]
[
Given a sequence of numbers, find the minimum number of jumps to go from the starting position to the end and come back to the starting position again.
Each element of the sequence denotes the maximum number of moves that one can move from that position.
At any position, you can make a jump of at max k moves, where k is the value stored at that position. After reaching the end, you can use only those positions for jumping which have not been used previously for jumping.
The input will be given as a sequence of numbers separated by single-spaces.
Output should be a single number which is the minimum number of jumps used.
If its not possible to go to the end and come back to the starting position, then print **-1**
**Input:**
2 4 2 2 3 4 2 2
**Output:**
6 (3 to reach end and 3 to come back)
**Input**
1 0
**Output**
-1
**Note**
* Assume all the numbers of the sequence are non-negative
**EDIT 1**
The line "Thus, it should be clear that one can always jump from the last position." might be confusing, so I removed it from the question. It will have no effect on the question.
**Winning Criteria :**
The winner will be the one with the shortest code.
[Answer]
## APL(Dyalog), 116
```
f←{{⊃,/{2>|≡⍵:⊂⍵⋄⍵}¨⍵}⍣≡1{(⍴⍵)≤y←⊃⍺:⍵⋄⍵[y]=0:0⋄x←⍵⋄x[y]←0⋄∇∘x¨,∘⍺¨y+⍳y⌷⍵},⍵}
{0≡+/⍵:¯1⋄(⌊/+/0=⍵)-+/0=x}↑⊃,/f¨⌽¨f x←⎕
```
**Test cases**
```
2 4 2 2 3 4 2 2
6
1 0
¯1
1 1 1 1
¯1
3 1 2 0 4
3
1
0
```
---
**Approach**
The approach is a brute force search using a recursive function.
Starting from position 1, set value at the current position to 0 and generate an array of the positions which can be jumped to from the current position. Pass the new position and the modified array to itself. Base cases are when the value at the current position is 0 (can't jump) or reaching the end.
Then, for each of the array generated, reverse it and do the search again. Because jumped positions are set to 0, we can't jump from there again.
For those array which we reached the end, find the ones which have the minimum number of 0's. Subtracting from it the number of 0's in the initial array gives the actual number of jumps performed.
[Answer]
# Mathematica, ~~197~~ 193 chars
Brute force.
```
Min[Length/@Select[Join[{1},#,{n},Reverse@#2]&@@@Tuples[Subsets@Range[3,n=Length[i=FromDigits/@StringSplit@InputString[]]]-1,2],{}⋃#==Sort@#∧And@@Thread[i[[#]]≥Abs[#-Rest@#~Append~1]]&]]/.∞->-1
```
[Answer]
# Mathematica 351
[Note: This is not yet fully golfed; Also, the input needs to be adjusted to fit the required format. And the no-jumping-on-the-same-position-twice rule needs to be implemented. There are also some code formatting issues that need addressing. But it's a start.]
A graph is constructed with nodes corresponding to each position, i.e. each input digit representing a jump. `DirectedEdge[node1, node2]` signifies that it is possible to jump from node1 to node 2. Shortest paths are found from start to end and then from end to start.
```
f@j_:=
(d={v=FromCharacterCode/@(Range[Length[j]]+96),j}\[Transpose];
w[n_,o_:"+"]:={d[[n,1]],FromCharacterCode/@(ToCharacterCode[d[[n,1]]][[1]]+Range[d[[n,2]]]
If[o=="+",1,-1])};
y=Graph[Flatten[Thread[DirectedEdge[#1,#2]]&@@@(Join[w[#]&/@Range[8],w[#,3]&/@Range[8]])]];
(Length[Join[FindShortestPath[y,v[[1]],v[[-1]]],FindShortestPath[y,v[[-1]],v[[1]]]]]-2)
/.{0-> -1})
```
**Usage**
```
f[{2,4,2,2,3,4,2,2}]
f[{3,4,0,0,6}]
f[{1,0}]
```
>
> 6
>
> 3
>
> -1
>
>
>
[Answer]
# Python 304
I think this new approach solves (I hope!) all the issues regarding the [2,0] case and similar:
In this version the input sequence is traversed (if possible) until the end and then
we start the process again with the reversed sequence. Now we can garantee that for every valid solution one of the the jumps lands on the last element.
```
## Back and forward version
# Changed: now the possible jumps from a given L[i] position
# are at most until the end of the sequence
def AvailableJumps(L,i): return range(1,min(L[i]+1,len(L)-i))
# In this version we add a boolean variable bkw to keep track of the
# direction in which the sequence is being traversed
def Jumps(L,i,n,S,bkw):
# If we reach the end of the sequence...
# ...append the new solution if going backwards
if (bkw & (i == len(L)-1)):
S.append(n)
else:
# ...or start again from 0 with the reversed sequence if going forward
if (i == len(L)-1):
Jumps(L[::-1],0,n,S,True)
else:
Laux = list(L)
# Now we only have to disable one single position each time
Laux[i] = 0
for j in AvailableJumps(L,i):
Jumps(Laux,i+j,n+1,S,bkw)
def MiniJumpBF(L):
S = []
Jumps(L,0,0,S,False)
return min(S) if (S) else -1
```
These are the golfed versions:
```
def J(L,i,n,S,b):
if (i == len(L)-1):
S.append(n) if b else J(L[::-1],0,n,S,True)
else:
L2 = list(L)
L2[i] = 0
for j in range(1,min(L[i]+1,len(L)-i)):
J(L2,i+j,n+1,S,b)
def MJ(L):
S = []
J(L,0,0,S,False)
return min(S) if (S) else -1
```
And some examples:
```
MJ( [2, 4, 2, 2, 3, 4, 2, 2] ) --> 6
MJ( [0, 2, 4, 2, 2, 3, 4, 2, 2] ) --> -1
MJ( [3, 0, 0, 1, 4] ) --> 3
MJ( [2, 0] ) --> -1
MJ( [1] ) --> 0
MJ( [10, 0, 0, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 0, 0, 10] ) --> 4
MJ( [3, 2, 3, 2, 1] ) --> 5
MJ( [1, 1, 1, 1, 1, 1, 6] ) --> 7
MJ( [7, 1, 1, 1, 1, 1, 1, 7] ) --> 2
```
[Answer]
## R - 195
```
x=scan(nl=1)
L=length
n=L(x)
I=1:(2*n-1)
P=n-abs(n-I)
m=0
for(l in I)if(any(combn(I,l,function(i)all(P[i[c(1,k<-L(i))]]==1,n%in%i,L(unique(P[i]))==k-1,diff(i)<=x[P][i[-k]])))){m=l;break}
cat(m-1)
```
Simulation:
```
1: 2 4 2 2 3 4 2 2 # everything after 1: is read from stdin
6 # output is printed to stdout
1: 1 0 # everything after 1: is read from stdin
-1 # output is printed to stdout
```
De-golfed:
```
x = scan(nlines = 1) # reads from stdin
n = length(x)
index = 1:(2*n-1) # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
position = c(1:n, (n-1):1) # 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
value = x[position] # 2 4 2 2 3 4 2 2 2 4 3 2 2 4 2
is_valid_path = function(subindex) {
k = length(subindex)
position[subindex[1]] == 1 & # starts at 1
position[subindex[k]] == 1 & # ends at 1
n %in% subindex & # goes through n (end of vector)
length(unique(position[subindex])) == k - 1 & # visits each index once (except 1)
all(diff(subindex) <= value[subindex[-k]])
}
min_length = 0
for(len in index) {
valid_paths = combn(index, len, FUN = is_valid_path)
if (any(valid_paths)) {
min_length = len
break
}
}
min_jumps = min_length - 1
cat(min_jumps) # outputs to stout
```
[Answer]
# Python 271
this is my solution:
```
## To simplify the process we unfold the forward-backward sequence
def unfold(L): return L + L[:-1][::-1]
## Possible jumps from a given L[i] position
def AvailableJumps(L,i): return range(1,L[i]+1)
# To disable a used position, in the forward and backward sites
# (the first one is not really necessary)
def Use(L,i):
L[i] = 0
L[ len(L) - i - 1] = 0
return L
def Jumps(L,i,n,S):
if (i >= len(L)-1):
S.append(n)
else:
Laux = list(L)
Use(Laux,i)
for j in AvailableJumps(L,i):
Jumps(Laux,i+j,n+1,S)
def MiniJump(L):
S = []
Jumps(unfold(L),0,0,S)
return min(S) if (S) else -1
```
Examples:
```
print MiniJump([2,4,2,2,3,4,2,2])
print MiniJump([0,2,4,2,2,3,4,2,2])
```
And these are the (partially by now) golfed versions:
```
def J(L,i,n,S):
if (i >= len(L)-1): S.append(n)
else:
La = list(L)
La[len(La) - i - 1] = 0
for j in range(1,L[i]+1):
J(La,i+j,n+1,S)
def MJ(L):
S = []
J(L + L[:-1][::-1],0,0,S)
return min(S) if (S) else -1
```
Some examples:
```
print MJ([2,4,2,2,3,4,2,2])
print MJ([0,2,4,2,2,3,4,2,2])
print MJ([3,4,0,0,6])
```
[Answer]
**Ruby - 246**
```
a=gets.split.map &:to_i
L=a.size;r=[];a.collect!{|v|([1,v].min..v).to_a};S=a[0].product *a[1..-1];S.each{|s|i=0;b=L==1&&s[i]!=0 ?0:1;(L*2).times{|c|r<<c if i==L-1&&b==0;break if !s[i]||s[i]==0;if i==L-1;b=i=0;s.reverse!end;i+=s[i]}}
puts r.min||-1
```
Simulation:
```
2, 4, 2, 2, 3, 4, 2, 2
6
0, 2, 4, 2, 2, 3, 4, 2, 2
-1
0
-1
1
0
```
[Answer]
Ruby - about 700 golfed. I started a golfed version, with single-character names for variables and methods, but after awhile I got more interested in the algorithm than the golf, so stopped trying to optimize code length. Nor did I worry about getting the input string. My effort is below.
To help you understand how it works I've included comments that show how a particular string (u = "2 1 4 3 0 3 4 4 3 5 0 3") is manipulated. I enumerate combinations of "rocks in the stream" that are available to hop on. These are represented with a binary string. I give the example 0b0101101010 in the comments and show how it would be used. The 1's correspond to the positions of rocks available for the initial trip; the 0's for the return trip. For each such allocation, I use dynamic programming to determine the minimal number of hops required in each direction. I also perform a few simple optimizations to eliminate some combinations early on.
I've run it with the strings given in other answers and get the same results. Here are some other results I obtained:
```
"2 1 4 3 0 3 4 4 3 5 0 3" # => 8
"3 4 3 5 6 4 7 4 3 1 5 6 4 3 1 4" # => 7
"2 3 2 4 5 3 6 3 2 0 4 5 3 2 0 3" # => 10
"3 4 3 0 4 3 4 4 5 3 5 3 0 4 3 3 0 3" # => 11
"2 3 2 4 5 3 6 3 2 0 4 5 3 2 0 3 4 1 6 3 8 2 0 5 2 3" # => 14
```
I would be interested in hearing whether others get the same results for these strings. Performance is reasonable good. For example, it took less than a minute to get a solution for this string:
"3 4 3 0 4 3 4 4 5 3 5 3 0 4 3 3 0 3 4 5 3 2 0 3 4 1 6 3 2 0 4 5 3 2 0 3 4 1 6 3 0 4 3 4 4 5 0 1"
The code follows.
```
I=99 # infinity - unlikely we'll attempt to solve problems with more than 48 rocks to step on
def leap!(u)
p = u.split.map(&:to_i) # p = [2,1,4,3,0,3,4,4,3,5,0,3]
s = p.shift # s=2, p = [1,4,3,0,3,4,4,3,5,0,3] # start
f = p.pop # f=3, p = [1,4,3,0,3,4,4,3,5,0] # finish
q = p.reverse # q = [0,5,3,4,4,3,0,3,4,1] # reverse order
# No path if cannot get to a non-zero rock from s or f
return -1 if t(p,s) || t(q,f)
@n=p.size # 10 rocks in the stream
r = 2**@n # 10000000000 - 11 binary digits
j = s > @n ? 0 : 2**(@n-s) # 100000000 for s = 2 (cannot leave start if combo number is smaller than j)
k=r-1 # 1111111111 - 10 binary digits
b=I # best number of hops so far (s->f + f->s), initialized to infinity
(j..k).each do |c|
# Representative combo: 0b0101101010, convert to array
c += r # 0b10 1 0 1 1 0 1 0 1 0
c = c.to_s(2).split('').map(&:to_i)
# [1,0,1,0,1,1,0,1,0,1,0]
c.shift # [0,1,0,1,1,0,1,0,1,0] s->f: rock offsets available: 1,3,4,6,8
d = c.map {|e|1-e}.reverse # [1,0,1,0,1,0,0,1,0,1] f->s: rock offsets available: 0,2,5,7,9
c = z(c,p) # [0,4,0,0,3,0,4,0,5,0] s->f: max hops by offset for combo c
d = z(d,q) # [0,0,3,0,4,0,0,3,0,1] f->s: max hops by offset for combo c
# Skip combo if cannot get from to a rock from f, or can't
# get to the end (can always get to a rock from s if s > 0).
next if [s,f,l(c),l(d)].max < @n && t(d,f)
# Compute sum of smallest number of hops from s to f and back to s,
# for combo c, and save it if it is the best solution so far.
b = [b, m([s]+c) + m([f]+d)].min
end
b < I ? b : -1 # return result
end
# t(w,n) returns true if can conclude cannot get from sourch n to destination
def t(w,n) n==0 || (w[0,n].max==0 && n < @n) end
def l(w) w.map.with_index {|e,i|i+e}.max end
def z(c,p) c.zip(p).map {|x,y| x*y} end
def m(p)
# for s->f: p = [2,0,4,0,0,3,0,4,0,5,0] - can be on rock offsets 2,5,7,9
# for f->s: p = [3,0,0,3,0,4,0,0,3,0,1] - can be on rock offsets 3,5,8,10
a=[{d: 0,i: @n+1}]
(0..@n).each do |j|
i=@n-j
v=p[i]
if v > 0
b=[I]
a.each{|h| i+v < h[:i] ? break : b << (1 + h[:d])}
m = b.min
a.unshift({d: m,i: i}) if m < I
end
end
h = a.shift
return h[:i]>0 ? I : h[:d]
end
```
[Answer]
# Haskell, ~~173~~ 166 bytes, 159 bytes in GHCi
Here is the normal version:
import Data.List
```
t=length
j[_]=0
j l=y[t f|f<-fst.span(>0)<$>permutations[0..t l-1],u<-f,u==t l-1,all(\(a,b)->abs(b-a)<=l!!a)$zip(0:f)$f++[0]]
y[]=0-1
y l=minimum l+1
```
Here is the GHCi answer (put the line one at a time):
```
t=length
y[]=0-1;y l=minimum l+1
j[_]=0;j l=y[t f|f<-fst.span(>0)<$>Data.List.permutations[0..t l-1],u<-f,u==t l-1,all(\(a,b)->abs(b-a)<=l!!a)$zip(0:f)$f++[0]]
```
Just a bruteforce. Generate the possible answer. (i.e. permutation of [0..n-1] with zero and following element dropped. Then check if the answer is correct. Get the minimum length and add by one. (Since the leading and trailing zeroes is delete).
How to use: `j[3,4,0,0,6]` -> `3`
] |
[Question]
[
[This anecdote](http://thedailywtf.com/Articles/Cheaters-Never-Prosper.aspx) contains the following intriguing exchange:
>
> "Fine, Fred," Avi interrupted. "Then how would you change this to
> avoid duplicate entries?"
>
>
> "Oh, just change that one there to a negative one."
>
>
>
While this claim is not accurate in context, I do wonder if there's some plausible code for which that makes sense.
Your challenge is to write code (a program, a function, whatever) that fits this criteria:
1. Merges two input lists into one, keeping duplicates. [edit: You can optionally assume that they are integers, and/or that the lists themselves are unique. You can't assume the integers are positive (the one answer that does this is grandfathered in).]
2. A literal "1" appears somewhere in the code. If you change this to a literal "-1", the code does the same thing but removing duplicates.
3. The code does not simply branch off of the 1/-1. We're not looking for `if (1 < 1) removeDuplicates()` or `[do_nothing, merge_with_dups, merge_without_dups][1].call()`, for example.
Input and output can be in any reasonable format you choose. One example might be
`[1,2],[2,3]->[1,2,2,3]` before the sign change, and `[1,2,3]` after.
This is a popularity contest. It is **not code golf**, unless you want to show off. I'll accept the highest-voted answer in about two weeks.
[Answer]
### JavaScript
Take a conventional algorithm and write it with a bug:
```
function merge(a, b) {
var ai = 0, bi = 0, oi = 0;
var o = [];
while (ai < a.length && bi < b.length) {
var v = a[ai] < b[bi] ? a[ai++] : b[bi++];
if (v !== o[oi + 1]) {
o[oi++] = v;
}
}
while (ai < a.length) o[oi++] = a[ai++];
while (bi < b.length) o[oi++] = b[bi++];
return o;
}
```
This code contains exactly one literal `1`. If it is changed to `-1`, then duplicates will be removed. It can be used on any comparable values.
[Answer]
## APL 22/23
Prompts for screen input via ←⎕ and returns an ordered merged list with or, if the leading one is set negative, without duplicates.
```
(~1=0,-2=/v)/v←v[⍋v←⎕]
⎕:
(1 2),(2 3)
1 2 2 3
(~¯1=0,-2=/v)/v←v[⍋v←⎕]
⎕:
(1 2),(2 3)
1 2 3
```
Byte counters please note that the single byte APL characters have been converted to UTF8 to render properly on this site.
[Answer]
# k (18)
Should work for any valid type of list
```
{(*1#(::;?:))@x,y}
```
Example:
```
k){(*-1#(::;?:))@x,y}[1 2 3 4;3 4 5 6]
1 2 3 4 5 6
k){(*1#(::;?:))@x,y}[1 2 3 4;3 4 5 6]
1 2 3 4 3 4 5 6
```
[Answer]
## Python
```
def merge(a, b):
return a + [i for i in b if i not in a*- 1]
```
[Answer]
## Bash
In the spirit of the context, this program removes the duplicates if you add a minus sign before the lowercase `l` on the `grep` line. If you add a minus sign before the uppercase `I` on the previous line, or before the digit `1` on the next line, the program doesn't behave differently.
The input files contain one integer per line (this is the usual representation of lists as text files). They must be passed as two arguments. The resulting list is written to standard ouptut.
```
# Create temp file for working
temp=$(mktemp -d)
# Copy left and right file to merge into same
cp $1 $temp/l
cp $2 $temp/r
cd $temp
while read num
do
# I remove the output
set `grep -Lax -e $num l ` <r> /dev/null
if [ $# != 1 ]
then echo $num >>r
fi
done <l
cp r /dev/stdout
cd
rm -r $temp
```
Feel free to use this program as an example of your best code in an interview. All I ask is that you don't say that it's my best code.
[Answer]
## Tcl
In the spirit of the quote
```
foreach item $list1 {
if {$item in $list2} {set item [expr {$item * 1}]}
lappend list2 $item
}
foreach item $list2 {
if {$item >= 0} {lappend result $item}
}
```
If it is a duplicate, multiply it with (-)1, after that filter out negative values.
[Answer]
I'm beginner in PHP I don't know if it's correct
```
$list1=explode(',',$_GET['list1']);
$list2=explode(',',$_GET['list2']);
$list_merged=array_merge($list1,$list2);
print_r($list_merged);
$list_unique=array_unique($list_merged);
print_r($list_unique);
```
] |
[Question]
[
Output "Mozart - Alla Turca" to stdout (see the sample for "reference implementation")
Try to find how to pack both synthesizer and the music into minimal size.
Requirements:
* Format suitable for feeding into `aplay -f cd` (signed 16-bit little endian, 2 channels);
* Entire music should be played (no skipped notes or parts, at least not less than in sample program), polyphony is not required though;
* Can't just call `/usr/bin/timidity`, `/usr/bin/sox` or something like that (e.g. require to install a special music module);
* Can't access network or assume that the music is available locally;
"Reference implementation" with parsable score: <https://gist.github.com/vi/5478693>
(Old sample Perl program: <https://gist.github.com/vi/5447962>)
[Answer]
## Polyphonic, Haskell, ~~2826~~ ~~3177~~ 4719
Audio output:
<https://www.dropbox.com/s/nba6489tfet740r/hs-golf-turca.ogg>
Features:
* All notes ~~from the *right hand*. I could of course add the left hand, too~~ (done that).
* Proper articulation of the staccato notes etc.
* Reasonably nice sound with dynamics. Not just simple volume modulation, but proper morphing of the attack character and overtone content, ~~like you get on a real piano~~ actually, rather more... hey this piece is supposed to be imitating [Turkish Janissary bands](http://en.wikipedia.org/wiki/Alla_turca#Structure), right?
* Reverb. Doesn't sound amazingly great, but not too bad, either.
* Dynamic compression. Don't ask...
* Dithering of the output. This is kind of ridiculous: with proper 16-bit resolution, hardly anybody would hear the quantisation artifacts, but to avoid including the [binary library](http://hackage.haskell.org/package/binary), I effectively use only 7-bits resolution, which I can cover with ASCII output. The dither itself is rather loud, no noise-shaping...
* Multithreaded calculation of polyphonic chords.
---
```
import Control.Parallel
main=mapM_ (\(d,s)->(\p->p>>p>>p>>p).putChar.toEnum.round.(+d).(*62).min 2.abs$s+1).zip(dθ 1).lim.rev.hgp 9. pl 9e6 (\_->0) . ä
$[mT%8.1,t2%16.1,t3(∡7)%8,t4%8,t5%16,t3(∡7)%8,mT%8.1,t2%16.1,t3(tev arp8)%8,cdT%99] >>= \e->[e,e]
mM=ä[2-^8,1-^8,0-^8,1-^8,3-^4]
cM=ä[7-^20,8-^20,9.^4,F[(7,0),(6,1)](map((∡2).(.^4))[6,5,6])%0.75]
cMv=ä[10-^2,8.^4,9.^4,hom(.^4)[[24,5],[23,8,12],[22,4],[21,6,9],[22,3],[19,5,8],[20,4],[18,6,9],[17]]#7&(-14)%2.5,tr 2%0.4,1-^9,2-^12,1-^1]%4.5
⋎(ä[6-^4,lp(8.^4∡3)%(3/4),sil%2,lp(5.^4∡3)%h,lp(5.^4∡2)%h,1-^1∡7]&(-14)#7#4%5)
mMa f=ä[(1-3*f).^4,lp(5.^4∡(-2-f))%0.75,mMa f%1.5,mMa(f*2)%h,mMa f%1]#7
mTm=ä[mM%1,mM&2%1,mM#4&4%h,mM&7%h,mM&7%1,8.^4,ä[10.^4]%0.2,cM%1,cM%1,cM%0.85,ä[4.^4∡2,5.^2]#6#4%2]#7
mT=p$ä[mTm%8.1⋎(ä[sil%h,mMa 0%4,mMa 1%2.75,2.^4,(-2)-^2]&(-7)%8)]
m2=ä[ä(map((∡2).(.^4))[1,2,3,3]++[es[6,5,4,3]%h]++[0-^2∡2])%2
⋎(ä[sil%h,1.^4,8.^4,3.^4,10.^4,5-^2]⊿1.3&(-14)%2)]
t2=p$ä[m2&2%1.8,0-^5,m2&2%2,m2#7%1.8,(-2)-^5,m2#7%2,mT%3.5,cMv]
m3=ä$[3-^4,4-^4,5-^2]++map(-^4)[3,4,5,4,3,2,1,2,3,4,2,0]
m3a=ä[(ä[sil%(1/8),lp(8.^4)%1]:zw(\d n->ä[sil%(d/24),n-^1]⊿cos d)[0..][1,3,5],s),m3a%1]
m3ra=(map((%1). \[a,b,c]->es[a,c,b,c,a,c,b,c])[[1,3,5],[1,4,6],[-2,0,5]]!!)
t3 o=ä[ä[o$ḋ[m3%4,m3%2.5,1-^4,4-^4,2-^4,0-^4]&(-2)%7.5,1-^2∡7]%8
⋎(ḋ[sil%(3/8),m3a&4%2,m3a%h,m3a#4%h,m3a&1%1,m3a&4%2,m3a%h,m3a&1%(5/8),5-^2]&(-18)%8)]
mQ=es[2,1,0,2]
m4=mM⇆4
i4 e=ḋ[m4⇅11%h,m4⇅9%h,mQ⇆4⇅8%h,F[(5,e),(4,1)][mQ⇅7%h,mQ⇅5%h,m4&5%h,m4&7%h]%2,es[10,9,10,9]#2%h ]
mla[b,c,d]=ä[b-^4,lp(c-^4⋎(d-^4))%1]%1
i4a=ḋ[sil%h,ä(map mla[[1,3,5],[2,4,5],[1,3,5],[0,2,5]])#5%4,ä(map mla[[1,3,5],[2,5,7],[2,6,8]])#4%3,5-^2⋎(7-^2)]
t4=p$ä[ḋ[i4 1%4,i4 0%2.5,ä[mQ⇅6%h,mQ⇅4%h]#4#2%1,3-^2]%8⋎(i4a&(-9)%8)]
mlaa=mla[1,3,5]
m5=ä$map(-^8)[1..4]
i5=ḋ[m5⇅6%h,m5%h,m5&4%h,m5⇅9%h]
i5d=hom(-^4)[[2],[4,5],[0],[4,5]]%1
i5a=ḋ[sil%h,mlaa,i5d,mlaa,mla[-2,0,4],mlaa,i5d,sq 4[1,-1,-3,-2,-6,1]%2]&(-7)
t5=ḋ[ḋ[i5%2,i5%1.5,ä[8-^4,9-^4]#1%h,i5%2,ḋ[es[5,4,3,2,3,5,1,3,2,4,0,2]%2]%1.5,1-^2]%8⋎(i5a%8)
,p(ä[ä[i4 1%4,es[3,2,3,1,4,3,4,3,4,3,4,3]#2#1&7%1.5,m5⇅13%h,mQ⇅8%h,m5&7%(3/8),6-^8,mQ⇅7#5%h,6-^2]%8
⋎(ä[i4a%3.5,F[(1,-1),(7,0),(6,1)][hom(-^4)[[-2],[3,5],[2,5],[1,5]]%1]%1,mla[-3,1,4],mla[-3,2,4],hom(-^4)[[-2],[1,3],[-2],[2,4],[1,3]]%1.5]&(-9)%8)])%8]⊿0.8
am d=3-^d∡2∡5
amf=1-^υ∡2⋎(5-^1∡3)
vh v(c,d)=lp(ä[v-^12]:map(\t->ä[t⊿0%0.04,t%d])c,d)
aam=vh 11.am
aar=ä[1-^10,4-^10,6-^1]&4
eam=vh 10.em
dm=6-^1∡2⋎(11-^1)
em d=5-^d∡2⋎(9-^1)
cdM=ḋ[4-^8,3-^8,2.^8,3.^8,cdM%1]
cdT=ḋ[ä[3-^(8/3)∡7,10-^6,am 1,am 1,cdM&7%1,dm,aam 4.05%1,em(4/3),12-^4,am 1,am 1,cdM&7%1,dm,aam 1%1,eam 4%1]%12.5⋎(ä(sil%(11/24) : map((%1).(m3a&))[4,4,4,0,4,1,4,4,4,0,4,1])&(-18)%13.1)
,p(ä[ä[ä[8-^2]⊿2%h,aar%(3/8),10-^8,aar%1,aar%1,cdM&7%1,11-^1,vh 11(10-^4)%1,9-^(4/3)]%7⋎(ä(map m3ra[0,0,0,0,1,0,2])&(-7)%7)])%6.75
,ä[p(ä[12-^4])%(1/4),am 1,am 1,cdM&7%1,dm,aam 1%1,eam 4%1,amf,ä[3-^4,1-^υ,5-^4,1-^υ,3-^4,1-^4,3-^4,1-^4,5-^4,1-^2]%3.75∡7,ä[amf∡(-14)]%0.56,ä[amf∡(-14)]⊿0.8%1]%12⋎(ä(sil%(1/8):map((%1).(m3a&))[4,4,4,0,4,1,4,4,4]++[m3a&4%h,m3a&4%h,5-^(8/5)])&(-18)%12)]
type D=Double
data F=N Int D|F[(Int,D)][([F],D)]
φ⇸F a fs=F a$map(\(f,d)->(map φ f,d))fs
_⇸N i d=N i d
i##c
|i<1=(i+7)##c/2
|i>7=(i-7)##c*2
|1>0=1.06**(c i+case i of{1->0;3->3;4->5;5->7;6->8;7->10;_->fri i})
pl dur acc(N n v)=(\ω η->map(sin.(\x->x+τ x^2/η). \i->v*exp(-i*η/s)*τ(i*v)*(0.8-τ((i-dur)/90))*sin(i*ω))[1..dur])(n##acc/15.5).exp$fri n/9
pl dur acc(F accm fs)=pl' dur (foldr(\(q,m)f i->if q==i then m else f i)acc accm) fs
pl' dur _ _|dur<=0 = []
pl' dur _ []=map(\_->0)[1..dur]
pl' dur acc((f,dr):fs)|n<-min dr dur=trans(round n)(foldr1(\a b->sum a`par`sum b`pseq`zw(+)a b)(map(pl(n+99)acc)f))$pl'(dur-dr)acc fs
trans n a b|(f,ol)<-splitAt n a,(or,l)<-splitAt 99 b=f++zw(+)ol or++l
fri=fromIntegral
F a fs#q=F((q,1):a)fs
N i d&n=N(n+i)d
f&n=(&n)⇸f
N i d⇅n=N(n-i)d
f⇅n=(⇅n)⇸f
N i d⇆_=N i d
F a fs⇆n=F a.reverse$take n fs
N i d⊿v=N i$d*v
f⊿v=(⊿v)⇸f
p=(⊿0.3)
n.^q=([F[][([N n 1],s/2/q)]],s/q)
n-^q=([N n 1],s/q)
(l,d)⋎(r,_)=(l++r,d)
(l,d)∡j=(l++map(\h->ä[h⊿0%0.01,h&j%100])l,d)
f%t=([f],s*t)
tr n=F[]$cycle[n-^15,(n+1)-^20]
ä=F[];ḋ=F$zip[6,3,7][1,1,1]
lp=ä.repeat
sil=N 0 0
tev f(l,d)=(map f l,d)
h=1/2
υ=4/3
s=4e+4
sq d=ä.map(-^d)
es=sq 8
arp8 n@(N i v)=F[][([n,ä[n⊿0%(1/8),n&7⊿(v/υ)%100]],s)]
arp8 f=arp8⇸f
hom q=ä.map(foldr((⋎).q)$sil%1)
dθ l=2*asin l/pi:dθ(abs.sin$l*1e+9)
rev ls=(\z->z id(foldr(\m sg->(\v->z(*v)(map(*0)[0..m*14349]++sg)sg)$abs(cos$(m*3)^2)-0.6)ls.take 9$dθ 1)ls)$(.lwp 3 0).zw.((+).)
lwp ω c(x:l)=c:lwp ω((x+c*ω)/(ω+1))l
lwp _ _ _=[]
hgp ω l=zw(-)l$lwp ω 0 l
lime e(x:l)
|abs(e*x)>1,e'<-((e*8+abs(1/x))/9)=e':lime e' l
|1>0=e:lime((e*49999+1)/5e4)l
lime _[]=[]
lim ls=zw(\a u->τ$a/9+max(-2)(min 2$a*u)/6)(map(*0)[0..500]++ls).lwp 9 0.lime 1$hgp 9 ls
zw=zipWith
τ=tanh
```
---
>
> $ make
>
> ghc -o bin/def0-hs def0.hs -O2 -fllvm -threaded
>
> [1 of 1] Compiling Main ( def0.hs, def0.o )
>
> Linking bin/def0-hs ...
>
> time sh -c 'bin/def0-hs +RTS -N4 > hsoutp.pcm'
>
> 189.39user 138.41system 2:06.62elapsed 258%CPU (0avgtext+0avgdata 6440240maxresident)k
>
> 0inputs+0outputs (0major+403037minor)pagefaults 0swaps
>
> ffmpeg -loglevel panic -y -f s16le -ar 44.1k -ac 2 -i hsoutp.pcm hsoutp.ogg
>
>
>
---
Here's a partially ungolfed and commented version: <https://gist.github.com/leftaroundabout/5517198>.
[Answer]
## Python, 331+286 = 617 (0.548 bytes per note)
My solution uses a data file and a python script. The data file should be used as input to the script. I don't have aplay, but it works when I import it as raw data in [Audacity](http://audacity.sourceforge.net/) with signed 16-bit PCM, little-endian, and 2 channels.
The data file is 331 bytes. Here's a python script which outputs it:
```
import sys
sys.stdout.write('\x08\x1c\x9d\xb9"\xc7\xea\xf0\xb7)\xc0D!u\x0bB~\'\x91S\xb2\x0c\xe9\xf8T;\xfd\xc13\xcf\xb9\xa6r>\xbc\xc5\xb4\xbb\xf8\xa4\x9a\x05H\xa0\x1d\x0eIq\t\\+\t\xdbn\x03\xc3&\x98\xa0\x11\xc5\xaa\xef\xbcSR^\x13\xe7\xc7\x0e\xc0\xa9^\x91Z\xfc\x02\x11\xb9\x1bE\xfc/=\xb8\xaf5<\x12\xa2\xc4\x02\xec\xdcO\xc2a\x04<Q\xfd\xe9L\xbc\xab%\xf5wX1F\xa6\x88\xddP\xfec(_#\xb4\x0bN\xba&m\xe3\xa4\x08Q\xdb\xd9\xf3<Q\xc6\xf6\x0e\xd7\xacd\x1f"g\xce\xae.\xb0\x90{|\x04\xc5X\xe6x>\xefE\xc8\xb0\xd2?N\x83?\x04\x86"a\xcc\x9b\x8fq\x9c\xce\xa2\xb6f\x9ab\x92\x9e:\xc0S\xcd\th\xb1\x87\xecT\x9d\xf4\n\xaf\xc9$`E5\xcc\xc5\xa0m\xcc\n8\xf8:\x03\xf5\x02H\xf3k\xe5\x86\xa64\x90\xa2\xc2w\xfa\xb7\xc0\x1e*2\x93\xca\x12\xe3^!\xd5yQ,LXW\xb4\x96D\x8dB\x9c`\xbf\x96`s;\xb7}\xeb\x8c\xebI\xa0o\x00\x08\xfe\xf1\xd2M3}\x8e\xd0\xda\x97\'\xca\x83-\x14\xda\xa1ET\n\xe8\xc7@\x1c\xa2a\xbb\xa7\x1b\x014\xdcz\xc7\xa6\xc4\x1d\x18\x04\r\xb1\x9e\xe3\xd0\x18<\x98`N?a\xe4\x8e\x9d\xd5\r\xe7Z[\xf4\xed\xf1PQ')
```
Here's the python script:
```
import sys
k=0
m=185
p=[]
q=[]
for c in sys.stdin.read():k=k*256+ord(c)
while k:
v=k%m;k/=m
if v<184:q+=[v]
elif v-m+1:q+=p[v-184]
else:m+=1;p+=[q];q=[]
for n in q:r=[1,2,3,4,6,8,12,15,16][n%9]*2000;sys.stdout.write(''.join(chr(int(i*1.06**(n/9)/4.3)%99)for i in range(r*3))+'\0'*r)
```
Note: If you're running Windows, use the `-u` switch for both scripts since stdin and stdout are dealing with binary data.
[Answer]
## GolfScript (129 + 369 = 498 bytes)
Both program and data file include unprintable characters, so I'm going to give Base64 and xxd representations.
Program (129 bytes):
```
MjU2YmFzZSA2OWJhc2VbMDpOXS8oNDMse1xbMSQpXS9cMiQ9Kn0vXCwpey19KyUuLDIvL3ppcHt+
TisyNSU6Tid7goqSm6SuuMPP2+j2/0FFSU1SV1xcYWdtdCc9OmY7MTc2MCosey41MD4qZioxNy8u
Li59JScnOm4rcHV0c30v
0000000: 3235 3662 6173 6520 3639 6261 7365 5b30 256base 69base[0
0000010: 3a4e 5d2f 2834 332c 7b5c 5b31 2429 5d2f :N]/(43,{\[1$)]/
0000020: 5c32 243d 2a7d 2f5c 2c29 7b2d 7d2b 252e \2$=*}/\,){-}+%.
0000030: 2c32 2f2f 7a69 707b 7e4e 2b32 3525 3a4e ,2//zip{~N+25%:N
0000040: 277b 828a 929b a4ae b8c3 cfdb e8f6 ff41 '{.............A
0000050: 4549 4d52 575c 5c61 676d 7427 3d3a 663b EIMRW\\agmt'=:f;
0000060: 3137 3630 2a2c 7b2e 3530 3e2a 662a 3137 1760*,{.50>*f*17
0000070: 2f2e 2e2e 7d25 2727 3a6e 2b70 7574 737d /...}%'':n+puts}
0000080: 2f /
```
Data (369 bytes):
```
LoDJFvCRQqNdL7+JDvjtSkX4HBS2FwgvjfdxAHrF1/DcMIBtG/g7QZBLLYHpzgaWaM1TaHwbtxG+
l1lqsL3A8nuprtpPI20YbHm3lf7NxmYNdEIMTlhwTG+TlSn802DzN3YgIwbcKbtty9gWmF2nVS55
iJHQZd4HCcokoLRwH1g2XqP8Yo5xj5/YQm9DH85obUv47mii5n+PwsoJZ6yaz4eSpGps6dQMl+Pa
YP/WC6cVDBBGs3vq5cGe51H2u7oVArFuHrsI2sHkGNYHlhWudKn5RRvJhe3sxfrtQE/MekKRuZBt
f4B9qdyss66vFipSi1zf2MXF9A/CzwvMQ/t9PEtxw8kzxxikp2Ek3kc9TiamLl+iG2vjdWp84JzY
Mg6cE+3bFI4kVdn+d1NEnBR/S9HMnksgEc9sdAcyWsbSaGjwetwGTr7UXkpKO9aHF01D2i5pCO40
/keR0+a+NsBEOXZfatpXav44AJjalywtLeWu
0000000: 2e80 c916 f091 42a3 5d2f bf89 0ef8 ed4a ......B.]/.....J
0000010: 45f8 1c14 b617 082f 8df7 7100 7ac5 d7f0 E....../..q.z...
0000020: dc30 806d 1bf8 3b41 904b 2d81 e9ce 0696 .0.m..;A.K-.....
0000030: 68cd 5368 7c1b b711 be97 596a b0bd c0f2 h.Sh|.....Yj....
0000040: 7ba9 aeda 4f23 6d18 6c79 b795 fecd c666 {...O#m.ly.....f
0000050: 0d74 420c 4e58 704c 6f93 9529 fcd3 60f3 .tB.NXpLo..)..`.
0000060: 3776 2023 06dc 29bb 6dcb d816 985d a755 7v #..).m....].U
0000070: 2e79 8891 d065 de07 09ca 24a0 b470 1f58 .y...e....$..p.X
0000080: 365e a3fc 628e 718f 9fd8 426f 431f ce68 6^..b.q...BoC..h
0000090: 6d4b f8ee 68a2 e67f 8fc2 ca09 67ac 9acf mK..h.......g...
00000a0: 8792 a46a 6ce9 d40c 97e3 da60 ffd6 0ba7 ...jl......`....
00000b0: 150c 1046 b37b eae5 c19e e751 f6bb ba15 ...F.{.....Q....
00000c0: 02b1 6e1e bb08 dac1 e418 d607 9615 ae74 ..n............t
00000d0: a9f9 451b c985 edec c5fa ed40 4fcc 7a42 [[email protected]](/cdn-cgi/l/email-protection)
00000e0: 91b9 906d 7f80 7da9 dcac b3ae af16 2a52 ...m..}.......*R
00000f0: 8b5c dfd8 c5c5 f40f c2cf 0bcc 43fb 7d3c .\..........C.}<
0000100: 4b71 c3c9 33c7 18a4 a761 24de 473d 4e26 Kq..3....a$.G=N&
0000110: a62e 5fa2 1b6b e375 6a7c e09c d832 0e9c .._..k.uj|...2..
0000120: 13ed db14 8e24 55d9 fe77 5344 9c14 7f4b .....$U..wSD...K
0000130: d1cc 9e4b 2011 cf6c 7407 325a c6d2 6868 ...K ..lt.2Z..hh
0000140: f07a dc06 4ebe d45e 4a4a 3bd6 8717 4d43 .z..N..^JJ;...MC
0000150: da2e 6908 ee34 fe47 91d3 e6be 36c0 4439 ..i..4.G....6.D9
0000160: 765f 6ada 576a fe38 0098 da97 2c2d 2de5 v_j.Wj.8....,--.
0000170: ae .
```
---
### Explanation
I've mangled the (updated) supplied score (more on that later) into a single string containing bytes with values from 0 to 24. The note lengths come first; then the note values, represented mod 25 and difference-encoded. The reason for the difference encoding is so that passages which are repeated in transposition will be reduced to the same sequence and can be compressed.
I then ran this through a string-to-GolfScript compression program which I've mentioned before (and which I improved in order to be competitive in this golf) to get the data file, which is decompressed by the first part of the program:
```
256base 69base[0:N]/(43,{\[1$)]/\2$=*}/\,){-}+%
```
It's a simple grammar expansion of a type which is familiar to anyone who's looked at many questions tagged [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'").
I then split this string into pairs `[length note]` and iterate through the pairs. The non-printable characters come from a magic string which contains frequency parameters for the notes: I'm using GolfScript's implicit truncation mod 256 of integer arrays which are converted to strings to produce a triangle wave\*, so the base frequency is 22050/256 Hz. I wrote a program to find integer ratios which give a good tuning; the magic string contains numerators, and the denominator 17 is the same for all notes. The average tuning error is about 3.4 cents.
The note lengths are represented as is, and are much more plausible than the previous version of the score. As I suspected, the rounding has increased the redundancy in the string and shortened the compressed data file by 30 bytes, not to mention saving the lookup array. However, there are still some passages which I find suspicious:
```
72 13
```
or
```
71 9
69 2
71 2
```
give bars which are a sixth of a crochet longer than the rest of the bars in the score, and
```
85 9
85 4
85 24
85 23
```
or
```
83 18
88 7
85 24
85 23
```
are an integral number of bars, but with some dubious offsets.
The program could be slightly shorter. I have deliberately chosen to trade in shortness for execution time. With some speed improvements to the GolfScript interpreter which I've submitted to Darren Smith and which I believe he plans to publish at some point, the current version runs in less than 15 minutes on my computer. If I don't `puts` each note after generating it then it runs much slower.
\* I hereby confess that my comment about everyone using square waves was wrong.
] |
[Question]
[
I thought it'd be interesting to turn [AoC day 3](https://adventofcode.com/2020/day/3) puzzle into a Golfing Challenge, so here it is.
### Task
Find the number of `#` you'd encounter in an 11x11 grid (consisting of `#` and `.`) that repeats itself (to the right side), starting at the top left corner, which is always a `.`. You will need to check the position that is \$x\$ right, \$y\$ down, then the position that is \$x\$ right, \$y\$ down from there and so on until you reach one of the bottom `#` or `.`.
### Input
Two arguments:
* `3,1`
* ```
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
```
means that you should traverse the grid going 3 right and 1 down. The output should be `7` (see the example in the AoC link above).
Without changing the grid but only the positions, here are some example inputs and outputs:
* \$x=1, y=1 \to 2\$.
* \$x=5, y=1 \to 3\$.
* \$x=7, y=1 \to 4\$.
* \$x=1, y=2 \to 2\$.
---
* `1,1`
* ```
.........##
.#.#.......
#.......#..
.........#.
.....#.....
...##...#..
#.#..#....#
........##.
......#....
...####...#
.........#.
```
means traversing the grid going 1 right, 1 down each time. You'd encounter only 1 `#` in this example, so the output should be `1`.
### Rules
* \$x\$ (right) and \$y\$ (down) will be positive integers, where \$y < 3\$ (no limits for \$x\$).
* The grid can be repeated unlimited times.
* You can replace `.` and `#` with whatever you like in the grid (e.g. `0`/`1`). Just mention which corresponds to which.
* You can receive input through any of the standard IO methods.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# [J](http://jsoftware.com/), ~~30 26 23~~ 22 bytes
```
0{0{[:+/|.^:(<@%&{.~$)
```
[Try it online!](https://tio.run/##TYyxCgIxEET7/YrBVWNQ16hdzoAgWFnZil7heYiNHxDx16O5jXILswzDvHmkgZgWwcNgBgf/1VywOx72yUUXT366eMnFTzbb0TjKe2iTpSYIDBsEnCupV6gy6EiEWfQomyLqTH4suVNy1px7udLUVZQprPrS4P9@r/PbtHS73p9YYo0WTfoA "J – Try It Online")
*Note: This solution works for any grid*
J supports multi-dimensional rotation, which reduces the problem almost to a single summation. To clarify what's happening, assume the board looks like this:
```
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
25 26 27 28 29
30 31 32 33 34
35 36 37 38 39
```
Now we rotate the columns left and the rows up `|.` by `1 3`, iteratively, 3 times:
```
┌──────────────┬──────────────┬──────────────┐
│ 0 1 2 3 4│ 8 9 5 6 7│11 12 13 14 10│
│ 5 6 7 8 9│13 14 10 11 12│16 17 18 19 15│
│10 11 12 13 14│18 19 15 16 17│21 22 23 24 20│
│15 16 17 18 19│23 24 20 21 22│26 27 28 29 25│
│20 21 22 23 24│28 29 25 26 27│31 32 33 34 30│
│25 26 27 28 29│33 34 30 31 32│36 37 38 39 35│
│30 31 32 33 34│38 39 35 36 37│ 1 2 3 4 0│
│35 36 37 38 39│ 3 4 0 1 2│ 6 7 8 9 5│
└──────────────┴──────────────┴──────────────┘
```
We are bringing the sled's "new position" to the top-left corner every time, rather than moving a pointer within a fixed grid and adjusting indexes with modular arithmetic.
Once we have every iteration like this, we need only "sum the planes" element-wise `[:+/`, and then our answer will the number in the top left corner of the resulting matrix `0{0{`.
The only piece left is to determine how many times we need to iterate. This amounts to dividing the first element of our "step" vector (the down part) into the height of the input matrix: `%&{.~$`.
## old approach, 26 bytes
```
1#.]{~[:;/$@]|"1#\@]*($~#)
```
[Try it online!](https://tio.run/##TYzBCsIwEETv@xVDt5BG6trqLSFQEDx58qrBg20RL36A0l@PponShVmGYd48QiFqhDNQqNHAfLUW7E/HQ2hZ/Gs6G7spO/8uWr50flWVE@ugqXcCxQoO3sp1CxvhhkSYJR1Fk0WziY8ldnLOKedFnmiaK4nJbPK5wf/9Ree3qWm43Z@oatNipzGiDx8 "J – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
Takes `y`, `grid` and `x` as seperate inputs where grid is a 2d-list of `0/1`.
```
ιнε³N*è}O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3M4Le89tPbTZT@vwilr///8NuaKjDXQMdAyB0AAZxupEw0RQaKC4AZJaQxgJFofwkdUboqg3xKHeEMVehClI9qDZiyyOaoYhFvdjNwfVnbFcxgA "05AB1E – Try It Online") Convert a grid into the required format with [this Retina script](https://tio.run/##K0otycxLNPz/PyRBTzkhhYtLh0vn0DYdrlidaK44Ha7oaC4dFa7Y2P//9fSUlfUggAvEgGIuMANEKAPZQAIirgwRV0YSh@jmAiuB6IHqhbChKpTh5iOpgZoJAA).
```
ι # un-interleave the grid with step y
н # take the first element grid[0::y]
ε } # map over each row
³N* # multiply x with 0-based iteration index N
è # index into row (modular)
O # sum the values
```
[Answer]
# [Scala](https://www.scala-lang.org/), ~~47~~ 44 bytes
*-3 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792)!*
When replacing the `.`/`#` grid with a `0`/`1` one:
```
(x,y,z)=>1 to 10/y map(i=>z(i*y)(i*x%11))sum
```
[Try it online!](https://tio.run/##hZFNa8MwDIbv/RXvpWAPw6yVMSg40GMPO@04evAaM1xSN03ckHTst2dOv@awNENYwnrQK8ku1zrT7e5jY9Yer9o6mNobl5ZY5Dm@JkClM@i0Ms7PwZbOC5zcm9m/dydcVisOlXRpqJbVohFHrhKC34HkY4OtzplVyZHZh4YHV0@JOC8P27bSBT4Lm0J1eix064IUUlAwGRsXF3rN9@KNyqiOrj6i52xcSwO1NFpLA1P96kb9B6f6S/uqdHffMeX@RhMecF5Y5zPHzp/HZgIkTq/NByiN0udR@vKf8tONfrc/)
---
## ~~77..62~~ 60 bytes
using a `.`/`#` grid:
```
(x,y,z)=>1 to 10/y map(i=>if(z(i*y)(i*x%11)==35)1 else 0)sum
```
[Try it online!](https://tio.run/##hVDBisIwEL3vVzwMQiKhmhURhBQ8evDkcdlD1kaJ1FhtlFbx27tpo7t0XTQww8x7M28mky9Vqqrd10YvHebKWOjCaZvkmGYZLm/ASaVQyUlbNwGdWcfRuIXefyzcwdj1J4OMaxCyogUv@ZnJWMDtIAb9EluVUSNjs6Jnanol867oCsGkHI6YgE5zjQHLj9sqzFofTAJZ61M/HehEESFReB0eoDq/2R1q8tqRX8jHoYq0qshjFWnJN31Bry3fgm5t5O9ej433JTzCvGX@ai61NFyVDjkEb77N/mHFU3b0lB2/Un7/Ya/VNw)
**Explanation**:
```
(x, y, z) => // x: steps to the right, y: steps to the bottoms, z: grid as a String sequence
(1 to 10 / y) // range r := [1;10/y]
.map ( // override every entry in r
i => if ( // every entry i in r if
z(i * y)(i * x % 11) // the character from the grid that is at the position (i * y, i * x),
// because i * x can get bigger than the number of columns modulo (%) it by 11
// so the correct position is: (i * y, i * x % 11)
== 35 // is equal to 35 (ASCII numeric value for '#')
) 1 else 0 // with 1 else 0
) sum // sum over all entries
```
**Example**: (5, 3, grid):
```
val grid = Seq(
"..##.......",
"#...#...#..",
".#....#..#.",
"..#.#...#.#",
".#...##..#.",
"..#.##.....",
".#.#.#....#",
".#........#",
"#.##...#...",
"#...##....#",
".#..#...#.#"
)
```
```
Steps | Sequence
------------------------|---------
init | [1, 2, 3]
i = 1; z(3)(5) == '.' | [0, 2, 3]
i = 2; z(6)(10) == '#' | [0, 1, 3]
i = 3; z(9)(4) == '#' | [0, 1, 1]
sum == 2
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 50 bytes
```
->x,y,m,r=c=t=0{t+=m[r][(c+=x)%11]while m[r+=y];t}
```
[Try it online!](https://tio.run/##fZDRCsIwDEXf@xV7EZRF6MVHiT9S@uJwKDiQMXFD/PbaMcqSukmgLbm9OUna53kINYf9qaeBGmq54o7tuyu5ca1326rkfrcB/Ot6u1@KmCx58MfuEx5F7Q4EMs5ZsvEBsjJ8VFJK3aNgxW@kcxKmhHRAO7DmgIbPhQQrhytBl8HSHCuldLvGe2PG/WDeT4aLoXuUIZF6S2ngX00ryKrl7UNxkHmwyMECR7o0R7L@dB1XFb4 "Ruby – Try It Online")
Expects a matrix of \$0\$s and \$1\$s. It is given that `m[0][0]` is never a tree, so I always skip it.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
```
#[[i+1,Mod[i#2,11]+1]]~Sum~{i,0,10/#3}&
```
[Try it online!](https://tio.run/##TU5Na8QgFLz7MxzYy76auHveIpQeC4UcxYNkPyI03ZLaU3D/emqiZiP4HMaZedNb3116611rp@tpgtZuL@njftYOB5LS7KUxj@avf4yOapJ1hWPYTZ@D@/bqqt86O9jWX4bfSr233b1SjY9ft@bny3kN4oybSoxc8JfXmjjiIwMBO7XIFQ4mQjWyKBGASIfNIF@2gHkg4jgSj8Rjwyc3WyTJk70JZwXW/I0mZ3IajyRDoKVOcYKVwGIVpdqqybhUEOsuhpI/r1ojixdPfXJsM2MdOddhYfoH "Wolfram Language (Mathematica) – Try It Online")
Input `f[grid, x, y]`, where `#`s are `1` and `.`s are 0.
[Answer]
# [Haskell](https://www.haskell.org/), ~~60~~ 54 bytes
```
f x y g=sum[cycle(g!!b)!!a|(a,b)<-zip[0,x..][0,y..10]]
```
[Try it online!](https://tio.run/##XY3LCoMwEEX3/YqJETSgg9Jt0x@xWUSJGhpFqgUt/fc0PoqtA/M43MudWvZ3ZYy1JYwwQcX7Z5MVU2FUWBGSM0LkO5RRzi7xS3dZEo2Iwq0JMU2EsI3ULXDoHrodwIcSzpCC38gunPs2xlftkjkPMIChVi0koEyvIGUsO4GHSCmu5UWOZ9h64QXmQTd2x6rTXacHne55i33N@MnbeXPTv/8H//ffCYT9AA "Haskell – Try It Online")
* saved 6 using 1 and 0 as '#' and '.'
[Answer]
# APL+WIN, 40 bytes
Prompts for y, x and the rows of the grid as a nested vector `1=#` and `0=.`:
```
+/(∊n⍴¨⎕)[((n←⌈/n)×y×m)+n←1+⎕×m←⍳10÷y←⎕]
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7a@xqOOrrxHvVsOrQBKaUZraOQBZR/1dOjnaR6eXnl4eq6mNkjEUBsoDeSBJHs3Gxoc3l4JYvZNjf0PNOh/GpchlzGXgoaBgoGCIRAaIENNBQUNmBAKDZIwQFJtCCMhEhABZB2GqDoMcekwRLUcYRCSXeiWo0igGmOIzR84jEJzLhcoZAxHQwZHyJiOhgyOkDEfDRmsIWM0mpuwhQwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes
```
mLḶ×⁵‘ị"mS
```
[Try it online!](https://tio.run/##y0rNyan8/z/X5@GObYenP2rc@qhhxsPd3Uq5wf8f7t5i@6hhrvLh5f//6@kpK@tBABeIAcVcYAaIUAaygQREXBkirowkDtHNBVYC0QPVC2FDVSjDzUdSAzXzv9F/QwA "Jelly – Try It Online")
-1 byte mostly thanks to caird coinheringaahing
Takes a grid of 1 for `#` and 0 for `.` as the first argument, y as the second argument, and x as the third argument.
```
m Take every yth row of the grid (starting from the first).
LḶ For the range from 0 to its length minus 1,
×⁵ multiply each of those numbers by x,
‘ị and 0-index into
" corresponding items from
m every yth row of the grid.
S Sum the retrieved items.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~71~~ \$\cdots\$ ~~54~~ 53 bytes
Saved 11 bytes thanks to [Command Master](https://codegolf.stackexchange.com/users/92727/command-master)!!!
Saved 4 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
Saved a byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!!
```
lambda g,r,d:sum(g[i*d][i*r%11]for i in range(11//d))
```
[Try it online!](https://tio.run/##dVPbboMwDH3nKyxNU0jltXHpVKkS@xGahw4CzbZSFKi0reLbWUIvgwJESsLx5RxbTvFT7Y950KThtvnaHd6THWRoMNmUp4OfRXqWSLuZZyKZHg1o0DmYXZ4pn2ixSDhvEpVC4WdGJ3zjgf2cn3F@DtsURueVz9j846hzn82fWKQ7qTj3nFsJIfhRJFAg2SV6S2J0g/qnNYiON9331nC5diOoH0FTEdQn/0/U5Xog7xn6aWisjolUD3Ilti1136U7j2TUFzjRNjFsmxgx9QyDJoiRou61irHuDMUOyGmco8szLVdyr1Jl1Q5PO4FlJCRCgEAcoYPQAHkdIOuxqOU/QtKpsvOqvgsVVypxrGtcYoAruxP34r2KP5VxONuelutVzBDaGwWMe7k1CM@NfoXKDf@vLvxWP8It5/UJuYpSf1bx9s96WT3Xe/ucUnaurKAawZ5LWcPLG5zLGs5XCZEKw1LWrBvDQjYj4s0f "Python 3 – Try It Online")
Inputs the grid as a list of lists of \$1\$s and \$0\$s (representing the number of trees at each place) along with the right and down moves and returns the number of trees hit.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ 21 bytes
```
NθNηSζIΣ⭆÷χη§⊟EηS×θ⊕ι
```
[Try it online!](https://tio.run/##TYzBCsMgEETvfkWOK6Tg0mNOpb3k0BJIf8AmUoVoE2NC6c/bGG1xQZnZfTOd5LZ78cH72oyLuy36ISxMtCK5lz/fOqvMEz6bbzbl4MxnB@2iIV6ufITauItaVS8AWVlIWhYnV5tevKF5jRAIWRZ5G6Ubc1dazDCFS2eFFsaJHhSNU3l/JEgYQ2RxSBDpkV2ED1lg0h7jHrN9TJMdiZmUjToR@O/PmNTpD@vwBQ "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte by using @Razetime's suggestion of taking input in an alternate format. Input is as a list of `[x, y, ...rows]` where each row is either a numeric or character array or string of digits representing the number of trees in each cell. In the case where each row is a string, the input does not need to be JSON encoded. Explanation:
```
NθNη
```
Input `x` and `y`.
```
Sζ
```
Ignore the first line of the grid as we know it always begins with a `.`.
```
⭆÷χη
```
Repeat `10/y` times (joining the results together)...
```
⊟EηS
```
... input `y` lines of the grid but keeping only the last...
```
§...×θ⊕ι
```
... and cyclically index its column.
```
IΣ...
```
Sum the number of trees.
Previous 22-byte version used the original `#` and non-`#` characters:
```
NθNηSζI№E÷χη§⊟EηS×θ⊕ι#
```
[Try it online!](https://tio.run/##TUzLCsIwELznK0pz2UANFo89iV56UAr6A7ENJmDTNk2L@PMxL6WB7M7MzkwrmG4H9rK2VuNirkv/4BomUqEtFz9@M1qqJ3wcbxwycGKzG8Pi4IWNUCtzlqvsOJT7IhOkyI6mVh1/QzOMwSGKbNtEiPPcZc9nmPyl1bznyvAOJAm3HOduV9YeUIkoxZjGhzxIHwXgB6bek3QcdbzRYxoFS8ykbMTJgf/9G0/qtLv19QU "Charcoal – Try It Online") Link is to verbose version of code. There are two differences, the first is that this version works just as will with a regular `Map` instead of a `StringMap`, and the second is that it counts `#`s instead of summing trees.
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), 42 bytes
```
->r,y,m{((0..10)%y).count{m[_1][_1*r%11]}}
```
[Try it online!](https://tio.run/##7ZbNCoJAFIX38xRtAo1pcAppVS8yzKJCQciKUReiPvuUVBg1zo@5sru5yB3ncO65n6AoDqWMt3K5E7jEaeUFhNDAJ1keXb3SJ8dLcc6rOqlTlnCWLMScUt408jqL2RpTzBCL96cswo@ai@JZ3rvayjFiPTcs262C9kLPYdfoFL5eNXtoH40W1MHYOzBnqrRgHsRhBn19SVg6V7dNMPwyhOUmEecItXhTwBvwni7eIeANeE8X7w3gDXhPF@@AhHgFgAPgf/T37ZZGv6HRvhBb1j/xGqJk1nCB1Ha1qkl0SToQMmCbbmnqvJiSMGUyykbvrMsb "Ruby – Try It Online")
Expect inputs as \$r = \frac xy\$, \$y\$ and a matrix of `true` and `false` values indicating the presence of a tree at that place. This solution uses a different approach from my previous one. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters and `Enumerable#%` method, which saves five bytes.
] |
[Question]
[
### Definition
We say a pair of integers \$(a,b)\$, where \$0<a<b<N\$ and \$N\$ is an integer larger than 4, is an inverse neighbor pair respect to \$N\$ if \$ab\equiv1\text{ }(\text{mod }N)\$ and \$1\le b-a\le\log\_2{N}\$. There may be no such pairs respect to some integers \$N\$.
To illustrate the definition, consider \$N=14\$. \$(3,5)\$ is an inverse neighbor pair respect to \$N\$ because \$3\times 5=15\equiv1\text{ }(\text{mod }14)\$ and \$1\le 5-3=2\le\log\_2{14}\approx 3.807\$. Another pair is \$(9,11)\$.
On the other hand, consider \$N=50\$. \$(13,27)\$ is not an inverse neighbor pair because although \$13\times 27=351\equiv1\text{ }(\text{mod }50)\$, their distance \$27-13=14\$ is too large to be "neighbors". In fact, there are no inverse neighbor pairs respect to this \$N\$, since there are no such pairs that both \$ab\equiv1\text{ }(\text{mod }50)\$ and \$1\le b-a\le\log\_2{50}\approx 5.643\$ can be fulfilled.
### Challenge
Write a program or function, that given an integer input \$N>4\$, outputs or returns all inverse neighbor pairs respect to \$N\$ without duplicate. You may output them in any reasonable format that can be clearly interpreted as distinct pairs by a human, e.g. two numbers per line, or a list of lists, etc.
The algorithm you use must in theory vaild for all integers \$N>4\$, although practically your program/function may fail or timeout for too large values.
### Sample I/O
For inputs without any inverse neighbor pairs, the word `empty` in the output column means empty output, not the word "empty" literally.
```
Input -> Output
5 -> (2,3)
14 -> (3,5), (9,11)
50 -> empty
341 -> (18,19), (35,39), (80,81), (159,163), (178,182), (260,261), (302,306), (322,323)
999 -> (97,103), (118,127), (280,289), (356,362), (637,643), (710,719), (872,881), (896,902)
1729 -> empty
65536 -> (9957,9965), (15897,15913), (16855,16871), (22803,22811), (42725,42733), (48665,48681), (49623,49639), (55571,55579)
65537 -> (2880,2890), (4079,4081), (10398,10406), (11541,11556), (11974,11981), (13237,13249), (20393,20407), (26302,26305), (39232,39235), (45130,45144), (52288,52300), (53556,53563), (53981,53996), (55131,55139), (61456,61458), (62647,62657)
524287 -> (1023,1025), (5113,5127), (59702,59707), (82895,82898), (96951,96961), (105451,105458), (150800,150809), (187411,187423), (192609,192627), (331660,331678), (336864,336876), (373478,373487), (418829,418836), (427326,427336), (441389,441392), (464580,464585), (519160,519174), (523262,523264)
```
### Winning Condition
This is a code-golf challenge, so shortest valid submission of each language wins. Standard loopholes are forbidden by default.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~14~~ 13 bytes
*Thanks to @KevinCruijssen and @Grimmy for the fix and inspiration from Kevin's now deleted answer*
*-1 byte further thanks to @Grimmy*
```
L.ÆʒRÆo@}ʒPI%
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fR@9w26lJQYfb8h1qT00K8FT9/98UAA "05AB1E – Try It Online")
---
# Explanation
```
L.Æ - Combinations of [1..N] with 2 elements
ʒ } - Filter this when ...
RÆo - 2^(The difference of each pair) is...
@ - <= the input
ʒPI% - Then filter this list further where the product modulo input is 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒcðIḢ2*>¬ȧ⁸P%⁼1ðƇ
```
A monadic Link accepting an integer which yields a list of pairs.
**[Try it online!](https://tio.run/##ASoA1f9qZWxsef//xZJjw7BJ4biiMio@wqzIp@KBuFAl4oG8McOwxof///8zNDE "Jelly – Try It Online")**
### How?
*not updated for less-than-or-equal...*
```
ŒcðIḢ2*<ȧ⁸P%⁼1ðƇ - Link: integer, n
Œc - unordered pairs (of implicit range [1..n])
Ƈ - filter keep those for which:
ð ð - ...this dyadic chain, f(pair,n), is non-zero:
I - deltas [a,b] -> [b-a]
Ḣ - head b-a
2* - 2 raised to 2^(b-a)
< - is less than (n) 2^(b-a)<n == b-a<log(n,2)
⁸ - chain's left argument, the pair
ȧ - logical AND [a,b] or 0
P - product a×b 0
% - modulo (n) (a×b)%n 0
⁼1 - equals one? (a×b)%n==1 0
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~61 59~~ 57 bytes
```
n=>{for(a=b=n;a=a||--b;)--a*b%n-1|2**(b-a)>n||print(a,b)}
```
[Try it online!](https://tio.run/##JYzBCoMwEETv/Yo9tJBItlSrtCGst177A6XgRhDtYStWvBi/PQ14GYY3vPnwwr92GsYZl3vsKArVa/edFJMncUwcAqJ3GpEzfxLMQ5FlyiPrWkIYp0FmxcbrLbpXZSAvDVQXA9cyN2CtTeRW2PfhnD4f3PZKgGpYYRebJxAcV9ka7aBTknIfUtl0/AM "JavaScript (V8) – Try It Online")
The way the `for` loop is written, we have \$b=N\$ during the first \$N\$ iterations and we have \$a=0\$ before \$b\$ is decremented. But in both cases, it implies \$ab\equiv 0\pmod N\$, so the corresponding pairs are rejected anyway.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 20 bytes
```
:2XN!tpG\1=yd|WG>>Z)
```
The output is a 2-row matrix where each column is a pair.
[Try it online!](https://tio.run/##y00syfn/38oowk@xpMA9xtC2MqUm3N3OLkrz/39LS0sA "MATL – Try It Online")
### How it works
Consider input `5` as an example.
```
: % Implicit input: N. Range [1 2 ... N]
% STACK: [1 2 ... N]
2XN % Combinations of 2 elements, as rows in a 2-column matrix
% STACK: [1 2;
1 3;
···;
4 5]
! % Transpose. Each combination is now a column in a 2-row matrix
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
tp % Duplicate. Product of each column
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
[2 3 4 5 6 8 10 12 15 20]
G\ % Modulo N
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
[2 3 4 0 1 3 0 2 0 0]
1= % Equal to 1?
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
[0 0 0 0 1 0 0 0 0 0]
y % Push another copy of the 2-row matrix
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
[0 0 0 0 1 0 0 0 0 0]
[1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
d| % Absolute difference between the two rows
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
[0 0 0 0 1 0 0 0 0 0]
[1 2 3 4 1 2 3 1 2 1]
W % 2 raised to that
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
[0 0 0 0 1 0 0 0 0 0]
[2 4 8 16 2 4 8 2 4 2]
G> % Greater than N? (**)
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
[0 0 0 0 1 0 0 0 0 0]
[0 0 1 1 0 0 1 0 0 0]
> % Greater than. This gives true for entries that are true in (*)
% and false in (**)
% STACK: [1 1 1 1 2 2 2 3 3 4;
2 3 4 5 3 4 5 4 5 5]
[0 0 0 0 1 0 0 0 0 0]
Z) % Use as a logical index into the columns of the 2-row matrix
% STACK: [2;
3]
% Implicit display
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 56 bytes
```
x=>{for(y=x;i=--y;)for(z=x;z>>=1;)y*++i%x-1||print(y,i)}
```
[Try it online!](https://tio.run/##TY7dCoIwHMXvfYo/QbDlDLf24RjzEXqB6EIiYyJOpohaPbstuunm/DgfF6eppmq4BdeP2VRsVXsPo735bvDt/dj6h0lqu822fNY@oMXOxtksWwz@2jXatSwtNXg5pKnbzxl9vfrguhEtxOH3FleApipAA76GiyBAOQGRE2BCEjhxSkBrHWPFokohTvIHFWeMsyKSSqUUo7HQXOeSifyK4ZnA30u0O4PdEWiwSaBGX7y3Dw "JavaScript (V8) – Try It Online")
This \$O(n\log{n})\$ algorithm works practically up to \$N\approx2^{26.5}\approx9.49\times10^7\$.
This was 67 bytes and was originally for my test case verifications only, and then I saw Arnauld's 57 bytes. Inspired by his solution, I checked whether I can golf the loops while keeping \$O(n\log{n})\$ complexity, and here it is.
[Answer]
## [Fortran (GFortran)](https://gcc.gnu.org/fortran/), ~~86~~ 79 bytes
```
read*,n
print*,((pack([i,j],mod(i*j,n)==1.and.2.**(j-i)<=n),j=i+1,n),i=1,n)
end
```
*-7 bytes thanks to @DeathIncarnate*
Yes, I still write Fortran in 2020. Here I'm reading an implicit integer n and looping over i and j (a and b would be implicitly reals). An array (i, j) is masked using the intrinsic pack().
[Try it online!](https://tio.run/##JckxCoAwDEDRvSdJYyxUHc1JxKFYlVRMpXj/qjj9B3/L5S5B2337UWtZQ0RScxXRGwngCssBk1Ca6cwRBBOpZfYuaHSdQ4TUih1ZLSWWxr@XhL@YVWOt/eAf "Fortran (GFortran) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
```
->n{(r=*1...n).product(r).select{|a,b|b>a&&a*b%n==1&&n>=1<<b-a}}
```
[Try it online!](https://tio.run/##BcFLDoMgEADQq7iw@MlAO62mIRm4iHEBVleWGqqJDXB2@p4/7C8vKnPtQu1Vi0II14jNf17HtNe@Ed95nac9RAM2Wm0YM629OKWQMacVElluUspDD9hBf4NHhyClBHze5SjeZgvxjKUmOomqguuiIlqGcyQqryn/AQ "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
NθFθFιF‹›X²⁻ικθ⁼¹﹪×ικθI⟦⟦κι
```
[Try it online!](https://tio.run/##LYo7C8IwFIV3f8UdbyAOFurSUUSEWjq4lQ6xRrw0TcxLf368Sg@cB5xveqowOWVKOdtXTl1ebjqgF83m4QLwgH/T2q2OEU9Bq8RU7z6clYQL2RyRJMxCSPDso8/KRNzx5@7ZOLzSolfkR7CgD2QTHlRMOAyzBBpHIZpSqnpftm/zBQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `N`.
```
FθFι
```
Loop `0 <= a < b < N`. (`a=0` can never be a solution, so it doesn't hurt to include it.)
```
F‹›X²⁻ικθ⁼¹﹪×ικθ
```
Check whether `2**(b-a)<=N` and `a*b%N==1`.
```
I⟦⟦κι
```
If so then output `a` and `b`, on separate lines, with each pair double-spaced.
[Answer]
# Python 3, ~~76~~ 71 bytes
```
lambda N:[(a,b)for a in range(N)for b in range(a)if(1<<a-b)-N<a*b%N==1]
```
Thanks, Jitse, for saving me 5 bytes after some discussion.
You can [try it online](https://tio.run/##RYzRCoMgGEbv9xQSDHT8wtSsGblH8AVaF8pyCzaL8mZEz@5WN/suvosD54yf@ByCSF7f0su@3d0iUzXYgiN@mJBFfUCTDY8Omx24P7Ck95jVtaWOUFPbkzsarVmbYjfHWTcSGAOWgzwDlwWInIFSCljJFRRSimL/EiTP@aVsD1s@bPndbyoq2uqAfhunPkTssyWsiF7R4nEga0bSFw), where I'm not running the larger test cases because it times out
[Answer]
# [C (gcc)](https://gcc.gnu.org/) -lm, 76 bytes
A port of [my JS answer](https://codegolf.stackexchange.com/a/198874/58563).
```
a,b;f(n){for(a=b=n;a=a?a:--b;)--a*b%n-1|pow(2,b-a)>n||printf("%d,%d ",a,b);}
```
[Try it online!](https://tio.run/##ZcxBCoMwFATQfU/xCQhJ8YO2utCQ9gaeoJsfJSJoFFvqQr160xQqLtzN8IYpsS5L5yjU0nArZtOPnJRWVpKiO@WIWgpEOuvAYrwM/cQvoUYSN7ssw9jYl@EsqMKgAhb6FyFX9@6bCjpqLBcwnwD@MwBWqBQgByYk/Hoq5M7sYQsVJzvHyYHTaOc0OvA1iTf28cBZlm3so@fVfUrTUv10ODlsuy8 "C (gcc) – Try It Online")
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 140 94 90 bytes
```
define f(n){for(a=2;a<n;a=a+1){for(d=1;2^d<=n;d++){if(a*(a+d)%n==1){print" ",a,",",a+d}}}}
```
[Try it online!](https://tio.run/##TY5RC4IwFIXf76@4DIItDdxymsz1SyJYzdEgl4gSIf52G@ulc@E8nO8cuLf7ttnO@dCho4Et7jVSo4UybVBGm4z/Iqu5Elfb6qBslrHFO2r21GSW7YLWsTSMPkwESW5yEi@SNWqD98M/O6Q@DPOkx85YyhgugFFpgonkSPBwRpJyO/f9B3X8JzH2VyaXQBSssEngJcgCjiWHpmmA16KBSspjlbwGKUpxqqH4Ag "bc Try It Online")
Function f() takes the number as input, writes its output to stdout, and returns 0, which should be ignored. The test wrapeper in the TIO needs a special marker for end-of-file, as it otherwise keeps trying to read
Having looked at another answer, I saw I could do \$2^{d}\le{n}\$ instead of \$d\le\log\_2{n}\$ -46, including the +2 for -l.
I was amazed to find it turned into a one-liner.
I then realized I had two unneeded pairs of parentheses. -4.
I have also realized that I allow b>n, but it apparently doesn't hit in the test cases.
Edit: it turns out with \$0<a<N<b\$, there can't be a hit unless \${{b-a}\over2}\ge\sqrt{N-1}\$ Combining with the neighbor requirement of \$b-a\le\log\_2{N}\$ we get \$2\sqrt{N-1} \le \log\_2{N} \$ This only happens at \$N=1\$, so I'm safe.
## ungolfed:
```
define f(n) {
for (a=2; a<n; a=a+1) {
for (d=1; 2^d<=n; d++) {
if (a*(a+d)%n==1) {
print " ", a, ",", a+d
}
}
}
}
```
## originally: [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html) -l, 138 + 2 = 140 bytes
```
define f(n){
scale=9
m=l(n)/l(2)
scale=0
for(a=2;a<n;a=a+1){c=a+m
if(c>=n)c=n
for(b=a+1;b<c;b=b+1){if(((a*b)%n)==1){print " ",a,",",b
}}}}
```
[Try it online!](https://tio.run/##TY7RasMwDEXf9RXGMLC3lCVu3My46pfsxXYSZnCckKaMEfrr81xvD5NAQveeC7IupX4YfRzIyCLf4epMGFDBhCHfr4EJ/qfVMM4rMyi0OUdt0Lw0fHd5TeBH5i4YucNYIPswtT07bdE@sAwwZp4tf4ocMQvL6uNGKKGVqWhuC/dcCT4/fBgI83G5bbgOpmeckx1Irt9IcaqcPFwILXp/m6Yvgvn/4vF/MH2PVMMdkoSmBVnDsW1AKQVNJxScpDyeyuxAila8dVB/z8vm53hNh/AD "bc Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 46 bytes
```
riJs1ro2CBf{Jp^.-ab2j**g1.<jpdg1.%1==&&}:U_:so
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KNOr2LAo38jZKa3aqyBOTzcxyShLSyvdUM8mqyAFSKka2tqqqdVahcZbFef//29sYqgAAA "Burlesque – Try It Online")
```
ri # Read as int
Js1 # Store a copy
ro # Range [1,N]
2CB # Combinations of length 2
f{ # Filter for
J # Duplicate
p^.- # i-j
ab # |i-j|
2j** # 2^|i-j|
g1.< # < N
jpd # i*j
g1.% # (i*j)%N
1== # Equal to 1
&& # Bitwise and
}
:U_ # Filter out i=j
:so # Filter for sorted (removing duplicates)
```
[Answer]
# Haskell, 57 bytes
A port of my Python answer
```
f n=[(a,b)|a<-[0..n],b<-[0..a-1],2^(a-b)<=n,1==mod(a*b)n]
```
You can [try it online](https://tio.run/##y0gszk7Nyfn/P00hzzZaI1EnSbMm0UY32kBPLy9WJwnCStQ1jNUxitNI1E3StLHN0zG0tc3NT9FI1ErSzIv9n5uYmadgq5CSz6WgUFBaElxS5JOnoKJQnJFfDqTSFExxiBua4NJggEPC2MQQh4ylpSUuW8yNLP8DAA)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 55 bytes
```
{grep {[*](@^a)%$_==1&&$_>=2**[R-](@a)>=2},(^$_ X ^$_)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAoTpaK1bDIS5RU1Ul3tbWUE1NJd7O1khLKzpIFyieqAnk1OpoxKnEK0QoAEnN2v/FiZUKekAj0vKLFEx1FAxNdBRMDXQUjE0M/wMA "Perl 6 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~77~~ 64 bytes
```
function(N)which((o=outer(x<-1:N,x,'-'))>0&2^o<=N&x%o%x%%N==1,T)
```
[Try it online!](https://tio.run/##FcW7CoAgFADQva9o0e4FhewxGNonODW3SGJLF0LJvzdcznlr6I2sIT8@3fSAwy/ePgKQpZyuF4qRanOiiEEOiPvIp5OMdbwwYoUxZ60SB9YAK3YB1NJcx@a8qJbWGusP "R – Try It Online")
Returns a matrix with columns `b,a` of all inverse neighbor pairs. Since it creates several `NxN` matrices, this will run out of memory in a hurry.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 24 bytes
```
fȯ≤¹`^2F-fȯ=1%¹F*fF>´×,ḣ
```
[Try it online!](https://tio.run/##yygtzv7/P@3E@kedSw7tTIgzctMFcmwNVQ/tdNNKc7M7tOXwdJ2HOxb////f2MQQAA "Husk – Try It Online") Nothing too complicated, just the three filters applied to the list of ordered pairs.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õ à2 fÈrͧU«1nX×uU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9SDgMiBmyHLNp1WrMW5Y13VV&input=MTQKLVI)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~73~~ ~~71~~ 69 bytes
```
n_:>Select[Range@n~Subsets~2,Mod[1##&@@#,n]==1&&2^#[[2]]<=2^#[[1]]n&]
```
[Try it online!](https://tio.run/##HcbRCoIwFADQXxEGe7pldymxaLIfCCofxy2WzhLyBjmfIn99RefpDD7ew@Bj3/jUmcSXbVWHR2iiO3m@BctzPV3HEMdZwf7ZOhRCWiuAyRiUUp2Fc4poZ/5DIpaUDq@eoxOL6jj14Zd82RHJLLfZuwQsoFzBukDQWgNulP6kLw "Wolfram Language (Mathematica) – Try It Online")
Defined as a [delayed rule](https://reference.wolfram.com/language/ref/RuleDelayed.html) that can be applied to any integer.
] |
[Question]
[
I have so many secrets and nowhere to keep them!
The goal is simple: write a program that lets you save a string and have it be protected by a password.
The program will take an alias, password and (optional) secret as parameters.
If this is the first time the program is called with a given alias, then it will store/remember the secret, and output whatever you want.
If the program is called with an alias that has been used before, then it will output the secret for that alias iff the password is the same as the first time the program was run with that alias.
## Other cases
* If its the first time being called with a certain alias and no secret is given - store nothing.
* If the program is called with an alias that has been used, and the password is incorrect - return any kind of error or nothing at all.
* If the program is called with an alias that has been used, the password is correct and a new secret is supplied - output the old secret and replace it with the new one so that next time only the new secret is output.
* If the program is called with an alias that has been used, the password is correct and no new secret is supplied - output the old secret and make sure it doesn't get replaced.
Note: These secrets/passwords do not need to be stored securely
Also note: any alphanumeric input for aliases passwords and secrets should be accepted
Standard rules apply, good luck!
[Answer]
# JavaScript (ES6), ~~60~~ 50 bytes
*Saved 10 bytes thanks to [@JonasWilms](https://codegolf.stackexchange.com/users/72288/jonas-wilms)!*
Takes input as either `(alias,password,secret)` or `(alias,password)`. Returns *undefined* the first time a secret is stored, or *false* if the password is incorrect.
```
f=(a,p,s,[P,v]=f[a]||[p])=>p==P&&(f[a]=[P,s||v],v)
```
[Try a 1st test case online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjUadAp1gnOkCnLNY2LToxtqYmuiBW09auwNY2QE1NAyRkC5Qtrqkpi9Up0/yfnJ9XnJ@TqpeTn66RpqHuWJSXWJqToq6joF5cWpBaVGBSXFxuUAQWCHZ1DnINUTBU19TkIlYbEUoTTU3L87EqjcxPSQSqAwLSTcV0txFp7v4PAA "JavaScript (Node.js) – Try It Online")
[Try a 2nd test case online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjUadAp1gnOkCnLNY2LToxtqYmuiBW09auwNY2QE1NAyRkC5Qtrqkpi9Up0/yfnJ9XnJ@TqpeTn66RpqHuWJSXWJqToq6joF5cWpBaVGBSXFxuUAQWCHZ1DnINUTBU19TkIqQt0dS0PB9FmxEp2ohQCnOYpuZ/AA)
### How?
We define a named function \$f\$ whose underlying object is also used to store the passwords and the secrets.
### Commented
```
f = ( // f = named function whose underlying object is used for storage
a, // a = alias
p, // p = password
s, // s = optional secret
[P, v] = f[a] // if f[a] is defined, retrieve the password P and the secret v
|| [p] // otherwise, copy p in P
) => //
p == P && ( // if p is not equal to P, yield false; else:
f[a] = [ // update f[a]:
P, // save the new password (or leave it unchanged)
s || v // save the new secret if it's defined, or keep the previous one
], //
v // return the previous secret
) //
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~94~~ 93 bytes
```
def f(a,p,s=0,d={}):
q,t=d.get(a,(0,0))
if q==p:d[a]=p,s or t;return t
elif q<1<s:d[a]=p,s
```
[Try it online!](https://tio.run/##jcyxCsIwFIXhPU9xtzRwkaY4SG2eRBwKSWxA0jS9QoL47DFdHMSC6zk/X8g0zb4rRRsLthkx4Kpa1Or5Ej2DBUnpw81QfZoWWyEYOAuLUqHXl/Gqag5zBDpHQ4/ogRiY@1YMclg/SQnReao@nxxH4DlnLtjXmFL6PSLI03/15iIcd5RO7iisvAE "Python 2 – Try It Online")
For once, Python's weird default dict parameter works in my favor...
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
Builds a hash for aliases to a single key-pair of `password => secret`. Probably could be more elegant.
```
->a,w,s=p{@q||={};(b=@q[a])?s&&b[w]?b[w]=s:b[w]:s&&@q[a]={w=>s}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5Rp1yn2Lag2qGwpsa2utZaI8nWoTA6MVbTvlhNLSm6PNYeRNgWW4EoK6AYWNa2utzWrri29n9atFJGppKOglJBOYisUIrlKlCAC5aXo/ILEPxUOB9ZNZCsJMIINFurMJX8BwA "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
(c=#~g~#2;#3!=##3||(#~g~#2=#3);c)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPZVrkuvU7ZyFrZWNFWWdm4pkYDImCrbKxpnayp9j@wNDO1JJoroCgzr8QhLVopMSczsVhJR6kgsbhYKRaHuI5ScWpyUWoJTgVYxJMSUwiaZ4THwNj/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~140~~ ~~138~~ 134 bytes
-2 bytes thanks to @Expired Data
```
a=>p=>s=>(a=P.ContainsKey(a)?P[a]:P[a]=new[]{p,s},o:p==a[0]?a[1]:p,s==""?s:p==a[0]?a[1]=s:s).o;var P=new Dictionary<string,string[]>()
```
[Try it online!](https://tio.run/##tVJdS8MwFH3frwh9aTLqug330poMmduLImUqIqUPly6OwExKbuYY4m@v7ZxgmboPMA8J53DO5dxDcjzLUZWTpc4vZmsNLyoPyAahs0rPm@DzEUKQycPtiHBSAhcFF8gFBZ50RkY7UBqv5ZoCGyYpZFF9cS1XafZWBPgemKjgHNJuNoS0l0UVx7nnDbFBc4yQdUz8CpYktZtcqdwpo8Gum2HSTFBWxq2kAo7Wsah3aTUsFzOPUQ@XhbTFOeKqazfE3Xg0Hd@TnsfY4ab9YhgMVuYX8ZOZwYljd4P3Twi@v8CYhKGVKB1BB062Hq1y8kZpSdl/VPutrcPX@qvivR2E7RZp50ajWcjOwszpM/W3Jj8gfsNUE1@7@IwdYTxIvN3jR3H9VSpldU6ZvJu/f2z@dlh@AA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
```
def f(a,p,s=0,d={}):
P,S=d.get(a,(p,0))
if p==P:
if s>0:d[a]=p,s
return S
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1GnQKfY1kAnxba6VtOKSyFAJ9g2RS89tQQoo1GgY6CpyaWQmaZQYGsbYMXFCWQV2xlYpUQnxtoC9XFxFqWWlBblKQT/LyjKzCsBmqeekamuo6BeWVmprsmFJlhRUYFdUEfB0II41SBzdRRMcJhiZIjdlP8A "Python 2 – Try It Online")
Similar to [Chas Brown's method](https://codegolf.stackexchange.com/a/185704/20260).
] |
[Question]
[
Look at the following string. Notice a pattern?
```
ABEFNOPEFGH
DC G Q I
M H R J
LKJI S K
D T L
C U M
BAZYXWV N
E O
D P
C Q
BAZYXWVUTSR
```
As some might have noticed, it's basically a spiral of the alphabet, where the distances between rows / columns are gradually increasing by 1 space / newline.
# Rigorous definition
* Let's have a counter **c**, which is initially 0.
* We write out the first **c + 1** letters of the alphabet from left to right: `A`.
* Then, from top to bottom the next **(c + 1)(c + 2)/2** letters (add `B`): `AB`.
* From left to right, the next **(c + 1)(c + 2)/2** (add `C`):
```
AB
C
```
* And from bottom to top, the next **c + 1** letters (add `D`):
```
AB
DC
```
* Reached the end of the cycle. Hence, let's increment **c** (which becomes 1). Then, it starts back from the first step, the only difference being that instead of using the *first **c + 1*** letters of the alphabet, we use the *next **c + 1*** letters, starting from the last element of this cycle (`D` in this case, so we continue with `EFG...`). When `Z` is reached, it cycles back from `A`.
# Task
Given an integer **N** (which is positive for 1-indexing or non-negative for 0-indexing), output the first **N** cycles of the spiral.
# Rules
* You can either use the lowercase or the uppercase alphabet, but your choice must be consistent (only use one of them, mixing is not allowed).
* You can take input and provide output through any of [the standard methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages), while noting that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default.
* Acceptable output formats: multiline string, a list of strings representing lines, a list containing multiple lists of characters, each representing one line, or anything else you find suitable. In case you don't choose the first format, it would be nice to include a pretty-print version of your code.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes (in each language) which fulfils the requirements wins!
---
# Test cases
The input integer will be separated by its corresponding output through a newline, and the tests will be separated using dashes. Note that these are 1-indexed.
```
1
AB
DC
--------
2
ABEF
DC G
M H
LKJI
--------
3
ABEFNOP
DC G Q
M H R
LKJI S
D T
C U
BAZYXWV
-------
4
ABEFNOPEFGH
DC G Q I
M H R J
LKJI S K
D T L
C U M
BAZYXWV N
E O
D P
C Q
BAZYXWVUTSR
-------
5
ABEFNOPEFGHFGHIJ
DC G Q I K
M H R J L
LKJI S K M
D T L N
C U M O
BAZYXWV N P
E O Q
D P R
C Q S
BAZYXWVUTSR T
R U
Q V
P W
O X
NMLKJIHGFEDCBAZY
------
6
ABEFNOPEFGHFGHIJSTUVWX
DC G Q I K Y
M H R J L Z
LKJI S K M A
D T L N B
C U M O C
BAZYXWV N P D
E O Q E
D P R F
C Q S G
BAZYXWVUTSR T H
R U I
Q V J
P W K
O X L
NMLKJIHGFEDCBAZY M
S N
R O
Q P
P Q
O R
NMLKJIHGFEDCBAZYXWVUTS
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
F⮌…⁰NB⁺²⊘×ι⁺³ι⭆α§α⁺λ÷×ι⊕×ι⁺⁹⊗ι⁶
```
[Try it online!](https://tio.run/##ZczPCsIwDAbwV8kxQgRRUMSTsoM7KDJ9gW6Ls9A/o2vL3r6uvXgwl4QvH7/uI1xnhUrpbR1gw5HdxNgIMzBuCGozBn8PumWHq2XgYmd8qDDhluAqVOQeX1LzhJKg5DsCmZsET@@kGW5iREFw9rXpec5nqals@0pG2fNPqE3nWLPxf@yRoLKhVcuj8Iu/L/uU0iGto/oC "Charcoal – Try It Online") Link is to verbose version of code. Note: The deverbosifier outputs a trailing separator for some reason. Explanation:
```
F⮌…⁰NB
```
Draw boxes in reverse order of size (largest to smallest).
```
⁺²⊘×ι⁺³ι
```
Calculate the size of the box.
```
⭆α§α⁺λ
```
Draw the border of the box using a rotated alphabet.
```
÷×ι⊕×ι⁺⁹⊗ι⁶
```
Calculate the letter that would appear at the top left of the box (0-indexed).
[Answer]
# [Python 2](https://docs.python.org/2/), 176 bytes
```
n=input()
k=n*-~n/2+1
a=eval(`[[' ']*k]*k`)
x=y=z=0
for s in range(4*n+4):exec s/4*(s/4+1)/2*"if'!'>a[y][x]:a[y][x]=chr(z%26+65);z+=1\nx+=abs(2-s%4)-1;y+=s%2-s%4/3*2\n"
print a
```
[Try it online!](https://tio.run/##LYfdCoIwGEDv9xRLEPeDLJd6oXy9iAqu0BTjU5zF9KJXN4ngcA5nWpduRL3vCD1Or4VxMgCK8INKy4gYaN7myeqiCGhQieGg5sTBChucSTvO1NIe6Wzw0bBYoIx51rjmTq2KBTskI6608Po2OAVXU6xV4arsX7h3M9t8nco04fkmISrRSTA3y3Ro/ZiHUb5KsP7v1EXoEj0yzT0u1Ox78gU "Python 2 – Try It Online")
## Explanation
We construct an empty array of spaces of the right size, then move over it like this, starting in the top-left corner:
* 1 step →, 1 step ↓, 1 step ←, 1 step ↑
* 3 steps →, 3 steps ↓, 3 steps ←, 3 steps ↑
* 6 steps →, 6 steps ↓, 6 steps ←, 6 steps ↑
* 10 steps →, 10 steps ↓, 10 steps ←, 10 steps ↑
* …
Every time we find a blank cell, we put a letter there and cycle to the next letter in the alphabet.
In the code, `s%4` is the direction (→↓←↑), and we step this many times:
```
TriangularNumber(s/4) = s/4*(s/4+1)/2.
```
## Golf opportunities
* Is there a shorter way to map `s%4` to `1,0,-1,0` than `abs(2-s%4)-1`?
* Is there a shorter way to map `s%4` to `0,1,0,-1` than `s%2-s%4/3*2`?
## Credits
* Mr. Xcoder saved a byte.
[Answer]
# C, ~~305~~ 281 bytes
*Thanks to @Mr. Xcoder for saving four bytes!*
```
#define L(x,y)l[x][y]=a++%26+65;
#define F for(
c,i,j,a,p;f(n){char**l=calloc(8,i=a=n*n*4);F;i--;memset(l[i],32,a))l[i]=malloc(a);F c=a=p=i=0;c<n;++c){F i=p;i<c+p+!c;)L(j=0,c+i++)F p=i;j<=-~c*(c+2)/2;)L(j++,c+i)F;c+i-1;)L(j-1,c+--i)F i=0;i<=c;)L(j+~i++,0)}F i=0;i<j;)puts(l[i++]);}
```
[Try it online!](https://tio.run/##NY/BasMwDIbveQqvY2BFNkuyrRsovubUNyg5GC3ZFBI3tB20lPbVMyelOhjx8f0/Mtsf5ml6/m5aCY3a6JM5Q7891dtz7TziS7HG9QclD6FS7W6vEzZiOuPNSK0OcOFfv0/T3rHv@x3rLyPOu5CG9B2oIrGWhmY4NEfdb6U2b4XxAPPqhnvAR01xzIxOXEZcBkJkuFRK3EhSMo74xAQb3bnMMAoiVCrK1JXO3jjVjAW8FouBOBtQUXxtviCbR2RthGrul9Ldy/AWm0wG1wfvCMa/42G@E7EGuk4SjmrwEjQkl0TFif9XeqbiclJSfpJCFKOW3GoFsFiLqQUouU7/)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~262~~ ~~260~~ ~~254~~ 245 bytes
```
lambda n:[[[' ',chr(65+(4*(i<j)+sum((i<j)*8+2+I*[5,9][i<j]+sum(2*R(I))for I in R(S(i,j)-1))+[i+j,-i-j][i<j])%26)][max(i,j)==S(i,j)*-~S(i,j)/2or i*j<1]for i in R(1+n*-~n/2)]for j in R(1+n*-~n/2)]
R=range
S=lambda x,y:int((8*max(x,y)+1)**.5+.99)/2
```
[Try it online!](https://tio.run/##ZU@7joMwEOzzFW5O3vUaIqwjgij@AFpSOhTcg4stMBGXSEmTX@eMSXfVzs7Mzmgvj@t59Gru9Gnu2@Hjq2V@b4zhjMvP8wS7nOBdgD04pN/bABGJghRVwuSybEwgmigpUUOF2I0Tq5j1rIYjWOkwyRDJWHIysYlbD/BN7bAxQ3uPFq1Xq0ieK9iqkGKFO2TNkmfXvIx8cPitwsi6f@ym1lPrf743R/165i4fe@uvAIVYysKKlKEQaU5pWYae@TIFnfGT56kbrQf@mn38pF86OigQ5z8 "Python 2 – Try It Online")
New method with more maths!
Returns a list of char-lists.
---
Old version:
# [Python 2](https://docs.python.org/2/), ~~322~~ ~~321~~ ~~308~~ 298 bytes
```
R=range
n=input()
w=1+n*-~n/2;r=[w*[' ']for _ in R(w)];r[0][0]='A';l=R(1,w*w*9);c=lambda:chr(65+l.pop(0)%26)
for i in R(n+1):
w=1+i*-~i/2;W=w-i
for x in R(W,w):r[0][x]=c()
for y in R(1,w):r[y][w-1]=c()
for x in R(1,w):r[w-1][w+~x]=c()
for x in R(1,w-W):r[w+~x][0]=c()
for l in r:print`l`[2::5]
```
[Try it online!](https://tio.run/##bY9Na4QwEEDv@RW5FBNd242wSxuZQ/@CFw8hdK392EA6hmAZvexft0YvLRTm9h7zZsI8XgeslqWB2OHnO0NwGL5HIRmBKjAvb/hQ1REM5Sbjmf0YIn/hDnkjSNo6mqNdB7LnrPbQCHWgnPInWffgu6/Xt0731yjOp8LfhyGIo7yrzpKlJW5fgoWSmvEUc2vMrbEWqHSMJ2napfZAUm@pyUK/3rbBeYdqh7M1VKpfePqDEzNU3KZ/jbLdnITTN8lIgk9C1CE6HC/@YiqtT3ZZHn8A "Python 2 – Try It Online")
[Answer]
# Perl 5, 177 +2 (-nl) = 179 bytes
2 bytes saved thanks to Xcali
```
sub n{chr 65+$c++%26}@O=(n);while($,++<$_){$_.=$"x$,for@O;push@O,($"x length$O[0])x$,;$O[0]=~s/ /n/eg;s/ $/n/e for@O;1while$O[-1]=~s/.*\K /n/e;s/^ /n/e for reverse@O}print for@O
```
[Try it online](https://tio.run/##NczdCoIwGMbxc69ixBto8zv0ZA0872AX0IeQLCfIlE0rELv01lI6@/Pye96eqzYzUFHwaUyMHm9ITpVQKM8wVBhv03wuGHWlR56iabkLPsYHKL0JypDC5gX@vVMFI/2oRcF8155Qy2U9CGCn@OJZQJaibx2hSEa8JjbgV2idJstni4JkUeHufFykhVf0h0jxB1eaF2zuVSOHdWxM4qTO3sk@XT80ndQmkO0X)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 47 bytes
```
(⎕a⍴⍨≢i)@i⍴∘''⊃⌈/i←∪+\↓1⍪⊃⍪⌿(+\⍳⎕)⌿¨⊂⍪∘-⍨∘.≠⍨⍳2
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CYZcjzra0/5rAPmJj3q3POpd8ahzUaamQyaI0zFDXf1RV/Ojng79TKDaRx2rtGMetU02fNS7CiQMJHv2awCFejcDtWsCOYdWPOpqAol3zNAFGdUxQ@9R5wIQq3ez0X@gTf/TuMwA "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
Inclusion-Exclusion lets you calculate the sizes of some unions and intersections between sets knowing some of the other values. I won't explain it exactly, but your challenge is to visualize inclusion-exclusion on a Venn Diagram.
Because I'm nice, you'll be using rectangles, not circles.
You will be given a list of rectangles denoted by top-left and bottom-right corner coordinates in any reasonable format (list of 4-tuples, list of pairs of pairs, list of pairs, etc). You can assume that all coordinates are non-negative and within your language's (reasonable) number range (please specify what it is if it's less than 128). You can choose to be left-inclusive or left-exclusive and right-inclusive or right-exclusive. Regardless of your chosen format, you can assume all rectangles are at least 1x1.
Then, you are to draw out each rectangle on the screen (ASCII canvas) using a single non-whitespace character `k`, which is yours to choose.
However, whenever two rectangles overlap, the overlapping area shall be drawn with another non-whitespace character `l != k`, also yours to choose.
Whenever *three* rectangles overlap, the overlapping area should be drawn with `k`, and for an odd number of rectangles covering, `k`, and an even number, `l`.
The background should be single whitespaces (`0x20`).
# Test Cases (`k = "#", l = "."`)
```
0 0 9 9
1 1 10 10
2 2 11 11
#########
#........#
#.#######.#
#.#######.#
#.#######.#
#.#######.#
#.#######.#
#.#######.#
#.#######.#
#........#
#########
1 1 3 3
2 2 4 4
##
#.#
##
1 1 9 9
2 2 8 8
3 3 7 7
########
#......#
#.####.#
#.####.#
#.####.#
#.####.#
#......#
########
```
# Notes
* Leading spaces and newlines (which occur if the minimum coordinate isn't `0, 0`) must be present
* Any trailing spaces and newlines are allowed to a reasonable extent (i.e. don't trail like 100000000 newlines, that's just annoying)
* x- and y- axes can face either way but you must be consistent and specify which (default is x- right and y- down)
* coordinates can be 0-, 1-, or 2- indexed.
[Reference Proton Implementation](https://tio.run/##hVDbaoMwGL5unuIjV8nWhaqUtgP3Ii4XoumaYZMQHbMUn90l1g07Bgv8EL7Tf3DedtaMY2Wtr7UpO9UiRyHJ50k3Ctq4j45xPL2g0UbhSlYLpSidU6Zm59Ixbbr1pBGta3TwcE4G8uZ1HfMKCirxgHPZs75IJY7Wo8czFml8AnUANxBilmZ/SyWJaHWPxul@xMVGxpQqNgv4RFwmIpmJ7Eas9BFxzKKXxUUiz1GdPMu2HNc7HFRQDNGgmlb9Jr89URBqCLs7H27CKMKjeAR9NdNXvFttppPFajvPIznj6@WS4YK3DP5/Fp39caiFcRwTJDjgQFKk2GNPMmTYYUfIFw)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the objective is to have the shortest code. Happy golfing!
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine (C64), 57 bytes
```
20 44 E5 A0 03 84 FB 20 9B B7 A4 FB 96 22 C6 FB 10 F5 85 FC A6 24 20 F0 E9 A4
25 B1 D1 09 01 49 02 91 D1 C8 C4 23 D0 F3 E8 E4 22 D0 E9 A9 2C C5 FC F0 D0 A5
C6 F0 FC C6 C6 4C 44 E5
```
This is position-independent code, put it somewhere in RAM and use the correct start address calling it with `sys`.
**[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"incexc.prg":"data:;base64,AMAgROWgA4T7IJu3pPuWIsb7EPWF/KYkIPDppCWx0QkBSQKR0cjEI9Dz6OQi0OmpLMX88NClxvD8xsZMROU="%7D,"vice":%7B"-autostart":"incexc.prg"%7D%7D)** (start address `$C000` / `49152`).
**Usage:** `sys<startaddress>,<x1>,<y1>,<x2>,<y2>[,<x1>,<y1>,<x2>,<y2>[,...]]`
**Example:** `sys49152,0,0,9,9,1,1,10,10,2,2,11,11`
On reasonable number ranges: The natural range on this 8-bit machine is [0-255], and the program will accept this as parameters. But the C64 screen only has 40 columns and 25 rows, therefore limiting the **reasonable** range to [0-40] for x values and [0-25] for y values. Using other values will have unpredictable behavior.
---
**commented disassembly listing:**
```
20 44 E5 JSR $E544 ; clear screen
.mainloop:
A0 03 LDY #$03 ; index for reading coordinates
84 FB STY $FB
.inputrect:
20 9B B7 JSR $B79B ; read 8bit value from parameter
A4 FB LDY $FB
96 22 STX $22,Y ; and store to $22-$25
C6 FB DEC $FB
10 F5 BPL .inputrect ; parameter reading loop
85 FC STA $FC ; store last character
A6 24 LDX $24 ; load y1
.rowloop:
20 F0 E9 JSR $E9F0 ; get pointer to screen row in $d1/$d2
A4 25 LDY $25 ; load x1
.colloop:
B1 D1 LDA ($D1),Y ; load character at screen position
09 01 ORA #$01 ; set bit 0 ( -> '#')
49 02 EOR #$02 ; toggle bit 1 (toggle between '#' and '!' )
91 D1 STA ($D1),Y ; store character at screen position
C8 INY ; next x
C4 23 CPY $23 ; equals x2?
D0 F3 BNE .colloop ; no -> repeat
E8 INX ; next y
E4 22 CPX $22 ; equals y2?
D0 E9 BNE .rowloop ; no -> repeat
A9 2C LDA #$2C ; load ','
C5 FC CMP $FC ; compare with last character from parsing
F0 D0 BEQ .mainloop ; if ',', repeat reading coordinates
.waitkey:
A5 C6 LDA $C6 ; load input buffer size
F0 FC BEQ .waitkey ; and repeat until non-empty
C6 C6 DEC $C6 ; set back to empty
4C 44 E5 JMP $E544 ; clear screen
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~218~~ ~~192~~ ~~189~~ ~~185~~ ~~158~~ ~~154~~ 147 bytes
```
def f(l):_,_,a,b=map(range,map(max,zip(*l)));print'\n'.join(''.join((' '+'#.'*len(l))[sum((x<=i<X)*(y<=j<Y)for x,y,X,Y in l)]for i in a)for j in b)
```
[Try it online!](https://tio.run/##XY9ha4NADIa/@ysO9uESF8qpLW03/R8tnRRLdTvRU1wHuj/vklMoDN5wb3JPcrl@enx1Lp7ne1mpChp8u9KVCrplbdHDULjPksS1xUi/toewQcT3frDuoT@c3tSddaDXE7TSr/plo8OmdDwLL98/LcCYZjY9YQhTmtXpGatuUCNNdKKzsk41mEvFii/8ZS32hnMFlwAMKZY6SiAFEJESGQnJY1KsSGoR5hgEvmuhEtaT2bL@Ezz2@CQOLMkS37pned5/N1i3McRv7ZZNDG0pXmzC1ld3XN0v9iCwWWHDCHduOclx/gM "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
WS«≔I⪪ι ιF…§ι⁰§ι²«Jκ§ι¹UMKD⁻§ι³§ι¹↓§10Σλ
```
[Try it online!](https://tio.run/##XYzBbsIwEETP8VesctqVgmSnJ9oTggtISKjpD1jBDSucdZQ4gFTx7W4ol1DNXmZm59Un29fB@pSuJ/YOcCvdGKvYszRIBD8qWw0DN4JrO0SsOs8RuYAccqICmD5U9h16wE8rjcNV3MrR3R4feqpntqQnLduNbfcV8PzSGnqAsr3t1qFtrRzx4Nx5w72rIwfBPcs4zOlv9H9fwPsmXGWW50bnBVRji57@@Hd1T0mDhiUslYFJejpVQglmMkalxcX/Ag "Charcoal – Try It Online") Link is to verbose version of code. ~~Will be 6 bytes shorter once @ASCII-only fixes a bug in Charcoal~~. Takes input as a newline-terminated list of space-separated list of co-ordinates. Explanation:
```
WS«
```
Loop over each line of input until a blank line is reached.
```
≔I⪪ι ι
```
Split the line into a list of co-ordinates.
```
F…§ι⁰§ι²«
```
Loop over all the X co-ordinates.
```
Jκ§ι¹
```
Jump to the top of the column.
```
UM
```
Map over each of...
```
KD⁻§ι³§ι¹↓
```
... all the cells in the column...
```
§10Σλ
```
... the new value is `0` if they contain `1`, otherwise `1`. Edit: Soon after writing this, Charcoal changed the behaviour of `¬` so that `I¬Σλ` works here to save 1 byte.
[Answer]
# [J](http://jsoftware.com/), 36 34 bytes
```
(' ','#.'$~#){~[:+/(-@]{.-~$1:)/"2
```
[Try it online!](https://tio.run/##ZY7RasIwFIbv@xQ/WohlNrZVUMsGY4OBIF7I7sYuuibVji5H2mRMhL56TcKYF@M7gXPId37O5zDirMJDDoYpEuT2xRzP@@3LMGFgUzbmLOzH0aV/y@9mk/jx/cLjPkzzaDbKhijYPXFs2LdEIYQU@KAf2aFoySgBfZQgo09Go6IWZVO0tT7D75Bqzhx4tUpHjdE1KVRGlb6pOyjSOLUkTFmrg0v64kEgyyPhHhXmyCyhPTbB2oLUkbjyP6md0pue/erOmlv8uMDif6Az1n8xK4tfWGI5XAE "J – Try It Online")
*-2 bytes thanks to Bubbler*
We take input as a list of 2x2 matrices.
* For each of them `"2`, draw a box of ones `1:` of the same shape `$` as the element-wise difference between the top-left and bottom-right coords `-~`.
* Then rotate that down and to the right with 0 fill `-@]{.` until the upper leftmost `1` is in the coords specified by the left arg `-@[`.
* `[:+/` Sum the resulting matrices element-wise. J guarantees they will be the same size by adding 0 fill to the right. This will produce a single matrix with integers 0, 1, 2, 3, etc. We'll use those to index into our ascii chars `{~`.
* `'#.'$~#` Repeat the pattern `#.` cyclically `$~` to the input length `#`, and then prepend a space `' ',`.
[Answer]
# [Python 2](https://docs.python.org/2/), 181 bytes
```
l=input()
_,_,x,y=map(max,zip(*l))
m=eval(`[[32]*x]*y`)
for v,w,x,y in l:
for i in range(v,x):
for j in range(w,y):
m[i][j]=max(m[i][j]^1,34)
for n in m:print''.join(map(chr,n))
```
[Try it online!](https://tio.run/##RY7RCoMgFIav51N4l8ZhUA22BT2JuJLRlqEm0kr38k7ZYPBdnP@D/5xjwzotpo5RddLY10oo6qEHD6HTwhItPLylJaWiFOlu3IQiA2NNzUvPyzBQ9Fgc3mDPDSwNVi3CWckcnDDPkWzgaYsO2c5/u0PIFmsmOZt5uubJb75V0Jy@m00u6NY6adaiOM6LNCT/dZ8cGEpjZKwCnLgmOLAacOKSSKEBnDgnOP8A "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 205 bytes
```
x[999][999];a;b;c;d;j;k;l;m;n;main(i){for(;scanf("%d %d %d %d",&a,&b,&c,&d)>3;m=d>m?d:m,n=c>n?c:n)for(i=b;i<d;++i)for(j=a;j<c;++j)x[i][j]=x[i][j]^2|1;for(;k<n||++l<(k=0,puts(""),m);putchar(x[l][k++]+32));}
```
[Try it online!](https://tio.run/##NY3RisMgEEXf@xUS2KDoQpI@2YnJh4gFM9JdTbRL00Jgs9@etaHlHmbmPAwXP78Qt23RUkqzD7AwAIKDACNMECFBtD5Rz34v1xuFGW260OLDkTeFKK0oB1GiKB3rjhCV62LvTlEkhV3q8ZTY89erAXzrgHO/e1AWQovZA1u0NzoY9drnZq1h7xvbtK6cTy0dVSV@HveZFgUTkUG@8dve6KIno0fODT82jMHftlWkIpLIQ01yqsyhIQ2ps9T/ "C (gcc) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~196~~ 189 bytes
```
m=matrix
x=m(scan(file("stdin")),4)
y=m(0,max(x[3,]),max(x[4,]))
n=ncol(x)
while(n){z=x[,n]
i=z[1]:z[3]
j=z[2]:z[4]
y[i,j]=y[i,j]+1
n=n-1}
i=!y
y=y%%2+1
y[i]=' '
cat(rbind(y,'\n'),sep='')
```
[Try it online!](https://tio.run/##LY3BCsIwEETv@xVrQZLFCKat2Ar5kphDrYopbZS2YFLx22uKMod9zOzu9PPcqa4ae@vBq44PdeX4zbZXngzjxbqESOQEIUY70VWee50JQ3/MIxI45epHyz3B675cOnpPymvhDCJYNWlpjpPODDSR04VzA0Fb0Rj1Gxu5PNnKT1xfhdgW1us0mjE1iiGDuhp5f7buwoNgJ8dIDNenYozmWaLEEktIcY8FFpDhIUruvg "R – Try It Online")
The code reads input as stdin, arranged as a
x1 y1 x2 y2
tuple, where x is the column and y is the row.
I am using 1 and 2 for the overlap levels, where 1 represents an even level.
Saved 7 bytes thanks to user2390246.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 54 bytes
```
{my@a;{@a[$^a..$^b;$^c..$^d]X+^=1}for $_;@a >>~|>>' '}
```
[Try it online!](https://tio.run/##fY3dCoJAEIXvfYpzsaSZLK6CGquLjxGIxvYjFJliV2L26tsseFsXZ/gGzjczXMdHYroJmxYFzNxNpZZzqSvWaM5Zc5KsOVu41IddU4il7Uewoyw1lPq8lXLhLqb1qjxEBooKHAC5wB6UdYsgQtih6sqXfr3lnR48n9/725O/9LSVjmNvCFtCpAIyYuL4T38VMhLsUzJSMlKLMRLSk5@y@QI "Perl 6 – Try It Online")
Takes input as a flat list of coordinates as inclusive coordinates, i.e. `x1,y1,x2,y2,x1,y1,x2,y2...` and outputs as a list of list of characters with `k` being `1` and `l` being `0`.
### Explanation:
```
{ } # Anonymous codeblock
my@a; # Declare an array
{ }for $_; # Loop over the input
@a[ ] # Indexing into @a
$^a..$^b # The range of rows
;$^c..$^d # And the range of columns for each
X # And for each cell
+^=1 # Set it to itself bitwise XOR'd with 1
# Cells not yet accessed are numerically zero
@a >>~|>>' ' # Stringwise OR each cell with a space
# Cells not yet accessed are stringily empty
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes
```
+µ>2Ḥạ
ạ1ẋ$0ẋ⁸¤;µ/€«þ/µ€z0z€0Z€Zz€0Z€ç"/o⁶Y
```
[Try it online!](https://tio.run/##y0rNyan8/1/70FY7o4c7ljzctZALiA0f7upWMQASjxp3HFpifWir/qOmNYdWH96nf2grkFVlUAUkDaKARBScdXi5kn7@o8Ztkf///4@ONtRRMI3VUYDQIEa0iY6CBYgBpsEi5joKhoYgFoQRCwA "Jelly – Try It Online")
# Explanation
```
+µ>2Ḥạ Helper Link; combines final rectangles (0 is blank, 1 is covered, 2 is uncovered)
+ add the two values
µ (with the sum...)
>2 check if it's greater than two
Ḥ double the result (2 if it's 3 or 4, 0 if it's 0, 1, or 2)
ạ absolute difference (0 should take whatever the other thing's value is, 1+1 and 2+2 should give 2, 1+2 and 2+1 should give 1)
ạ1ẋ$0ẋ⁸¤;µ/€«þ/µ€z0z€0Z€Zz€0Z€ç"/o⁶Y Main Link
µ€ For each rectangle stored as [[x1, x2], [y1, y2]]
µ/€ For each of [a, b] = [x1, x2] and [y1, y2], reduce it by (in other words, use a dyad on a size-2 list)
1ẋ$ repeat [1] times
ạ abs(a - b)
; and append to
0ẋ ¤ [0] repeated times
⁸ a
«þ/ and reduce by minimum outer product table (take the outer product table, by minimum, of the x results and the y results)
[NOTE] At this point, we have a list of matrices with 0s as blanks and 1 as covered
z0z€0Z€Zz€0Z€ Make all of the matrices the same size:
z0 zip, fill with 0 (all matrices are the same length, but not width, and now are lists of row-wise lists of rows)
z€0 zip each, fill with 0 (all rows are the same length within their row-wise lists, and are now lists of row-wise lists of columns)
Z€ zip each (flip rows back to lists of row-lists of rows)
Z zip (flip back to matrices); however, if a matrix is smaller on both axes, its rows will not be the same length
z€0 zip each, fill with 0 (all rows in each matrix are the same length and the value is now a list of transposed matrices)
Z€ zip each (the value is now a list of matrices, all the same length, filled with 0 (empty space))
ç"/ reduce by (vectorized) the relation in the Helper Link (to combine all of the final values)
o⁶ logical OR with " "; replace 0s with spaces
Y join with newlines (formatting)
```
] |
[Question]
[
Given a matrix, sum its values up/down or left/right to form an X, fold it up, and return the list. I describe the algorithm here:
# Algorithm
Your input will be a odd-sized square matrix of integers within your language's reasonable numerical capacity.
Let's take the following matrix as an example:
```
1 2 3 2 1
0 3 2 3 0
4 2 5 6 3
7 4 7 9 4
0 6 7 2 5
```
First, add every number to the closest number that is on the main diagonal or antidiagonal. That is, divide the matrix into four sections along the main diagonal and antidiagonal, and then sum all of the numbers in each section towards the center, like so:
```
1 2 3 2 1
↓ ↓ ↓
0 → 3 2 3 ← 0
↓
4 → 2 → 5 ← 6 ← 3
↑
7 → 4 7 9 ← 4
↑ ↑ ↑
0 6 7 2 5
```
This step gives the following result:
```
1 1
5 5
39
17 15
0 5
```
Then, we fold it by flattening the X and interweaving the elements with the top-left first and the bottom left last. This gives the following result:
```
1, 0, 5, 17, 39, 5, 15, 1, 5
```
You can imagine this as stretching the main diagonal and rotating it counterclockwise.
This is the final result.
# Challenge
Implement this algorithm. Standard loopholes apply. All reasonable I/O formats acceptable.
# Test Cases
```
Input
Output
1 2 3 2 1
0 3 2 3 0
4 2 5 6 3
7 4 7 9 4
0 6 7 2 5
1, 0, 5, 17, 39, 5, 15, 1, 5
1 2 3 4 5
5 4 3 2 1
1 3 5 7 9
0 9 8 7 6
6 7 8 9 0
1, 6, 11, 16, 47, 7, 22, 5, 0
1 3 7 4 8 5 3
8 4 7 5 3 8 0
0 6 3 6 9 8 4
2 6 5 8 7 4 2
0 6 4 3 2 7 5
0 6 7 8 5 7 4
8 5 3 2 6 7 9
1, 8, 15, 11, 23, 20, 62, 32, 25, 13, 18, 3, 9
```
[Answer]
# JavaScript, 113 bytes
```
s=>(l=s.length-1,a=[],s.map((v,y)=>v.map((n,x)=>a[q=2*[x,y,l-y].sort((u,v)=>u-v)[1]+(y>l/2),q-=q>l]=~~a[q]+n)),a)
```
```
f=
s=>(l=s.length-1,a=[],s.map((v,y)=>v.map((n,x)=>a[q=2*[x,y,l-y].sort((u,v)=>u-v)[1]+(y>l/2),q-=q>l]=~~a[q]+n)),a)
```
```
<p><textarea id="i" style="width: 400px; height: 120px">1 2 3 2 1
0 3 2 3 0
4 2 5 6 3
7 4 7 9 4
0 6 7 2 5</textarea></p>
<p><button onclick="o.value=f(i.value.trim().split`\n`.map(l=>l.trim().split(/\s+/).map(v => parseInt(v,10)))).join` `">Run</button></p>
<p><output id="o"></output></p>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ ~~23~~ 21 bytes
```
AṂ×ṠṚ
LHŒRṗ2Ç€ḅLĠịFS€
```
[Try it online!](https://tio.run/##VY89DsIwDIX3nCIHyNCfJA0jCzB0gjHKyIJ6AdZKiIGNpRJTD8ABiBgLBwkXCa7TRO1ixZ8dv/dOx6Y5e792th06Z3tnH6Tefe97Z7tiuP7ap3td6k/v3rfNATqPbOu9JlTrnNGC0RJrbhihVGexh5oFxLEXjEqgAVWMAoW6gkf6KBGNuwbYQoCPEPcENgvNHHsRDqZrcFohkgGF6woH2UygRM5xJJJDFR0K3FApTfBZYg0SU4ACkYiqY@r5j2S6SlFSZBXd8yQu4rqcYhli/g "Jelly – Try It Online")
### Alternate version, 19 bytes
```
AṂ×ṠṚ
LHŒRṗ2Ç€ĠịFS€
```
This didn't use to work because `Ġ` behaved improperly for nested arrays. The only difference is that the pairs **[q, p]** mentioned in *How it works* are sorted lexicographically instead of mapping them to **p + nq** before sorting.
[Try it online!](https://tio.run/##VY8tEsIwEIV9TpEDRPQnSYPEAAIFMhOJYXoBbA0Ch@kMqgfgAhlk4SDhImG7aXao2cl@u9n33vnUtpcY18F3Yx/8EPyD7Xef@yH4vhqv3@75HsLrtjnCK2K/jdEybm0peCV4jbV0gnFui9xDLRKS2CvBNdCEGsGBQl3Bgz5qRNOuA7YQkBPEPYXNQrPEXqWDdA1OG0Q6oXTd4KD4E6iRSxwpcmiyQ4UbhtIknzXWJDEHqBCprDql/v9BphuKQpFNdi9JXOV1PcdyzP0A "Jelly – Try It Online")
### Background
We start by replacing its elements with coordinates, increasing leftwards and downwards and placing **(0, 0)** in the center of the matrix.
For a 7x7 matrix **M**, we get the following coordinates.
```
(-3,-3) (-3,-2) (-3,-1) (-3, 0) (-3, 1) (-3, 2) (-3, 3)
(-2,-3) (-2,-2) (-2,-1) (-2, 0) (-2, 1) (-2, 2) (-2, 3)
(-1,-3) (-1,-2) (-1,-1) (-1, 0) (-1, 1) (-1, 2) (-1, 3)
( 0,-3) ( 0,-2) ( 0,-1) ( 0, 0) ( 0, 1) ( 0, 2) ( 0, 3)
( 1,-3) ( 1,-2) ( 1,-1) ( 1, 0) ( 1, 1) ( 1, 2) ( 1, 3)
( 2,-3) ( 2,-2) ( 2,-1) ( 2, 0) ( 2, 1) ( 2, 2) ( 2, 3)
( 3,-3) ( 3,-2) ( 3,-1) ( 3, 0) ( 3, 1) ( 3, 2) ( 3, 3)
```
We now compute the minimum absolute value of each coordinate pair and multiply the signs of both coordinate by it, mapping **(i, j)** to **(sign(i)m, sign(j)m)**, where **m = min(|i|, |j|)**.
```
(-3,-3) (-2,-2) (-1,-1) ( 0, 0) (-1, 1) (-2, 2) (-3, 3)
(-2,-2) (-2,-2) (-1,-1) ( 0, 0) (-1, 1) (-2, 2) (-2, 2)
(-1,-1) (-1,-1) (-1,-1) ( 0, 0) (-1, 1) (-1, 1) (-1, 1)
( 0, 0) ( 0, 0) ( 0, 0) ( 0, 0) ( 0, 0) ( 0, 0) ( 0, 0)
( 1,-1) ( 1,-1) ( 1,-1) ( 0, 0) ( 1, 1) ( 1, 1) ( 1, 1)
( 2,-2) ( 2,-2) ( 1,-1) ( 0, 0) ( 1, 1) ( 2, 2) ( 2, 2)
( 3,-3) ( 2,-2) ( 1,-1) ( 0, 0) ( 1, 1) ( 2, 2) ( 3, 3)
```
Matrix elements that correspond to the same pair have to be summed. To determine the order of the sums, we map each pair **(p, q)** to **p + nq**, where **n** is the number of rows/columns of **M**.
```
-24 -16 -8 0 6 12 18
-16 -16 -8 0 6 12 12
-8 -8 -8 0 6 6 6
0 0 0 0 0 0 0
-6 -6 -6 0 8 8 8
-12 -12 -6 0 8 16 16
-18 -12 -6 0 8 16 24
```
The order of sums corresponds to the order of integers the correspond to its summands.
### How it works
```
LHŒRṗ2Ç€ḅLĠịFS€ Main link. Argument: M (matrix)
L Compute n, the length (number of rows) of M.
H Halve it.
ŒR Symmetric range; map t to [-int(t), ..., 0, int(t)].
ṗ2 Compute the second Cartesian power, yielding all pairs [i, j]
with -t ≤ i, j ≤ t.
Ç€ Map the helper link over the resulting array of pairs.
L Yield n.
ḅ Unbase; map each pair [q, p] to (p + nq).
Ġ Group the indices of the resulting array of n² integers by their
corresponding values, ordering the groups by the values.
F Flatten M.
ị Index into the serialized matrix.
S€ Compute the sum of each group.
AṂ×ṠṚ Helper link. Argument: [i, j] (index pair)
A Absolute value; yield [|i|, |j|].
Ṃ Minimum; yield m := min(|i|, |j|).
Ṡ Sign; yield [sign(i), sign(j)].
× Multiply; yield [p, q] := [sign(i)m, sign(j)m].
Ṛ Reverse; yield [q, p].
```
[Answer]
# Python, 159 158 bytes
```
def f(m):l=len(m)-1;r=range(1,l);return m[0][::l]+f([[sum(m[x][1%y*y:(y>l-2)-~y])+m[0][y]*(x<2)+m[l][y]*(x>l-2)for y in r]for x in r])+m[l][::l]if l else m[0]
```
[Try it online!](https://tio.run/##XY/NasMwEITveoq9FKREBv/Frp24LyJ0KFRqDJISFAesS1/dkVaGlsIeZkffzqB7WK4312zbl9KgqWWjmYxyURTV2U/@030rWnHDzl4tT@/AilKKcTTyqKkQj6elVqxSVG/hEEYaPkxRs@InSHZEMsgDXS912sy@IaJvHgLMDrxMcs1yx1L8rMGAMg@FjRsQCxMIIioOJYeWQx@F5ETUHBoONXpdMvJ2QqL/JToOQ3xJRs5o8OQkiSR3P7uFpu8z8qcoZmS022NavBr23Aa3CL3HSUaLzT3OkIwcMGB5@a9oewE)
[Answer]
# [Dyalog APL](https://www.dyalog.com/), ~~101~~ ~~99~~ ~~64~~ ~~62~~ 59 bytes
[*3 bytes saved by @Adám*](https://chat.stackexchange.com/transcript/message/40562622#40562622)
```
{+/∘,¨⍵∘רd∘=¨k[⍋k←↑∪/,d←∘.((+/1x×××⌊/∘|),)⍨(⍳x)-⌈.5×x←≢⍵]}
```
[Try it online!](https://tio.run/##dY6xTsMwEIb3PIW32mraOEldJ0OeBDFUisrQSjAGAQtDFUItwZTOnSJW4AWSN7kXCf85DB1A1t3/@3z3nTd3@0V5v9nf3ozjlg5vD/OI6lPYd@S@YYa270po0Xe7K3KvO7TQ4Z3qjygs2denpZTzKK6Glg8dG55/VKEi10lyn5Va0LFemqGtuP/lDPD10zhKSc0zNWcVbpUwwpD7ikUiUkQstNcUuoIasYa38FbkyBp3y/VgVhTFLPgXteIb8gSNocYjNCKDW3tQxpW/UFZYj5p2ZxhOkfkXk9P@Jyki9/UEzngwe36bVnO//l1lLliJr@Ui@AE)
Using Dennis' [awesome algorithm](https://codegolf.stackexchange.com/a/145385/65326).
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 60 bytes\*
In collaboration with my colleague [Marshall](http://dyalog.com/meet-team-dyalog.htm#Marshall).
Anonymous prefix lambda. Takes matrix as argument and returns vector. Assumes `⎕IO` (**I**ndex **O**rigin) to be zero, which is default on many systems.
```
{(,⍉{+/,(s×-×⍺)↓⍵×i∊¨⍨s←⌊⊃r÷2}⌺r⊢⍵)/⍨,(⊢∨⌽)=/¨i←⍳r←⍴⍵}
```
[Try it online!](https://tio.run/##XU2xSsRAEO39iu2ywYRskttLUvgBVn5DODkJBJUECzmuEsIZsiKKpLcKtirCgc3lT@ZH4puNhVjMzJs3773Jr0v//DYvry78VZnXdbGa6OHl9IyaRzWt0TfSI3O/OQ48WY@9P/Zk9i41z2Q@x76gXXsYyAw1lNS11N5V41e0pW5fUfsKjRvg6kledgN13@5JcBgKVpv3yo4PqLZTdXPJz8i8OcKRoBxqnhy55gjXnoUWGupQRCJGhULZGWMuMLVYAifAicjQFfaE@aP/3gVv6HNKiKmtR6FSoKV1psxYbyIS653TU6hjdP4zI2V/xajM8hGQtkmM@Tb/Yr36zdZ/siLLZT8 "APL (Dyalog Classic) – Try It Online")
`{`…`}` anonymous lambda; `⍵` is right argument (as rightmost letter of the Greek alphabet):
`⍴⍵` shape of the argument (list of two identical elements)
`r←` store as `r` (as in **r**ho)
`⍳` all **ɩ**ndices of an array of that size, i.e. `(0 0)`,`(0 1)`…
`i←` store in `i` (as in **i**ota)
`=/¨` Boolean where the coordinates are equal (i.e. the diagonal)
`(`…`)` apply this anonymous tacit prefix function:
`⌽` reverse the argument
`⊢∨` OR that with the unmodified argument
`,` ravel (straighten into simple list)
We now have a Boolean mask for the diagonals.
`(`…`)/⍨` use that to filter the following:
`⊢⍵` yield (to separate from `r`) the argument
`{`…`}⌺r` call the following anonymous infix lambda on each element, with the `r`-neighbourhood (padded with zeros as needed) as right argument (`⍵`), and a two element list of number padded rows,columns (negative for bottom/right, zero for none) as left argument (`⍺`):
`r÷2` divide `r` with two
`⊃` pick the first element (they are identical)
`⌊` floor it
`s←` store as `s` (for **s**hape)
`i∊⍨¨` for each element of `i`, Boolean if `s` is a member thereof
`⍵×` multiply the neighbourhood therewith
`(`…`)↓` drop the following number of rows and columns (negative for bottom/right):
`×⍺` signum of the left argument (i.e. the direction of paddings)
`-` negate
`s×` multiply `s` therewith
`,` ravel (straighten into list)
`+/` sum (plus reduction)
Now we have full matrix of sums, but we need to filter all the values read columnwise.
`⍉` transpose
`,` ravel (straighten into simple list)
---
\* By counting `⌺` as `⎕U233A` . [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20THnUuUq/W0HnU21mtra@jUXx4uu7h6Y96d2k@apv8qHfr4emZjzq6Dq141LuiGKS6p@tRV3PR4e1GtY96dhU96loEVKOpD5TV0QBxOlY86tmraat/aEUmSHXv5iIwtQWoqlb9/38A "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
Many of us are familiar with the game Tron. You control a "lightcycle" placed on a grid. The lightcycle always moves forward (though you control the direction) and leaves a permanent trail behind it. If you run into a trail, you crash!
The goal here is to determine if a given path is a valid loop, that is, it returns to its starting point without "crashing". To do this, we assume we start at the point `(0,0)`. An input is given in the form `N2E1S2W1`, with a series of cardinal directions (`N` is `north`, `E` is `east`, and so on), each followed by the distance to travel that direction. In this example, you would travel
```
N2 : North 2 to (0,2)
E1 : East 1 to (1,2)
S2 : South 2 to (1,0)
W1 : West 1 to (0,0)
```
A path is considered valid if it ends at `(0,0)` without visiting any other coordinate more than once (it visits `(0,0)` exactly twice. Once at the start, and once at the end). Keep in mind than in the above example, to get from `(0,0)` to `(0,2)`, we necessarily visit `(0,1)` as well.
Other examples:
```
input -> output
N1E1S1W1 -> true
N1E1N1E1S2W2 -> true
N1S1E1W1 -> false // Visits (0,0) 3 times
N4E2S2W4S2E2 -> false // Visits (0,2) twice
N3E2S3 -> false // Does not return to (0,0)
N1S1 -> anything //I don't care how you evaluate this case
```
Your output can be in any form so long as it gives the same output for any truthy or falsey value.
The input can be taken as a string or as a list of characters, either in the form `S1N2E3`... or `SNNEEE`... There's is also no hard limit on the grid size, but assume the input isn't going to overflow anything. As long as the code is fundamentally sound, It's not crucial to handle cases like `N99999999999999`.
NOTE: You may evaluate the cases `N1S1`, `E1W1`, `S1N1`, and `W1E1` however you would like. They're technically valid paths, but they go against the "Tron" spirit of the challenge.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~44~~ 39 bytes
```
&!eJsM._smm^.j)x"NESW"hdstd:z".\d+"1{IJ
```
[Test suite](http://pyth.herokuapp.com/?code=%26%21eJsM._smm%5E.j%29x%22NESW%22hdstd%3Az%22.%5Cd%2B%221%7BIJ&test_suite=1&test_suite_input=N1E1S1W1%0AN1E1N1E1S2W2%0AN1S1E1W1%0AN4E2S2W4S2E2%0AN3E2S3&debug=0).
[Answer]
# JavaScript, 247 200 bytes
```
n=s=>{r=s.match(/\w\d+/g)
x=y=z=0
e=""
for(d of r){a=d[0]
b=d.slice(1)
while(b--){
y+=a=="N"
y-=a=="S"
x+=a=="E"
x-=a=="W"
p=[x,y]+";"
if(~e.indexOf(p))if(!x&!y)z++
else return 0
e+=p}}return!x&!y&!z}
```
`n` is a function of input string `s` that returns `1` for true and `0` for false
Here's an ungolfed version for reference/explanation:
```
function n(s)
{
var dir = s.match(/\w\d+/g);
var x = y = z = 0;
var been = "";
for (d of dir)
{
var a = d[0];
var b = 1*d.substring(1);
while(b-- > 0)
{
if (a == "N") y++;
if (a == "S") y--;
if (a == "E") x++;
if (a == "W") x--;
var pt = [x,y] + ";";
if (~been.indexOf(pt))
if (x==0 && y==0)
z++;
else
return false;
been += pt;
}
}
return (x == 0 && y==0 && z == 0);
}
```
```
n=s=>{r=s.match(/\w\d+/g)
x=y=z=0
e=""
for(d of r){a=d[0]
b=d.slice(1)
while(b--){
y+=a=="N"
y-=a=="S"
x+=a=="E"
x-=a=="W"
p=[x,y]+";"
if(~e.indexOf(p))if(!x&!y)z++
else return 0
e+=p}}return!x&!y&!z}
console.log(n("N1E1S1W1"))
console.log(n("N1E1N1E1S2W2"))
console.log(n("N1S1E1W1"))
console.log(n("N4E2S2W4S2E2"))
console.log(n("N3E2S3"))
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~236~~ ~~161~~ 150 bytes
```
import re
p=0
a=[]
for i in''.join(s[0]*int(s[1:])for s in re.findall(r".\d+",input())):p+=1j**"NESW".find(i);a+=[p]
print(len({*a})-len(a)==0==a[-1])
```
[Try it online!](https://tio.run/##HYyxDoMgFEV3vsK4yMNqxG42b3R1cXCgDCRqirFAkA5N02@n0uEmJzn3XvcOD2uuMeqnsz5kfiEOG6JQSLJan@lMm6KoN6sNPUQjmTbhBN5JSPo49bmpV21mte/U5/V9LvOLNu4VKAB0rkS@MZYP/Tjl/x7VcFMlCieJ8@luXwz9MPWFKpECxAZRiYpLiHHgPU8Z26n9AQ "Python 3 – Try It Online")
-75 bytes thanks to Leaky Nun
-11 bytes thanks to Leaky Nun
Or, if we're allowed to take input as a list of run length decoded complex numbers:
# [Python 2](https://docs.python.org/2/), ~~85~~ 73 bytes
```
c=0;k=[]
for i in input():c+=i;k+=[c]
print(k[-1]==0==len(set(k))-len(k))
```
[Try it online!](https://tio.run/##LYhBCoAgFET3ncKlYoK2TP5JxJUYmaFituj0P6XgzbxhytP2nBZEB1JHMHbaciWBhNQpd6NsdRyCjhyMs1OpITUajVAWQAKcPtHL94cxMXY3olHHTFTnkxj@a8S@ "Python 2 – Try It Online")
-12 bytes thanks to Mr. Xcoder / -9 bytes thanks to Leaky Nun (merged into one edit)
This feels too long to me lol
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes
```
Œṙ+\µQ⁼ȧṛ/¬$
```
This is my first time golfing in Jelly. Suggestions are welcome.
Input is as an array of `[direction, distance]` pairs, where the direction is given as a complex number.
## Explanation:
```
Œṙ+\µÇȧṛ/¬$ Main link. Argument: n = [[i, 3], [1, 2], [-i, 3]]
Œṙ Run-length decode = [i, i, i, 1, 1, -i, -i, -i]
+\ Cumulative sum = [i, 2i, 3i, 3i+1, 3i+2, 2i+2, i+2, i]
µ Begin a new monadic chain
Q Remove duplicates = [i, 2i, 3i, 3i+1, 3i+2, 2i+2, i+2]
⁼ Equal to original? = 0
$ Make a monadic link:
ṛ/ Reduce by right argument = i
(Gets the last element)
¬ Logical NOT: = 0
ȧ Logical AND the two values = 0
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 86 bytes
```
\d+
$*
1(1*)
$1
+`(.)1
$1$1
.
$`$&¶
%O`.
+`NS|E(.*)W
$1
M`\w$|(?m)(^.+$)(?s).+^\1$
^0
```
[Try it online!](https://tio.run/##HYohDgIxEEX9nAIxS6ZtMmG661c1KBZRUdM0JQGBAAEkmD0XB@BiZYp77/3/uLyu91MbaF9bPjtAC0JiDaCAq8RGlJQZNlhx@/3AcKys0xLXQGxN6s9DzW9cab4ZKuzQ0Pw07EoWhLJrbZEgUZJAh7/45FWiYq9T8Fqm6IPWUWX8AQ "Retina – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert the numbers to unary.
```
1(1*)
$1
+`(.)1
$1$1
```
Run-length decode the letters. `N111` needs to turn into `NNN`, so one is subtracted from each unary number and then each 1 duplicates the previous letter.
```
.
$`$&¶
```
Generate all the prefixes (i.e. points on the path) as separate lines. A space is prefixed to avoid issues with empty lines.
```
%O`.
+`NS|E(.*)W
$1
```
Sort all the letters in each line into order and then delete matching pairs. We end up with a unique code for any given point on the grid.
```
M`\w$|(?m)(^.+$)(?s).+^\1$
```
Check for one of two things: a) the last point doesn't end in a space (i.e. the loop didn't close), or two duplicate points in the path. If the path is valid, all checks fail and the result is zero.
```
^0
```
Invert the result.
[Answer]
## Perl, 140
Works with string input. Perhaps I can shorten with array,but I doubt it.
Happy for any further golfing help :)
```
sub w{$i=$_[0];%d=(E,[0],S,[1,-1],W,[0,-1]);$i=~s/(.)(.)/($d,$o)=(@{$d{$1}},1,1);for(1..$2){$s[$d]+=$o;$r+=$d{"@s"}++}/eg;!($s[0]+$s[1]+$r)}
```
] |
[Question]
[
The keyboard layout people commonly use is the **QWERTY** layout as shown below.
[](https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/KB_United_States.svg/1000px-KB_United_States.svg.png)
But there are also other keyboard layouts:
**DVORAK**
[](https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/KB_United_States_Dvorak.svg/1280px-KB_United_States_Dvorak.svg.png)
**COLEMAK**
[](https://i.stack.imgur.com/cupPt.png)
**WORKMAN**
[](https://i.stack.imgur.com/b1KV8.png)
## Your task
Your code will take two inputs: the name of the keyboard layout and a string to transcribe.
Your goal is to convert your QWERTY input as if you were typing with the keyboard layout given as first parameter.
### Rules
The input format is free, you can use strings, arrays, etc. Moreover, you can use any three distinct values to represent the layouts to reduce your byte count, but they each have to be representable in 10 bytes or less.
You need only to handle the keys with a white background. Specifically, you must transpose the printable ASCII characters from the QWERTY alphabet to one of the other alphabets:
```
QWERTY: !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
DVORAK: !_#$%&-()*}w[vz0123456789SsW]VZ@AXJE>UIDCHTNMBRL"POYGK<QF:/\=^{`axje.uidchtnmbrl'poygk,qf;?|+~
COLEMAK: !"#$%&'()*+,-./0123456789Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJZ[\]^_`abcsftdhuneimky;qprglvwxjz{|}~
WORKMAN: !"#$%&'()*+,-./0123456789Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJZ[\]^_`avmhrtgyuneolkp;qwsbfcdxjz{|}~
```
(Note: this was transcribed by hand by @ETHproductions, so if you see any errors, please point them out!)
### Example
`DVORAK zZxX` as input will give as output `;:qQ`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins!
[Answer]
# JavaScript (ES7), ~~282~~ ~~273~~ ~~251~~ 250 bytes
Takes a keyboard layout ID `k` and an array of characters `a` in currying syntax `(k)(a)`. Returns an array of translated characters.
The layout IDs are:
* DVORAK: \$-32\$
* COLEMAK: \$64\$
* WORKMAN: \$160\$
```
k=>a=>a.map(c=>1/(t=`1_3-2}w[vz8SsW]VZ1XJE>UIDCHTN0BRL"POYGK<QF:/0=0{1xje.uidchtn0brl'poygk,qf;?0+995Oo6SFTD0UNEI0KY:0PRGL2J8sftd0unei0ky;0prgl2j998Ii5VMHRT0YUNEOLKP:0W0BFCD0J6vmhrt0yuneolkp;0w0bfcd0j5`.replace(/\d/g,n=>15**n)[c.charCodeAt()+k])?c:t)
```
[Try it online!](https://tio.run/##hc/JboJQGAXgfZ/CdCM4XH6wGsWiUZxBQRzRmkovgwgCBRybPrtl4dqenO35krPXTlqEQzuI856vG3eTuztcTUuKDlpAYK5GU0TMbenPQp75Pa9Pt/IkWmzmK3o5aNdm/Rbfm46gqYivsqR2hfdxh6WAgx/6sjfQ0dbxLvbgK3TTgX@1nNy3Wa1DtlIpSn5p0pm2YDZq90FQWZCVrsgMypEZ63D0DBucaxWC0HKZfaVS7tvF@bCnTEFNBpIoyCwsoNnhWzAonQ67MIZrMvJdJ6jCGb5MrMO@uEWhEbgaNgjqQ6esnJecKWYyHrnGCO@0kE8ON2KCzDobso7ZmLxj34t810CubxGDiTRCURzanmWbV8Ik8gWGJNYIofRtdVmmNyRJph6hqFRrLikN4eWpkCq9PYTxoq1M1Vlfkh9OIvCS2B7@R9AleEIsJEUYNkb3Pw "JavaScript (Node.js) – Try It Online")
### How it works
**Compression**
All three target layouts are stored in a single compressed string, where each character is either:
* a translation character from QWERTY
* a digit representing the number of consecutive characters that do not need to be translated
More specifically, a digit \$n\$ is interpreted as the length of the number \$15^n\$ in base \$10\$:
```
n | 15**n | length
--+-------------+-------------
0 | 1 | 1
1 | 15 | 2
2 | 225 | 3
3 | 3375 | 4
4 | 50625 | 5 (not used)
5 | 759375 | 6
6 | 11390625 | 8
7 | 170859375 | 9 (not used)
8 | 2562890625 | 10
9 | 38443359375 | 11
```
For instance, `#$%&-()*` in DVORAK is stored as `3-2` because `#$%&` and `()*` have identical mappings in QWERTY and only `-` is an actual translation.
In particular, `0123456789` is mapped the same way on all layouts and never has to be translated. Therefore, there's no possible ambiguity between a digit used for compression and a digit used for translation.
**Decompression**
To decompress the layout string, we replace each digit \$n\$ with \$15^n\$. For instance, `3-2` is decompressed as `3375-225`.
**Translation**
For each character `c` in `a`, we extract the translation character `t`, using `k` as an offset in the uncompressed layout string, and test whether it's a digit with `1/t`. If so, we output the original character `c` instead.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~273~~ 270 bytes
```
T`p` !_#-&\-()*}\w[vzdSsW]VZ@AXJ\E>UIDC\HTNMBR\L"P\OYGK<QF:/\\=^{\`axje.ui\dc\htnmbr\l'\p\oygk,qf;?|+~`^D.*
T`p` -9\O\o<-CSFTD\HUN\EIMKY:QPRG\LVWXJZ-csft\d\huneimky;q\prg\lv-xjz-~`^C.*
T`p` -9Ii<-AVM\HRTGYUN\E\O\LKP:QWSBFCDXJZ-avm\hrtgyune\o\lk\p;q\wsbfc\dxjz-~`^W.*
^.
```
[Try it online!](https://tio.run/nexus/retina#Rc3ZUoJgAAbQe5@iZabF@ulapEVBXBCVRUD6IhRcEBUURLDl1QmbZnqBc3LVDu2z8/dLcgVyc1v@wuE1ObpKpL9p5kvN6KDxNGxzLFpqT6zL6F4M0B81BUbi6Qfg0fqAPU6XU2rvwXWwiDfryQ6ra4QIsrl/v51Vnz/vvm2Lo8ql34tU0EfAEFbhVQ6tYQ@NtiiMaGkgN9HVdKNjEieaxXCx2G@m3trPqluEuzlWCUmXR1Jg7D/W9hhS00S0ZLU5OmGF3hUGtKQrdZ7lTto4WWOxi@dZwSHAykdYiIdoMnPg/ol6IVpUKc@5o5kaPw "Retina – TIO Nexus") Prefix the message with a single letter `D`, `C` or `W` for the desired keyboard layout. Unfortunately Retina supports a bunch of magic letters (`p` being the obvious one, but I did manage to slip in a `d`) which all need to be quoted, except I was able to use `v-x` instead of `v\wx`. Edit: Saved 3 bytes thanks to @ETHproductions.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~258~~ ~~247~~ 238 bytes
```
->c,t{c.tr"#{$f='\'"+,-./<=>?[]{'}}:;B-Z_b-z",%W(-_}w[vzW]VZ/=?+SsXJE>UIDCHTNMBRL"POYGK<QF:{xje.uidchtnmbrl'poygk,qf;
#$f}OoBCSFTDHUNEIMKY:QPRGLVWXJZ_bcsftdhuneimky;qprglvwxjz
#$f}IiVMHRTGYUNEOLKP:QWSBFCDXJZ_vmhrtgyuneolkp;qwsbfcdxjz)[t]}
```
[Try it online!](https://tio.run/nexus/ruby#Hc3bkkJgAADg@30MtWN3Qvd0mEEOIZRI1jSDHEJOf4Tx7NbuA3zzjejGRUDvYqCEZv3cX8M/MLRAUGy5Wm@2lt3Dw4ATJHq9OWgHIZ/GF3obGqvuDFu/Ltfbxam67HebM09TnHaQyKMIKbLJCiuVwfv34469Is8NwTN1ygTOszaIkcInPmZzf5AzkjoxGs2dDzteEkxcVY6sqBuX/ZS5lQ@88PW8R2ncEkVeBkndvB/dv@QjXeKOGmtOUhYFBVeNE8lQ9J@s07AEQTvJLIlzomgqx3e9SX5bwB7G8Rc "Ruby – TIO Nexus")
This is a function taking two arguments: the message to be swapped, and a value 0-2 representing the layout to be swapped to, where 0 corresponds to Dvorak, 1 to Colemak, and 2 to Workman.
Fundamentally, I don't think this is much different than the other answers. More readably, it looks like this:
```
def swap_layout(message, layout)
keyboards = [DVORAK, COLEMAK, WORKMAN] # Omitted here for brevity
return message.tr(QWERTY, keyboards[layout])
end
```
Ruby's `string#tr` function takes two arguments: a string containing characters to be replaced, and a string containing their replacements. Helpfully, it allows you to specify ranges of characters using `a-z` syntax. The other key space-saving realization is that it's not necessary to include characters that are the same in all four layouts, which allowed me to get rid of all digits, the letter "A" in both upper- and lowercase, and a handful of special characters.
One other weird bit of syntax is the use of `%W()`. This creates an array of strings containing everything inside the parentheses, separated by whitespace. All linebreaks in the submission actually function as element separators. `%W()` also permits string interpolation (which is done with the `#{}` operator) - `%w()` would've been the same thing, but without string interpolation.
I'd also like to take a moment to blame Dvorak for messing with my plans for optimization through its insistence on being totally different than everyone else, all the time; a Qwerty/Colemak/Workman solution could have been so beautifully short...
[Answer]
# PHP, 364 Bytes
```
echo strtr($argv[2],($t=[[":;BCDEFHIJKLMNOPRTUVWYbcdefhijklmnoprtuvwy","IiVMHRTYUNEOLKP:WBFCDJvmhrtyuneolkp;wbfcdj"],[":;DEFGIJKLNOPRSTUYdefgijklnoprstuy","OoSFTDUNEIKY:PRGLJsftduneiky;prglj"],["\"'+,-./:;<=>?BCDEFGHIJKLNOPQRSTUVWXYZ[]_bcdefghijklnopqrstuvwxyz{}","_-}w[vzSsW]VZXJE>UIDCHTNBRL\"POYGK<QF:/={xje.uidchtnbrl'poygk,qf;?+"]][ord($argv[1])%3])[0],$t[1]);
```
Array contains 3 arrays where key stands for 0=W, 1=C, 2=D
[Try it online!](https://tio.run/nexus/php#LdBZb4JAFIbhv9IQGzWidrkDl1QR2RREFhEnprK6gsOAovG3U8Z6eW6e98vp9OMwLjwnjN4SBBGsVX5hkNlfgKxVUNe2CYoeDJkRy/GCKE2msqJqumFaG8f1/HC72x@OpyiGKM0uOUES/NaYcKpm6dORLIkKZQ7YISNkxxCiPD150WEf05eN77g7ApDYLuUxljE813SrVAOsYjRBKTblaM5qTCnyokUp6lgSEh@5pbbd53QMg8O/tSKqDbLZalN0p9vrPzePuRc9w7ZhLqylDdbP6UH4qpxxJrtc89v9UcbWzcfFzm7zxATGciGMejrPDDltOlClFaHI1ljszFiq3b1fd14r3bpOiE4beKjGUR7sybNP9xsEAHYE3dcjP0H9/RvU7Q9AVhC@6KIoGENWf8Titrwu/gA "PHP – TIO Nexus")
[Answer]
## Python 2, 422 bytes
Tried to combine layouts with some clever way, but it didn't help much.
[Try it online](https://tio.run/nexus/python2#ZZDbToNAFEXf5ysQLwc6iD6DqI1oom1SqklviMq9U25TGAptrb9eKfrWx33Wyk7O3gd5lnAFy0kaciShWc46aKgBB5g2N2Y7sY/0NnskJKxAVDI0WqYuK21GslQuaEyYAIoKIqo0sFfJPGfhukz9LI6ouqwKJ3C9erEB5DbYcYuAefMGkyRaq0uah/GqarGn8SXx3DlLEyePgWbrMOJRT9vCAyg6drErl5T6uSDKuU9j2/UFmKogwVQBEVMMgwywIcH4YFe4OraNg23828@ktfWDDXa98OXmRwzSMlC7k5fH2yYdNfB94CXo800D3AyflJPP07Pzi0tB7Owqc7V5K8bWaHZ/9a59bL/uvvEP7FAkFRpJacmamr@tRNROCyAvMpIKiU2F2E4cz@ZqpWdG5rVlmUOZpJ5fC7VoSYUo7vegjwav3R63mdUT@AU)
```
from string import*
Q=' '+printable
D=' '+digits
p,P=punctuation.split(':;')
w='avmhrtgyuneolkp;qwsbfcdxjz'
c='abcsftdhuneimky;qprglvwxjz'
d="uidchtnmbrl'poygk"
K={'C':D+c+c.upper().replace('Y;','Y:')+p+'Oo'+P,'W':D+w+w.upper().replace('P;','P:')+p+'Ii'+P,'D':D+'axje.'+d+',qf;AXJE>'+d.upper().replace("L'",'L"')+'<QF:!_#$%&-()*}w[vzSsW]VZ@/\=^{`?|+~'}
k,s=input().split()
print''.join(map(lambda x:K[k[0]][Q.index(x)],s))
```
[Answer]
# JavaScript (ES6), ~~461~~ ~~409~~ ~~404~~ ~~395~~ 385 bytes
I wrote the original version of the below up on my phone while sitting on a bus and then ran out of time to properly golf it so there's more crunching to follow. Thanks to @ETHproductions for the help so far.
The Keyboard strings were copied directly from the question so blame ~~Antoine~~ ETH for any errors!
This takes an integer representing the keyboard layout (0 for DVORAK, 94 for COLEMAK & 188 for WORKMAN) and an array of the string as arguments by currying - e.g., `f(0)(["z","Z","x","X"])` outputs `;:qQ`.
```
k=>s=>s.map(c=>`!_#$%&-()*}w[vz${a="0123456789"}SsW]VZ@AXJE>UIDCHTNMBRL"POYGK<QF:/\\=^{\`axje.uidchtnmbrl'poygk,qf;?|+~${b="!\"#$%&'()*+,-./"+a}Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJ${d="Z[\\]^_\`a"}bcsftdhuneimky;qprglvwxjz{|}~${b}Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJ${d}vmhrtgyuneolkp;qwsbfcdxjz{|}~`[`${b}:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY${d}bcdefghijklmnopqrstuvwxyz{|}~`.search(c)+k]).join``
```
---
## Try It
```
f=
k=>s=>s.map(c=>`!_#$%&-()*}w[vz${a="0123456789"}SsW]VZ@AXJE>UIDCHTNMBRL"POYGK<QF:/\\=^{\`axje.uidchtnmbrl'poygk,qf;?|+~${b="!\"#$%&'()*+,-./"+a}Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJ${d="Z[\\]^_\`a"}bcsftdhuneimky;qprglvwxjz{|}~${b}Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJ${d}vmhrtgyuneolkp;qwsbfcdxjz{|}~`[`${b}:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY${d}bcdefghijklmnopqrstuvwxyz{|}~`.search(c)+k]).join``
o.innerText=f(j.value=0)([...i.value="zZxX"])
i.oninput=j.oninput=_=>o.innerText=f(+j.value)([...i.value].filter(c=>`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~`.includes(c)))
```
```
<select id=j><option value=0>DVORAK<option value=94>COLEMAK<option value=188>WORKMAN</select><input id=i><pre id=o>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~199~~ ~~192~~ 187 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žQDIiA¦'mKDuì“"'+,-./:;<=>?[]_{}“«.•4Zl˜η‡#ûwj˜ÐAδO•Duìð“>"<:.',;“S.;“_-}w[vzSsW]VZ/={?+“«ë¹<i.•2¸3'ÐQïK¤)•Duì„:;©ì.•C^ÿ¶₆*γŽ¨ï•Duì„Ooìë.•Brì·=ζW˜ΛlÝδ•Duì®ì.•]X)àƒ₆ä¤QúØM•Duì„Iiì}ð®S.;}‡‡
```
Uses IDs `1` for DVORAK; `2` for COLEMAK and `3` for WORKMAN.
Pushes the ID first, then the string we want to transliterate.
[Try it online](https://tio.run/##yy9OTMpM/f//6L5AF89Mx0PL1HO9XUoPr3nUMEdJXVtHV0/fytrG1s4@Oja@uhYoeGi13qOGRSZROafnnNv@qGGh8uHd5Vmn5xye4Hhuiz9QBqT38AagQjslGys9dR1rIDNYD0TG69aWR5dVBReHx4ZF6dtW22uDjTu8@tBOm0yQoUaHdhirH54QeHi996ElmlCzHjXMs7I@tPLwGpAK57jD@w9te9TUpnVu89G9h1YcXo9Q5Z8PtBjsOKeiw2sObbc9ty0c6MbZOYfnntsCVXZoHcSc2AjNwwuOTQIadHjJoSWBh3cdnuGLMMkz8/Ca2sMbDq0Duhvo5YVA9P@/IVdJanFJZl46AA) or [verify full ASCII-range for all three](https://tio.run/##yy9OTMpM/W/senRfoJ@9ksKjtkkKSvb/gTwXv0zHQ8vUc71dSg@vedQwR0ldW0dXT9/K2sbWzj46Nr66Fih4aLXeo4ZFJlE5p@ec2/6oYaHy4d3lWafnHJ7geG6LP1AGpPfwBqBCOyUbKz11HWsgM1gPRMbr1pZHl1UFF4fHhkXp21bba4ONO7zazyYTZKbRoR3G6ocnBB5e731oiSbUqEcN86ysD608vAakwjnu8P5D2x41tWmd23x076EVh9cjVPnnA@0Fu82p6PCaQ9ttz20LBzpxds7huee2QJUdWgcxJzZC8/CCY5OABh1ecmhJ4OFdh2f4IkzyzDy8pvbwhkPrgM4G@nghEP3X@Q8A).
**Explanation:**
```
žQ # Push printable ASCII builtin string:
# “ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~“
D # Duplicate it
Ii # If the input-integer is 1:
A # Push the lowercase alphabet
¦'mK '# Remove the first character (the 'a') and 'm'
Duì # Prepend an uppercase copy
“"'+,-./:;<=>?[]_{}“«
"# And then append the string “"'+,-./:;<=>?[]_{}“
.•4Zl˜η‡#ûwj˜ÐAδO•
# Push compressed string "xje uidchtnbrl poygk qf "
Duì # Prepend an uppercase copy
ð # Push a space " "
“>"<:.',;“S "# Push the characters [">",'"',"<",":",".","'",",",";"]
.; # Replace the first space with ">", second with '"', etc.
“_-}w[vzSsW]VZ/={?+“«
# And then append the string “_-}w[vzSsW]VZ/={?+“
ë # Else:
¹<i # If the input-integer is 2 instead:
.•2¸3'ÐQïK¤)• '# Push compressed string "defgijklnoprstuy"
Duì # Prepend an uppercase copy
„:; # Push string ":;"
© # Store it in the register (without popping)
ì # And then prepend this ":;" in front of the "DEF...def..."-string
.•C^ÿ¶₆*γŽ¨ï• # Push compressed string "sftduneiky prglj"
Duì # Prepend an uppercase copy
„Ooì # And then prepend "Oo"
ë # Else (so the input-integer is 3):
.•Brì·=ζW˜ΛlÝδ• # Push compressed string "bcdefhijklmnoprtuvwy"
Duì # Prepend an uppercase copy
®ì # And then prepend ":;" (from the register)
.•]X)àƒ₆ä¤QúØM• # Push compressed string "vmhrtyuneolkp wbfcdj"
Duì # Prepend an uppercase copy
„Iiì # And then prepend "Ii"
} # After the inner if-else:
ð # Push a space " "
®S # Push the characters [":",";"] (from the register)
.; # Replace the first space with ":" and the second space with ";"
} # After the outer if-else:
‡ # Transliterate the two strings we created,
# in the duplicate printable ASCII string
‡ # And then transliterate the printable ASCII string with this string,
# in the (implicit) string-input
# (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 how the compressed strings work.
[Answer]
# C++, 528 bytes
```
#include <map>
#define M(a,b)a!='\0'?a:b
std::map<char,char>t[3];char*c[]={"\"'+,-./:;<=>?BCDEFGHIJKLMNOPQRSTUVWXYZ[]_bcdefghijklmnopqrstuvwxyz{}","_-}w[vzSsW]VZXJE>UIDCHTNMBRL\"POYGK<QF:/={xje.uidchtnmbrl'poygk,qf;?+","\"'+,-./Oo<=>?BCSFTDHUNEIMKY:QPRGLVWXJZ[]_bcsftdhuneimky;qprglvwxjz{}","\"'+,-./Ii<=>?VMHRTGYUNEOLKP:QWSBFCDXJZ[]_vmhrtgyuneolkp;qwsbfcdxjz{}"};int main(int d,char*v[]){for(int i=1;i<4;i++)for(int j=0;j<68;j++)t[i-1][c[0][j]]=c[i][j];for(int k=0;v[2][k];k++)printf("%c",M(t[v[1][0]-'0'][v[2][k]],v[2][k]));}
```
Run with `./multitrans <0-2> <string>` where 0=Dvorak, 1=Colemak, and 2=Workman.
I added newlines in between to make the code slightly more readable below. This code generates a translation map from the strings where looking up the Qwerty character returns the translation (`t[0]['s'] = 'o'` for s into Dvorak), and then it uses the map to translate. The translation strings are shortened because some characters don't need to be changed ever. It could probably be reduced further, though.
```
#include <map>
#define M(a,b)a!='\0'?a:b
std::map<char,char>t[4];
char*c[4]={
"\"'+,-./:;<=>?BCDEFGHIJKLMNOPQRSTUVWXYZ[]_bcdefghijklmnopqrstuvwxyz{}",
"_-}w[vzSsW]VZXJE>UIDCHTNMBRL\"POYGK<QF:/={xje.uidchtnmbrl'poygk,qf;?+",
"\"'+,-./Oo<=>?BCSFTDHUNEIMKY:QPRGLVWXJZ[]_bcsftdhuneimky;qprglvwxjz{}",
"\"'+,-./Ii<=>?VMHRTGYUNEOLKP:QWSBFCDXJZ[]_vmhrtgyuneolkp;qwsbfcdxjz{}"};
int main(int d,char*v[]){
for(int i=1;i<4;i++)
for(int j=0;j<68;j++)
t[i-1][c[0][j]]=c[i][j];
for(int k=0;v[2][k];k++)
printf("%c",M(t[v[1][0]-'0'][v[2][k]],v[2][k]));
}
```
### Extra: Qwerty -> Dvorak Only (197 bytes)
I recently wrote this code that changes Qwerty into Dvorak, though capitals go untranslated.
```
#include<string>
char*d="\',.pyfgcrlaoeuidhtns;qjkxbmwvz ";std::string t="qwertyuiopasdfghjkl;zxcvbnm,./ ";int main(int c,char*v[]){for(int j=0;j<strlen(v[1]);j++)printf("%c",d[t.find(v[1][j])]);}
```
[Answer]
# C, 394 bytes
[**Try Online**](https://tio.run/nexus/c-gcc#hdDZboJQAATQd75Csa2KuNJVFPcV910BFQHlKoLKFVf66xRtmvatb5PJJCcZywVUQdmLkiOmQxFoAZlCEEHmdxjNEFz8gjonrofHJ7/Hi5kHxjiHwhHi@eX17f2jrfe53iiZGpRzVLeUzRQ7tWq6VWHRRn1YoGPNfDTIsvHxZcofl1JgD0RBhup6tlPcG@20WOHbOZm4@j5RHEGdLHpD3Dbiw/2B4C9S12JxKpFMpTPtfCdb7NZypSo9jDYbrUKl1x@URwzLcuPJlJ8J@hyK8l6VwHp1Ireb3UIxDsfl@XI1/zFK4NvoVYutTmFoG/UK3Yg2@@10PpP9YxhreQcXJ9vQlNWG3B702VwQfwyTRNY8UD1AhQ4Bv1@IGd7LPcC4wUQ48iADRfJg0LvZw1tvR4qIJGiGhxrwGEyY83IMBv0EwUXtFQ59PtJELMsKWefRcfAF)
```
char*K[3]={"!_#$%&-()*}w[vz0123456789SsW]VZ@AXJE>UIDCHTNMBRL\"POYGK<QF:/\\=^{`axje.uidchtnmbrl'poygk,qf;?|+~",
"!\"#$%&'()*+,-./0123456789Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJZ[\\]^_`abcsftdhuneimky;qprglvwxjz{|}~",
"!\"#$%&'()*+,-./0123456789Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJZ[\\]^_`avmhrtgyuneolkp;qwsbfcdxjz{|}~"};
main(int c,char**v){char*t=v[2];while(*t)putchar(*t>32?K[atoi(v[1])][*t-33]:*t),t++;}
```
] |
[Question]
[
# The 3x3 Hexa Prime Square Puzzle
### Introduction
We consider 3x3 squares of hexadecimal digits (from `0` to `F`) such as:
```
2 E 3 1 F 3
8 1 5 7 2 7
D D 5 B B 9
```
We define a **3x3 Hexa Prime Square** (**HPS3**) as such a square for which all hexadecimal numbers read from left to right and from top to bottom are odd primes (i.e. primes greater than 2).
This is true for the left square and false for the right square:
```
2 E 3 --> 0x2E3 = 739 1 F 3 --> 0x1F3 = 499
8 1 5 --> 0x815 = 2069 7 2 7 --> 0x727 = 1831
D D 5 --> 0xDD5 = 3541 B B 9 --> 0xBB9 = 3001
| | | | | |
| | +---> 0x355 = 853 | | +---> 0x379 = 889 = 7 x 127
| +-----> 0xE1D = 3613 | +-----> 0xF2B = 3883 = 11 x 353
+-------> 0x28D = 653 +-------> 0x17B = 379
```
### Goal
Given a list of 9 hexadecimal digits, your goal is to find an arrangement that forms a HPS3.
**Example:**
```
Input: 123558DDE
Possible output: 2E3815DD5 (a flattened representation of the above left example)
```
### Input / Output
Input and output formats are flexible. The only requirement is that output digits are ordered from left to right and from top to bottom. Below are some possible options:
```
"2E3815DD5"
[ 0x2, 0xE, 0x3, 0x8, 0x1, 0x5, 0xD, 0xD, 0x5 ]
[ "2", "E", "3", "8", "1", "5", "D", "D", "5" ]
[
[ 0x2, 0xE, 0x3 ],
[ 0x8, 0x1, 0x5 ],
[ 0xD, 0xD, 0x5 ]
]
[ "2E3", "815", "DD5" ]
etc.
```
Using the same format for both input and output is not required.
### Rules
* This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.
* Your algorithm must be deterministic
* You can't just bogosort the array until it's valid, even in a deterministic way (by using a constant random seed).
* You *may* list all possible solutions for a given input, but this is neither required nor subject to a bonus.
* You're not required to support inputs that do not admit any solution. (It's perfectly fine if your code is looping forever or crashing in that case.)
### Test cases
```
Input Possible output
---------------------------
123558dde 2e3815dd5
1155578ab a7b851551
03bddffff ffd0dfb3f
35899beff 8f99e3bf5
15899bbdf 581bb9fd9
14667799f 6f1469779
13378bcdd 78d1cd33b
24577bbdd 7274bd5db
1118bbddd 11b18dbdd
223556cdd 623c25dd5
12557899a 8a5295971
113579bbd 5b3db7191
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~23~~ 21 bytes
Uses [CP-1252](http://www.cp1252.com) encoding.
```
œJvy3ôD€SøJìHDps2›*P—
```
Too slow for TIO.
**Explanation**
```
œJ # all permutations of input as strings
v # for each permutation
# EXAMPLE: 2E3815DD5
y3ô # split in pieces of 3
# EXAMPLE: ['2E3','815','DD5']
D # duplicate
# EXAMPLE: ['2E3','815','DD5'], ['2E3','815','DD5']
€SøJ # zip the copy to swap rows and columns
# EXAMPLE: ['2E3','815','DD5'], ['28D','E1D','355']
ì # attach them to the same list
# EXAMPLE: ['2E3','815','DD5','28D','E1D','355']
H # convert from base 16 to base 10
# EXAMPLE: [739, 2069, 3541, 653, 3613, 853]
D # duplicate
# EXAMPLE: [739, 2069, 3541, 653, 3613, 853],[739, 2069, 3541, 653, 3613, 853]
p # check first copy for primality
# EXAMPLE: [739, 2069, 3541, 653, 3613, 853],[1,1,1,1,1,1]
s2› # check that each in second copy is larger than 2
# EXAMPLE: [1,1,1,1,1,1],[1,1,1,1,1,1]
* # pairwise multiplication
# EXAMPLE: [1,1,1,1,1,1]
P # product (1 if all were primes larger than 2, else 0)
# EXAMPLE: 1
— # if 1, print y
# EXAMPLE: 2E3815DD5
```
[Answer]
# Python 2, ~~212~~ ~~206~~ ~~197~~ 194 bytes
Requires input enclosed in quotes, like `"123558dde"`
```
from itertools import*
k,p,P=3,4,[]
while k<5e3:P+=[k][:p%k];p*=k;k+=1
print[s for s in map(''.join,permutations(input()))if all(int(s[3*i:][:3],16)in P and int(s[i::3],16)in P for i in(0,1,2))]
```
Saving 9 and 3 bytes thanks to Jonathan Allan
Found new prime filter from [xnor](https://codegolf.stackexchange.com/a/27022/53667 "xnor") (modified the square away, since we dont want 2 as prime here), old prime filter is from [Bob](https://codegolf.stackexchange.com/questions/70001/list-prime-numbers/70019#70019 "Bob")
[Answer]
# Pyth, ~~23~~ 21 bytes
```
f*F}R-Pd2iR16sCBc3T.p
```
Times out online, but finishes in 1.5 minutes on my laptop. Takes input in quotes.
### Explanation
```
f*F}R-Pd2iR16sCBc3T.p
.pQ permutations of input (implicit Q)
f T filter each T:
c3 divide into rows
CB make pair (rows, columns)
s join those lists
iR16 interpret items as hex
}R check if each number d is in
Pd its prime factors
- 2 with twos removed
*F product (also known as all)
implicitly print matches
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~34~~ 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
i@€ØH’
s3µ;ZÇ€ḅ⁴µ>2aÆPẠ
Œ!ÇÐfḢ
```
*(I should be able to use an nfind to just fetch the first match, `1#` in place of `ÐfḢ`, for less bytes and more speed, but I'm seeing errors when I try. EDIT: wrote some changes to possibly implement this in Jelly.)*
Brute force search of all permutations, filtered for the criteria, returning first match.
Way too slow for TtyItOnline. Local output examples:
```
C:\Jelly\jelly-master>python jelly -fu test.txt "123558DDE"
28DE1D355
C:\Jelly\jelly-master>python jelly -fu test.txt "1155578AB"
11B8A5557
```
### How?
```
i@€ØH’ - Link 1, convert from hexadecimal string to integer list: string
ØH - yield hexadecimal characters, "0123456789ABCDEF"
i@€ - index of €ach character of s in hex chars
’ - decrement (vectorises) (from 1 based jelly index to place value)
s3µ;ZÇ€ḅ⁴µ>2aÆPẠ - Link 2, check if a flattened square is "all prime": string
s3 - split into threes (rows)
µ - monadic chain separation
; - concatenate with
Z - transpose (columns)
Ç€ - call last link (1) as a monad for €ach string in the list
-> list of integer lists
ḅ⁴ - convert from base 16 (vectorises) -> list of decimals
µ - monadic chain separation
>2 - greater than 2
a - and
ÆP - isPrime? -> list of 1s and 0s
Ạ - all truthy?
Œ!ÇÐfḢ - Main link: string
Œ! - all permutations of the string
Ðf - filter keeping entries that evaluate to truthily for
Ç - last link (3) as a monad
Ḣ - head - return first entry
```
[Answer]
# J, 49 bytes
```
[:(#~([:*/@(2&<*1&p:)@(,&dfh|:)_3]\])"{)i.@!@#A.]
```
Brute-force search that tests all permutations and outputs all permutations that satisfy the conditions for the puzzle.
The performance is good enough to compute each test case in about 3 seconds.
## Usage
```
f =: [:(#~([:*/@(2&<*1&p:)@(,&dfh|:)_3]\])"{)i.@!@#A.]
f '123558dde'
28de1d355
28de1d355
28de1d355
28de1d355
2e3815dd5
2e3815dd5
2e3815dd5
2e3815dd5
timex 'f ''123558dde'''
3.68822
```
## Explanation
```
[:(#~([:*/@(2&<*1&p:)@(,&dfh|:)_3]\])"{)i.@!@#A.] Input: string S
# Length of S
!@ Factorial
i.@ Range [0, len(S)!)
] Get S
A. Find the permutations of S by index
[:( ) Operate on the permutations
( )"{ For each permutation P
] Get P
_3]\ Get sublists of size 3
[: ( ) Operate on the sublists
|: Transpose
&dfh Convert both the transpose and
initial from hex to decimal
, Join them
( ) Operate on the decimals
1&p: Test each for primality
2&< Test each if greater than 2
* Multiply them (AND)
*/@ Reduce using multiplication
#~ Filter the permutations by those
values and return
```
[Answer]
# Mathematica, 115 bytes
```
#<>""&@@Select[Permutations@#,And@@(PrimeQ@#&&#>2&)/@(FromDigits[#<>"",16]&/@#~Join~Transpose@#)&[#~Partition~3]&]&
```
The input must be a list of characters (e.g. `{"1", "2", "3", "5", "5", "8", "D", "D", "E"}`)
[Answer]
# Ruby, 146 bytes
Anonymous function takes an array of nine integers, returns one solution as an array of nine integers. Relies on helper function `g` and a `require`.
```
require'prime'
g=->x,y,z{(2<s=x<<8|y<<4|z)&&s.prime?}
->r{r.permutation{|i|a=1
3.times{|j|a&&=g[*i[j*3,3]]&&g[i[j],i[j+3],i[j+6]]}
a&&(return i)}}
```
This **140-byte** version prints all possible solutions, with the integers as decimals (not sure if that's allowed.)
```
require'prime'
g=->x,y,z{(2<s=x<<8|y<<4|z)&&s.prime?}
->r{r.permutation{|i|a=1
3.times{|j|a&&=g[*i[j*3,3]]&&g[i[j],i[j+3],i[j+6]]}
a&&p(i)}}
```
**Ungolfed in test program**
```
require'prime'
g=->x,y,z{(2<s=x<<8|y<<4|z)&& #combine 3 input values, check if >2
s.prime?} #and check if prime
h=->r{
r.permutation{|i| #iterate over all permutations
a=1 #a=truthy
3.times{|j|
a&&=g[*i[j*3,3]]&& #check rows (3 consecutive integers)
g[i[j],i[j+3],i[j+6]] #and columns
}
a&&(return i) #if a still truthy, return solution.
}
}
#test cases: uncomment to run. solutions do not always match example solution from OP.
a=10;b=11;c=12;d=13;e=14;f=15
#p h[[1,2,3,5,5,8,d,d,e]] #2e3815dd5
#p h[[1,1,5,5,5,7,8,a,b]] #a7b851551
#p h[[0,3,b,d,d,f,f,f,f]] #ffd0dfb3f
#p h[[3,5,8,9,9,b,e,f,f]] #8f99e3bf5
#p h[[1,5,8,9,9,b,b,d,f]] #581bb9fd9
#p h[[1,4,6,6,7,7,9,9,f]] #6f1469779
#p h[[1,3,3,7,8,b,c,d,d]] #78d1cd33b
#p h[[2,4,5,7,7,b,b,d,d]] #7274bd5db
#p h[[1,1,1,8,b,b,d,d,d]] #11b18dbdd
#p h[[2,2,3,5,5,6,c,d,d]] #623c25dd5
#p h[[1,2,5,5,7,8,9,9,a]] #8a5295971
#p h[[1,1,3,5,7,9,b,b,d]] #5b3db7191
```
[Answer]
# Groovy, 134 Bytes
Finds all possible solutions and returns them as an array, returns `[]` if there isn't a solution.
```
{it.toList().permutations().collect{it.collate(3).every{x=Integer.parseInt(it.join(),16);(2..x**0.5).every{x%it>0};}?it.join():0}-[0]}
```
Example input: `123558dde`
Output:
```
[8235d5e1d, 2dd851e35, 815e352dd, 2e3d5518d, d2d3e5581, 853de5d21, 2dd3558e1, 2dd3e5581, 2e355d18d, 2518dd3e5, dd52e3185, e1d5d5283, 823ed1d55, 28d3e515d, 28d15de35, e351258dd, e5dd21853, 851d2d3e5, ed515d283, 2dd3e5185, 85de35d21, 5d1ed5823, 8dd355e21, d2d3e5815, d2d3e5851, 251e358dd, 2dde35851, 8235d5ed1, 2dde35815, e3585dd21, d2d8153e5, 85d5d12e3, 21dd85e35, d8521de35, 21d85d3e5, e1d5d5823, e35581d2d, 3e52dd581, dd52e3851, dd52e3815, 3e5281dd5, 8dd1253e5, 3e5815d2d, 3e55d128d, ed515d823, de5853d21, e218dd355, d8d1253e5, d8d251e35, d8d5512e3, 2dde35581, 3e52dd851, 5d1ed5283, e21dd5853, 3e5d2185d, 2513e58dd, 2dd3e5815, 2dd3e5851, e1d823d55, 3e52dd815, 581d2de35, e3515d28d, 2e318dd55, ed1823d55, dd52813e5, dd52e3581, 2e3515d8d, 28d3e55d1, 82355de1d, 82355ded1, 2dde35185, 3e5d8d125, 85d21de35, 281dd53e5, d21d85e35, d21e35d85, 2dd8e1355, 28d5d1e35, 85d15d2e3, 2813e5dd5, 3e5d2d185, 5d1e5d283, 3e5d2d581, e1dd55823, 3558e12dd, d55283e1d, 15dde5283, 5d128d3e5, 5518dd2e3, e5d28315d, 5d5823ed1, d2d1853e5, 823d55e1d, de521d853, d81d552e3, 5d5823e1d, 21ded5853, 823e1dd55, 3e52dd185, 5812dde35, d85e35d21, 3e585d21d, 8512dd3e5, 3e5251d8d, d2d8513e5, e1dd55283, 2e3d81d55, 853ed5d21, 2835d1ed5, 15d2e3d85, 5d1e3528d, 15dde5823, e35851d2d, 55d283e1d, 2e3551d8d, 8dd3e5125, 85d3e5d21, 8152e3dd5, 28de1d355, e1d55d823, 8dd3e5251, 5158dd2e3, e3521dd85, e1d35528d, 2e35d185d, 21de5d853, 823d55ed1, 5813e52dd, 8153e5d2d, e1d55d283, 21de3585d, d85d21e35, 5152e3d8d, 8513e5d2d, dd5e21853, 3552dd8e1, d552e318d, e5d2835d1, 2835d1e5d, 2835d1de5, 5d1e5d823, 8dde35125, 5d52e3d81, 3e5821dd5, 28d5d13e5, e35d21d85, dd51852e3, d2d185e35, 8dde35251, 8dd2513e5, e35d2d185, 2835d5e1d, 1852e3dd5, d85d213e5, 515d8d2e3, dd53e5821, d5518d2e3, 8dd5512e3, 283d55ed1, e5d5d1823, 28d355ed1, 3e58152dd, d812e3d55, e5d85321d, d8515d2e3, d2d581e35, 3e5581d2d, 85d21d3e5, 283d55e1d, dd53e5281, 851dd52e3, e35dd5821, 3e51258dd, dd58512e3, 28d355e1d, d8d2513e5, 125e358dd, e35dd5281, e35d2d851, d8d2e3515, e35d2d815, d21853ed5, d8d2e3551, 1852dd3e5, d21853e5d, 85dd213e5, d21853de5, 5d1283e5d, 823ed155d, 5d1283de5, ed521d853, 283e1dd55, d8d355e21, d8de35251, 5d1283ed5, e35d2d581, 3e528d15d, d55283ed1, 8512dde35, 3e5851d2d, 823ed15d5, 15d28de35, 15d3e528d, 2835d5ed1, 5d12e385d, 5d185d2e3, 5d5283e1d, 55d2e3d81, d2185de35, d55e1d283, ed582315d, 2dd8513e5, 853e5d21d, e352dd581, 851e352dd, 2dd5813e5, e352dd815, 853d21e5d, e352dd851, dd5821e35, ed155d283, 3e5d8d251, d8de35125, 2e3d8d551, 3e528d5d1, e5d21d853, dd5853e21, 853d21ed5, 85de3521d, e352518dd, 2e3d8d515, 125d8de35, e352dd185, 853d21de5, 8e13552dd, 1258dde35, 581e352dd, e21d8d355, ed155d823, e21853dd5, e3528d5d1, d2d851e35, 5512e38dd, 125d8d3e5, 2e3815dd5, 2513e5d8d, 21dde5853, 355d2d8e1, d55ed1283, 815dd52e3, 283ed1d55, 8152dd3e5, 281e35dd5, 28355de1d, 355e1d28d, ed182355d, 853dd5e21, e3528d15d, ed18235d5, 15d85d2e3, e351852dd, d55e1d823, 8e12dd355, 28355ded1, 2dd815e35, 581d2d3e5, d55ed1823, 15d283ed5, 821dd53e5, 2e35d518d, 5d5283ed1, 15d283e5d, 15d283de5, e1d28355d, e5d5d1283, 251d8d3e5, e1d2835d5, dd5281e35, ed15d5823, 21de35d85, dd58152e3, 2dd1853e5, 1258dd3e5, 5d5e1d283, 1253e58dd, 3e5d8521d, 18d2e3d55, e358152dd, 5512e3d8d, e35251d8d, 853ed521d, 3e5dd5281, 5813e5d2d, ed15d5283, 18d55d2e3, 281dd5e35, 8dde21355, 1852dde35, 3e585dd21, d85e3521d, 581e35d2d, ed1283d55, d812e35d5, 2e35518dd, 5d128de35, 8153e52dd, ed55d1823, e5d82315d, e35d85d21, d812e355d, d853e521d, 8dd2e3551, 2e3581dd5, 15de5d823, 8dd2e3515, 185e35d2d, 125e35d8d, 581dd52e3, 5d5e1d823, 5812e3dd5, 5152e38dd, 3558e1d2d, 85d3e521d, 5d1d852e3, 823de55d1, 2e3d8155d, d213e585d, ed55d1283, 2e3dd5581, 2e3dd5815, 15d823ed5, 2e3dd5851, d552e3d81, 55de1d823, e5d8235d1, 21d853de5, de528315d, d21e3585d, 2e3d815d5, 21d853e5d, ed58235d1, 2e3dd5185, 21d853ed5, de52835d1, 15d823e5d, e1d28d355, 355ed128d, 5812dd3e5, 815d2d3e5, 15d823de5, 823de515d, 55de1d283, ed5853d21, 2dd8153e5, 2e3d855d1, 185dd52e3, 8e1355d2d, 2e3d55d81, d2d3558e1, d8521d3e5, e5d15d823, ed52835d1, 35528de1d, dd5e35281, 3e58dd251, 5d5ed1283, dd58213e5, e355d128d, 3e58dd125, 3e5125d8d, 8213e5dd5, 355e218dd, 2e3d8515d, 35528ded1, e5d15d283, 853e21dd5, 8dd125e35, 15ded5823, e358dd251, 2e315dd85, 851d2de35, 551d8d2e3, d2d5813e5, ed528315d, 2e3185dd5, 185d2de35, 8152dde35, e35d2185d, 15de3528d, e358dd125, 251e35d8d, 5d5ed1823, 821dd5e35, 251d8de35, 8512e3dd5, 5d1823de5, d2d815e35, 3e51852dd, 5d1823e5d, 82315dde5, 3e5dd5821, 82315de5d, 5d518d2e3, 1853e5d2d, 8dd251e35, ed128355d, e1d8235d5, 82315ded5, d21ed5853, 823ed515d, 2e38dd551, ed135528d, 2e38dd515, 5d1823ed5, 2e318d55d, 15de5d283, e1d82355d, ed1d55823, 2e3851dd5, d8d5152e3, 283de515d, 823ed55d1, 3e55812dd, dd5e35821, 15ded5283, e21355d8d, 21d85de35, 8dd5152e3, e35125d8d, e355812dd, 5d52e318d, 8e1d2d355, d8155d2e3, 3e5d21d85, 21d3e5d85, ed12835d5, de585321d, d2185d3e5, 85dd21e35, 2e318d5d5, d213e5d85, 2e385d5d1, 55d823ed1, 15d2e385d, 3e521dd85, 283de55d1, ed1d55283, d8de21355, de5d21853, 55d823e1d, d852e315d, 355d8de21, d852e35d1, 8513e52dd, 185d2d3e5, 853e5dd21, 21d3e585d, 2dd581e35, de582315d, 823e5d15d, de515d283, 185e352dd, 28de3515d, 3e5d2d815, d21de5853, 283ed155d, 3e5d2d851, 55d283ed1, 3558dde21, 283ed15d5, d815d52e3, 28de355d1, 851e35d2d, de515d823, 5d1de5823, 55dd812e3, 283e5d15d, dd55812e3, 823e5d5d1, 15dd852e3, d2de35185, 1253e5d8d, 2e35d5d81, 1853e52dd, 2e35158dd, 21dd853e5, e35185d2d, 283e5d5d1, 18dd552e3, e35281dd5, 5d13e528d, e1d283d55, 2e385d15d, 28315de5d, 85d2e35d1, 28315dde5, 2dd185e35, e3585d21d, 283ed55d1, 5d1de5283, 28315ded5, d55823ed1, 5d12e3d85, e5d853d21, e35d8d125, e358512dd, d55823e1d, 815e35d2d, e35d8d251, 18d5d52e3, 28ded1355, e3521d85d, 283ed515d, 821e35dd5, d2d3e5185, 85321de5d, d2de35815, e35d8521d, d55d812e3, e213558dd, e35815d2d, d855d12e3, 15d28d3e5, d21e5d853, 85d2e315d, 3e58512dd, d2de35851, ed128d355, 28d15d3e5, 3e52518dd, 18d2e355d, de55d1823, d2de35581, 85321ded5, d2d8e1355, d853e5d21, 18d2e35d5, 2e35d1d85, 85321dde5, 3e5185d2d, 853de521d, 355e21d8d, 5d5d812e3, 55ded1823, de55d1283, 8235d1ed5, e35821dd5, 2518dde35, 8235d1de5, 8235d1e5d, 3e521d85d, d8d125e35, 2e315d85d, ed5d21853, 55ded1283, 815d2de35, 283e1d55d, 823e1d55d, 2e355dd81, 3e5d85d21, d8d3e5125, 3e515d28d, d21d853e5, 283e1d5d5, ed585321d, 823e1d5d5, 55d2e318d, d8d3e5251, 55d18d2e3, de58235d1]
```
Example input: `222222222`
Output: `[]`
If anyone wants me to comment it out, holler at a brother.
] |
[Question]
[
Given (on STDIN, as command line arguments, or as function arguments) two distinct non-empty strings, find and return the shortest substring of the first string which is not a substring of the second. If no such substring exists, you may return the empty string, return any string which isn't a substring of the original string, or throw an exception. If you are returning from a function, you may also return null (or undefined, None, etc.) in this case. If multiple such substrings are tied for the shortest, you may return any one of them.
Strings can consist of any printable ascii characters.
Input given on STDIN will be given with one string on each line. At your request, a single empty line may be added at the end of the input.
This is code golf, so the shortest valid program wins.
# SOME TEST CASES
INPUT:
```
STRING ONE
STRING TWO
```
OUTPUT:
```
E
```
INPUT:
```
A&&C
A&$C
```
VALID OUTPUTS:
```
&&
&C
```
INPUT:
(Two randomly-generated 80-letter strings)
```
QIJYXPYWIWESWBRFWUHEERVQFJROYIXNKPKVDDFFZBUNBRZVUEYKLURBJCZJYMINCZNQEYKRADRYSWMH
HAXUDFLYFSLABUCXUWNHPSGQUXMQUIQYRWVIXGNKJGYUTWMLLPRIZDRLFXWKXOBOOEFESKNCUIFHNLFE
```
ALL VALID OUTPUTS:
```
AD
BJ
BR
CZ
DD
EE
ER
EY
EY
FF
FJ
FW
FZ
HE
IJ
IN
IW
JC
JR
JY
KL
KP
KR
KV
LU
MH
MI
NB
NQ
OY
PK
PY
QE
QF
QI
RA
RB
RF
RO
RV
RY
RZ
SW
UE
UH
UN
UR
VD
VQ
VU
WB
WE
WI
WU
XN
XP
YI
YK
YK
YM
YS
YW
YX
ZB
ZJ
ZN
ZV
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes
```
:1foh.,{,.[A:B]hs?'~sB}
```
Works on the old Java transpiler. Expects the two strings in a list as input, unifies the output with the substring. If no substring is found, returns false.
Unfortunately I have not yet coded the subset built-in in the new Prolog transpiler.
### Explanation
```
:1f Find all bindings which satisfy predicate 1 with that binding as input and
with the Input of the main predicate as output.
oh., Order that list of bindings, and unify the output with the first one.
{
,.[A:B] Unify the output with the list [A,B]
hs? Unify the input with a subset of A
'~sB Check that no subset of B can be unified with the input
}
```
[Answer]
# Python, ~~119~~ ~~115~~ 91
```
lambda a,b:[a[m:m+n]for n in range(1,len(a)+1)for m in range(len(a))if a[m:m+n]not in b][0]
```
Test cases:
```
| Input 1 | Input 2 | Output |
|----------+-------------+---------------|
| 'abcd' | 'abc' | 'd' |
| 'abcd' | 'dabc' | 'cd' |
| 'abcd' | 'dcbabbccd' | 'abc' |
| 'abcdf' | 'abcdebcdf' | 'abcdf' |
| 'abc' | 'abc' | (IndexError) |
```
Working on making it shorter, but this is my brain instinct. Not really much of a golfer yet.
Thanks to @user81655 and @NonlinearFruit for the extra bytes.
**Edit**:
Dang. Tried this code:
```
def z(a,b):
for s in [a[m:m+n]for n in range(1,len(a)+1)for m in range(len(a)-n+1)]:
if s not in b:return s
return''
```
Thought it was a few bytes shorter. Turns out it was 1 byte longer than what I had before the edit.
[Answer]
# Python, ~~87~~ 86 bytes
```
lambda s,t,e=enumerate:[s[i:i-~j]for j,_ in e(s)for i,_ in e(s)if(s[i:i-~j]in t)<1][0]
```
If it exists, this will return the leftmost of all shortest unique substrings.
If there is no unique substring, an *IndexError* is raised.
Test it on [Ideone](http://ideone.com/9LuLtC).
[Answer]
# Python, 82 bytes
```
g=lambda u:{u}|g(u[1:])|g(u[:-1])if u else{''}
f=lambda s,t:min(g(s)-g(t),key=len)
```
Usage: `f('A&&C', 'A&$C')` -> returns `'&&'`
Raises ValueError if there is no suitable substring.
Explanation:
`g=lambda u:{u}|g(u[1:])|g(u[:-1])if u else{''}` recursively creates a set of the substrings of `u`
`f=lambda s,t:min(g(s)-g(t),key=len)` takes the shortest substring from the set difference
[Answer]
## JavaScript (ES6), 79 bytes
```
f=
(a,b)=>[...a].some((_,i,c)=>c.some((_,j)=>b.indexOf(s=a.substr(j,i+1))<0))?s:''
```
```
<div oninput=o.textContent=f(a.value,b.value)><input id="a"/><input id="b"/><pre id=o>
```
If returning `false` is acceptable, save 2 bytes by using `&&s` instead of `?s:''`.
[Answer]
# Pyth, 11 bytes
```
Jwhf!}TJ.:z
```
[Try it online!](http://pyth.herokuapp.com/?code=Jwhf!%7DTJ.%3Az&input=hello%0Aworld+the+fellow&debug=0)
[Answer]
# JavaScript (Firefox), 80 bytes
```
solution=
a=>b=>[for(_ of(i=0,a))for(_ of(j=!++i,a))if(b.includes(s=a.substr(j++,i)))s][0]
document.write("<pre>"+
[ [ "test", "best" ], [ "wes", "west" ], [ "red", "dress" ] ]
.map(c=>c+": "+solution(c[0])(c[1])).join`\n`)
```
Test works only in Firefox. Returns `undefined` if there is no substring.
[Answer]
## [Retina](https://github.com/mbuettner/retina), 37 bytes
```
M!&`\G(.+?)(?!.*¶.*\1)
O$#`.+
$.&
G1`
```
Output is empty if no valid substring is found in `A`.
[Try it online!](http://retina.tryitonline.net/#code=JShgXHMKJG4KTSEmYFxHKC4rPykoPyEuKsK2LipcMSkKTyQjYC4rCiQuJgpHMWA&input=YWJjZCBhYmMKYWJjZCBkYWJjCmFiY2QgZGNiYWJiY2NkCmFiYyBhYmMKYWJjZGYgYWJjZGViY2Rm) (Slightly modified to run several test cases at once. The input format is actually linefeed separated, but test suites are easiest to write with one test case per line. The test framework turns the space into a linefeed before the actual code starts.)
### Explanation
```
M!&`\G(.+?)(?!.*¶.*\1)
```
For each possible starting position in `A`, match the shortest substring which does not appear in `B`. The `&` is for overlapping matches, such that we actually try every starting position, even if a match is longer than one character. The `\G` ensures that we don't skip any positions - in particular, this way we have to stop at the linefeed, such that we don't get additional matches from `B` itself. The reason this doesn't mess things up is actually quite subtle: because if there's a starting position in `A` where we can't find any valid substring, then that's also a failure which will cause `\G` to stop checking any further positions. However, if (from the current starting position) all substrings appear in `B`, so will all substrings that start further right of the current position, so discarding those is not an issue (and actually improves performance).
Due to the `M!` configuration, all of these matches will be returned from the stage, joined with linefeeds.
```
O$#`.+
$.&
```
This sorts the lines of the previous result by length. This is done by matching the line with `.+`. Then `$` activates a form of "sort-by", such that the match is substituted with `$.&` for determining sort order. The `$.&` itself replaces the match with its length. Finally, the `#` option tells Retina to sort numerically (otherwise, it would treat the resulting numbers as strings and sort them lexicographically).
```
G1`
```
Finally, we simply keep only first line, by using a grep stage with an empty regex (which always matches) and a limit of `1`.
[Answer]
# Perl, ~~87~~ 85
```
sub{(grep{$_[1]!~/\Q$_/}map{$}=$_;map{substr($_[0],$_,$})}@}}(@}=0..length$_[0]))[0]}
```
This is an anonymous function which returns the first (by position) of the shortest substrings of `$_[0]` that do not occur in `$_[1]`, or `undef` if no such substring exists.
Test program with strings taken from @iAmMortos's answer, tested with Perl 5.22.1:
```
#!/usr/bin/perl -l
use strict;
use warnings;
my $f = <see above>;
print $f->('abcd', 'abc');
print $f->('abcd', 'dabc');
print $f->('abcd', 'dcbabbccd');
print $f->('abcdf', 'abcdebcdf');
print $f->('abc', 'abc');
```
[Answer]
## Haskell, 72 bytes
```
import Data.Lists
a#b=argmin length[x|x<-powerslice a,not$isInfixOf x b]
```
Usage example: `"abcd" # "dabc"`-> `"cd"`.
A straightforward implementation: build all substrings of `a` and keep those which do not appear in `b`. `argmin` returns an element of a list which minimizes the function given a the 2nd argument, here: `length`.
[Answer]
# Pyth - ~~9~~ 6 bytes
```
h-Fm.:
```
[Try it online here](http://pyth.herokuapp.com/?code=h-Fm.%3A&input=%22hello%22%2C+%22world+the+fellow%22&debug=1).
[Answer]
## C#, 152 bytes
```
string f(string a,string b){int x=a.Length;for(int i=1;i<=x;i++)for(int j=0;j<=x-i;j++){var y=a.Substring(j,i);if(!b.Contains(y))return y;}return null;}
```
[Answer]
# Ruby, 70 bytes
Collects all substrings of a certain length from the first string, and if there is one that isn't in the second string, return it.
```
->a,b{r=p;(1..l=a.size).map{|i|(0...l).map{|j|b[s=a[j,i]]?0:r||=s}};r}
```
[Answer]
## Burlesque - 26 bytes
Right now the shortest way I can come up with is:
```
lnp^sujbcjz[{^p~[n!}f[-][~
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
Êõ!ãU c k!èV g
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=yvUh41UgYyBrIehWIGc=&input=IlFJSllYUFlXSVdFU1dCUkZXVUhFRVJWUUZKUk9ZSVhOS1BLVkRERkZaQlVOQlJaVlVFWUtMVVJCSkNaSllNSU5DWk5RRVlLUkFEUllTV01IIgoiSEFYVURGTFlGU0xBQlVDWFVXTkhQU0dRVVhNUVVJUVlSV1ZJWEdOS0pHWVVUV01MTFBSSVpEUkxGWFdLWE9CT09FRkVTS05DVUlGSE5MRkUiCi1R)
Returns `undefined` if there is [no valid substring](https://ethproductions.github.io/japt/?v=1.4.6&code=yvUh41UgYyBrIehWIGc=&input=IkhJIgoiSEkiCi1R). This is distinct from [returning the string "undefined"](https://ethproductions.github.io/japt/?v=1.4.6&code=yvUh41UgYyBrIehWIGc=&input=InVuZGVmaW5lZCIKIm5kZWZpbmVkdW5kZWZpbmUiCi1R), though the difference is only visible because of the -Q flag.
Explanation:
```
Ê :Length of the first input
õ :For each number in the range [1...length]:
!ãU : Get the substrings of the first input with that length
c :Flatten to a single array with shorter substrings first
k :Remove ones which return non-zero to:
!èV : Number of times that substring appears in second input
g :Return the shortest remaining substring
```
[Answer]
# Japt `-h`, 11 bytes
```
à f@øX «VøX
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=4CBmQPhYIKtW+Fg=&input=ImFiY2RmIgoiYWJjZGViY2RmIgotaA==)
```
:Implicit input of strings U & V
à :All combinations of U
f@ :Filter each as X
øX : Does U contain X?
« : Logical AND with the negation of
VøX : Does V contain X?
:Implicit output of last element
```
] |
[Question]
[
You should write a program or function which receives a string representing an ASCII art as input and outputs or returns the number of endpoints in the input.
The input will consist of the characters `space - | +` (with 0, 2, 2 and 4 endpoints respectively) and linebreaks. E.g.:
```
-|++-
+
```
Two adjacent characters are connected and hence lose 1 endpoint each in the following cases:
```
-- -+ +- | | + + ++
| + | +
```
The first example has
```
2+2+2+2+1+
3 = 12
```
endpoints.
## Input
* Input will be a string consisting of the characters space, `-`, `|`, `+` and newline.
* Input length can be 0 length and any input matching the above description is valid (in regex input is `[ -+|\n]*`).
* Trailing newline is optional.
## Output
* A single non-negative integer, the number of endpoints.
## Examples
Outputs are after the last row of their inputs.
```
+
4
-|++-
+
12
+--+
| |
+--+
8
| |
+--+-- |||
12
--++
|||--
10
<empty input>
0
|
|
2
--
++--
++
--+
+++ ||
----
30
```
This is code golf so the shortest entry wins.
[Answer]
# [Snails](https://codegolf.stackexchange.com/a/47495/30688), 29
```
A
\+|\-)lr!\-|(\+|\|)n!\|}!\+
```
I added line comments with `,,`, in order to make a commented version.
```
A ,, Count all accepting paths
\+ | \- ) ,, Literal '+' or '-'
lr ,, Set direction to left or right
!\- ,, Assert next char is not '-'
| ,, Or...
( \+ | \| ) ,, Literal '+' or '|'
n ,, Turn 90 degrees right or left (from initial direction right)
!\| ,, Assert next char is not '|'
} ,, Group everything previous
!\+ ,, Assert next char is not '+'
```
[Answer]
# JavaScript (ES6), 168
Using template strings, all newlines are significant and counted.
Test running the snippet below in Firefox. (Chrome still does not support `...`)
```
f=s=>`
${s}
`.split`
`.map((r,y,s,v=c=>c>' '&c!='-',h=c=>c>' '&c<'|')=>[...r].map((c,x)=>t+=(v(c)?2-v(s[y-1][x])-v(s[y+1][x]):0)+(h(c)?2-h(r[x-1])-h(r[x+1]):0)),t=0)&&t
// Less golfed
u=s=>{
s = ('\n' + s + '\n').split('\n'); // split in rows, adding a blank line at top and one at bottom
t = 0; // init counter
v = c => c>' ' & c!='-'; // function to check if a character has vertical end points
h = c => c>' ' & c<'|'; // function to check if a character has horizontal end points
s.forEach( (r,y) =>
[...r].forEach( (c,x) => {
if (v(c)) // if current character has vertical endpoints, check chars in previous and following row
t += 2 - v(s[y-1][x]) - v(s[y+1][x]);
if (h(c)) // if current character has horizontal endpoints, check previous and following chars in row
t += 2 - h(r[x-1]) - h(r[x+1]);
})
)
return t
}
//TEST
out=x=>O.innerHTML+=x+'\n'
;[
[`+`,4]
,[`-|++-
+`,12]
,[`+--+
| |
+--+`,8]
,[` | |
+--+-- |||`,12]
,[`--++
|||--`,10]
,[``,0]
,[`
|
|`,2]
,[`
--
++--
++
--+
+++ ||
----`,30]
].forEach(t=>{ r=f(t[0]),k=t[1],out('Test '+(r==k?'OK':'Fail')+'\n'+t[0]+'\nResult:'+r+'\nCheck:'+k+'\n') })
```
```
<pre id=O></pre>
```
[Answer]
# Python 2, 123
```
l=[]
i=p=t=0
for c in input():
l+=0,;h=c in'-+';t+=h>p;p=h;v=c in'|+';t+=v>l[i];l[i]=v;i+=1
if' '>c:l=l[:i];i=0
print t*2
```
A one-pass method. Takes as input a string with linebreaks.
For the horizontals, the idea is to count the number of horizontal segments, each of which has two endpoints. A segment starts whenever a character is one of `+-` (boolean `h`) but the previous one isn't (boolean `p`).
For the verticals, we'd like to do the same thing on the transposed input, looking at runs of `+|`. Unfortunately, Python's transposing is really clunky. It requires something like `map(None,*s.split('\n'))` to fill in the blanks with `None`, which are also themselves to deal with.
Instead, we do the vertical count while iterating horizontally. We keep a list `l` of which columns indices are still "running", i.e. where that the previous character in that column connects down. Then, we do the same thing as with the horizontal, counting newly starting vertical segments. When we hit a newline, we cut off the list right of where we are, since all segments to the right were broken, and reset the current index to `0`.
[Answer]
# CJam, ~~66~~ ~~62~~ 61 bytes
```
q_N/_z,S*f.e|zN*"-|++"2$fe=1b"|-"{'++:R:a@+2ew{aR2m*&},,-}/2*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q_N%2F_z%2CS*f.e%7CzN*%22-%7C%2B%2B%222%24fe%3D1b%22%7C-%22%7B'%2B%2B%3AR%3Aa%40%2B2ew%7BaR2m*%26%7D%2C%2C-%7D%2F2*&input=--%0A%2B%2B--%0A%20%2B%2B%0A%20%20%20--%2B%0A%20%20%2B%2B%2B%20%7C%7C%20%0A%0A%20----).
### Idea
We can compute the endpoints as follows:
1. Count the number of `-`s, `|`s and `+`s in the input.
2. Multiply the last one by 2 and add the results.
3. Count the number of `--`s, `-+`s, `+-`s and `++`s in the rows.
4. Count the number of `||`s. `|+`s, `+|`s and `++`s in the columns.
5. Subtract the results from 3 and 4 from the result from 2.
6. Multiply the result from 5 by 2.
### Code
```
q e# Read all input from STDIN.
_N/ e# Push a copy and split it at linefeeds.
_z, e# Count the number of rows of the transposed array.
e# This pushes the length of the longest row.
S* e# Push a string of that many spaces.
f.e| e# Perform vectorized logical OR with the rows.
e# This pads all rows to the same length.
zN* e# Transpose and join, separating by linefeeds.
"-|++" e# Push that string.
2$ e# Copy the original input.
fe= e# Count the occurrences of '-', '|', '+' and '+' in the input.
1b e# Add the results.
"|-"{ e# For '|' and '-':
'++ e# Concatenate the char with '+'.
:R e# Save the resulting string in R.
:a e# Convert it into an array of singleton strings.
@ e# Rotate one of the two bottom-most strings on top of the stack.
e# This gets the transposed input for '|' and the original input for '-'.
+ e# Concatenate both arrays.
e# This pads the input with nonsense to a length of at least 2.
2ew e# Push a overlapping slices of length 2.
{ e# Filter the slices; for each:
a e# Wrap it in an array.
R2m* e# Push the second Cartesian power of R.
e# For '|', this pushes ["||" "|+" "+|" "++"].
& e# Intersect.
}, e# If the intersection was non-empty, keep the slice.
, e# Count the kept slices.
- e# Subtract the amount from the integer on the stack.
}/ e#
2* e# Multiply the result by 2.
```
] |
[Question]
[
>
> *This challenge is **not** code golf. Please read the scoring before you attempt to submit an answer.*
>
>
>
You will be given a multi-line string as input. You should output the *size of the largest contiguous chunk* of non-space characters. Contiguous just means that the chunk is a single piece rather than multiple disconnected pieces.
Characters are adjacent to characters directly before and after then in the same row or column. So this means that chunks cannot be connected via diagonals only.
```
alskdm
askl so
mmsu 89s
ks2mks
3klsl
```
These two chunks are disconnected the bigger one has 16 characters.
You must support all printable ASCII plus space and newline. If your program includes any characters outside of this range you must support those characters too. Nothing else needs to be supported. The input will contain at least 1 non-space character and may have trailing spaces on lines.
## Scoring
Answers will be scored first on the size of their own largest chunk with lower score being better. As a tie breaker they will be scored simply in their total length with lower score being better.
## Test cases
If you want to copy and paste them you can view the source [here](https://codegolf.stackexchange.com/revisions/3e6d56c1-287b-40a9-a101-5cee463667a8/view-source).
```
a
=> 1
a a
=> 1
a
a
=> 2
5a $
a @
=> 3
yus
8 2
3
=> 4
323
ke
=> 3
alskdm
askl so
mmsu 89s
ks2mks
3klsl
=> 16
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), score 1, ~~125~~ ~~112~~ 108 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{ ⌈ ´ + ˝ ∨ ˝ ∘ × ⎉ 1 ‿ ∞ ˜ ⍟ ≠ 2 > + ´ ∘ | ∘ - ⌜ ˜ '
' ( + ¬¥ ‚àò = ‚àæ ‚äê Àú ) ¬® ( ' ' < ‚äë ) ¬® ‚ä∏ / ‚åΩ ¬® 1 ‚Üì ‚Üë ùï© }
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgIHsg4oyIIMK0ICsgy50g4oioIMudIOKImCDDlyDijokgMSDigL8g4oieIMucIOKNnyDiiaAgMiA+ICsgwrQg4oiYIHwg4oiYIC0g4oycIMucICcKJyAoICsgwrQg4oiYID0g4oi+IOKKkCDLnCApIMKoICggJyAnIDwg4oqRICkgwqgg4oq4IC8g4oy9IMKoIDEg4oaTIOKGkSDwnZWpIH0KCj4oPOKLiEYpwqjin6gKImEiCiJhIGEiCiJhCmEiCiI1YSAkCmEgIEAgIgoieXVzCjggIDIKICAgMyIKIjMyMwogIAprZSIKImFsc2tkbSAgCmFza2wgIHNvICAKbW1zdSAgODlzCiAgICBrczJta3MKICAgM2tsc2wiCuKfqQ==)
`1‚Üì‚Üëùï©` Non-empty prefixes of the input.
`⌽¨` Reverse each prefix.
`(' '<⊑)¨⊸/` Keep the prefixes that don't start with whitespace.
`'␤'(+´∘=∾⊐˜)¨` For each prefix, get ⟨*number of newlines*, *index of newline*⟩. These are the 1-based coordinates of non-space characters.
`2>+´∘|∘-⌜˜` Convert the coordinate list to an adjacency matrix.
`∨˝∘×⎉1‿∞˜⍟≠` *OR* matrix power to 2^length.
`⌈´+˝` Maximum number of 1s in a single row.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), score 3, ~~628~~ 518 bytes
```
(n, S= 'm' + 'a' + 'p' , T= 'f' + 'l' + 'a' + 't' + 'M' + 'a' + 'p' , L= 'l' + 'e' + 'n' + 'g' + 't' + 'h' , R=n [ 's' + 'p' + 'l' + 'i' + 't' ](' \n '[ 's' + 'l' + 'i' + 'c' + 'e' ]( 1,2 ))[ S ](e =>[ ... e]) )=> R[ S ](( e,i ) => e[S ](( E,I ) =>k =( G= (F= l=> ( M=R [ T ](( a,b ) => a[ T ](( A,B ) => l [ 's' + 'o' + 'm' + 'e' ](j => (j[ 0]- b<0 ?b- j[ 0]: j[ 0]- b)+ (j[ 1]- B<0 ?B- j[ 1]: j[ 1]- B)< 2) &&A !=' '? [[b , B]] : [ ])) )[ L ]== l[ L ]?M [ L ] :F( M)) ([[ i,I ]]) ) > k&& E !=' '?G :k ) , k = 0 ) | k
```
[Try it online!](https://tio.run/##7VRdb9owFH3PrziTJmKrAfGhSR2qYUVqq0nlhfYtjYQTbOLYScrcjZf9d2acpQXE69Y9zA831@ece32upbjgP7jNvqnnl25Vr8ROsh2pIjwwhGWIC4Tcx@cQER4dKP3WHFAvPs5PxfeslQkfKx/XByX5XrZgFWKEti18ba5aZUJCPFUIX1WHfNaekBAMoiEojfHgNgJsEqPX60EkFJRNsGgIAhEpUEdDxA1wE331gAYjuGMgtwzG8QRztnDmHr2KR2lTxlvkOpo1iHmboPaxfHNV7AWkiNFPukiv@pimXfjtGC1KL7xi4PLZXjHzikGj8Ci9wpCi07nGBxYinCKOU3d5syTB2B2eUDdjjHskzFn3yXQO/8X41s3heBLHUG7SZH8fmEB3Orj53e4OY@3ACO4K0HfZT@hdVle2NqJn6jWRZMmN1asSCLjVBrC1S8vSfgcuP9sAbmk7LLVPR9pYs6Q0OO0BfgYdDUdBoMUZ5hPHx4ADX85wAU@zVSDkGscrD3IU6hgTWyXrjRTbjdjK5iuF9KZPGqgGzY/LPaa2Qqpik7dr2bNGZYIM6Puaey936z/k7l98fv6/P3/9/XG//O4X "JavaScript (Node.js) – Try It Online")
Assuming I've interpreted the rules correctly, this has a score of 3 (the longest contiguous non-space chunk has 3 characters, and there are a lot of 3-char chunks). Pretty long, however, and if it were code-golf the length would be more like 400.
Explanation: we have a counter `k` which holds the max size. It is initially set at 0. We loop through each non-space character and in each case, we capture the chunk that contains that character. If its size is bigger than `k`, we set `k` to its size. Eventually `k` will hold the biggest one and we just return that.
To capture the chunk containing some character, start with the character in question, then we get the adjacent ones and add them to the list. We then get the adjacent ones to the characters in this bigger list, and add them to the list, etc etc, until no more characters are added. The list now represents the chunk which contains the character in question.
[Answer]
# [Python 3](https://docs.python.org/3/), score=3, 320 bytes
```
def f(L ,m= 0,i =-1 ):
for l in L:
i+= 1;j =0
for _ in l:
V=[ 0]; g(L ,i, j,V );m = max (m, V[0 ]); j+= 1
L [:] =m,
def g(L ,i, j,V ):
if len (L) >i> -1 <j< len (L[ i]) !=( i,j ) not in V!= ' ' <L[ i][ j]:
V[0 ]+= 1;V +=( i,j ),
for x,y in [(0 ,1) ,(0 ,-1 ),( 1,0 ),( -1, 0)] :g( L,i +x, j+y ,V)
```
[Try it online!](https://tio.run/##VVLbjtowEH33V5xlK8UW3lVC2mobMKrUbp8i9WFRXtKoyhIDJhciHLTw9XRsYKtVInk0M@fMmUt/Gja7Lj4vd5WGwmg0Old6hRVPIVuFUBqohwgiYQyr3R4NTIc0YQD9ZqwQTbdQIUV9@K8LNy4ZyFSOsJhi7biMxFZmENOWqrTlEbyVyPIQhZhi63gIkyJPCqhWMuZEfAA6TrNCozvwVGBu5iBds@3s6sphCoE7xWHkFgLdbnBasjuFgL6ZT8ixLbw4X9mrzzC@YeSti6M8OWzOQ8hIQLrXDUFyRDL070MkEYoCyZojpSGNj6RzfILMxJmG@GiHvem5YEwf9ZK76ZJ9j1@mq/Bq1mttByw3h67GbgUXZikNxhmPtm/MwIM/XSAY7UGwvbaHZqBwmocFY/3edBT/8fvncxJIXKLi6qYqVGbh6Uur7S178fyyeElAlOxtYxqNiHbIcE/wskKE4YZwW1DIC4b/eWhM567DdP3BlYDfBPmozXI/2DczbHig5oFwyXglzpqM9LHse91V3KUSSh97vRx05ZkGfiHwzYo8KkgZyXE6GHzb@Ng3Lp3cnOqd7n0E55KuUs3plEqUV4N5Y8K@lPhEbnz3GTE7HSx7AgVIb@xcn1k8id1Z1/qSUTa2rlpylLZuALsjs23tAXj6Zh0MtZ20tTfjurGNr/j1Hw "Python 3 – Try It Online")
The function `f` takes in a list of strings `L` as input. Outputs by modifying `L` to becomes `[answer]` (a list containing the answer as the only element).
# Big idea
This is a straightforward DFS implementation. `g(L,i,j,V)` is the recursive DFS part, taking in the lines `L`, the coordinates `i, j` and the list of visited coordinates `V`.
To get a score of 3, the following features become unavailable:
* `eval` and `exec`: we cannot do any string manipulation of the source code
* `import`: no library outside of built in functions and operators
* `input`: we cannot get input from STDIN. Thus we cannot write a full program, and instead must answer with a function
* `lambda`: cannot create lambda function, so we must relies on `def`. Luckily `def` is usable.
* `print`, `return` and `exit`: this leaves modifying function arguments as the only output method.
Fortunately, `for` and `if` are available for flow control.
# More details
`V` is originally the list of visited coordinates, however for convenience I reserve `V[0]` to store the current size of the chunk. Thus `g` returns by incrementing `V[0]` by 1 every time it finds a new valid coordinate.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 1, 51 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
·ª¥ n ‚Å∂ T ‚Ǩ ·π≠ ‚Ǩ " J $ ·∫é W ·∫° ¬ß ·ªä ·∫∏ ã ∆á @ ∆¨ ·∫à …ó ‚Ǩ ` F ·πÄ
```
A monadic Link accepting a list of characters that yields the size of the biggest chunk.
**[Try it online!](https://tio.run/##y0rNyan8///h7i0KeQqPGrcphCg8alqj8HDnWjCtpOCloKLwcFefQjiQXKhwaLnCw91dQOYOhVPdCsfaFRwUjgFV7@pQODkdrCFBwQ2oueH///@JSckpqQpAkMiVlp6RqaCQla2QxJUFElEA8pK5wKyM9LTUFAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##HYuxCsIwFEX3fMVF@gUNQh0KTg7OgqsBu5hEh9ChW3WpKLg6OYiDi24itt0UCvoX6Y/Ely73nXt5Z5EolTln6weWaNdPTNBubrDlvbs9jBHAVgdMKc94X2HrHeELvz2aAkM09F1t8T12wgwjknNny0ubn@JPQaNzAmAxExA@mc@@QEAD@VSy1LAICBkATp2HnJDJxL8rI@eamjBSAWZFqLVJgWhgvABpQi075FIZ9Qc "Jelly – Try It Online") (cases split with `=`).
### How?
We can place spaces between instructions in Jelly without affecting the code (literals being single instructions). Unfortunately, many useful instructions for this challenge are two bytes long - for example: getting truthy multidimensional indices; forming powersets; matrix multiplication, determinants or powers. So, we just have to use the basics here.
```
·ª¥n‚Å∂T‚Ǩ·π≠‚Ǩ"J$·∫éW·∫°¬ß·ªä·∫∏ ã∆á@∆¨·∫à…ó‚Ǩ`F·πÄ - Link: list of characters, X
Ỵ - split X at newline characters
n⁶ - not equal space character? (vectorises)
T€ - truthy indices of each
$ - last two links as a monad:
J - range of length -> row_numbers
" - zip with:
ṭ€ - tack each -> coordinates
Ẏ - tighten -> list of coordinates
` - use as both arguments of:
ɗ€ - for each, last three links as a dyad:
W - wrap -> our initial list of collected coordinates
Ƭ - collect inputs up while they're distinct:
@ - with swapped arguments:
Ƈ - keep those (of all coordinates) for which:
ã - last four links as a dyad
·∫° - absolute difference
(vectorises across collected coordinates)
§ - sums -> Manhatten distances
Ị - -1 <= x <= 1? (vectorises)
·∫∏ - any?
Ẉ - length of each
F - flatten
Ṁ - maximum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal) -v, score 6, 305 bytes
```
while Input Push u i Assign []q for Map u Map i[k, m, l] for i if Less " " Pop k Push q k Assign 0 h while q{ Assign [Pop q]z while Filter Minus q z Filter 4 Count z Map l Plus p And Equals r Modulo n 2 Minus Minus n r 1 for k Push z l Assign Minus q z q if Less h Length z Assign Length z h} Print Cast h
```
[Try it online!](https://tio.run/##7VBBCsIwELz7isGzgoofkKIgKPQuPQTbmsWYNE2iUPHtddvGevYugU2yM7Mz7FmK@myEatuHJFVgr6vgkQYnEUDYOEcXjVNmUZoaR1Fxu6t0us5wm0FlPUCgEofCOUz5pKbCdRhi@RGHLCAxmNjnOLij2qyJwI6UL9iGdHAsbT6NNRITtOdG562QKsYrbHSOrQ1CObDI5EEZaKyifqiaoWWfMSZqWB/dvz52zC/50hff8SJr/MsX0po4RiKch/yv7OeVTdr5/Q0 "Charcoal – Try It Online") Takes input as a list of newline-terminated strings. Readable version:
```
while (Input()) Push(u, i);
Assign([], q);
for (Map(u, Map(i, [k, m, l]))) for (i) if (Less(" ", Pop(k))) Push(q, k);
Assign(0, h);
while (q) {
Assign([Pop(q)], z);
while (Filter(Minus(q, z), Filter(4, Count(z, Map(l, Plus(p, And(Equals(r, Modulo(n, 2)), Minus(Minus(n, r), 1))))))))
for (k) Push(z, l);
Assign(Minus(q, z), q);
if (Less(h, Length(z))) Assign(Length(z), h);
}
Print(Cast(h));
```
[Try it online!](https://tio.run/##VVDBasMwDD3HXyF6kkGDrdtho6dSNhi00HvpIbRZY@zYSRRv0LFvz@TG7ZgPtvSk9/TkQ132h1C6cfyqjasA330bB9QatpFrjARGL9SS2Zw87vYEnaQfoQfclG0qp8cQ7CxBQ@D2WqiXutFgPgDXFTPOYEawDS1afVXuCOyf8j1BLVn20Gn4VsV1aOJ1WkafpaPILW/GDVWPG@MjJ62zJsjYE8EqRD/geXLnZLSTrpZg6Y/42sXSMfZSDMfoAnqCuRb6pDXdgvUCPeh8VFFclrLZvUi75CZ7/Gcj/VBxW70mWFf@NAgn7Z4JN2ja@0dteyOOVyUPWGu9GEfxaI8NgCrZOgAOEjYNR4DnF1Ygx/K8sZfw0Tp2arz7dL8 "Charcoal – Try It Online") Explanation:
```
while (Input()) Push(u, i);
```
Input the multiline string as a list of strings.
```
for (Map(u, Map(i, [k, m, l]))) for (i) if (Less(" ", Pop(k))) Push(q, k);
```
Create a list of coordinates of all of the non-blank characters.
```
Assign(0, h);
```
Start tracking the maximum chunk size.
```
while (q) {
```
Loop until all of the coordinates have been assigned to a chunk.
```
Assign([Pop(q)], z);
```
Start a new chunk.
```
while (Filter(Minus(q, z), Filter(4, Count(z, Map(l, Plus(p, And(Equals(r, Modulo(n, 2)), Minus(Minus(n, r), 1))))))))
```
While there are coordinates not in the chunk that are adjacent to at least one coordinate in the chunk, ...
```
for (k) Push(z, l);
```
... add all of the discovered coordinates to the chunk.
```
Assign(Minus(q, z), q);
```
Remove the chunk from the coordinates.
```
if (Less(h, Length(z))) Assign(Length(z), h);
```
Update the maximum chunk size if necessary.
```
}
Print(Cast(h));
```
Output the maximum chunk size.
[Answer]
# JavaScript (ES7), score 3, 211 bytes
```
s =>( o=g =(X ,Y) =>m . map ((r ,y) =>r . map ((c ,x) =>c ==' '|| (1/ Y?( X-x )** 2+( Y-y )** 2-1 :k= 0) || g(x ,y, o=o >++ k?o :k, r[x ]=' ')) ))( m=s [ 's' + 'p' + 'l' + 'i' + 't' ]`
`
. map (s =>[ ... s]) )|o
```
[Try it online!](https://tio.run/##3VHRTsIwFH3vV5wYk7WwVdhigpqBL/oDvECAhGYMnOvW2TvMFvHbsduMH@HLufec9pz25r6rT0WJzao6KM0hvR7jKyGec5j4hJiv4K@F4wUkClWBcwu/7RT7pyTwm05JEMcevMsFfHqH9YJjFTQQoxHCMcc6aIc@mOIxjzERcDdPvHF5vnvNYD4eI18Yd@rDbhrsujQhIARHERM28MjDGF7Vo@4x67H2sNuzPfv9UjfBBlJK0M75L@Zq049zZlPuHckT0qbq8JrpdNmWCZ8IWZtlbbPyxIWkSmc1v9mWQRBsyxshj8a@qOStz8QXAxJTktGp1ObEj5yEeGLf4qoA5ixMQQ2VDfVe4daJeO5ZeyY2A0IXg6hXojByhOXp4NKUHwqmKNcAGVYUdAZmD9QZkFNY5H0b5Zp07/iHy/oB "JavaScript (Node.js) – Try It Online")
### Commented
In the final code, we use `[ 's' + 'p' + 'l' + 'i' + 't' ]` instead of `split` and a literal line feed instead of `\n`. Everything else is just extra spaces all over the place.
```
s => ( // s = input string
o = // initialize o to a zero'ish value
g = // g is a recursive function taking
(X, Y) => // the current position (X, Y)
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((c, x) => // for each character c at position x in r[]:
c == ' ' || ( // do nothing if c is a space
1 / Y ? // otherwise, if Y is defined:
(X - x) ** 2 + // make sure that the quadrance between
(Y - y) ** 2 // (X, Y) and (x, y)
- 1 // is equal to 1
: // else:
k = 0 // reset k to 0
) || // if the above is falsy:
g( // do a recursive call:
x, y, // pass the new position (x, y)
o = // update o to ...
o > ++k ? o : k, // max(o, k) where k is pre-incremented
r[x] = ' ' // put a space at the new position
) // end of recursive call
) // end of inner map()
) // end of outer map()
)( // initial call to g:
m = // initialize m[] to
s.split`\n` // the input string split by new lines
.map(s => [...s]) // and each row turned into a list of chars.
) | o // end of call: return o
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), score 1, ~~626~~ 613 bytes
```
[ L = `
` , s = ' s ' [ 1 ] , l = ' l ' [ 1 ] , c = ' c ' [ 1 ] , o = ' o ' [ 1 ] , t = ' t ' [ 1 ] , r = ' r ' [ 1 ] , n = ' n ' [ 1 ] , i = ' i ' [ 1 ] ] [ ' f ' [ 1 ] + i + l + l ] [ c + o + n + ' s ' [ 1 ] + t + r + ' u ' [ 1 ] + c + t + o + r ] ( W = ' o ' , ` g = ( X , Y ) = > s . m a p ( ( r , y ) = > r . m a p ( ( c , x ) = > c > W ? ( x - X ) * * 2 + ( Y - y ) * * 2 - 1 | | g ( x , y , k = 1 / Y ? k + 1 : 1 , r [ x ] = o = o > k ? o : k ) : 0 ) )
g ( s = o . s p l i t ( L ) . m a p ( t = > [ . . . t ] ) )
r e t u r n + o ` [ s + ' p ' [ 1 ] + l + i + t ] ` ` [ ' j ' [ 1 ] + o + i + n ] ( [ ] ) )
```
[Try it online!](https://tio.run/##7ZNNbtswEIX3PMVDUEBkZamJjQJpgtjdtKvuskgLx4AFWXYV0aQrykWMtmd3nsaCwRygu4AYzvCbH45G4FPxuwhlW@@6zPlVdVzfHTHHN9xhqZYYIdBKuCekV1iQWCE2IqWQMiJeiI9IJ6SLSCukjYgT4iJSC6nPZEGdYH0@p/Sl7KWX3lfS8hRHibtOeXPKu3q6j2g5eLx4F9B4OHc@whIbnjS@0/4BQ3vKmjm2KLAj18wZ4TB42leekp7nwVNSHjAjfUbGagbvuca8U7NuJhVOJGNff7k2EtvXHqFhjSt8YOSMdkr7htLPb86YBb1eZErvjPqG2nC/5G6UlAoSkFPvOKian6z5i03UcCeNzkn61bFsn9yior3nVU6GtGREkCHuoiHa4Tf0WUuJSfAU@f3gdzLg@an28batfu3rttLJOiQmb6ti9bW21f3BlfrS5J2/79rabbTJw87Wnb54dFmWPboLk699@6Uof2p@1hR/FFB6F7ytcus3eq2DMbfqn1GvaJok5lgAikVUgeKk1Ul/LPCOEJ/ldNgHdQ2MWRgTIZPxhAfVVKcsG5rVVhWhsUDwarsNe@D6U@gT0ITxthFz0thgJePtRb29qP/@ol4A "JavaScript (Node.js) – Try It Online")
That's what I meant "something like jsfuck". Can only define function using "constructor". Other code quite like Arnauld's besides that I forgot that `=>` is 2 char
[Answer]
# [Python](https://www.python.org) SciPy, score 8, 167 bytes
```
lambda x:max( bincount (label( ((a:= array([x .split( "\n")]). T.view( "U1"))!= " ")&(a !="\x00" ))[0]. ravel()) [1:])
from scipy. ndimage import*
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=1ZFdTuMwFIXFq1dxsBCy0UzUNsxMiZSKRQxPaR5u2xQ88Z_ipG3WMi-VELAmWA1OWhaBn46_e3zvsf3_1fftk7PH522-fOna7c_5-5sms9oQDpmhg8BK2bXrbAuhaVVpASEoy0FNQ70oDkiC16oV4EvLZSkT_E12qtpH8DDlUl7m4ODyWhAuc748TCYcUhaTMkFDu9hPShTTrJSMbRtnENbK9wnsRhl6rKCMd017cy7azvj-i53j7vdPSleYZgxQyFGUUZyYCFmurO_aOKTIZmUMkC_4YIxLJeR9ZTciyPPJ4QbJP6esUANyEVU70iIU6ZAP8I2yrXA_ttEgT-OPHxd_CGD5AlNGoLNgo5ixX4SriHE_OlLWd4HNEQsxQDqgW5bO0rhjdXVykA71xkRAodZAcFEaEzpgfhfG5HWYmXqUaa2DHif-Zt_k04a0PKxdU_HTA34C)
Leaves the chunking to `scipy.ndimage.label`. The chunk sizes are extracted by `numpy.bincount` which is also the longest function name used at 8 characters
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-r`, score 1, 181 bytes
```
g M : 1 - { _ Q s M a } + $ + : ^ 0 X # _ M g W J % : g { i : # : K 0 ~ J g ( g i / Y # @ g i % y ) : 2 L y + # g g : Z ( J * g ) R K 1 . 2 . K 1 2 X # _ Y 2 N J g I y > x x : y } x
```
Takes input from stdin. [Attempt This Online!](https://ato.pxeger.com/run?1=LY_NasJAFIX3PsWHUfCHWBM3MYvSbbUKdmNVVALiECah4ihYir6IG0HaN-jD-DY9ROdymW_OPffOzPm6STe_s7K_Lc8vP_vd2o9uf4YBMQE-3ywZ4XROONKkooxZ0OYDT7UBhjE9qlKN3Kl2T9mX4yTdUFOmPDGR_lJwlS_q8oS8iZrSjSJmKm-PhrjOuyYEtORpFRQ-7puIhsXcV_U-c1DEoiOH--Mff7jcgiRzdpVDKXE2A_cpzHO3h6jrSmhZF-a2wI7NXHbv_Ac) (Runs all of the test cases easily, but times out if passed its own source code.)
### Explanation
Several operators that would have been useful are two characters (`ZD`, `MM`, `MX`, `@?`), so we have to work around them.
```
gM:1-{_QsMa}+$+:^0X#_Mg
g List of lines of stdin (due to -r flag)
M: Map this function to each line in-place:
{ Ma} Map this function to each character of the line:
_Qs Is it equal to space? (1 if so, 0 if not)
1- Subtract each result from 1, swapping 1s with 0s
+ Pad each line to the same length by adding the following:
Mg Map this function to each line of the input:
#_ Length of the line
0X String of that many zeros
^ Split into a list of digits
$+: Sum down the columns of the resulting list of lists
```
Here's a demonstration of how the padding logic works:
```
g ["ab"; "cde"; ""; "f"]
#_M [2; 3; 0; 1]
0X [00; 000; ""; 0]
^ [[0; 0]; [0; 0; 0]; []; [0]]
$+: [0; 0; 0]
```
When two lists of different lengths are added, the part of the longer one that sticks out past the end of the shorter one is included in the result unchanged. Thus, summing the list of lists gives us the longest list-of-zeros in it, and adding that list to each processed row from the input essentially right-pads it with zeros to match the length of the longest row.
```
W J%:g{...}x
W Loop while
g g, which is now a list of lists of integers
%: Take each of those numbers mod 2 in-place
J Join them together into a single string
is truthy (i.e. not all 0s):
{...} (see below)
x After the loop, x holds the max chunk size; output it
```
The initial value of `x` is `""`, which is equivalent to 0 in numeric contexts. Since the maximum chunk is of size at least 1, the value of `x` will always be updated, so we don't have to worry about the possibility of outputting its initial value.
Our flood-fill algorithm finds a chunk of 1s and turns them into 2s. The mod-2 operation at the beginning of the loop then turns these 2s into 0s. Once all chunks have been found, `g` is entirely 0s, at which point the loop halts.
Inside the loop, the first thing we do is find a 1 and change it to 2:
```
i:#:K0~Jg (gi/Y#@gi%y):2
Jg Join g into a single string
~ Find the first regex match of
K0 0, zero or more times (equivalent to `0*`)
#: Length of that match
This is the row-major flat index of the first nonzero entry in g
i: Store it in i
@g First row in g
# Length
Y Yank that value into y
(g ) Index into g at
i/ Row: i/y
i%y Column: i mod y
:2 Set the element at that location to 2
```
Then we flood-fill by changing every run of 1s adjacent to a 2 to a run of 2s, swapping rows for columns, and repeating several times:
```
Ly+#g g:Z(J*g)R K1 .2.K1 2X#_
L Loop
y Length of first row in g (width of grid)
+ Plus
#g Length of g (height of grid)
times:
J*g Join each row in g into a single string
( )R Replace each match of this regex:
K1 1, zero or more times
.2 Followed by 2
.K1 Followed by 1, zero or more times
with this callback function:
#_ Length of match
2X String of that many 2s
Z Zip (transpose) the resulting list of strings
(note: it becomes a list of lists of digits again)
g: Assign back to g
```
Finally, we get the size of the chunk we just found and update `x` if the chunk size is bigger:
```
Y2N Jg Iy>xx:y
Jg Join g into a single string
2N Count the number of 2s
Y Yank that value into y
I If
y>x y (chunk size) is greater than x (previous max chunk size):
x:y Set x to y
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 1, ~~107~~ 101 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
S ¶ ¡ ζ ζ ð Ê Ð U ˜ ƶ s g ä Δ ε 0 š Ć } ¬ 0 * š Ć 2 F ø € ü 3 } X * ε ε 1 è y ø 1 è « à ] ˜ 0 K D ¢ à
```
[Try it online](https://tio.run/##LYyhCsJQGIX7nuJj0TRd0S4WowgWw0QRuRsLPwaDxWAwGYwGJwbBBYvDYLpXLcIewheZd8OfE875v8OJJRjNJkXRQ2fohDwrZa6YDWZLn8@ed4YwxZzId@Q3PF4JzzVLdGpD7R8bdDB3vqsU88C3eGCZ7VvVMWcWJa6cvmAODMtxjy5t9NE@isJ13SAUNY6cQFQIEjtRJHNotsTBnpJGpCrrq1BC2/8B) or [verify all test cases](https://tio.run/##NYyxSsRAFEV7v@IwWEmQNUFYbbQQQSwsRBGcLbJuFJlkVpiNkMLGwsLKwtLCFQvBLWwMFlYzaiPsR/gjcSar8ODe8@67b2jS/mnWnIstfVaOVhFRFc2JnXL0T6LZxdbYMdM6jHvBXeNu2OP7jq8awwnukekt01c6fI75uOICO/Gw8Icxm7g3fi4nuHcSHx/4zN/7WcI9UYW4dfYZd08vPO@wzQb2wS8asbgf2XqtORSpiBApM5G61eWUeW9hPVBVGqm7EEsNJGGVxEkAqVXW9nKjBoVvGJWDGUpdFKaE7oppOygTF2rmE5WbPJRI@1IfMZA6Oxa9Xw).
**Explanation:**
Most of it is similar as [my 05AB1E answer for the *Is there a stable way to stack these?* challenge](https://codegolf.stackexchange.com/a/242080/52210), except that `0δ.ø` is `ε0šĆ}` and `Ås` is `1è`, since the 2-byte builtins `.ø` and `Ås` cannot be separated to minimize the score. (Also, `S¶¡ζζ` could have been `.B€S`, but `.B` is a 2-byte builtin as well.)
Step 1. Convert the input to a matrix of characters:
```
S # Convert the (implicit) input-string to a list of characters
¶¡ # Split it on newlines to a character-matrix
```
Step 2. Right-pad this input-matrix with spaces:
```
ζ # Zip/transpose the input-matrix; swapping rows/columns,
# using a space as filler if the rows are of unequal length
ζ # Zip/transpose back
```
Step 3. Transform all spaces to `0` and all other characters to `1`:
```
ðÊ # Check for each character whether it's NOT a space
# (0 if a space; 1 otherwise)
Ð # Triplicate the matrix
U # Pop and store a copy in variable `X`
```
Step 4. Create a matrix of the same size with unique positive integers:
```
Àú # Flatten the matrix
∆∂ # Multiply every 1 by its 1-based index
s # Swap so the matrix is at the top
g # Pop and push its length (amount of rows)
√§ # Split the list into that many equal-sized parts
```
Step 5. Flood-fill this matrix based on the matrix of 0s/1s we stored in variable `X`:
```
Δ # Loop until the matrix no longer changes:
```
Step 5.1: Add a border of 0s around the matrix:
```
ε # Map over each row:
0š # Prepend a 0
Ć # Enclose; append its own head
} # Close the map
¬ # Push the first row (without popping the matrix)
0* # Transform all 0s/1s to 0s by multiplying by 0
šĆ # Prepend and enclose this row as well
```
Step 5.2: Create overlapping 3x3 blocks of this matrix:
```
2F # Loop 2 times:
√∏ # Zip/transpose; swapping rows/columns
€ # Map over each row:
ü3 # Pop and push its overlapping triplets
} # Close the loop
```
Step 5.3: Transform the `0`s back, based on the matrix of variable `X`:
```
X* # Multiply the values at the same positions by matrix `X`
```
Step 5.4: For each 3x3 block, get the maximum of its center and its horizontal/vertical neighbors:
```
εε # Nested map over the 3x3 blocks:
1è # Get the middle row
yø1è # As well as the middle column
¬´ # Merge these triplets together
à # Pop and push the maximum of this list
] # Close the nested maps and until_no_changes loop
```
Step 6: Check which island is the largest:
```
Àú # Flatten the matrix to a list
0K # Remove all 0s
D # Duplicate this list
¢ # Count each value
à # Pop and push the maximum
# (after which it is output implicitly as result)
```
] |
[Question]
[
Following the theme of [strange kitchen appliances](https://codegolf.stackexchange.com/questions/218360/what-temperature-is-my-stove), let's talk about my microwave.
# Introduction
My microwave has a keypad that is laid out like this:
```
30 > 15
1 2 3
4 5 6
7 8 9
+/- 0 S/M
```
* I can press the +/- and S/M keys to switch between adding and subtracting minutes or seconds.
* The microwave starts in add minutes mode.
* The 0-9 keys add or subtract 1-10 minutes/seconds to the time (0 adds 10.)
* The 30 and 15 keys always add or subtract 30 or 15 seconds.
* The > key starts the microwave.
* The time cannot go below 0 seconds.
## Example
If I pressed `0 3 +/- 15 S/M 4 >` I would microwave my food for 12 minutes and 41 seconds:
1. 0: Add 10 minutes
2. 3: Add 3 minutes
3. +/-: Switch to subtract mode
4. 15: Subtract 15 seconds
5. S/M: Switch to seconds
6. 4: Subtract 4 seconds
7. >: Start the microwave
Other test cases:
* `0 3 +/- 15 S/M 4 S/M 1 S/M +/- 0 S/M 7 -/+ 30 >` = 1101
# The Challenge
Write me a program that takes as input a string of button presses (separator doesn't matter) and outputs how long my microwave will run for (in seconds). This is code-golf, so shortest code in bytes wins!
## Button Codes
These are the button codes your program should accept: (I should be able to input exactly these strings):
* `0 1 2 3 4 5 6 7 8 9` (0 equals 10)
* `30`
* `15`
* `+/-`
* `S/M`
* `>`
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 106 86 bytes
Big thanks to both @mazzy and @Julian for saving me an ENORMOUS 20 bytes!!!
```
$s=1
switch -r($args){\d{$t+=$s*(10*!+$_+$_)*(1+59*!$m*(9-ge$_))}-{$s=-$s}s{$m=!$m}}$t
```
[Try it online!](https://tio.run/##lU9Na8MwDD3bv8IFbYnjerHZulKGR6DsuFOvgxIa9wOatkSGDjz/9kyjNJSxy0DvoSc9ntDpePYdbv1@38PaxR7QWY7nXVhthe5yqLsNyvjRRAjKARa5NcVIwZJKklCTWTGCtshneuNpJJOOFKEBE0ZoHe1SgtAnDsFjmNfoUTjBqpwzxqo4P7ZtfWjQVXlmsnH2SFClJrYTokX5TvxEeM3ky9vnya@Cb9z02abxPwMunR26i8kMekrQpfqJML/vWWv@OnjjMIm28vbJL3EXOYOrnZ6G5cNVcXYPa1ENMvH@Gw "PowerShell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~112~~ 109 bytes
Reads a list of instructions from STDIN. Prints duration in seconds.
```
t=0;d=1;r=60
for c in input()[:-1]:exec['k=int(c)or+10;t+=k*r**(k<11)*d','d=-d','r^=61'][hash(c)>>62]
print t
```
[Try it online!](https://tio.run/##jY1BC4JAEIXv/oq9ja6KO1YetPUfdKrbskHoxoqhMq1Uv94UPEYFA/Pem@8xw8vZvkunh21uhp1oNDkzT1MBwOSkKGqJBclMeNeeWMWabp5hdH6g8hh1vqAKWtl0zq@CnkIUhQtly4lzv90jBryGCGoZL4vOMkPQyl7udsbLMku1N9BcZm5aPioQEDEoQXur3HzyYRJ/iXH383hMDv8y2xV8Aw "Python 2 – Try It Online")
`hash(c)>>62` maps all the numbers to 0, `+/-` to 1 and `S/M` to -1.
[Answer]
## Batch, 192 bytes
```
@set/at=0,s=1,m=60
:l
@set/pb=
@if "%b%"==">" echo %t%&exit/b
@if %b%==+/- set/as=-s
@if %b%==S/M set/am=60/m
@if %b%==0 set b=10
@if %b% gtr 10 (set/at+=s*b)else set/at+=s*m*b
@goto l
```
Takes newline-terminated input on STDIN, as `>` is tricky to use on the command line. Explanation:
```
@set/at=0,s=1,m=60
```
Initialise the total and sign and minutes flags.
```
:l
```
Start a loop.
```
@set/pb=
```
Read in the next button.
```
@if "%b%"==">" echo %t%&exit/b
```
Output the total and finish if this is the `>` button.
```
@if %b%==+/- set/as=-s
@if %b%==S/M set/am=60/m
```
Update the flags for the `+/-` and `S/M` buttons.
```
@if %b%==0 set b=10
```
`0` counts as `10`.
```
@if %b% gtr 10 (set/at+=s*b)else set/at+=s*m*b
@goto l
```
Update the number of seconds and loop back. Note that non-numeric strings silently evaluate to 0, thus leaving the total undisturbed.
[Answer]
# JavaScript (ES6), 68 bytes
Expects a list of commands. Returns a number of seconds. Assumes that the last command is `>`, as stated in the comments.
```
a=>a.map(c=>1/c?t+=s*(+c||10)*(c>9|a||60):c<','?s=-s:a^=1,t=0,s=1)|t
```
[Try it online!](https://tio.run/##BcFLCsIwEADQqwzZNOk3wQ9YnPQErtwLw9hKJTbFCa5y9/jem34k/F331G3xOZcFC6Gn/kO7ZvRu4Ck1KLVuOGdnTa3ZXzLlfLZm5GvVVpNgJyM90LUJbSvoTE6F4yYxzH2IL71oZeEAzdCBO8F9uMERvOplD2vSCpQxpvwB "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array, reused as a flag to figure out
// if we are in 'seconds' mode
a.map(c => // for each command c in a[]:
1 / c ? // if c is numerical:
t += // add to t:
s * // the sign multiplied by
(+c || 10) * // either c, or 10 if c is 0
( // multiplied by
c > 9 // 1 if c is 15 or 30
| a // or we are in seconds mode
|| 60 // otherwise 60
) //
: // else:
c < ',' ? // if c is '+/-':
s = -s // invert the sign
: // else:
a ^= 1, // switch between 'seconds' and 'minutes' mode
// (c is either 'S/M' or '>')
t = 0, // start with t = 0
s = 1 // start in 'add' mode
) | t // end of map(); return t
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~53~~ 51 bytes
```
≔⁶⁰η≔⁰ζWη«Sθ≡θ>≔⁰η+/-≦±ηS/M≦÷⁶⁰η≧⁺×∨Iθχ÷ηX↔η⊖Lθζ»Iζ
```
[Try it online!](https://tio.run/##VVBda8JAEHxOfsXi04VGTLAfUEGQ@iJoG6p/4JqsdwfnxeY2Biz@9nQT09bew7CzMzvsXq5llZfStu3Ce6OceExi0NEsHCizM7NGG4sgdARfYbByx5q2VBmnxCeLgW8M5RqYdHIuPcJoPnqGv4wucRDuJmOWNvI4qK@oJOE/y3ayubWscU9i5WhpTqZg58@KQYF7WVu6sb4bpUlktvYx7MwBvXirxIv0xLvFkCYMv0FCx5CVDVZi8eFLWxN3WF9iXuEBHWEh1ugUaZ7t3vUngkt4CTO@na655yiatW0CU@DDIH0AXh7ue0x77NpJXz319TSBeTs@2W8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as either space or newline separated (but not both at the same time). Explanation:
```
≔⁶⁰η
```
Start in add minutes mode.
```
≔⁰ζ
```
Start with `0` seconds.
```
Wη«
```
Repeat until `>` has been processed.
```
Sθ≡θ
```
Input the next button and switch on it.
```
>≔⁰η
```
If this is the start button then clear the mode, allowing the loop to terminate. (If there are at least two button presses, then a byte could be saved by using a different termination condition.)
```
+/-≦±η
```
If this is the `+/-` button then flip between add and subtract mode.
```
S/M≦÷⁶⁰η
```
If this is the `S/M` button then flip between minutes and seconds mode. (I don't get to use `≦` much with binary operators. Both `≦` and `≧` work with unary operators but the deverbosifier always picks `≦`.)
```
≧⁺×∨Iθχ÷ηX↔η⊖Lθζ
```
Get the current value, change it to 10 if it is zero, multiply it by the mode, but if the value was greater than 10 then divide by the absolute value of the mode, so that the minute mode is ignored. Edit: Saved 2 bytes by porting this calculation from @tsh's Python answer.
```
»Iζ
```
Output the final number of seconds.
[Answer]
# [Perl 5](https://www.perl.org/) -apl, 81 bytes
```
$f=60;$S=0;$_||=10,/-/?$f=-$f:/S/?$f=60/$f:($S+=$_*$f/($_%15?1:abs$f))for@F;$_=$S
```
[Try it online!](https://tio.run/##hY3BasMwEETv@YqBqJA0cSUlsQMpTnrqrSf1bhRHqgWKZCyZXPLtdWVDeymlsAy7b2dnW9XZfJi/NwpRhYhaBgWvEROoG2mtch8KJkxAmy5ZrHGJuFRtH3FW1t8g3QUmolOx79xsvi84gqq9uwTcGlM33wlBXhVkAN/galyfXk6nux/700B0WbBnIsok1f1ecramGT0lnBF9oGJqC0bTsCBiVZLqkWi6INUDz0/8IM@B6OVS@@7lNQWURAwDwxYrmoHnEPQNOxxnv9Co/O/FqCPe/m9hOH76NhrvwpDJ1n4B "Perl 5 – Try It Online")
```
$f=60; # starts in plus mode and minute mode (f=multiplying factor)
$S=0; # reset output sum
$_||=10, # convert 0 to 10 for current button in $_
/-/?$f=-$f: # -/+ negates $f
/S/?$f=60/$f: # S/M toggles $f between 1 and 60 or -1 and -60
($S+=$_*$f # add button times $f (factor) to sum in $S
/($_%15?1:abs$f)) # force seconds as temporary unit if 15 or 30
for@F; # for each button in input array @F (due to -a)
$_=$S # print current sum in $S which is seconds to run
# (challenge just said "outputs how long" and I chose
# seconds as my unit of time).
```
[Answer]
# [Python 3](https://docs.python.org/3/), 112 bytes
```
c=60
t=0
for k in input().split():
try:t+=c*int(k)/abs(c)**~-len(k)or 10*c
except:c=(k>'0')*60/c or-c
print(t)
```
[Try it online!](https://tio.run/##HYtBCoMwEEXX5hSzM4mkGbG1IMQbdNUTtIOlosQQp1A3vXoahc/7nwc/bPxefJMSuRYFOxSvJcIEo88JH5bqtIZ5zN2JguPWceVIj57lpOzjuUpSWv/MPPgs8rNGTaIYvjQE7sjJqS@xVLpFS7BEQyLE/cwqJYQGKmugvsDd3uB8sD64azzWFYytoEHo/w "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 178 bytes
```
l=eval(input());n=0;m=0;d=1;exec(";".join([['n+=15*d','d*=-1','m=1-m','n+=30*d',f"n+=(({x} or 10)*(60-59*m))*d"][[(sum(map(ord,x))%10)//3,4][len(x)<2]]for x in l[:-1]]));print(n)
```
[Try it online!](https://tio.run/##FY/dboMwDIXv9xQW1RSHwiClVOpY9ga96u6iXCCSakzEQfxMTNOenSUXPp/l4yPZ48/y6anaD0Dw4Zd2gNl289MBHNx6Whdb3G3nyYSJgWOR74O03@2APY3rgpw3JMvGhTJSNHazHSZN8vLle0KlGB2lqFPDMmZSmYtAJ0XuAoNTldF5JKFF/N3@wE8gSp7ipczra@o4T02ilcJ5dejaEf1kso3z57BUFFV21mqwhBt/O2n9COENeoJBveZC63DZOPW0IPF9V6xkGbAqSvghQtRR78Ut4hzlnel/ "Python 3 – Try It Online")
longer than @ovs but should be more portable since it sums up the charcodes, mods by 10 and integer divides by 3 to distinct the inputs.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÎvyÐdigi0T.:¾È59*>*}X*+ë\нai¼ëX(U
```
Input as a list.
[Try it online](https://tio.run/##yy9OTMpM/f//cF9Z5eEJKZnpmQYhelaH9h3uMLXUstOqjdDSPrw65sLexMxDew6vjtAI/f8/WslASUfJGIi19XWBpKEpkAjW9wWSJkBspxQLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSvUElkHd4QkpmeqZBiJ7VoX2HO0wttey0aiO0tA@vjrmwNzHz0J7DqyM0Qv/X1tbq6B3aahj6PzpayUBJR8kYiLX1dYGkoSmQCNb3BZImQGynFKtDQAmEZQhnQRQZwPnmQKyrrw0ywgBiYiwA).
**Explanation:**
```
Î # Push 0 and the input-list
vy # Foreach over the items:
Ð # Triplicate the current item
di # Pop one, and if it's an integer:
gi # Pop another, and if it's a single digit:
0T.: # Replace the 0 with 10
¾ # Push the counter_variable
# (the counter_variable is 0 by default)
È # Pop and check if it's is even (1 if even; 0 if not)
59* # Multiply this by 59
> # Increase it by 1
* # Multiply it to the current integer
} # After the inner-most if-statement
X* # Multiply the value by `X`
# (`X` is 1 by default)
+ # And add it to the result
ë # Else (it's not an integer):
\ # Discard one of the remaining copies
н # Pop the last one, and push its first character
ai # Pop, and if this is a letter:
¼ # Increase the counter_variable by 1
ë # Else (it's a '+' or '>' instead):
X(U # Negate `X`, and store it as new `X`
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes
```
f=A=>A.map(k=>1/k?t+=k>9?c%59*k:c*k||c*10:c=k>f?60/c:-c,c=60,t=0)&&t
```
[Try it online!](https://tio.run/##hYxLDoIwFEXnruJNpOVT2gbBQNISFuDIFZAnGCxSIo0j9l6FoRMnJzcnJ/fRvtsFX8Ps2GRvnfe9apRu0mc7U6O05KZ2sTK6rPGYl5GpMDLripEUFX51XxeCY8UwQVWIxCkRBoHzaKfFjl062jvtKRGQQcwZyByu/AIn0CRd5nFwlAAJw/Dwr98od25a7OsMjMeQid8z/wE "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
# Input
4 integers w, x, y, z from the range -999 to 999 inclusive where none of the values is 0.
# Output
4 integers a, b, c, d so that a*w + b*x + c*y + d*z == 0 where none of the values is 0.
# Restrictions
Your output should be the solution with the smallest sum of absolute values possible. That is the smallest value of \$|a|+|b|+|c|+|d|\$. If there is more than one solution with the same sum of absolute values you can choose any one of them arbitrarily.
# Examples
```
Input: 78 -75 24 33
Output: b = -1, d = 1, a = -2, c = 2
Input: 84 62 -52 -52
Output: a = -1, d = -1, b = -2, c = -3
Input: 26 45 -86 -4
Output: a = -3, b = -2, c = -2, d = 1
Input: 894 231 728 -106
Output: a = 3, b = -8, c = -1, d = 1
Input: -170 962 863 -803
Output: a = -5, d = 8, c = 2, b = 4
Added thanks to @Arnauld
Input: 3 14 62 74
Output: -2, 4, -2, 1
```
# Unassessed bonus
Not in the challenge but does your code also work on this?
```
Input: 9923 -9187 9011 -9973
```
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), ~~139~~ 137 bytes
Assumes no boundary and runs fine for the additional test case.
```
f=lambda x,b=4,t=0:[[s*~i]+v for i in range(b)for s in(1,-1)for v in f(x[1:],b-i,t+s*~i*x[0])][:1]or x[3:]and f(x,b+1)if x else[x]*(t==0)
```
[Try it online!](https://tio.run/##HY/BjoQgEETv@xUcQZuEBhQx8UsIB83oLMmsY5RM8LK/7oCHPnRVvUr3dsbf96r4dm7ndS3Da/ybHiNJMA0a4iB6547qP/j6Q5b3TgIJK9nH9TnTiRXhyAJF4Hhvn2IvNDnsPUw8QKwLXSUnPPOuR59Dyanej@ujBGGqkYWFJDK/jtklX9E4DIJdpS3ORyyFzpkOuGlAalDKg@s0tBJ4c0/eZQu6Ad61wHWxrQapEIzMGIo2SxyNAJuhrlU5KEqLArx7TGGsldmw2BmwAvND1hrlff9DyLaHNdJqoeUexq4v "Python 3 (PyPy) – Try It Online")
[Answer]
# JavaScript, ~~221~~ 205 bytes
```
(w,x,y,z)=>(g=n=>[...g+""].flatMap((_,k)=>(i=(x,a=[1,1,1,1])=>x?a.flatMap((_,z)=>((b=[...a])[z]++,i(x-1,b))):[a])(n).map(a=>a.map((r,s)=>(k>>s-1&2)*r-r))).find(c=>w*c[0]+x*c[1]+y*c[2]==-z*c[3])||g(n+1))(0)
```
[Try it online!](https://tio.run/##VU7dboIwFL7nKZpdLKfSVgoKOFOWPcCegDRLZeKYrpBSFZx7dlfYXFyb9Jx8v31XB9UWpmosPaSXJ2NUzxpT29r2zZqVO2WfVYMEKve6sFWtodQYfXrIHbO2e6NRLllR60JZpppm10MuCbJvVcs@VDOo8dL7WnpeKS5wJB3pyQmLDDZCiyxnjG38uzt5LQJ4IduBrgR0RImck/FKh3WP6lY2psBKDBlK4vwkfZ9U0FFOVhjjh9yBoPH4CyUyNS5gSDv4tlnWUn4f4omhxqlZWelXKER2nBR5IP3ODS793o1QCkFPbokkPp83oH2OMQT40phKWyghSQmiyZygcEZQFGHsXZnUAXHo2PnPc0OFMUEz56GpW@jMMdMp@vMtnDGMOEFJOITzIP4voDwJCFoM2WkcDSnBba9D@G914qIv3w "JavaScript (V8) – Try It Online")
**How it works:**
I count up from `0`, and for each number, I increment all possible combinations of items in an array which is initially `[1, 1, 1, 1]`. I then find all 16 signs of this array. I then just have to check for the one that is correct. That guarantees the minimum absolute value.
This is actually really fast for most of the test cases, with the speed being determined by the sum of the absolute values of the correct output rather than by the size of the input. It runs near-instantly for most of the test cases, takes about 20s with the `894` one, and times out for the `-170` one.
I think I found the world's most cursed golf. Instead of using `[...Array(16)]` to get an array (the indices of which I'd use to find the various signs), it seems `[...g+""]` works...by casting `g` (a function) into a string and splitting it into characters. Since there's modulo stuff going on with the indices, going over 16 doesn't matter since it just results in some duplicate arrays in the possible outputs that are checked.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~52~~ 51 bytes
```
ArgMin[{Tr[d=Abs@v],v.#==0<d},v={a,b,c,},Integers]&
```
[Try it online!](https://tio.run/##HYxNa4NAFEX3/gpRCC3cKfOlM0M6JVl20VJoduLCGJO40MJE3AyTv25HFw8e595zh2a6d0Mz9W2zXO1ydLevfqz8yVUXezw/DnON@S23lr5fAmbrG5zRIuBznLpb5x71bvlx/ThVzl4P@T7NyYdDmqUvGdLvPzdUDqyO4DWrd8/fthmfPvFKg6gCXEKIgMRriZKDFNutgJeQBYguQeRWMBJcMCgeTUbLlRGmKEz0dClilW5LAmzbUquWeGN4zAzTCoYyFl@jREjC8g8 "Wolfram Language (Mathematica) – Try It Online")
Input the list of numbers.
```
ArgMin[ , ] find:
v={a,b,c,},Integers integers {a, b, c, n}
{ , } such that:
Tr[d=Abs@v] |a|+|b|+|c|+|n| is minimal,
v.#==0<d satisfying the output conditions
```
[Answer]
# [R](https://www.r-project.org/), ~~136~~ ~~118~~ ~~110~~ ~~104~~ 102 bytes
```
function(v,r=combn(rep(c(1:4e3,-4e3:-1),4),4),s=r[,order(colSums(abs(r)))])s[,!apply(s,2,`%*%`,v)][,1]
```
[Try it online!](https://tio.run/##HYxBCoMwFET3nsJShP/LZBG1WARP0aUIamqgoIn8VKGnT6u84S1m8STaJtrNmc/bO9ohjfHL6EimlQzpupwKqL9qpRnludBICy@vScj4@bktgYYxkDBzx6HFZVjX@UsBOfrslvXYuWuhu2iPIk6YE3vUObkeb/VAqqo70rxEWhTM8Qc "R – Try It Online")
Searches solutions in space bounded by sum of absolute values of the inputs (as input is bounded, we simply take `4e3`). This however makes the code run forever for the test cases.
This bound is sufficient, as `a,b,c,d=-x,w,-z,y` is a solution (courtesy of [@loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)).
Here is a version (with lower fixed upper bound) that terminates in reasonable time: [Try it online!](https://tio.run/##JYxBCoMwFET3PUW6EP4v4yKa1iLkFF2KoKYGCo2RpAo9faqWGRjeLF5IVie7TObz8hOtcFohaOPdMFEYZzIka4fc1blkqKNRhwY@PMdAxr8fi4vUD5ECM7ccG5z7eX5/KaJAl12yDiu3DWSb7G7DEeaT3cxqH0PVHSKvrhCFgihL/r8lhNz4VkBUijn9AA "R – Try It Online").
### Explanation:
```
function(v, # take the input vector
m=4e3, # calculate the upper bound for solutions
r=combn( # combine potential solutions into one matrix (potentially with repetitions)
rep(c(1:m,-m:-1),4) # get 4 times the range from -m to m excluding 0
,4) # combinations of length 4
,s=r[,order( # sort the potential solutions
colSums(abs(r)) # by sums of absolute values
)]
)
s[, # take from that array
!apply(s,2,`%*%`,v) # rows which dot-multiplied by input are zero
][,1] # and the first one from that
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
₄4*LD(«4ãʒ*O_}ΣÄO}н
```
[Try it online!](https://tio.run/##ATYAyf9vc2FiaWX//@KChDQqTEQowqs0w6PKkipPX33Oo8OET33Qvf//Wzc4LCAtNzUsIDI0LCAzM10 "05AB1E – Try It Online")
Finishes in unreasonable time. Uses [-4000, 4000] as the bound. The code is verified with changing `₄4*` with `3` for the first test case.
```
₄4* Push 4000 (1000*4)
LD(« Make range of [-4000, 4000] (joining two seperate lists)
4ã All 4-combos (Cartesian power of 4)
ʒ*O_} Filter who dot producted with input cast 0
ΣÄO}н Sort by sum of abs and head (No min by builtin)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
³²R;N$ṗ4ḋÐḟµAS$ÞḢ
```
[Try it online!](https://tio.run/##y0rNyan8/9/40KYgaz@Vhzunmzzc0X14wsMd8w9tdQxWOTzv4Y5F/w@3P2pa4/7/fzSXQrS5hY6uuamOkYmOsXGsDlDAwkTHzEhH1xSMwSJGZjompjq6FmY6uiYQJZYmOkbGhjrmRkDNhgZmYEFdQ3MDHUugVgszY6BiA4hpxjqGYPPMTWK5YgE "Jelly – Try It Online") (Replaced 100 with 3 to actually have this finish in finite time)
```
³² -- 100² = 10000
R -- range from 1 to 10000
$ -- apply the two-atom function to this range
;N -- append the negative
ṗ4 -- 4th cartesian power
ḋÐḟ -- discard all values which have a non-zero dot product with the input
AS$Þ -- sort the remaining 4-tuples by the sum of the absolute values
Ḣ -- get the first value
```
[Answer]
# JavaScript (ES6), 156 bytes
Expects an array of 4 integers.
```
f=(A,n)=>(g=(a,s=n,q=n=>--n?g([...a,n],s-n)||q(n):0)=>a[3]?!s&&(h=i=>a.map((v,j)=>t+=A[j]*(b[j]=i>>j&1?v:-v),b=[t=0])|t?i--&&h(i):b)(15):q(n))([])||f(A,-~n)
```
[Try it online!](https://tio.run/##bY7NboMwEITvfQr3gtbtGtn8GZAMynNYHEgaCCg1SUGcUF@drtWeKi6rXc3sNzO2aztfvobHItz0cd33zsAJHTcV9AZanI3Dp3GmEsLVPdgwDFt0Dc7C8W17guOlJHNr46Z@nYMAbmagM/xsHwArjqQt7@Zkx@YNzjTNUFVjoOq1FCvHs7GLkQ3flnoQIghuMPDyzEGlvPRsDpbEraNK4tvx/TK5ebpfw/vUQwdW58iETpFFCbI4bjh/@efIScgicqW/48ASZcgSYoicFpEcQQqiRLFCpiOfqGR24BJKS2SFT8uz2PPkUSNS1F8pfRRWFJF/LlSuiSaV8kehPWr/AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
f = (A, n) => ( // A[] = input / n = sum of absolute values
g = ( // g is a recursive function taking:
a, // a[] = partition of n in 4 integers
s = n, // s = n - sum of partition
q = n => // q is another recursive function which
--n ? // works together with g to build the
g([...a, n], s - n) // partition
|| q(n) // we stop as soon as a solution is found
: //
0 //
) => //
a[3] ? // if the partition is complete:
!s && ( // abort if s is not 0; otherwise:
h = i => // h is yet another recursive function:
a.map((v, j) => // for each value v at position j in a[]:
t += A[j] * ( // add to t: A[j] multiplied by
b[j] = // b[j] which is
i >> j & 1 ? v // either v or -v
: -v // depending on the j-th bit of i
), //
b = [t = 0] // start with t = 0 and b = [ 0 ]
) | t ? // end of map(); if t is not 0:
i-- && h(i) // try again with i - 1
: // else:
b // success: return b[]
)(15) // initial call to h with i = 15
: // else:
q(n) // invoke q to get the next partition term
)([]) // initial call to g with a = []
|| f(A, -~n) // if failed, try again with n + 1
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 115 bytes
```
f=([h,...t],p=r=[],s=0,m=0,i)=>h?eval("for(i=-4e3;++i<4e3;)i&&f(t,[...p,i],i>0?s+i:s-i,m+i*h)"):m|s>r.s?r.p:r={p,s}
```
[Try it online!](https://tio.run/##bY7BboQgEIbvfQqyhw3UgQV0RWzRBzEeNlutNLoaMHtp@@wW2p42HoAh8833z8flfvFXZ5eV3ua3btt6g5sBGGNrC4txpmnBGw5TOJaYaqi7@2XEh3522BoqOvGSJPY1vsQejz1eoQnDC9gWbMVrn9jSUwtTYp8HciDl9OUrx3zt2FI687mA/96u883PY8fG@R33uFEFIKrOgGQGKE1bQp4eiCI0chmo89@1g8gcUBYctAgFzfYkOlhkKgApGRMFz3coKhQHpGNakafRx/c2Ch3xv5T6DTud0AOitYzzWhQqCLkQ8aNVtG0/ "JavaScript (Node.js) – Try It Online")
It works in theory. The tio link replaced `4e3` by `1e1` so it won't time out. It just need \$2.56×10^{10}\$ times current time usage to run. (So don't try it at home.) But as we are targeted to code-golf, why not make it a bit slower as long as it could be shorter.
```
f=(
[h,...t], // input array
p=r=[], // `p` is array of \$[a, b, c, d]\$
// `r` is an object `{ p: number[], s: number }`
// `r.p` is the best answer found, `r.s` is sum of abs of `r.p`
s=0, // sum of abs of `p`
m=0, // dot product of `p` and input vector
i // loop variable used in the function body
)=>
h?eval(`
for(i=-4e3;++i<4e3;)i&& // loop from -4000 to +4000 exclusive 0
f(t,[...p,i],i>0?s+i:s-i,m+i*h) // apply i
`):
m|s>r.s?
r.p: // output the best answer we ever found
r={p,s} // if dot product is 0 and current abs sum is less than prev one
// we update the best answer we ever found
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~180~~ 150 bytes
-30 bytes thanks to ovs.
```
import itertools as t;lambda*x,q=4000:min([s for s in t.product(*[range(-q,q)]*4)if sum(map(int.__mul__,x,s))==0<all(s)],key=lambda p:sum(map(abs,p)))
```
[Try it online!](https://tio.run/##NY3tCoIwFEBf5f7cZIqVRVh7EhOZ6Wq0j@vuBH16E6J/Bw6Hg2t6B3@6YtyMwxATmDTGFIIlUATppuVjs8r1g8oWMclDWTvjWUOgQwQC4yEVGMMwPxPLmqj8a2T5JCbeZhU3Gmh2zClkxqei69xsu04sgjiXsrwraxnxVnzGVf4mgPW/UD0J5JxvGPeYaXa8CKjOAvLrDnm1my8 "Python 3.8 (pre-release) – Try It Online")
~~I am fairly certain there are some bytes to be shaved off. Here are some clever tricks that are close to working, but don't:~~
You can define the lambda function to be `lambda q=8,*x`, but there isn't a builtin prod function similar to sum that would allow us to take the product of the zip of `(a,b,c,d)` and `x`. You could try using `math.prod` perhaps.
You can try to use Python 3.8's walrus operator inside the list comprehension to avoid having to use `(a,b,c,d)` everywhere like this: `min([s:=(a,b,c,d) for (a,b,c,d) in ... and all(map(bool, s))`, but unfortunately this gives a `NameError` while inside a lambda (see [PEP 572](https://www.python.org/dev/peps/pep-0572/#scope-of-the-target)).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~83~~ 84 bytes
```
MinimalBy[{a,b,c,d}/.Solve[a#+b#2+c#3+d#4==0<Abs@{a,b,c,d}<7!,Integers],Total@*Abs]&
```
How it works:
`Solve[eqn, restrictions]` solves the given equation, with the restrictions that `Abs@{a,b,c,d}<7!`, and that the solutions are all integers.
`{a,b,c,d}/.` removes the `a->`, `b->`, etc. from the solution set, leaving only the numbers
`MinimalBy....Total@*Abs` takes the solution set, and finds the solutions whose values are the smallest according to the criterion `Total@*Abs`, which was specified by the OP.
I've run it with an upper bound of `Abs@{a,b,c,d}<20`, which is sufficient to answer all test cases plus the bonus. That's the bound I've used on Try It Online!, to avoid a timeout.
However, for codegolf purposes, I've changed the upper bound to 7! (=5040), which adds a byte, and is sufficient to exceed the 4000 upper bound others have specified. Unfortunately, this exceeds the memory capacity of my machine, and thus I can't actually run the code with this bound.
[Try It online!](https://tio.run/##TY1PC4JAEMXvfYoFoUOOtX/U3YUE69YhCOomHlYTE9SgliCiz26zFLGXYea993szGHtpBmO72kxtNu27sRtMv30WLwMV1HB@r5bHa/9oChOEVcDDOhDhOYizjK431T3/x9acwm60Tdvc7iWcrtb0@QIT5Xw63LrRkrwtpAISyQQIj4EIUc7@jkIh5egm3@FZPAUSIxMpXKLYhzRSXDAgkrtmRlPPjZikQLRrValwPPU/osJ@T6VfqjV3Yc2URJoy5g4tEZ0@)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes
```
≔³ηW¬ⅉ«≔⁻…±ηη⟦⁰⟧ζ≦⊕ηFζFζFζ«≔⟦κλμ⟧ε¿‹Σ↔εη«⊞ε⁻ηΣ↔ΣEε×ν§θξ«⎚Iε
```
[Try it online!](https://tio.run/##XZBBT8MgFMfP9FO84yPBZOqiB0/LTkvcsqgX0/SA3VshUqpAdZnpZ0doq4eRAAmP3@//oFbS1Z00Ma68143FWwGKPxTfShsC3HUBX5FzDj8Fm29ste09PknbEO6okYFQ8UwJKBdVWs@JZ1v5Md/f2NpRSzbQYXKzY@cAzxwu95TxF1K@CzAC2koAZYTpI@AjeY/PfYurN9@ZPgUTH5MnlO17r5AE/JenVpWASyiNLB2t@Y25njrO8ItuyaNNlrCxBzrhp4DTSMwpbG1IOpwEbO@0DbiWPmTveDYU4xyKIcayTB96vRRwdyPgfllV8erL/AI "Charcoal – Try It Online") Link is to verbose version of code. Not terribly efficient. Takes input as an array. Only outputs a solution with positive `d` (trivially the signs of `a`, `b`, `c` and `d` can always be flipped simultaneously). Explanation:
```
≔³η
```
Start with a sum of absolute values of `3` (which is impossible, but this gets incremented at the start of the loop).
```
W¬ⅉ«
```
Repeat until something has been printed.
```
≔⁻…±ηη⟦⁰⟧ζ
```
Create a range that more than suffices for the integers to test, but delete `0` from it.
```
≦⊕η
```
Increment the desired absolute sum.
```
FζFζFζ«
```
Loop `a`, `b` and `c` over the range.
```
≔⟦κλμ⟧ε
```
Make them into an array.
```
¿‹Σ↔εη
```
If the absolute sum of the array is less than the desired absolute sum, then:
```
⊞ε⁻ηΣ↔ε
```
Add positive `d` to give the desired absolute sum.
```
¿¬ΣEε×ν§θξ«⎚Iε
```
If this list is a solution then clear any previous solution of the same sum and print it.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 20 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
◙╤ç■■m─gÆêm*Σ┌áűΣ├Þ
```
Unfortunately 'minimum by filter' isn't implemented yet despite being mentioned in the docs, otherwise the `áűΣ├Þ` could have been `╓űΣ` for -2 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py).
[Try it online](https://tio.run/##y00syUjPz0n7///RzKZHU5ccXv5o2gIgyn00pSH9cNvhVbla5xY/mtJzeOHh1kMbQcw5h@f9/29uoaNrbqpjZKJjbMxlYaJjZqSjawrGXEZmOiamOroWZjq6JlwWliY6RsaGOuZGQA2GBmZcuobmBjqWQOUWZsZARQbGXMY6hmD95iYA) (with `10` instead of `4096` as range).
**Explanation:**
```
◙ # Push 4096
╤ # Pop and push a list in the range [-4096,4096]
ç # Remove the 0 with a falsey filter
■ # Take the cartesian product with itself to create pairs
■ # Do it again to create pairs of pairs
m # Map over each pair of pairs
─ # Flatten it to a single quadruple-list
g # Filter this list of quadruplets by,
Æ # using the following five characters as inner code-block:
ê # Push the inputs as integer-list
m* # Multiply the values at the same positions in the two lists
Σ # Sum it
┌ # Check that it's equal to 0
á # Sort the remaining quadruplets by,
Å # using two characters as inner code-block:
± # Take the absolute value on each
Σ # And sum them together
├ # After the sort-by, pop the first item from the list
Þ # Discard the list itself, only keeping this first item
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 104 bytes
```
f=->a,z=4{r=[*-z..z]-[0];r.product(r,r,r).find{|w|z==w.sum(&:abs)&&w.zip(a).sum{|x,y|x*y}==0}||f[a,z+1]}
```
[Try it online!](https://tio.run/##NYzLDoIwEEX3foUrAjhteArRjD/SzAIkTVigpEhKS/n2iiTm5CzuWVw1t8Z7iezRgMViVShiZjm3xERCd8VH9e7m5ydUsBNx2b@61WlnETWf5iEMbk07RUGgue3HsIl@cXULGLfEZkNMNuek2M8vKW1@PEshUjggOh2zqoFVJWQF5Pm/1QVcM2DlIZH/Ag "Ruby – Try It Online")
] |
[Question]
[
The challenge is to golf a program that checks if a statement of propositional calculus/logic is a [logical tautology](https://en.wikipedia.org/wiki/Tautology_(logic)) (i.e. it is true for all possible values of the variables).
## Input
Input formulas will use `P`, `P'`, `P''` ect. as variables. They can either be true or false.
`(P and P')` means both `P` and `P'` are true.
`(P or P')` means at least one of `P` and `P'` is true.
`(P implies P')` means that if `P` is true, than `P'` must be true.
`(not P)` means that P is false.
These forms can be nested.
Example input: `(P implies ((P' or P'') and P'''))`
## Output
Output will be a truthy value if the input is a tautology, and a falsy value if it is not.
(i.e True/False 1/0)
## Test Cases
`P`: False
`(P implies P)`: True
`((P implies P') implies ((P' implies P'') implies (P implies P'')))`: True
`(P implies (P or P'))`: True
`(P implies (P and P'))`: False
`(P or (not P))`: True
`and`, `or`, `not`, and `implies` are the ONLY operators.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest program in bytes wins.
## Clarification
The type of logic used here is [Classical](https://en.wikipedia.org/wiki/Classical_logic) logic.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~136~~ ~~124~~ 121 bytes
```
{T`()`<>
.*P.*
<$& ¶ $&>
(?=(P'*))(?=.*\1[^P']*(¶|$))\1
$.2
¶
a
<not 1>|<0 or 0>|<1 [ai]\w* 0>|<0 a\w* .>|(<[^P<>]*>)
$#1
```
[Try it online!](https://tio.run/##XY6xDoIwFEX39xUvsUJfh4Y61zq6dnADDE1kaKJgkMRBvosP4MdqZTDV7dxzk5s7tKPvXNjyYxNep4ZTow1IYaUAzTJcZmSZAX7Yc5sLoghSVKo827wWfJknRlQpYHIHywwOdNePqMykC@wHLCIoLJ2vq6dYU4Hug9JMXMcRbWphCNhGhWCBW/S3@9W3D7QEPI05fTn6PCnSxv54onQxYnwUh/6t6y6rfgM "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Works by considering each variable in turn, replacing the string `f(p)` with the string `<f(1) and f(0)>` for each variable `p`. The resulting string is then evaluated according to Boolean arithmetic.
```
{`
```
Repeat the entire program until the buffer stops changing.
```
T`()`<>
```
Change the `()`s to something that doesn't need to be quoted.
```
.*P.*
<$& ¶ $&>
```
If the line still contains a variable, then duplicate it, and wrap the whole buffer in `<>`, however the two copies are still separated by a newline for now.
```
(?=(P'*))(?=.*\1[^P']*(¶|$))\1
$.2
```
Replace all copies of the last variable in the line with `1` or `0` depending on whether this is the original or duplicate line.
```
¶
a
```
Replace the newline with an `a` so that the two lines are joined together by an `< and >` operation.
```
<not 1>|<0 or 0>|<1 [ai]\w* 0>|<0 a\w* .>|(<[^P<>]*>)
$#1
```
Simplify any expressions that only contain constants. The expressions `<not 1>`, `<0 or 0>`, `<1 implies 0>`, `<1 and 0>`, `<0 and 0>`, `<0 and 1>` and `<0 and P>` (edge case) all evaluate to `0`, while any other expression that contains no sub-expressions or variables evaluates to `1`. (The original version of the code was buggy in this respect and needed a byte to fix it which I have included in the revised byte count in the header.)
[Answer]
# [Python 3](https://docs.python.org/3/), 128 bytes
```
lambda s:eval("all("+s.replace("implies","<=").replace(*"'_")+"".join(f" for P{'_'*i} in[0,1]"for i in range(s.count("P")))+")")
```
[Try it online!](https://tio.run/##fY/BCsIwDEDvfkXJpc02huJN3D/0rjLq1mmla0s3BRG/vXYoYwP1EpL3EpK4e3@2Zh2aYh@0aI@1IN1G3oRmIHQMaZd76bSoJAPVOq1kBxlsC8CRJ0BLwBQgv1hlWAOksZ7wBy1pop5Emd0yWx1ggCpWxAtzkqzLK3s1PQMOiHEaAYPzKpLmzRZjxTj5rCYc52aqKI555HQipobPOOKvTTEdvqB/O4Spv7bESWZsH88dVHgB "Python 3 – Try It Online")
The operator names in the task definition are the same as in Python (except `implies`, which is replaceable by `<=`), but there is an extra annoyance due to the necessity to replace apostrophes with something else.
To enumerate all possible values of variables, we construct a multi-level list comprehension of the form `<given expression> for P in[0,1] for P_ in[0,1]...` and evaluate whether all values are `True`.
I haven't found a short way to determine the number of distinct variables (= the number of levels), so I'm just counting all instances of `P` (which is more than necessary, and thus does the job). In principle, we could even shorten this check to `len(s)`, but this would lead to timeouts for longer expressions...
[Answer]
# JavaScript (ES6), ~~129 ... 122~~ 115 bytes
*Saved 1 byte thanks to @Neil*
Returns **0** or **1**.
```
f=(s,n)=>eval(s.replace(m=/\w+'*/g,s=>(m|=l=s.length,{a:"&",i:"<=",n:"!",o:"|"})[s[0]]||n>>l-1&1))?n>>m||f(s,-~n):0
```
[Try it online!](https://tio.run/##pZAxT8MwEIV3foW5ofEVJ2lXqw5bZw9spYOVOmkqx47itAwY/nowCwSQKtredLrTfe/dO6iT8mXfdENq3U6PYyWoZxZFoU/KUJ/1ujOq1LQV@fPLQzLPa@ZFQdsgjPCZ0bYe9uxVcZgBazisBDDL4R6Y4xDgDTd@s9huQ7BFYdLlbIn4GNs2hCrqpO8W@WIsnfXO6My4mlYUJJCbC5HkOVkr4/XdLzyVpGk702hPJMIt@Kf@@Jc@xSf41cd5MllMN/LHHBHO0OX0zPWfEpf@8F@6srsr8OeDj46pdUMM/srkv82PHw "JavaScript (Node.js) – Try It Online")
### How?
We use `/\w+'*/g` to match all variables and operator names.
The operators `and`, `not` and `or` can be easily translated to `&`, `!` and `|` respectively.
Translating `implies` is a little trickier. We know that \$A \Rightarrow B\$ is equivalent to \$\neg A \lor B\$. But inserting a leading `!` would be quite difficult. Fortunately, this can also be expressed as \$(A \operatorname{xor} 1)\lor B\$. Given the precedence of JS operators, no parentheses are needed. So, `implies` ~~is~~ could be translated to `^1|`.
**Edit**: Better yet, as noticed by @Neil, `implies` can also be translated to `<=`, which is 1 byte shorter.
Variables are replaced by either \$0\$ or \$1\$ depending on their size and the current value of the counter \$n\$.
Once everything has been replaced in the original expression, we test whether it `eval()`uates to \$1\$.
We keep track in \$m\$ of all lengths of the matched strings OR'ed together. This value is greater than or equal to the length of the longest string and *a fortiori* of the longest variable name. We use it to make sure that all possible combinations are tried at least once.
### Commented
```
f = (s, n) => // s = input string, n = counter
eval( // evaluate as JS code:
s.replace( // replace in s:
m = /\w+'*/g, // all operator and variable names
s => // s = matched string
( //
m |= // do a bitwise OR between m and ...
l = s.length, // ... the length l of the matched string
{ // lookup object:
a: "&", // "and" -> "&"
i: "<=", // "implies" -> "<="
n: "!", // "not" -> "!"
o: "|" // "or" -> "|"
} //
)[s[0]] || // translate the operator name according to
// its first letter
n >> l - 1 & 1 // or replace the variable name with 0 or 1
) // end of replace()
) ? // end of eval(); if truthy:
n >> m || // stop if n is equal to 2 ** m (success)
f(s, -~n) // otherwise, do a recursive call with n + 1
: // else:
0 // failure: return 0
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands/2649a799300cbf3770e2db37ce177d4a19035a25), 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„€Ÿ(ì'''_:'Ø¢„<=:D'P¢ƒ1Ý'_Nד €‡ Pÿ€†ÿ“}')J.Eb
```
Port of [*@KirillL.*'s Python answer](https://codegolf.stackexchange.com/a/206561/52210), so make sure to upvote him!
Outputs `1`/`0` respectively. If outputting `True`/`False` is allowed (even though these are both falsey in 05AB1E), the trailing `b` could be omitted.
Uses the legacy version of 05AB1E, where list `[0,1]` will be input as string with `ÿ`, whereas this would result in an error in the new version of 05AB1E.
[Try it online](https://tio.run/##MzBNTDJM/f//UcO8R01rju7QOLxGXV093kr98IxDi4CCNrZWLuoBhxYdm2R4eK56vN/h6Y8a5igAlT5qWKgQcHg/mLUASDfMqVXX9NJz/f9fQyNAITO3ICcztVghQF0TzgaKqyNJIMsEoIhragIA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3l/0cN8x41rTm6Q@PwGnV19Xgr9cMzDi0CCtrYWrmoBxxadGyS4eG56vF@h6c/apijAFT6qGGhQsDh/WDWAiDdMKdWXdNLz/W/zv8ALo0AhczcgpzM1GKFAE0uDWSuuiacDRRXR5JAlglAEdfURDYRyMwvAhmELpqYlwIXBqrQyMsvAVqvCQA).
**Explanation:**
```
„€Ÿ( # Push dictionary string "all("
ì # Prepend it in front of the (implicit) input-string
'' '_: '# Replace all "'" with "_"
'Ø¢ „<=: '# Replace dictionary string "implies" with "<="
D # Duplicate the string
'P¢ '# Pop and count the amount of "P" in this string
ƒ # Loop `N` in the range [0, count]:
1Ý # Push list [0,1]
'_N× '# Push a string consisting of `N` amount of "_"
“ €‡ Pÿ€†ÿ“ # Push dictionary string " for Pÿ inÿ",
# where the first `ÿ` is automatically replaced with the "_"-string
# and the second the stringified "[0,1]" list
}') '# After the loop: push a ")"
J # Join all strings on the stack together
.E # Execute it as Python code
b # Then convert the "True"/"False" to 1/0 with the binary builtin
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„€Ÿ(` is `"all("`; `'Ø¢` is `"implies"`; and `“ €‡ Pÿ€†ÿ“` is `" for Pÿ inÿ"`.
[Answer]
# [SageMath](https://doc.sagemath.org/html/en/index.html), ~~140~~ ~~134~~ 132 bytes
```
lambda p:propcalc.formula(r(*"'0",r("implies","->",r("or","|",r("and","&",r("not","~",p)))))).is_tautology()
from re import sub as r
```
[Try it online!](https://sagecell.sagemath.org/?z=eJx1j00KwjAQhfc9xZCFTSQW1wU9Qw4gSPongbQTJulCEM_uNBStgrOZx_cek7zhdCm8HZvOQqgDYWitb6sBaZy9lST3ojwKTVK4MXjXR6HF4ZwBEutHlnbqWO-ynjCxfgodVJ7KxWuyc0KPt7tUxUA4AvXA95ASxLkBG4GK1McU4QSyAB4hDawvglFCr3BLS_XWzMuNsXXMF1efU2abQVru_TG53a_LeclF-WsL5VIMlgLgprxjnaOB3JTkAjQMeSv1AkAoaIw=&lang=sage&interacts=eJyLjgUAARUAuQ==)
[Answer]
# [J](http://jsoftware.com/), ~~114~~102 bytes
```
[:*/([:;e.&' ()'({.;(<./@i.~&'rapt'{ ::''+`*`<:,'1-';'&{',~&":1-~#)@}.);.1]),/&.":"#.2#:@i.@^1#.e.&'P'
```
[Try it online!](https://tio.run/##bY7NSsNQEIX3fYohgXvu1GRiXE4qBAUXIhLcFqWBppBSk9rEVTCvHqddqC0u5o/vzJnZToFgQ7dKoIiuSS1iofuXp4dpqfPELzWrxIE8ww@S@YUkeS2jw6Hc9xhIFbhazVcLjZDGyOAGRKMLNI3HkPMv4UzSV44SJ4EGodyEavv5WxrK0bfAxNOGrM4s@4Lq9/2urjoqGLPnO7G36o4@Ptu@WlPZEWxu6PEk/qsG@GcwcJT9ojNYXBDmy9PWtoeT5X@obNbnzLS@aXv7mPEN "J – Try It Online")
### How it works
```
2|:@#:@i.@^1#.e.&'P'
```
Count the P's in the string, 2^y, range, and base 2 it. This is a matrix with all boolean combinations for P variables. Now transforming the string to a J expression:
```
e.&' ()'
```
Bit mask if `()` is at that position.
```
(…);.1]
```
Split the string based on the bit masks first item (which will be 1 expect in the single `P` case.) The groups start whenever the bit mask is 1, i.e. we either have the single groups ,`(`,`)` or a group that starts with that and also has a word like `(P'''`
```
{.;(…)@}.
```
Take the first character of the group unmodified, and for the rest apply:
```
'&{',~&":1-~#
```
Length - 1 as string prepended with `&{`, e.g. `3&{` for `P'''`.
```
+`*`<:,'1-';
```
The operators: or, and, implies, not. Now we have a list of things we have to pick from.
```
<./@i.~&'rapt'{ ::''
```
Search for any of `rapt` (o*r*, *a*nd, im*p*licit, no*t*) with the implicit `P` at the 5th place), reduce the word to that index, and take from the list (with an empty string if the group was only one character long.) We now have a list of valid J expressions like `(0&{ <: (2&{ + 1&{))`.
```
,/&.":"1
```
With the function on the left side and the booleans on the right side: Convert from numbers to strings with `":` (this will only change the booleans), append them to the function, and with `&.` the inverse of `":` will be called afterwards, so `(0&{ <: (2&{ + 1&{)) 0 1` will then be called and converted to the integer 1.
```
[:*/
```
Multiply-reduce the results.
[Answer]
# [R](https://www.r-project.org/), ~~230~~ ~~197~~ 191 bytes
```
f=function(s,`[`=gsub)`if`(grepl("P",s<-sapply(0:1,`[`,pa="Q","and"["&","or"["|","not"["!","implies"["<=","P([^'])|P$"["Q\\1",s]]]]])),all(sapply("P'"["P",s],f)),all(sapply(parse(t=s),eval)))
```
[Try it online!](https://tio.run/##jVBNS8QwEL37K2oUOwMR3Ktsrp6z4K1bbdS0BGITMqmwsP@9TmRxW2TBnN689/LmI82OXrOZcvBhOKi5V/00vmcXRiDZNZ0aaHrDzvUdDMlGD0ILSdt7MjH6Azw8bopLRqPETkhhxg/RiDtGITE4MhhDZnTNyH1G7yxxtVVcamhe6haP@paZ3X6/4eC2PERpvIdTC6Fr1kvXVvZrKZpEFrIilPbLeERcbVNmxeqmejKe7NVaAV2dxqk0/rie0/THtHTV@IuZrxfCUtErHi9H6@WfkEr@P81847P7wm4cCHx43u0cOn8D "R – Try It Online")
*Edits: -39 bytes in exchange for quite a lot of warnings*
This was a lot of fun, but I must confess that I needed to look at the other answers for inspiration about how to handle 'implies'...
Works by recursively substituting each `P` (without any apostrophes) for `1` and `0`, then reducing the number of apostrophes after all the remaining `P`s and calling itself, until there are no more `P`s left, at which point it evaluates each expression.
My pattern matching & substitution is rather clunky, so I suspect that this could still be reduced quite a lot.
Commented version:
```
is_tautology=f=function(string) {
string= # exchange in string:
gsub("and","&", # and -> &
gsub("or","|", # or -> |
gsub("not","!", # not -> !
gsub("implies","<=", # implies -> <=
gsub("P([^'])","Q\\1",
gsub("P$","Q", # P (but not P') -> Q
string))))))
# now exchange Q for 1 or for 0:
string=sapply(0:1,gsub,pattern="Q",string)
if(!any(grepl("P",string))){ # if there are no more P's left:
# return true if expression evaluates true
# in both cases (Q->1 and Q->2)
return(eval(parse(text=string[1]))&&eval(parse(text=string[2])))
} else { # otherwise (there are still some P's):
string=g("P'","P",string) # remove one apostrophe from each P'
# and recursively call self
# with both cases (Q->1 and Q->2)
return(f(string[1])&&f(string[2]))
}
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 10 bytes
```
TautologyQ
```
Yep, there's a builtin.... Now, the OP will have to decide if the input format is acceptable (I feel that it is well within the spirit of this site's guidelines).
In terms of the variables themselves, we need to use strings of letters in place of `P`, `P'`, `P''`, and so on: we can use `P`, `Pp`, `Ppp`, and so on (as has been done in the TIO link), or `a`, `b`, `c`, `foo`, `bar`, or whatever. (Strangely, `TautologyQ` seems to be ok with a single variable containing primes, but two different such variables seems to break it.)
Logical input can be taken in two different formats.
We can preserve the infix notation in the examples, such as:
```
TautologyQ[(P \[Implies] (P \[And] Pp))]
```
Or we can use prefix notation, such as:
```
TautologyQ[Implies[P, And[P, Pp]]]
```
(If the input format is completely inflexible, then one can add some processing commands like `StringReplace` followed by `ToExpression`.)
[Try it online!](https://tio.run/##jZC9DsIgEIB3nwI7SVLfQUcXeyZuyEC0UZK2EIqDT4@0pYqUFtnuvo/7q5l@lDXT/MqMObOnFpW4v04GFG/07psgQFeT3AbQhRxqWfGypQhwTAkcif3QUvmLAw4hxTg5Rx8Vqm/2p71vbvN62hgbrmdu8CngCSTbdi@L@LFTu3kJ5AjoAvc9SXM0ycsO@ASGBKXLXQvlaiY8u@eCOFQ5Cm2XjHH3exTMGw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
As the title -- although discretely -- hints, I only pay with dollars.
## The challenge
Write a function/program that takes a string as input, which is a monetary value preceded by a symbol. `ex) £4.99`. Then, return that same amount converted to USD.
## Input
You will get a string as input. It will have the currency symbol followed by a number with two decimal places (which could be `.00`). There will either be decimal points `.` and/or commas `,` separating the number. The following currency symbols will come in the inputs:
>
> Euro: €
> Pound Sterling: £
> Yuan Renminbi: ¥
>
>
>
Also, there will be a comma or decimal point depending on the currency to separate the 'dollars' from the 'cents':
>
> Euro: #.###,##
> Pound Sterling: #,###.##
> Yuan Renminbi: #,###.##
>
>
>
## Output
You will convert the input from the currency determined by the symbol to USD, rounding to two decimal places. The output will be in the format `$#,###.##`, and there will of course be more numbers on the left of the output if need be (**EDIT: this means that there is an arbitrary number of commas in the output, just like in the input**). The currency exchange rate we will be using are below.
You can assume that the input contains a symbol that is only one of the above (`€ £ ¥ . ,`)--that it is always valid.
## Exchange rates
```
€1 : $1.10
£1 : $1.37
¥1 : $0.15
```
## Examples
```
Input:
€1,37
£4.00
¥2,782,122.78
Respective output:
$1.51
$5.48
$417,318.42
```
## Final words
1. If you use one of the above symbols (€, £, ¥), you may count them as 1 byte
2. This is code golf, so shortest code in bytes wins!
[Answer]
## Python 3.6 (pre-release), 87
```
lambda s:f"${int(s.translate({46:'',44:''})[1:])*[110,15,0,137][ord(s[0])%4]/1e4:,.2f}"
```
Uses [f-strings](https://www.python.org/dev/peps/pep-0498/) to evaluate the result and [format it](https://docs.python.org/3/library/string.html#format-specification-mini-language).
`s.translate({46:'',44:''})` removes dots and commas from `s`, thus making it a valid `int` literal, then `int(...)` converts it into the actual `int` object.
[Answer]
## Convex, ~~56~~ ~~55~~ 54 bytes
```
(\®\.|,"ö)\e_\'.\++~\"€£¥"#[1.1_.27+.15]=*"%,.2f"\Ø'$\
```
Well, this can definitely be shortened. [Try it online!](http://convex.tryitonline.net/#code=KFzCrlwufCwiw7YpXGVfXCcuXCsrflwi4oKswqPCpSIjWzEuMV8uMjcrLjE1XT0qIiUsLjJmIlzDmCckXA&input=&args=wqUyLDc4MiwxMjIuNzg)
Saved a byte thanks to Lynn!
Explanation to come when I can get access to a computer.
[Answer]
# Python 3.5, ~~137~~ ~~131~~ ~~121~~ ~~120~~ 117 bytes:
*(Thanks to [Maltysen](https://codegolf.stackexchange.com/users/31343/maltysen) for a hint on saving 6 bytes `(137 -> 131)`!)*
```
lambda u:'${:,.2f}'.format(float(u[1:].translate([{44:''},{44:46,46:''}]['€'in u]))*{'€':1.1,'£':1.37,'¥':.15}[u[0]])
```
[Try It Online! (Ideone)](http://ideone.com/RjjqOt)
[Answer]
# JavaScript (ES6), 107
Simple and straightforward~~, probably more golfable~~
Note: tested in FireFox. Many browsers (especially mobile) have buggy support of `toLocaleString`
```
a=>(a.replace(/\D/g,'')/1e4*(a<'¥'?137:a>'€'?110:15)).toLocaleString('en',{style:'currency',currency:'USD'})
```
**TEST**
```
function test()
{
var i=I.value
var F=a=>(a.replace(/\D/g,'')/1e4*(a<'¥'?137:a>'€'?110:15)).toLocaleString('en',{style:'currency',currency:'USD'})
O.textContent=F(i)
}
test()
```
```
<input id=I value='¥2,782,122.78' oninput='test()'>
<pre id=O></pre>
```
[Answer]
# Java 7, ~~240~~ ~~227~~ ~~215~~ ~~211~~ ~~207~~ ~~202~~ ~~199~~ 196 bytes
(201 - 2 bytes because of the rule "*If you use one of the above symbols (€, £, ¥), you may count them as 1 byte*")
Thanks to *@Frozn* for saving a lot of bytes.
```
String c(String a){int c=a.charAt(0);return java.text.NumberFormat.getCurrencyInstance(java.util.Locale.US).format(new Long(a.substring(1).replaceAll(",|\\.",""))*(c<'¥'?1.37:c>'¥'?1.1:.15)/100);}
```
**Ungolfed & test code:**
[Try it here.](https://ideone.com/aYoXta)
```
class Main{
static String c(String a){
int c = a.charAt(0);
return java.text.NumberFormat.getCurrencyInstance(java.util.Locale.US)
.format(new Long(a.substring(1).replaceAll(",|\\.","")) *
(c < '¥'
? 1.37
: c > '¥'
? 1.1
: .15
) / 100);
}
public static void main(String[] a){
System.out.println(c("€1,37"));
System.out.println(c("£4.00"));
System.out.println(c("¥2,782,122.78"));
}
}
```
**Output:**
```
$1.51
$5.48
$417,318.42
```
[Answer]
# Pyth - ~~54~~ ~~53~~ ~~48~~ 47 bytes
Forgot about conditional application `W`.
```
.F"${:,.2f}"*v-tXWqhQ\€Q",.")\,@[1.1.15d1.37)Ch
```
[Test Suite](http://pyth.herokuapp.com/?code=.F%22%24%7B%3A%2C.2f%7D%22%2av-tXWqhQ%5C%E2%82%ACQ%22%2C.%22%29%5C%2C%40%5B1.1.15d1.37%29Ch&test_suite=1&test_suite_input=%22%E2%82%AC1%2C37%22%0A%22%C2%A34.00%22%0A%22%C2%A52%2C782%2C122.78%22&debug=0).
[Answer]
# F#, 198 bytes
```
(s:string)="$"+(System.Double.Parse(if s.[0]='€'then s.[1..].Replace(".","").Replace(',','.')else s.[1..].Replace(",",""))*(if s.[0]='€'then 1.1 else if s.[0]='£'then 1.37 else 0.15)).ToString("N2")
```
Un-Golfed:
```
let IOnlyUseDollars(s : string) =
let cur = s.[0]
let str = if cur = '€' then s.[1..].Replace(".","").Replace(',', '.') else s.[1..].Replace(",","")
let amt = System.Double.Parse(str)
let dol = amt * (if cur = '€' then 1.1 else if cur = '£' then 1.37 else 0.15)
"$" + dol.ToString("N2")
```
I'm still trying to figure out F#, so dealing with the thousands separators is taking up a lot of bytes.
According to the challenge rules, the Euro, Yen, and Pound symbols count as one byte each, despite how Unicode stores them internally.
[Answer]
# Python 3.5, ~~101~~ 98
```
lambda x:'${:,.2f}'.format(int(x[1:].translate({44:'',46:''}))*{'€':110,'£':137,'¥':15}[x[0]]/1e4)
```
The Euro, Pound, and Yen symbols are counted as 1 byte/character each, per the challenge rules.
Instead of translating among or interpreting thousands and decimal separators, these are just stripped out to give a plain digit string.
The digit string (after the currency symbol) is converted to an integer.
The currency symbol is used as an index into a dictionary of conversion rates; the conversion is performed by multiplying by the conversion rate and dividing by 10000.
The result is formatted with a leading dollar sign, two decimal places of precision, and commas for grouping.
[Answer]
## Python 3, 112 bytes NOT COMPETING
```
def c(x):x=x.translate(None,",.");print“$”+‘{:,.2f}’.format([1.1,1.37,0.15][“€£¥”.index(x[0])]*int(x[1:])/100,2)
```
This is not competing because I do not think that I am allowed to answer my own question.
Also, I have not yet had a chance to run this on a computer, but it seems to me like it should work. I will run it on a computer as soon as I have a chance.
[Answer]
# PHP, 117 bytes
```
function f($s){return'$'.number_format(ereg_replace('[^0-9]','',substr($s,1))*[E=>.011,P=>.0137,Y=>.0015][$s[0]],2);}
```
This makes use of a deprecated function; replace `ereg_replace('[^0-9]'` with `preg_replace('%[^\d]%'` to make the code fully modern; adds 1 byte.
[Answer]
# CJam, 54 bytes
```
'$q(\",."-de-2\"€£¥"#[1.1 1.37 .15]=*2mOs'./~\3/',*'.@
```
[Try it here!](http://cjam.tryitonline.net/#code=JyRxKFwiLC4iLWRlLTJcIuKCrMKjwqUiI1sxLjEgMS4zNyAuMTVdPSoybU9zJy4vflwzLycsKicuQA&input=4oKsMSwzNw)
] |
[Question]
[
Your challenge is to write 5 different full programs for the 5 following tasks:
1. Print `Hello, World!`.
2. Given an input on STDIN, output the factorial (you can assume that the input is an integer ≥ 0).
3. Given an integer N, calculate the sum of the primes ≤ N.
4. Given an input on STDIN, output the letters used in the input.
For example: the input is `Hello world`, you need to output `helowrd`.
Note that the output is in lowercase.
You can assume that the input is always alphabetic with white spaces, the white spaces are ignored.
5. Output the following diamond exactly like this:
```
*
***
*****
*******
*****
***
*
```
All these challenges are probably very easy, but there is a catch.
Every letter you use **cannot be used again** in the other programs.
This is not prohibited, but will give you a penalty of **+8 bytes**.
For example, if this is your program for the first task:
```
print("Hello, World!");
```
Then you cannot use the following letters (in uppercase or lowercase form): `p`, `r`, `i`, `n`, `t`, `h`, `e`, `l`, `o`, `w`, `d` in the other programs.
If you do have to use them, you can “buy” each letter for 8 bytes.
So if you want to use the letter `l` again in another program, you receive a penalty of 8 bytes.
After you have paid the penalty, you can use each letter as many times as you want in *this* program.
Other characters don’t matter.
Also, all 5 programs should be in the same language.
This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), least amount of bytes wins!
[Answer]
# CJam, 73 bytes
```
"Obkkh+'Phukc&"7f^
q~m!
ri){'j3+_3++~},:+
lS-el_&
4{_' *4@-Y*('**+}%_1>W%\+N*
```
Each line is a full program. Try them online: [1](http://cjam.aditsu.net/#code=%22Obkkh%2B'Phukc%26%227f%5E) | [2](http://cjam.aditsu.net/#code=l~m!&input=10) | [3](http://cjam.aditsu.net/#code=ri)%7B'j3%2B_3%2B%2B~%7D%2C%3A%2B&input=5) | [4](http://cjam.aditsu.net/#code=lS-el_%26&input=Hello%20world) | [5](http://cjam.aditsu.net/#code=4%7B_'%20*4%40-Y*('**%2B%7D%25_1%3EW%25%5C%2BN*)
### Letter map
```
bc f h k op u 18
m q 4
ij r 17
e l s 7
n w y 27
```
If you want (and each of your programs fits in a line), you can use [this CJam program](http://cjam.aditsu.net/#code=qN%2F%7B_el'%7B%2C97%3E%5Cf%7B%26Se%7C%7DS%40%2Cs3Se%5BN%7D%2F&input=%22Obkkh%2B'Phukc%26%227f%5E%0Aq~m!%0Ari)%7B109c_3%2B%2B~%7D%2C%3A%2B%0AlS-el_%26%0A4%7B_'%20*4%40-Y*('**%2B%7D%25_1%3EW%25%5C%2BN*) to create a letter map for your own submission.
[Answer]
## Pyth, 90 bytes
First attempt...
### Task 1: 20 bytes
```
+"Hello, "+C87"orld!
```
### Task 2, 3 bytes
```
.!Q
```
### Task 3, 9 bytes
```
sf}TPTSvz
```
### Task 4, 6+8=14 bytes
```
@G{rw0
```
### Task 5, 44 bytes
```
" *
***
*****
*******
*****
***
*
```
[Answer]
# osascript, 759 Bytes
I knew this was going to be a lot when I started. o-o
**Task 1: 15 Bytes**
```
"Hello, World!"
```
I knew that it was going to be bad from this point.
**Task 2: 64 + 8\*4 = 96 Bytes**
```
on run a
set o to 1
repeat a
set o to a*o
set a to a-1
end
o
end
```
Oh gawd.
**Task 3: 170 + 8\*13 = 274 Bytes**
```
on run a
set o to 0
set t to false
repeat with i from 2 to a
set t to true
repeat with c from 2 to i-1
if i mod c=0 then set t to false
end
if t then set o to o+i
end
end
```
Dennis ≠ outgolfed.
**Task 4: 225 + 8\*13 = 329**
```
on run a
set o to""
repeat with i in items of a
repeat with c in characters of i
if c is not in o then
if ASCII number of c<91 then
set o to o&(ASCII character of(ASCII number of c+32))
else
set o to o&c
end
end
end
end
o
end
```
...
**Task 5: 45 Bytes**
```
" *
***
*****
*******
*****
***
*"
```
So, yeah. I knew I was gonna lose from the start. But it was interesting, I'd be interested to know if there's a way to do this in fewer characters. Character map (as provided by Dennis):
```
de h l o r w 15
a cdef hi lmnop rstu w 160
a de nop rstu 57
abcdef hi lmnop rstu w 214
39
0
```
The character count above is slightly off - newlines made it have issues, as the newlines were uncounted.
NOTE: The reason for not using stuff like `a's characters` or the like is that the `'` character has to be used when executing from the osascript command line. If I had used `'`, I'd have to use `\'` or something similar, which wouldn't have helped me at all. Also, it only recognizes `"` as string capturers, so I was kinda screwed there as well. But that was fun.
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 83 bytes, no characters repeated between programs
The five programs separated by newlines:
```
"Olssv'^vysk("7-
P
µf«äµL1=×S
32|ÍÌM64á<F¥
» *
***
*****
*******
*****
***
*
```
online interpreter:
[1](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=Ik9sc3N2J152eXNrKCI3LQ)
[2](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=UA==&in=NQ==)
[3](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=tWar5LVMMT3XUw==&in=MTA=)
[4](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=MzJ8zcxNNjThPEal&in=IkhlbGxvIFdvcmxkIg==)
[5](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=uyAgICoKICAqKioKICoqKioqCioqKioqKioKICoqKioqCiAgKioqCiAgICo=)
*The letters in problem 4 are printed in alphabetical order instead of the order they appear in, I did not find any rule against that*
## Explanation
```
"Olssv'^vysk("7- ; Hello World! shifted by 7 to avoid space
P ; product over the 1-based range to the input
µf«äµL1=×S
µf« ; replace the numbers in the range 1 : input with their prime-factorisation
äµL1=× ; only keep the elements with a length of one
S ; sum up the array
; assumes that the input consists of ASCII letters and white-spaces
32|ÍÌM64á<F¥
32| ; or with 32 -> converts uppercase ascii to lowercase
ÍÌ ; get a list of all unique elements
M64á<F¥ ; print the elements that are larger that 64 (filters out white spaces)
M ; for all elements
64á< ; is the the number greater than 64
F ; repeat that many times
¥ ; print
; string-literal containing the required output
; all possibilities to loop are used up by the previous answers
» *
***
*****
*******
*****
***
*
```
[Answer]
# NARS2000 APL, 144 bytes (85 characters)
## Task 1, 21 bytes (17 characters)
```
⎕←"Hello, World!"
```
## Task 2, 10 bytes (4 characters)
```
⎕←!⎕
```
## Task 3, 22 bytes (11 characters)
```
⎕←+/¯2π⍳2π⎕
```
## Task 4, 53 bytes (29 characters)
```
⎕←∪Q[26∣Q⍸⍞∩Q←⎕AV[97+⍳26]∪⎕A]
```
## Task 5, 38 bytes (24 characters)
```
⎕←" *"[1+4<∘.+⍨(⍳3),⊖⍳4]
```
[Answer]
# [Jelly](//github.com/DennisMitchell/jelly), 46 bytes (non-competing)
```
“3ḅaė;œ»
Ɠ!
ÆRS
ɠQḲŒl
4Ḷ¤‘+¤ṖṚṭ×”*Fµ4Ḷṭ4ḶṚṖ¤F×⁶+⁸Y
```
[Try it online!](//jelly.tryitonline.net) (Copy/paste each snippet)
Apparently, the restriction did not restrict golfing :) Just suggestions for the last one, of course, please.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 398 bytes
I don't know why I decided to try this.
`-rprime` flag loads the `Prime` library for task 3. As per [the meta post on program flags](https://codegolf.meta.stackexchange.com/a/14339/52194), adding flags treats it as a "different language", so I can't add `-n` or `-p` for some tasks and remove it for others, even if it would save bytes. (Tasks 1 and 5 take no input, and no input means programs with those flags won't run, which is why they can't be used.)
### Task 1, 47 bytes
Backslash-escaped almost every letter to free letters up for usage in later tasks. `$>` is an alias for `STDOUT`, which will be used later.
```
$><<"H\x65\154\154\x6f\54\40W\x6f\x72\154\x64!"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7IKlpSVpuhY39VXsbGyUPGIqzExjDE1NwLjCLC0GSJkYhIOZFeZGUGETRSWINqjuBVAaAA)
### Task 2, 31 bytes
`3+9+~9 == 2` to avoid reusing `2`.
```
p((3+9+~9..gets.to_i).inject:*)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7IKlpSVpuhb7CzQ0jLUttess9fTSU0uK9Ury4zM19TLzslKTS6y0NCGqoIoXLDSFMAA)
### Task 3, 28 bytes + 56 (`().ceis`) = 84
Since this is the only task that doesn't say to take input from STDIN, this one is a lambda instead so I don't need to take a huge penalty from doing things with `gets.to_i` or something similar. This is probably the only time where `lambda` saves bytes over its stabby syntax `->`, which has to buy back `>` and uses up the `-` needed in Task 4.
```
lambda{|e|Prime.each(e).sum}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7KI026WlJWm6FntyEnOTUhKra1JrAkBSeqmJyRkaqZp6xaW5tRAlywsU0qJNDWIhvAULIDQA)
### Task 4, 67 bytes + 96 (`*.<achinrstu`) = 163
This one had wayyyyyy too much overlap but it was needed to do the given task. Uses `t,=*STDIN` to get the line of input, assuming newlines won't be present. Let me know if that's an incorrect assumption.
```
t,=*STDIN;t=t.tr'A-Z','a-z';t=t.tr'^a-z','';STDOUT<<t.chars.uniq*''
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7IKlpSVpuhY3nUt0bLWCQ1w8_axLbEv0SorUHXWj1HXUE3Wr1GEicSCOjrq6NVCdf2iIjU2JXnJGYlGxXmleZqGWujrEKKiJC1Z7pObk5CuU5xflpECEAA)
### Task 5, 53 bytes + 20 (`$*<>`) = 73
Buys back virtually every character in the program, since it's still cheaper than any alternative I could think of. Uses heredoc syntax for the string since we no longer have `'` or `"` and we're buying back `<` anyways since it's cheaper than buying back `puts`.
```
$><<<<Q
*
***
*****
*******
*****
***
*
Q
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7IKlpSVpuhY3TVXsbIAgkEtBQUELSGhpAUktEODSggAYFyoHUhYI0Qw1YwGUBgA)
] |
[Question]
[
## Leaderboard
```
User Language Score
=========================================
Ell C++11 293,619,555
feersum C++11 100,993,667
Ell C++11 78,824,732
Geobits Java 27,817,255
Ell Python 27,797,402
Peter Taylor Java 2,468
<reference> Julia 530
```
## Background
When working on a 2-D grid of integer coordinates, you sometimes want to know whether two vectors (with integer components) have the same magnitude. Of course, in Euclidean geometry the magnitude of a vector `(x,y)` is given by
```
√(x² + y²)
```
So a naive implementation might compute this value for both vectors and compare the results. Not only does that incur an unnecessary square root computation, it also causes trouble with floating point inaccuracies, which might yield false positives: vectors whose magnitudes are different, but where the significant digits in the floating point representation are all identical.
For the purposes of this challenge, we define a **false positive** as a pair of coordinate pairs `(a,b)` and `(c,d)` for which:
* Their squared magnitude is different when represented as 64-bit unsigned integers.
* Their magnitude is identical when represented as 64-bit binary floating point number and computed via a 64-bit square root (as per [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point)).
As an example, using 16-bit representations (instead of 64), the smallest1 pair of vectors which yields a false positive is
```
(25,20) and (32,0)
```
Their squared squared magnitudes are `1025` and `1024`. Taking the square root yields
```
32.01562118716424 and 32.0
```
But in 16-bit floats both of these get truncated to `32.0`.
Likewise, the smallest2 pair yielding a false positive for 32-bit representations is
```
(1659,1220) and (1951,659)
```
1"Smallest" as measured by their 16-bit floating point magnitude.
2"Smallest" as measured by their 32-bit floating point magnitude.
Lastly, here are a handful of valid 64-bit cases:
```
(51594363,51594339) and (54792160,48184783)
(54356775,54353746) and (54620742,54088476)
(54197313,46971217) and (51758889,49645356)
(67102042, 956863) and (67108864, 6) *
```
`*` The last case is one of several with the smallest possible magnitude for 64-bit false positives.
## The Challenge
In less than 10,000 bytes of code, using a single thread, you're to find as many false positives for **64-bit (binary) floating point numbers** in the coordinate range `0 ≤ y ≤ x` (that is, only within the first octant of the Euclidian plane) such that `x² + y² ≤ 253` within **10 minutes**. If two submissions tie for the same number of pairs, the tie breaker is the actual time taken to find the last of those pairs.
Your program must not use more than **4 GB** of memory at any time (for practical reasons).
It must be possible to run your program in two modes: one which outputs every pair as it finds it, and one which only outputs the number of found pairs at the end. The first will be used to verify the validity of your pairs (by looking at some sample of outputs) and the second will be used for actually timing your submission. Note that the printing must be the *only* difference. In particular, the counting program may not hardcode the number of pairs it *could* find. It must still perform the same loop that would be used to print all the numbers, and only omit the printing itself!
I will test all submissions on my Windows 8 laptop, so please ask in the comments if you want to use some not-too-common language.
Note that pairs must *not* be counted twice under switching of the first and second coordinate pair.
Note also that I will run your process via a Ruby controller, which will kill your process if it hasn't finished after 10 minutes. Make sure to output the number of pairs found by then. You can either keep track of time yourself and print the result just before the 10 minutes elapse, or you just output the number of pairs found sporadically, and I will take the last such number as your score.
[Answer]
## Python, 27,797,402
Just to set the bar a little higher...
```
from sys import argv
verbose = len(argv) > 1
found = 0
for x in xrange(67108864, 94906266):
found += 1
if verbose:
print "(%d, 0) (%d, 1)" % (x, x)
print found
```
It's easy to verify that for all *67,108,864 <= x <= 94,906,265 = floor(sqrt(253))* the pairs *(x, 0)* and *(x, 1)* are false positives.
**Why it works**: *67,108,864 = 226*. Therfore, all numbers *x* in the above range are of the form *226 + x'* for some *0 <= x' < 226*.
For all positive *e*, *(x + e)2 = x2 + 2xe + e2 = x2 + 227e + 2x'e + e2*.
If we want to have
*(x + e)2 = x2 + 1* we need at least *227e <= 1*, that is, *e <= 2-27*
However, since the mantissa of double-precision floating point numbers is 52-bit wide, the smallest *e* such that *x + e > x* is *e = 226 - 52 = 2-26*.
In other words, the smallest representable number greater than *x* is *x + 2-26* while the result of *sqrt(x2 + 1)* is at most *x + 2-27*.
Since the default IEEE-754 rounding mode is round-to-nearest; ties-to-even, it will always round to *x* and never to *x + 2-26* (where the tie-break is really only relevant for *x = 67,108,864*, if at all. Any larger number will round to *x* regardless).
---
## C++, 75,000,000+
Recall that *32 + 42 = 52*.
What this means is that the point *(4, 3)* lies on the circle of radius *5* centered around the origin.
Actually, for all integers *n*, *(4n, 3n)* lies on such circle of radius *5n*.
For large enough *n* (namely, such that *5n >= 226*), we already know a false-positive for all points on this circle: *(5n, 1)*.
Great! That's another *27,797,402 / 5* free false-positive pairs right there!
But why stop here? *(3, 4, 5)* is not the only such triplet.
This program looks for all positive integer triplets *(a, b, c)* such that *a2 + b2 = c2*, and counts false-positives in this fashion.
It gets to *70,000,000* false-positives pretty fast but then slows down considerably as the numbers grow.
Compile with `g++ flspos.cpp -oflspos -std=c++11 -msse2 -mfpmath=sse -O3`.
To verify the results, add `-DVERIFY` (this will be notably slower.)
Run with `flspos`. Any command-line argument for verbose mode.
```
#include <cstdio>
#include <cmath>
#include <cfloat>
using namespace std;
/* Make sure we actually work with 64-bit precision */
#if defined(VERIFY) && FLT_EVAL_METHOD != 0 && FLT_EVAL_METHOD != 1
# error "invalid FLT_EVAL_METHOD (did you forget `-msse2 -mfpmath=sse'?)"
#endif
template <typename T> inline long long sqr(T x) { return 1ll * x * x; }
template <typename T>
T gcd(T a, T b) { while (b) { T t = a; a = b; b = t % b; } return a; }
int main(int argc, const char* argv[]) {
const bool verbose = argc > 1;
const int min = 1 << 26;
const int max = sqrt(1ll << 53);
int found = 0;
auto add = [=, &found] (int x1, int y1, int x2, int y2) {
#ifdef VERIFY
auto n1 = sqr(x1) + sqr(y1), n2 = sqr(x2) + sqr(y2);
if (n1 == n2 || sqrt(n1) != sqrt(n2)) {
fprintf(stderr, "Wrong false-positive: (%d, %d) (%d, %d)\n",
x1, y1, x2, y2);
return;
}
#endif
if (verbose) printf("(%d, %d) (%d, %d)\n", x1, x2, y1, y2);
++found;
};
for (int x = min; x <= max; ++x) add(x, 0, x, 1);
for (int a = 1; a < max; ++a) {
auto a2b2 = sqr(a) + 1;
for (int b = 1; b <= a; a2b2 += 2 * b + 1, ++b) {
int c = sqrt(a2b2);
if (a2b2 == sqr(c) && gcd(a, b) == 1) {
int max_c = max / c;
for (int n = (min + c - 1) / c; n <= max_c; ++n)
add(n * a, n * b, n * c, 1);
}
}
if (a % 512 == 0) printf("%d\n", found), fflush(stdout);
}
printf("%d\n", found);
}
```
[Answer]
## C++, 275,000,000+
We'll refer to pairs whose magnitude is accurately representable, such as *(x, 0)*, as *honest pairs* and to all other pairs as *dishonest pairs* of magnitude *m*, where *m* is the pair's wrongly-reported magnitude.
The first program in [the previous post](https://codegolf.stackexchange.com/a/37671/31403) used a set of tightly related couples of honest- and dishonest-pairs:
*(x, 0)* and *(x, 1)*, respectively, for large enough *x*.
The second program used the same set of dishonest pairs but extended the set of honest pairs by looking for all honest pairs of integral magnitude.
The program doesn't terminate within ten minutes, but it finds the vast majority of its results very early on, which means that most of the runtime goes to waste.
Instead of keep looking for ever-less-frequent honest pairs, this program uses the spare time to do the next logical thing: extending the set of *dishonest* pairs.
From the previous post we know that for all large-enough integers *r*, *sqrt(r2 + 1) = r*, where *sqrt* is the floating-point square root function.
Our plan of attack is to find pairs *P = (x, y)* such that *x2 + y2 = r2 + 1* for some large-enough integer *r*.
That's simple enough to do, but naively looking for individual such pairs is too slow to be interesting.
We want to find these pairs in bulk, just like we did for honest pairs in the previous program.
Let *{**v**, **w**}* be an orthonormal pair of vectors.
For all real scalars *r*, *||r **v** + **w**||2 = r2 + 1*.
In *ℝ2*, this is a direct result of the Pythagorean theorem:

We're looking for vectors ***v*** and ***w*** such that there exists an *integer* *r* for which *x* and *y* are also integers.
As a side note, note that the set of dishonest pairs we used in the previous two programs was simply a special case of this, where *{**v**, **w**}* was the standard basis of *ℝ2*; this time we wish to find a more general solution.
This is where Pythagorean triplets (integers triplets *(a, b, c)* satisfying *a2 + b2 = c2*, which we used in the previous program) make their comeback.
Let *(a, b, c)* be a Pythagorean triplet.
The vectors ***v*** = (b/c, a/c) and ***w*** = (-a/c, b/c) (and also
***w*** = (a/c, -b/c)) are orthonormal, as is easy to verify.
As it turns out, for any choice of Pythagorean triplet, there exists an integer *r* such that *x* and *y* are integers.
To prove this, and to effectively find *r* and *P*, we need a little number/group theory; I'm going to spare the details.
Either way, suppose we have our integral *r*, *x* and *y*.
We're still short of a few things: we need *r* to be large enough and we want a fast method to derive many more similar pairs from this one.
Fortunately, there's a simple way to accomplish this.
Note that the projection of *P* onto ***v*** is *r **v***, hence *r = P **·** **v** = (x, y) **·** (b/c, a/c) = xb/c + ya/c*, all this to say that *xb + ya = rc*.
As a result, for all integers *n*, *(x + bn)2 + (y + an)2 = (x2 + y2) + 2(xb + ya)n + (a2 + b2)n2 = (r2 + 1) + 2(rc)n + (c2)n2 = (r + cn)2 + 1*.
In other words, the squared magnitude of pairs of the form
*(x + bn, y + an)* is *(r + cn)2 + 1*, which is exactly the kind of pairs we're looking for!
For large enough *n*, these are dishonest pairs of magnitude *r + cn*.
It's always nice to look at a concrete example.
If we take the Pythagorean triplet *(3, 4, 5)*, then at *r = 2* we have *P = (1, 2)* (you can check that *(1, 2) **·** (4/5, 3/5) = 2* and, clearly, *12 + 22 = 22 + 1*.)
Adding *5* to *r* and *(4, 3)* to *P* takes us to *r' = 2 + 5 = 7* and *P' = (1 + 4, 2 + 3) = (5, 5)*.
Lo and behold, *52 + 52 = 72 + 1*.
The next coordinates are *r'' = 12* and *P'' = (9, 8)*, and again, *92 + 82 = 122 + 1*, and so on, and so on ...

Once *r* is large enough, we start getting dishonest pairs with magnitude increments of *5*.
That's roughly *27,797,402 / 5* dishonest pairs.
So now we have plenty of integral-magnitude dishonest pairs.
We can easily couple them with the honest pairs of the first program to form false-positives, and with due care we can also use the honest pairs of the second program.
This is basically what this program does.
Like the previous program, it too finds most of its results very early on---it gets to 200,000,000 false positives within a few seconds---and then slows down considerably.
Compile with `g++ flspos.cpp -oflspos -std=c++11 -msse2 -mfpmath=sse -O3`.
To verify the results, add `-DVERIFY` (this will be notably slower.)
Run with `flspos`. Any command-line argument for verbose mode.
```
#include <cstdio>
#define _USE_MATH_DEFINES
#undef __STRICT_ANSI__
#include <cmath>
#include <cfloat>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
/* Make sure we actually work with 64-bit precision */
#if defined(VERIFY) && FLT_EVAL_METHOD != 0 && FLT_EVAL_METHOD != 1
# error "invalid FLT_EVAL_METHOD (did you forget `-msse2 -mfpmath=sse'?)"
#endif
template <typename T> struct widen;
template <> struct widen<int> { typedef long long type; };
template <typename T>
inline typename widen<T>::type mul(T x, T y) {
return typename widen<T>::type(x) * typename widen<T>::type(y);
}
template <typename T> inline T div_ceil(T a, T b) { return (a + b - 1) / b; }
template <typename T> inline typename widen<T>::type sq(T x) { return mul(x, x); }
template <typename T>
T gcd(T a, T b) { while (b) { T t = a; a = b; b = t % b; } return a; }
template <typename T>
inline typename widen<T>::type lcm(T a, T b) { return mul(a, b) / gcd(a, b); }
template <typename T>
T div_mod_n(T a, T b, T n) {
if (b == 0) return a == 0 ? 0 : -1;
const T n_over_b = n / b, n_mod_b = n % b;
for (T m = 0; m < n; m += n_over_b + 1) {
if (a % b == 0) return m + a / b;
a -= b - n_mod_b;
if (a < 0) a += n;
}
return -1;
}
template <typename T> struct pythagorean_triplet { T a, b, c; };
template <typename T>
struct pythagorean_triplet_generator {
typedef pythagorean_triplet<T> result_type;
private:
typedef typename widen<T>::type WT;
result_type p_triplet;
WT p_c2b2;
public:
pythagorean_triplet_generator(const result_type& triplet = {3, 4, 5}) :
p_triplet(triplet), p_c2b2(sq(triplet.c) - sq(triplet.b))
{}
const result_type& operator*() const { return p_triplet; }
const result_type* operator->() const { return &p_triplet; }
pythagorean_triplet_generator& operator++() {
do {
if (++p_triplet.b == p_triplet.c) {
++p_triplet.c;
p_triplet.b = ceil(p_triplet.c * M_SQRT1_2);
p_c2b2 = sq(p_triplet.c) - sq(p_triplet.b);
} else
p_c2b2 -= 2 * p_triplet.b - 1;
p_triplet.a = sqrt(p_c2b2);
} while (sq(p_triplet.a) != p_c2b2 || gcd(p_triplet.b, p_triplet.a) != 1);
return *this;
}
result_type operator()() { result_type t = **this; ++*this; return t; }
};
int main(int argc, const char* argv[]) {
const bool verbose = argc > 1;
const int min = 1 << 26;
const int max = sqrt(1ll << 53);
const size_t small_triplet_count = 1000;
vector<pythagorean_triplet<int>> small_triplets;
small_triplets.reserve(small_triplet_count);
generate_n(
back_inserter(small_triplets),
small_triplet_count,
pythagorean_triplet_generator<int>()
);
int found = 0;
auto add = [&] (int x1, int y1, int x2, int y2) {
#ifdef VERIFY
auto n1 = sq(x1) + sq(y1), n2 = sq(x2) + sq(y2);
if (x1 < y1 || x2 < y2 || x1 > max || x2 > max ||
n1 == n2 || sqrt(n1) != sqrt(n2)
) {
fprintf(stderr, "Wrong false-positive: (%d, %d) (%d, %d)\n",
x1, y1, x2, y2);
return;
}
#endif
if (verbose) printf("(%d, %d) (%d, %d)\n", x1, y1, x2, y2);
++found;
};
int output_counter = 0;
for (int x = min; x <= max; ++x) add(x, 0, x, 1);
for (pythagorean_triplet_generator<int> i; i->c <= max; ++i) {
const auto& t1 = *i;
for (int n = div_ceil(min, t1.c); n <= max / t1.c; ++n)
add(n * t1.b, n * t1.a, n * t1.c, 1);
auto find_false_positives = [&] (int r, int x, int y) {
{
int n = div_ceil(min - r, t1.c);
int min_r = r + n * t1.c;
int max_n = n + (max - min_r) / t1.c;
for (; n <= max_n; ++n)
add(r + n * t1.c, 0, x + n * t1.b, y + n * t1.a);
}
for (const auto t2 : small_triplets) {
int m = div_mod_n((t2.c - r % t2.c) % t2.c, t1.c % t2.c, t2.c);
if (m < 0) continue;
int sr = r + m * t1.c;
int c = lcm(t1.c, t2.c);
int min_n = div_ceil(min - sr, c);
int min_r = sr + min_n * c;
if (min_r > max) continue;
int x1 = x + m * t1.b, y1 = y + m * t1.a;
int x2 = t2.b * (sr / t2.c), y2 = t2.a * (sr / t2.c);
int a1 = t1.a * (c / t1.c), b1 = t1.b * (c / t1.c);
int a2 = t2.a * (c / t2.c), b2 = t2.b * (c / t2.c);
int max_n = min_n + (max - min_r) / c;
int max_r = sr + max_n * c;
for (int n = min_n; n <= max_n; ++n) {
add(
x2 + n * b2, y2 + n * a2,
x1 + n * b1, y1 + n * a1
);
}
}
};
{
int m = div_mod_n((t1.a - t1.c % t1.a) % t1.a, t1.b % t1.a, t1.a);
find_false_positives(
/* r = */ (mul(m, t1.c) + t1.b) / t1.a,
/* x = */ (mul(m, t1.b) + t1.c) / t1.a,
/* y = */ m
);
} {
int m = div_mod_n((t1.b - t1.c % t1.b) % t1.b, t1.a, t1.b);
find_false_positives(
/* r = */ (mul(m, t1.c) + t1.a) / t1.b,
/* x = */ m,
/* y = */ (mul(m, t1.a) + t1.c) / t1.b
);
}
if (output_counter++ % 50 == 0)
printf("%d\n", found), fflush(stdout);
}
printf("%d\n", found);
}
```
[Answer]
# C++11 - 100,993,667
### EDIT: New program.
The old one used too much memory. This one halves the memory usage by using a giant vector array instead of a hash table. Also it removes the random thread cruft.
```
/* by feersum 2014/9
http://codegolf.stackexchange.com/questions/37627/false-positives-on-an-integer-lattice */
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <vector>
using namespace std;
#define ul unsigned long long
#define K const
#define INS(A) { bool already = false; \
for(auto e = res[A.p[0][0]].end(), it = res[A.p[0][0]].begin(); it != e; ++it) \
if(A.p[0][1] == it->y1 && A.p[1][0] == it->x2 && A.p[1][1] == it->y2) { \
already = true; \
break; } \
if(!already) res[A.p[0][0]].push_back( {A.p[0][1], A.p[1][0], A.p[1][1]} ), ++n; }
#define XMAXMIN (1<<26)
struct ints3 {
int y1, x2, y2;
};
struct pparm {
int a,b,c,d;
int E[4];
pparm(int A,int B,int C, int D):
E{B*B+D*D,A*B+C*D,A*A+C*C+2*(B+D),A+C}
{
a=A;b=B;c=C;d=D;
}
};
struct ans {
int p[2][2];
};
ostream&operator<<(ostream&o, ans&a)
{
o<<'('<<a.p[0][0]<<','<<a.p[0][1]<<"),("<<a.p[1][0]<<','<<a.p[1][1]<<')'<<endl;
return o;
}
vector<ints3> res[XMAXMIN];
bool print;
int n;
void gen(K pparm&p1, K pparm&p2)
{
#ifdef DBUG
for(int i=0;i<2;i++){
K pparm&p=i?p2:p1;
cout<<' '<<p.a<<' '<<p.b<<' '<<p.c<<' '<<p.d<<' ';}
cout<<endl;
#endif
for(ul x = 0; ; ++x) {
ans a;
ul s[2];
for(int i = 0; i < 2; i++) {
K pparm &p = i?p2:p1;
int *pt = a.p[i];
pt[0] = p.b+x*(p.a+x);
pt[1] = p.d+x*(p.c+x);
s[i] = (ul)pt[0]*pt[0] + (ul)pt[1]*pt[1];
}
if(*s >> 53)
break;
if(s[1] - s[0] != 1)
exit(4);
if(sqrt(s[0]) == sqrt(s[1])) {
for(int i = 0; i < 2; i++)
if(a.p[i][0] > a.p[i][1])
swap(a.p[i][0], a.p[i][1]);
if(a.p[0][0] > a.p[0][1])
for(int i = 0; i < 2; i++)
swap(a.p[0][i], a.p[1][i]);
INS(a)
}
}
}
int main(int ac, char**av)
{
for(int i = 1; i < ac; i++) {
print |= !strcmp(av[1], "-P");
}
#define JMAX 43000000
for(ul j = 0; j < JMAX; j++) {
pparm p1(-~j,j,~-j,0),p2(j,1,j,j);
gen(p1,p2);
if(!print && !(j%1024))
#ifdef DBUG
cout<<j<<' ',
#endif
cout<<n<<endl;
}
if(print)
for(vector<ints3>& v: res)
for(ints3& i: v)
printf("(%d,%d),(%d,%d)\n", &v - res, i.y1, i.x2, i.y2);
return 0;
}
```
Run with a `-P` argument to print out the points instead of the number thereof.
For me it takes under 2 minutes in the counting mode and about 5 minutes with printing directed to a file (~4 GB), so it did not quite become I/O limited.
My original program was neat, but I dropped most of it since it only could produce on the order of 10^5 results. What it did is to look for parameterizations of the form (x^2+Ax+B, x^2+Cx+D), (x^2+ax+b, x^2+cx+d) such that for any x, (x^2+Ax+B)^2 + (x^2+Cx+D)^2 = (x^2+ax+b)^2 + (x^2+cx+d)^2 + 1. When it found such a set of parameters {a,b,c,d,A,B,C,D} it proceeded to check all of the x values under the maximum. While looking at my debug output from this program, I noticed a certain parameterization of the parameterization of the parameterization that allowed me to produce a lot of numbers easily. I elected not to print out Ell's numbers since I had plenty of my own. Hopefully now someone won't print out both of our sets of numbers and claim to be the winner :)
```
/* by feersum 2014/9
http://codegolf.stackexchange.com/questions/37627/false-positives-on-an-integer-lattice */
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <unordered_set>
#include <thread>
using namespace std;
#define ul unsigned long long
#define h(S) unordered_##S##set
#define P 2977953206964783763LL
#define K const
#define EQ(T, F)bool operator==(K T&o)K{return!memcmp(F,o.F,sizeof(F));}
struct pparm {
int a,b,c,d;
int E[4];
pparm(int A,int B,int C, int D):
E{B*B+D*D,A*B+C*D,A*A+C*C+2*(B+D),A+C}
{
a=A;b=B;c=C;d=D;
}
EQ(pparm,E)
};
struct ans {
int p[2][2];
EQ(ans,p)
};
ostream&operator<<(ostream&o, ans&a)
{
o<<'('<<a.p[0][0]<<','<<a.p[0][1]<<"),("<<a.p[1][0]<<','<<a.p[1][1]<<')'<<endl;
return o;
}
#define HASH(N,T,F) \
struct N { \
size_t operator() (K T&p) K { \
size_t h = 0; \
for(int i = 4; i--; ) \
h=h*P+((int*)p.F)[i]; \
return h; \
}};
#define INS(r, a) { \
bool new1 = r.insert(a).second; \
n += new1; \
if(print && new1) \
cout<<a; }
HASH(HA,ans,p)
bool print;
int n;
void gen(h()<ans,HA>&r, K pparm&p1, K pparm&p2)
{
#ifdef DBUG
for(int i=0;i<2;i++){
K pparm&p=i?p2:p1;
cout<<' '<<p.a<<' '<<p.b<<' '<<p.c<<' '<<p.d<<' ';}
cout<<endl;
#endif
for(ul x = 0; ; ++x) {
ans a;
ul s[2];
for(int i = 0; i < 2; i++) {
K pparm &p = i?p2:p1;
int *pt = a.p[i];
pt[0] = p.b+x*(p.a+x);
pt[1] = p.d+x*(p.c+x);
s[i] = (ul)pt[0]*pt[0] + (ul)pt[1]*pt[1];
}
if(*s >> 53)
break;
if(s[1] - s[0] != 1)
exit(4);
if(sqrt(s[0]) == sqrt(s[1])) {
for(int i = 0; i < 2; i++)
if(a.p[i][0] > a.p[i][1])
swap(a.p[i][0], a.p[i][1]);
INS(r,a)
}
}
//if(!print) cout<<n<<endl;
}
void endit()
{
this_thread::sleep_for(chrono::seconds(599));
exit(0);
}
int main(int ac, char**av)
{
bool kill = false;
for(int i = 1; i < ac; i++) {
print |= ac>1 && !stricmp(av[1], "-P");
kill |= !stricmp(av[i], "-K");
}
thread KILLER;
if(kill)
KILLER = thread(endit);
h()<ans, HA> res;
res.reserve(1<<27);
#define JMAX 43000000
for(ul j = 0; j < JMAX; j++) {
pparm p1(-~j,j,~-j,0),p2(j,1,j,j);
gen(res,p1,p2);
if(!print && !(j%1024))
#ifdef DBUG
cout<<j<<' ',
#endif
cout<<n<<endl;
}
exit(0);
}
```
[Answer]
## Java, Bresenham-esque circle scan
Heuristically I expect to get more collisions by starting at the wider end of the annulus. I expected to get some improvement by doing one scan for each collision, recording values for which `surplus` is between `0` and `r2max - r2` inclusive, but in my testing that proved slower than this version. Similarly attempts to use a single `int[]` buffer rather than lots of creation of two-element arrays and lists. Performance optimisation is a strange beast indeed.
Run with a command-line argument for output of the pairs, and without for simple counts.
```
import java.util.*;
public class CodeGolf37627 {
public static void main(String[] args) {
final int M = 144;
boolean[] possible = new boolean[M];
for (int i = 0; i <= M/2; i++) {
for (int j = 0; j <= M/2; j++) {
possible[(i*i+j*j)%M] = true;
}
}
long count = 0;
double sqrt = 0;
long r2max = 0;
List<int[]> previousPoints = null;
for (long r2 = 1L << 53; ; r2--) {
if (!possible[(int)(r2 % M)]) continue;
double r = Math.sqrt(r2);
if (r != sqrt) {
sqrt = r;
r2max = r2;
previousPoints = null;
}
else {
if (previousPoints == null) previousPoints = findLatticePointsBresenham(r2max, (int)r);
if (previousPoints.size() == 0) {
r2max = r2;
previousPoints = null;
}
else {
List<int[]> points = findLatticePointsBresenham(r2, (int)r);
for (int[] p1 : points) {
for (int[] p2 : previousPoints) {
if (args.length > 0) System.out.format("(%d, %d) (%d, %d)\n", p1[0], p1[1], p2[0], p2[1]);
count++;
}
}
previousPoints.addAll(points);
System.out.println(count);
}
}
}
}
// Surprisingly, this seems to be faster than doing one scan for all two or three r2s.
private static List<int[]> findLatticePointsBresenham(long r2, long r) {
List<int[]> rv = new ArrayList<int[]>();
// Require 0 = y = x
long x = r, y = 0, surplus = r2 - r * r;
while (y <= x) {
if (surplus == 0) rv.add(new int[]{(int)x, (int)y});
// Invariant: surplus = r2 - x*x - y*y >= 0
y++;
surplus -= 2*y - 1;
if (surplus < 0) {
x--;
surplus += 2*x + 1;
}
}
return rv;
}
}
```
[Answer]
## Java - 27,817,255
Most of these are the same as what [Ell shows](https://codegolf.stackexchange.com/a/37671/14215), and the rest are based on `(j,0) (k,l)`. For each `j`, I walk back some squares and check if the remainder gives a false positive. This takes up basically the entire time with only a 25k (about 0.1%) gain over just `(j,0) (j,1)`, but a gain is a gain.
This will finish in under ten minutes on my machine, but I don't know what you have. Because reasons, if it *doesn't* finish before the time runs out, it will have a drastically worse score. In that case, you can tweak the divisor on line 8 so that it finishes in time (this simply determines how far back it walks for each `j`). For some various divisors, scores are:
```
11 27817255 (best on OPs machine)
10 27818200
8 27820719
7 27822419 (best on my machine)
```
To turn on output for each match (and, god, it is slow if you do), just uncomment lines 10 and 19.
```
public class FalsePositive {
public static void main(String[] args){
long j = 67108864;
long start = System.currentTimeMillis();
long matches=0;
while(j < 94906265 && System.currentTimeMillis()-start < 599900){
long jSq = j*j;
long limit = (long)Math.sqrt(j)/11; // <- tweak to fit inside 10 minutes for best results
matches++; // count an automatic one for (j,0)(j,1)
//System.out.println("("+j+",0) ("+j+",1)");
for(int i=1;i<limit;i++){
long k = j-i;
long kSq = k*k;
long l = (long)Math.sqrt(jSq-kSq);
long lSq = l*l;
if(kSq+lSq != jSq){
if(Math.sqrt(kSq+lSq)==Math.sqrt(jSq)){
matches++;
//System.out.println("("+j+",0) ("+k+","+l+")");
}
}
}
j++;
}
System.out.println("\n"+matches+" Total matches, got to j="+j);
}
}
```
For reference, the first 20 outputs it gives (for divisor=7, excluding `(j,0)(j,1)` types) are:
```
(67110083,0) (67109538,270462)
(67110675,0) (67109990,303218)
(67111251,0) (67110710,269470)
(67111569,0) (67110668,347756)
(67112019,0) (67111274,316222)
(67112787,0) (67111762,370918)
(67115571,0) (67115518,84346)
(67117699,0) (67117698,11586)
(67117971,0) (67117958,41774)
(67120545,0) (67120040,260368)
(67121043,0) (67120118,352382)
(67122345,0) (67122320,57932)
(67122449,0) (67122444,25908)
(67122633,0) (67122328,202348)
(67122729,0) (67121972,318784)
(67122849,0) (67122568,194224)
(67124195,0) (67123818,224970)
(67125201,0) (67125172,62396)
(67125705,0) (67124632,379540)
(67126195,0) (67125882,204990)
```
[Answer]
## Julia, 530 false positives
Here is a very naive brute force search, which you can view as a reference implementation.
```
num = 0
for i = 60000000:-1:0
for j = i:-1:ifloor(0.99*i)
s = i*i + j*j
for x = ifloor(sqrt(s/2)):ifloor(sqrt(s))
min_y = ifloor(sqrt(s - x*x))
max_y = min_y+1
for y = min_y:max_y
r = x*x + y*y
if r != s && sqrt(r) == sqrt(s)
num += 1
if num % 10 == 0
println("Found $num pairs")
end
#@printf("(i,j) = (%d,%d); (x,y) = (%d,%d); s = %d, r = %d\n", i,j,x,y,s,r)
end
end
end
end
end
```
You can print out the pairs (and their exact squared magnitudes) by uncommenting the `@printf` line.
Basically this starts the search at `x = y = 6e7` for the first coordinate pair and scans down about 1% of the way to the x-axis before decrementing x. Then for each such coordinate pair, it checks the entire arc of the same magnitude (rounding up and down) for a collision.
The code assumes that it's run on a 64-bit system, so that the default integer and floating-point types are 64-bit ones (if not, you can create them with `int64()` and `float64()` constructors).
That yields a meagre 530 results.
] |
[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/28714/edit).
Closed last month.
[Improve this question](/posts/28714/edit)
Many of you already know [JSF\*\*k](http://www.jsfuck.com/). For those who don't, it's a script that basically turns any JavaScript code into something written using only `[]()!+`.
Your task is to build, using any language of your choice, a program which converts JSF\*\*k into unobfuscated JavaScript.
* **Input**: A string with valid JSF\*\*k code.
* **Output**: A string with the regular JavaScript code that has been previously JSF\*\*ked to generate the input.
For this challenge, consider that the input string has only been JSF\*\*ked once.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") contest, so the shortest code, in bytes, wins.
[Answer]
# Javascript - 68 55 51
```
alert(/\n(.+)/.exec(eval(prompt().slice(0,-2)))[1])
```
Alternatively: (same length)
```
alert(/.+(?=\n})/.exec(eval(prompt().slice(0,-2))))
```
Runs in the console of your browser. Only guaranteed to work with code generated by jsfuck.com with the 'Eval Source' option ticked.
Ungolfed:
```
alert(
/\n(.+)/.exec( // regex to extract code from inside outer function braces {}
eval(prompt().slice(0,-2)) // remove the final set of parens () and evaluate the code
// this results in a function, which will be converted to a string as 'exec' expects a string
)[1] // get the first capture group
)
```
[Answer]
# JavaScript, 122, works with any input
```
s=prompt().slice(0,-2)
i=s.length
while(i--){if((l=s.slice(i)).split(')').length==l.split('(').length)break}alert(eval(l))
```
Pretty simple; it just goes back in the string until the parentheses (`(` and `)`) are balanced. The last three characters of the JSF output are *always* `)()`, so slicing off the last 2 parens and then finding the matching paren for the other will always work. (It works with input with `[]` too.)
] |
[Question]
[
This is a basic version of the rather more difficult [Drawing 3d nets - Archimedean solids](https://codegolf.stackexchange.com/questions/10660/drawing-3d-nets-archimedean-solids) .
I have a weakness for 3d nets which when cut out and folded allow you to make 3d shapes out of paper or card. The task is simple, write the shortest program you can that draws nets for the 5 Platonic solids. The output should be an image file in any sensible format of your choosing (png, jpg, etc.).
All five shapes are described at <http://en.wikipedia.org/wiki/Platonic_solid> . Their nets looks like this (taken from <http://www.newscientist.com/gallery/unfolding-the-earth/2> ).

**Input:** An integer from 1 to 5. Assume the shapes are numbered in order of the number of sides they have. So, 1 would be a tetrahedron and 5 the icosahedron.
**Output:** An image file containing the net for that shape. Just the outline including the internal lines is OK. There is no need to fill it in with colors
You can use any programming language you like as well as any library that was not made especially for this competition. Both should be available freely however (in both senses) online.
I will accept the answer with the smallest number of characters in exactly one week's time.
**Winner.** Only one entrant but it was wonderful. The winner is ... Raufio for what is my favourite piece of code golf ever.
[Answer]
## Python, 456 429 381
```
import turtle as t
L="fl"
R="fr"
d=L*3+R*3
b=(d+R)*3
a=[b,120,L*3+"fflflffflflfrflflfffl"+R*4+"flf",90,b+"ffrfrflffrffrfrfrflflf",120,(R*5+L*5+R+L)*5+"rrfr"+L*5+R*2+L*2+R*4+"f",72,(d+"f")*5+"rfl"+((d+"b")*5)[:-1],120]
l=t.lt
f=t.fd
b=t.bk
r=t.rt
p=input()*2-2
t.setup(.9,.9)
t.goto(-200,150)
t.clear()
for c in a[p]:exec c+"(a[p+1])"
t.getscreen().getcanvas().postscript(file="o")
```
I implemented a primitive interpreter with `l r f b` as operators that move the turtle cursor around at the angle of the shapes. At one time, it turns only one angle. I compressed the strings by reusing strings (kind of like psuedo-subroutines), other than that, I didn't check to see if I was using the best path. It outputs to a postscript file.
A little explanation of un-golfed code:
```
import turtle as t
Left="fl"
Right="fr"
diamond= Left*3 + Right*3
tetrahedron=(d+R)*3 #used to be b
```
Imports the built-in turtle module and defines the macros that shorten the strings. The turtle module uses commands to move a 'turtle' around the screen (ie forward(100), left(90))
```
netList=[
#tetrahedron
tetrahedron,120,
#cube
Left*3+"fflflffflflfrflflfffl"+Right*4+"flf",90,
#octohedron, builds off the tetrahedron
tetrahedron+"ffrfrflffrffrfrfrflflf",120,
#dodecahedron
(Right*5 + Left*5 + Right + Left)*5
+"rrfr"+
Left*5 + Right*2 + Left*2 + Right*4 + "f",72,
#icosahedron
(diamond+"f")*5 +"rfl"+((diamond+"b")*5)[:-1],120
]
```
This list holds the angles and movement sequences. The tetrahedron was saved to reuse with the octohedren.
```
l=t.left
f=t.forward
b=t.back
r=t.right
```
This is the part that i like, it makes single character local functions so the calls can be shortened and automated through pre-defined strings.
```
input=int(raw_input())*2-2
t.setup(.9,.9)
t.goto(-200,150)
t.clear()
```
This starts by taking the input (between 1 and 5), and converting that to an index that points to the shape string in the netList. These setup turtle to show the whole net. These could be left out if the task was just to draw them, but since we need a picture output they are needed.
```
for command in netList[input]:
exec command+"(netList[input+1])"
t.getscreen().getcanvas().postscript(file="o")
```
The for loop takes the commands in the command sequence string and executes them, so for a string like "fl", this executes "forward(angle);left(angle);" by calling the newly created local functions. the last line outputs a file called 'o' that is in postscript format format using turtle function.
**To run**:
Copy it into a file and run it from there. When you run it, it will wait for a number input between 1 and 5 (i just changed it so that it asks before setting up turtle). When you input a number, a window pops up and draws the net. if you want it to go faster you can add `t.speed(200)` before `setup`.
You can copy-paste it into the interpreter, but when `raw_input()` is called it consumes the next string you input `"t.setup(.9,.9)"` instead of a number. So if you do this, copy up until `raw_input()`, input a number, than copy paste the rest. It is intended to be run as a whole. Or you could copy it into a function and call it.
Here are it's outputs (converted from postscript):
Note: the position of these in the window has changed, but their overall shape is the same.





It's a little brute force for code golf, but I got tired of trying to find a consistent pattern between the shapes.
[Answer]
## Mathematica
Out of competition, not a free language (unless a [free trial](http://www.wolfram.com/mathematica/trial/) counts as free)
```
f[n_] := PolyhedronData[ Sort[PolyhedronData["Platonic", {"FaceCount","StandardName"}]][[n,2]],
"NetImage"]
```
Usage:
```
f /@ Range@5
```

[Answer]
# Python 2 (with cairo) - 239
```
from cairo import*
s=PSSurface(None,99,99)
g=Context(s)
g.move_to(30,20)
a=str([34,456,3455,568788,3454445555][input()-1])
f=6.28
for c in a+a[::-1]:exec'g.rel_line_to(8,0);g.rotate(f/int(a[0]));'*int(c);f=-f
g.stroke()
s.write_to_png('o')
```
Results:

[Answer]
# Logo, 199 bytes
```
TO p:d:n:s
rt :n*45 for[i 1 :n/8][pu setxy :d*:i 0 pd repeat 2[for[k 1 :s*2+2][fd 40 rt (360-720*(:k>:s))/:s] rt 720/:s]]END
TO q:j
apply "p item :j [[70 9 3][56 23 4][70 16 3][105 26 5][40 42 3]]END
```
Reading this back I see my original version did not comply with the spec as written (take a numerical argument and draw one shape) but rather as interpreted by some of the other answers (draw all shapes.) The new version fixes this. It expects to be called as for example `q 5`. `cs` should be done before to clear the screen and point the turtle north.
`q` calls the main function `p` with 3 arguments. The syntax for this is pretty bloated, so to beat my previous score I had to shave off bytes elsewhere.
the new version of `p` takes 3 arguments. There is no need for `x` and `y` because we only plot one net, but `d` the pitch between subunits remains. `s`
is still the number of sides per polygon, and `n` now encodes for two different things> `n/8` is the number of subunits to be plotted, and `n*45` is an angle through which the turtle must be turned before starting (taking advantage of the natural mod 360 for rotations.)
Improved looping accomplishes drawing `s` lines with righthand rotation and `s+2` lines with lefthand rotation in a single loop.
the calormen interpreter seems to be less tolerant of missing whitespace now than at the time of my first post, but the code runs fine on <http://turtleacademy.com/playground/en>
# Logo, 200 bytes
```
TO p:x:y:d:n:s
for[i 1:n][pu setxy:x:y-:d*:i if:i<>6[pd]repeat 2[repeat:s[fd 40 rt 360/:s]repeat:s+2[fd 40 lt 360/:s]rt 720/:s]]END
p 0 200 40 7 3
p 70 0 80 2 3
p -200 200 105 3 5
rt 45
p 90 90 56 2 4
```
Interpreter at <http://www.calormen.com/jslogo/#> It is assumed the turtle is pointing North before the program is run. Use the `cs` command to clear the screen, point the turtle north, and place it at the origin in the centre of the screen.
[](https://i.stack.imgur.com/SuM2H.png)
The basic unit of all the above nets is a pair of back to back polygons. These are arranged in 2 staggered rows, making a subunit of 4 polygons which can be translated vertically to make all the nets (except the octahedron, which hitches a ride on the drawing of the icosahedron and tetrahedron). The subunit forms 1 tetrahedron net, 1/5 of the icosahedron net, 1/3 of the dodecahedron net and 2/3 of the cube net (two subunits are drawn, with the middle two squares overlapping.)
**Ungolfed code**
```
TO p :x :y :d :n :s ;x,y=starting point d=negative vertical offset for each iteration n=#of iterations s=# of sides on polygon
for[i 1 :n][ ;iterate n times
pu ;pen up
setxy :x :y- :d* :i ;move pen to start of iteration
if :i<>6[pd] ;pen down (supressed for i=6 to enable part of octahedron to be drawn with icosahedron)
repeat 2[ ;draw lower row of 2 polygons, then upper row of 2 polygons
repeat :s[fd 40 rt 360/ :s] ;starting at lower left of polygon facing up, draw righthand polygon
repeat :s+2[fd 40 lt 360/ :s] ;starting at lower right of polygon facing up, draw lefthand polygon, duplicating last two sides
rt 720/ :s ;return turtle to upwards facing in order to draw second row
]
]
END
cs
p 0 200 40 7 3 ;draw icosahedron and left side of octahedron (6th iteration is suppressed)
p 70 0 80 2 3 ;draw right side of octahedron, and tetrahedron
p -200 200 105 3 5 ;draw dodecahedron
rt 45 ;turn turtle in preparation for drawing cube
p 90 90 56 2 4 ;draw cube
```
] |
[Question]
[
You are given a [Bingo](http://en.wikipedia.org/wiki/Bingo_%28U.S.%29) board and a list of calls. You must print BINGO! as soon as your board wins the game.
Bingo boards look like this:

They will be specified like this:
```
14 29 38 52 74
4 18 33 46 62
7 16 * 60 71
9 27 44 51 67
12 23 35 47 73
```
Immediately following the board will be calls, like this:
```
B7
I29
G60
G51
O71
I23
I16
N38
```
You must echo the calls out to standard output until just after the call that makes you win (get a row, column, or 5-long diagonal all filled), then print `BINGO!`.
For the above example, print:
```
B7
I29
G60
G51
O71
I23
I16
BINGO!
```
**Rules**
Standard code-golf rules, shortest code wins.
**Details**
There will always be enough calls to guarantee you a Bingo. There will be no duplicate numbers on the board, and no duplicate calls. Boards will always have correctly matched numbers and letters (the `B` column contains only 1-15, the `I` column contains only 16-30, and so on), as will calls. The one and only free space will always be in the middle, marked with `*` instead of a number. Consuming and discarding calls from standard input after the winning call is allowed, but not required.
[Make your own test cases!](https://codegolf.stackexchange.com/questions/2631/bingo-card-generator)
[Answer]
## C# – 536
(OK, this is probably not the most suitable language for that, but anyway…)
```
using System;using System.Collections.Generic;using System.Linq;class C{static void Main(){var s=Enumerable.Range(1,12).Select(_=>new HashSet<string>()).ToList();var b=Enumerable.Range(1,5).Select(_=>Console.ReadLine().Split(' ')).ToList();int i;for(i=0;i<5;++i){for(int j=0;j<5;++j){s[i].Add(b[i][j]);s[i+5].Add(b[j][i]);}s[10].Add(b[i][i]);s[11].Add(b[4-i][i]);}while(i>0){var l=Console.ReadLine();Console.WriteLine(l);l=l.Substring(1);foreach(var x in s){x.Remove("*");x.Remove(l);if(x.Count==0){Console.WriteLine("BINGO!");i=0;}}}}}
```
Formatted and commented:
```
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void Main()
{
// all possible winnable five-item sets – any one of them need to be emptied to win
var s = Enumerable.Range(1, 12).Select(_ => new HashSet<string>()).ToList();
// read the board from input to a list of arrays of numbers
var b = Enumerable.Range(1, 5).Select(_ => Console.ReadLine().Split(' ')).ToList();
int i;
// split the board into the winnable sets
for (i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
// sets 0–4 represent rows
s[i].Add(b[i][j]);
// sets 5–9 represent columns
s[i + 5].Add(b[j][i]);
}
// set 10 represent one diagonal
s[10].Add(b[i][i]);
// set 11 represent the other diagonal
s[11].Add(b[4 - i][i]);
}
while (i > 0)
{
// read and echo another input
var l = Console.ReadLine();
Console.WriteLine(l);
// ignore the initial letter – we are guaranteed it is correct, anyway
l = l.Substring(1);
// remove the number from all sets
foreach (var x in s)
{
x.Remove(l);
// also remove the center * (inside the loop just to shave off a few characters)
x.Remove("*");
// if any set became empty, we won!
if (x.Count == 0)
{
Console.WriteLine("BINGO!");
// ensure the loop will stop (might not be necessary per the rules, but anyway)
i = 0;
}
}
}
}
}
```
[Answer]
## Ruby 1.9 (194, 130)
This probably isn't the most sensible way to check for empty columns, but it was the first thing I thought to try! In particular, that `#transpose` costs a lot.
Either a blank line between the board and the numbers or fixed width fields when declaring the board would save a lot of characters. I couldn't think of a really nice way to read exactly 5 lines.
```
b=(R=0..4).map{gets}.join.scan /\d+|\*/
loop{gets
puts$_
~/\d+/
(e=b.index$&)&&b[e]=?*
R.map{|y|$><<:BINGO!&&exit if R.map{|x|[b[5*x+y],b[5*y+x],b[y<1?x*6:4*x+4]]}.transpose.any?{|a|a==[?*]*5}}}
```
**EDIT:** 130 character solution using the regular expression technique from mob's perl answer:
```
b=(0..4).map{gets}*'~ ~ '
loop{gets
puts$_
~/\d+/
b[/\b#$&\b/]=?*
7.times{|i|$><<:BINGO!&&exit if b=~/(\*\s(\S+\s){#{i}}){4}\*/m}}
```
[Answer]
*Given the long, long, long overdue announcement of Rebol's [impending release as open source software](http://www.rebol.com/article/0512.html), I returned to my pet dialect to solve [this Bingo problem](https://codegolf.stackexchange.com/questions/8501/code-golf-bingo/). I may soon be able to distribute Rebmu as its own, teensy GPL package. :)*
---
## [Rebmu](http://hostilefork.com/rebmu/) 88 characters
In the compact notation:
```
rtZ5[GisGpcRaZisGaAPgPCaSB6zAPv'*]l5[AgL5[apGfAsk+A5]]hd+Gu[raGin-NTrM'*fisGv5]p"BINGO!"
```
The dialect uses a trick I call *mushing* which is explained on the [Rebmu page](http://hostilefork.com/rebmu/). It's "legit" in the sense that it doesn't cheat the parser; this is valid Rebol...and can actually can be freely intermingled with ordinary code as well as (ahem) "long-form" Rebmu...which BTW would be 141 characters:
`[rt z 5 [g: is g pc r a z is g a ap g pc a sb 6 z ap v '*] l 5 [a: g l 5 [ap g f a sk+ a 5]] hd+ g u [ra g in- nt r m '* fis g v 5] p "BINGO!"]`
*(Given that I claim the compression is a trick that one can do without the help of automation or compilation, I actually develop the code in the mushed form. It's not difficult.)*
It's actually quite simple, nothing special--I'm sure other Rebol programmers could shave things off. Some [commented source is on GitHub](https://github.com/hostilefork/rebmu/blob/master/examples/bingo.rebmu), but the main trick I use is to build all the possible solutions in a long series ("list", "array", what-have-you). I build the diagonal solutions during the input loop, as it takes five insertions at the head and five appends at the tail to make them...and there's already a five-iteration loop in progress.
The whole thing easily maps to Rebol code, and I haven't yet thrown any "matrix libraries" into Rebmu with transposition or other gimmicks that seem to come up often. Someday I will do that but for now I'm just trying to work relatively close to the medium of Rebol itself. Cryptic-looking things like:
```
[g: is g pc r a z is g a ap g pc a sb 6 z ap v '*]
```
...are rather simple:
```
[
; assign the series pointer "g" to the result of inserting
; the z'th element picked out of reading in some series
; from input that was stored in "a"...this pokes an element
; for the forward diagonal near the front of g
g: insert g (pick (readin-mu a) z)
; insert the read-in series "a" from above into "g" as well,
; but *after* the forward diagonal elements we've added...
insert g a
; for the reverse diagonal, subtract z from 6 and pick that
; (one-based) element out of the input that was stored in "a"
; so an element for the reverse diagonal is at the tail
append g (pick a (subtract 6 z))
; so long as we are counting to 5 anyway, go ahead and add an
; asterisk to a series we will use called "v" to search for
; a fulfilled solution later
append v '*
]
```
*Note: Parentheses added above for clarity. But Rebol programmers (like English speakers) generally eschew the application of extra structural callouts for indicating the grammar in communication...rather save them for other applications...*
Just as an added bonus to show how interesting this actually is, I'll throw in some mix of normal code to sum the board. The programming styles are actually...compatible:
```
rtZ5[GisGpcRaZisGaAPgPCaSB6zAPv'*]
temp-series: g
sum: 0
loop 5 * 5 [
square: first temp-series
if integer! == type? square [
sum: sum + square
]
temp-series: next temp-series
]
print ["Hey grandma, the board sum is" sum]
l5[AgL5[apGfAsk+A5]]hd+Gu[raGin-NTrM'*fisGv5]p"BINGO!"
```
That's valid Rebmu as well, and it will give you a nice board sum before playing Bingo with you. In the example given, it says `Hey grandma, the board sum is 912`. Which is probably right. But you get the point. :)
[Answer]
## Perl, 122 120 char
```
$b=join'. .
',map~~<>,0..4;while(<>){/(\d+)/;$b=~s/\b$1\b/*/;print;
$b=~/(\*\s(\S+\s){$_}){4}\*/&&die"BINGO!
"for 0..7}
```
Build the card in `$b` with two additional junky columns.
Replace the numbers that are called on the card with `*` and print the called number.
Then the last regular expression will evaluate to true when there are 5 regularly spaced `*`s on the board.
[Answer]
# Mathematica 250
Disclosure: I assumed that the input was given in lists which are far more natural to use for Mathematica. So,with `b` representing the board and `c` representing the calls,
```
b//Grid
c//Column
```

If the input were to be in strings, the code would grow by about 30 characters. (I'll later include that variation.)
**Code**
```
y = ReplacePart[ConstantArray[0, {5, 5}], {3, 3} -> 1]; d = Diagonal;
t := Tr[BitAnd @@@ Join[y, Transpose@y, {d@y}, {d[Reverse /@ y]}]] > 0;
r@i_ :=(y = ReplacePart[y, Position[x, ToExpression@StringDrop[i, 1]][[1]] -> 1];
Print@If[t, Column[{i, "BINGO!"}], i])
n = 1; While[! t, r@c[[n]]; n++]
```
>
> B7
>
>
> I29
>
>
> G60
>
>
> G51
>
>
> O71
>
>
> I23
>
>
> I16
>
>
> BINGO!
>
>
>
[Answer]
# Python 249
```
R=raw_input;F=B=[[[x,0][x=='*']for x in row]for row in[R().split()for i in'11111']];A=any
while all([all(map(A,B)),all(map(A,zip(*B))),A(F[::6]),A(F[4:24:4])]):c=R();print c;C=c[1:];B=[[[x,0][x==C]for x in row]for row in B];F=sum(B,[])
print'BINGO!'
```
### Usage:
```
$ ./bingo.py < bingo.txt
B7
I29
G60
G51
O71
I23
I16
BINGO!
```
[Answer]
## APL (82)
```
{(D≡(⍵∨⌽⍵)∧D←=/¨⍳⍴⍵)∨∨/(∧⌿⍵)∨∧/⍵:'BINGO!'⋄∇⍵∨B=⍎1↓⎕←⍞}0=B←↑{⍎(K,K)[⍞⍳⍨K←11↑⎕D]}¨⍳5
```
* `{`...`}¨⍳5`: do 5 times:
* `⍎(K,K)[⍞⍳⍨K←11↑⎕D]`: read a line (`⍞`) and map all characters that aren't digits or space to `0`, then evaluate the line.
* `B←↑`: turn it into a matrix (5x5 if the input was correct), and store in B.
* `{`...`}0=B`: the starting board has a 1 in the free space (0) and 0 in the other spaces.
* `(D≡(⍵∨⌽⍵)∧D←=/¨⍳⍴⍵)∨∨/(∧⌿⍵)∨∧/⍵`: if a line, a column, or a diagonal is filled:
* `'BINGO!'`: then output `BINGO`
* `∇⍵∨B=⍎1↓⎕←⍞`: otherwise, read a line (`⍞`), echo it (`⎕←`), drop the first character (`1↓`), evaluate it to get a number (`⍎`), see where it occurs on the board (`B=`), mark it (`⍵∨`), and try again (`∇`).
[Answer]
# K, 114
Given the board `b` and the calls `c`
```
b{-1@y;a:(5*!5)_@[,/x;&(,/x)~\:1_y;:;"*"];$[max{max@min'"*"=,/'x}@/:(a;a ./:/:+:'(r;)'(r;|:r:!5));'"BINGO!";];a}/c
```
.
```
k)b
"14" "29" "38" "52" "74"
,"4" "18" "33" "46" "62"
,"7" "16" ,"*" "60" "71"
,"9" "27" "44" "51" "67"
"12" "23" "35" "47" "73"
k)c
"B7"
"I29"
"G60"
"G51"
"O71"
"I23"
"I16"
"N38"
k)b{-1@y;a:(5*!5)_@[,/x;&(,/x)~\:1_y;:;"*"];$[max{max@min'"*"=,/'x}@/:(a;a ./:/:+:'(r;)'(r;|:r:!5));'"BINGO!";];a}/c
B7
I29
G60
G51
O71
I23
I16
'BINGO
```
] |
[Question]
[
This is a math problem which takes quite many things into question, making it rather challenging, and as you might have guessed, it's a code golf, so it should be as short as possible as well.
The **input**, \$n\$, is any *integer* number (should at least support integers, but needn't be limited to). The **output** is the *average* of:
* \$n\$
* The square of \$n\$, \$n^2\$
* The closest prime number to \$n\$, \$p\$
* The closest number to \$n\$ in the [Fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_number), \$f\$
Shortly, the program should **print to the standard output channel** the *result* of $$\frac {n + n^2 + p + f} 4$$.
You *don't* have to care about possible overflows etc. Normal floating point precision is also ok.
The way the input is given is completely up to you. Shortest program (in characters) wins, as always with code golfs.
In the case a tie occurs when you are looking for the closest, choose one of the following:
1. Go up
2. Go down
3. Choose one randomly
[Answer]
**Python 160 Chars**
```
p=lambda n:any(n%x<1for x in range(2,n))
N=input()
a=0;b=1
while b<N:a,b=b,a+b
c=d=N
while p(c)and p(d):c-=1;d+=1
print (N+N*N+[b,a][2*N-a-b<0]+[c,d][p(c)])/4.0
```
A little explanation about the closestFib part:
>
> When the while loop ends a is smaller
> than N and b is either equal to or
> greater than N. Now the
> `[b,a][2*N-a-b<0]` part. Look at it as
> [b,a][(N-a)-(b-N)]. (N-a) is the
> difference between N and a and
> similarly (b-N) the difference between
> b and N. If the difference between
> these two is less than 0 it means a is
> closer to N and vice-versa.
>
>
>
[Answer]
## GolfScript, 59 characters
```
~:N..*.,2>{:P{(.P\%}do(!},{{N-.*}$0=}:C~[1.{.@+.N<}do]C+++4/
```
This script does not fulfill some of the requirements:
* It only works correctly for inputs `n >= 2`, otherwise it crashes.
* The output is truncated to an integer.
* Terrible performance for any moderately large `n`
A brief walkthrough of the code:
1. `~:N..*` The input is stored in N, and we push both `n` and the square `n*n` right away.
2. `.,2>` We will generate a list of primes by filtering the array `[2..n*n]`. We use our previous calculation of `n*n` as a (very bad!) upper bound for finding a prime that is larger than n.
3. `{:P{(.P\%}do(!},` Our previous array is filtered by trial division. Each integer P is tested against every integer [P-1..1].
4. `{{N-.*}$0=}:C~` Sorts the previous array based on the distance to `n`, and grabs the first element. Now we have the closest prime.
5. `[1.{.@+.N<}do]C` We generate Fibonnacis until we get one greater than `n`. Fortunately, this algorithm naturally keeps track of the previous Fibonnaci, so we throw them both in an array and use our earlier distance sort. Now we have the closest Fibonnaci.
6. `+++4/` Average. Note that GolfScript doesn't have support for floats, so the result is truncated.
## GolfScript, 81 characters
Here is a variant that fulfills all of the requirements.
```
~:N..*2N*,3,|2,^{:P{(.P\%}do(!},{{N-.*}$0=}:C~[0.1{.@+.N<}do]C+++100:E*4/.E/'.'@E%
```
To ensure proper behavior for `n<2`, I avoid `2<` (crashes when the array is small), and instead use `3,|2,^`. This makes sure the prime candidate array is just `[2]` when `n < 2`. I changed the upper bound for the next prime from `n*n` to `2*n` ([Bertrand's postulate](http://en.wikipedia.org/wiki/Bertrand%27s_postulate)). Also, 0 is considered a Fibonnaci number. The result is calculated in fixed point math at the end. Interestingly, it seems like the result is always in fourths (0, .25, .5, .75), so I hope 2 decimal places of precision is sufficient.
My first crack at using GolfScript, I'm sure there is room for improvement!
[Answer]
# JavaScript, 190
```
function n(n)
{z=i(n)?n:0
for(x=y=n;!z;x--,y++)z=i(x)?x:i(y)?y:0
for(a=b=1;b<n;c=a+b,a=b,b=c);
return(n+n*n+(2*n-a-b<0?a:b)+z)/4}
function i(n)
{for(j=2;j<n;j++)
if(!(n%j))return 0
return 1}
```
[257]
```
function n(n)
{return(n+n*n+p(n)+f(n))/4}
function p(n)
{if(i(n))return n
for(a=b=n;;a--,b++){if(i(a))return a
if(i(b))return b}}
function i(n)
{for(j=2;j<n;j++)
if(!(n%j))return 0
return 1}
function f(n)
{for(a=b=1;b<n;c=a+b,a=b,b=c);
return 2*n-a-b<0?a:b}
```
Uncompressed:
```
function closest( a, b, c )
{
return 2*a-b-c < 0 ? b : c;
}
function closestPrime( n )
{
a=b=n;
if (isPrime( n ) ) return n;
while ( true )
{
a-=1;
b+=1;
if (isPrime(a))return a;
if (isPrime(b))return b;
}
}
function isPrime( n )
{
for (i=2;i<n;i++)
{
if ( !( n % i ) ) return false;
}
return true;
}
function closestFib( n )
{
for(fib1=0,fib2=1;fib2<n;fib3=fib1+fib2,fib1=fib2,fib2=fib3);
return closest( n, fib1, fib2 );
}
function navg(n)
{
n2 = n*n;
np = closestPrime( n );
nf = closestFib( n );
return ( n + n2 + np + nf ) / 4;
}
```
[Answer]
# Mathematica, ~~70~~ 69 bytes
One byte saved thanks to Sp3000 (sometimes built-ins aren't the best way to go).
```
((n=#)+#^2+(f=#&@@#@Range@Max[1,2n]~Nearest~n&)@Prime+f@Fibonacci)/4&
```
This defines an unnamed function taking an integer and producing the exact mean as a rational number. In the case of ties, the smaller prime/Fibonacci number is chosen.
This is very inefficient for large inputs, because it actually generates the first `2n` primes and Fibonacci numbers before picking the closest.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~18~~ 15 bytes
```
₌∆p²?:ɾ∆f‡?ε∵Wṁ
```
*-3 bytes thanks to [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)*
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoziiIZwwrI/Osm+4oiGZuKAoT/OteKItVfhuYEiLCIiLCIxMyJd)
Explanation:
```
₌ # Parallel apply:
∆p # Nearest prime
² # Square
? # Push the input
: # Duplicate
ɾ # Range from 0 to n
∆f # Nth fibonacci number
∵ # Minimum by:
‡ # A two element lambda that gets
ε # The absolute difference of it's input
? # And the program's input
ṁ # Mean of
W # The stack
```
[Answer]
# Q, 119
Not the most efficient.
```
{%[;4]x+(x*x)+((*:)a(&)b=min b:abs x-a:{x,sum -2#x}/[x-2;1 1])+(*:)d(&)e=min e:x-d:(&)1={(min x mod 2_(!)x)}each(!)x+2}
```
[Answer]
# MATLAB 88 Chars
```
C=@(F)(F(abs(F-n)==min(abs(F-n))));(n+n^2+C(primes(n*2))+C(round(1.618.^(1:n)/2.236)))/4
```
n is your integer
Works with non integers, as far as I've tested it works with very large numbers as well, runs pretty damn quickly too.
[Answer]
### Scala 299
```
object F extends App{type I=Int
def f(n:I,b:I=1,a:I=1):I=if(a>=n)if(a-n>n-b)b else a else f(n,a,b+a)
def p(n:I)=(2 to n-1).exists(n%_==0)
def i(n:I,v:I):Int=if(!p(n+v))n+v else i(n+v,v)
val a=readInt
println(({val p=Seq(-1,1).map(i(math.max(a,3),_))
if(a-p(0)>p(1)-a)p(1)else p(0)}+f(a)+a+a*a)/4.0)}
```
Test and invocation:
```
a a² nP(a) nF ∑ /4.0
------------------------
-2 4 2 1 5 1.25
-1 1 2 1 3 0.75
0 0 2 1 3 0.75
1 1 2 1 5 1.25
2 4 2 2 10 2.5
3 9 2 3 17 4.25
4 16 3 5 28 7.0
5 25 3 5 38 9.5
```
The question talks about `any Integer` but the problem isn't that interesting for values below 0. However - how do we start? At 0? At 1? And what is the next prime for 11? 11 itself?
The idea to allow the next bigger or lower in case of a tie is bad, because it makes comparing needless difficult. If your results differ, they can have chosen the other fib, the other prime, the other fib and the other prime, or yours are wrong, or the result of the other person is wrong, or it is a combination: different choice, but wrong although, maybe both wrong.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
ÆnÆRạÞ+ÆḞ€ạÞ$Ḣ++²÷4
```
[Try it online!](https://tio.run/##y0rNyan8//9wW97htqCHuxYenqd9uO3hjnmPmtaAeSoPdyzS1j606fB2k////xsbAAA "Jelly – Try It Online")
## How it works
```
ÆnÆRạÞ+ÆḞ€ạÞ$Ḣ++²÷4 - Main link. Takes N on the left
Æn - Get the next prime after N
ÆR - Primes up to this
Þ - Sort by:
ạ - Absolute difference with N
This moves the smallest, closest prime to N to the front, p
$ - Last 2 links as a monad f(N):
€ - For each 1 ≤ i ≤ N:
ÆḞ - Get the ith Fibonacci number
ạÞ - Sort by abs diff with N
This moves the smallest, closest Fib to N to the front, f
+ - Add element-wise. The first element will be p+f
Ḣ - Extract p+f
+ - Add N
² - N²
+ - Add N². We now have N+N²+p+f
÷4 - Divide by 4
```
[Answer]
# [Haskell](https://www.haskell.org/), 150 bytes
```
import Data.List
f n=print$let q=head.sortOn(abs.(n-)).take(1+n^2);z=1:zipWith(+)z(1:z)in(read$show$q[p|p<-[2..],all((>0).mod p)[2..p-1]]+q z+n+n^2)/4
```
[Try it online!](https://tio.run/##HYyxDoIwFEV3v6IDQxvkSYmTipOjxtGBoHnGkja0j0KbmDT@O6LjPTnnagy9snaejfPDFNkJI8LZhLjqGNV@MhQzqyIba63wBWFxrsTxGYBTIQRE7BWXOd0rsU@13CXjbyZqnovElyUM8WkJs6CHdzY2/uMPRVMBtGu0lvNjKcANL@bFD/pCtm0@spTT/3GznR0aqh36y4N1TSFLAFm28xc "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
+²+UÆMgXÃñaU Î+_j}c+U)*¼
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=K7IrVcZNZ1jD8WFVIM4rX2p9YytVKSq8&input=MjM)
] |
[Question]
[
How many ways can one place (unlabelled) dominoes on a square chequerboard such that the number placed horizontally is equal to the number placed vertically?
The dominoes must align with, and may not protrude, the chequerboard and may not overlap.
This is OEIS sequence [A330658](https://oeis.org/A330658), `1, 1, 1, 23, 1608, 371500, 328956227, 1126022690953, ...`
### Challenge
Given the side length of the chequerboard, \$n\$, produce the number of ways to arrange dominoes as described above, \$a(n)\$, in as [few bytes as possible](https://codegolf.stackexchange.com/tags/code-golf/info) in your chosen programming language. Alternatively you may use any of the [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") [defaults](https://codegolf.stackexchange.com/tags/sequence/info).
You do not have to handle \$n=0\$
If you're producing a list/generator/etc. it may start either:
* `1, 1, 23, 1608, ...` or,
* `1, 1, 1, 23, 1608, ...`
### A Worked Example, \$n=3\$
There are \$23\$ ways to place an equal number of horizontal and vertical dominoes on a three by three board. Here they are represented as `0` where no dominoes lie and labelling cells where distinct dominoes lie as positive integers:
There is one way to place zero in each direction:
```
0 0 0
0 0 0
0 0 0
```
There are twenty ways to place one in each direction:
```
1 1 0 1 1 0 1 1 0 1 1 2 0 0 2 2 0 0 2 1 1 0 1 1 0 1 1 0 1 1
2 0 0 0 2 0 0 0 2 0 0 2 1 1 2 2 1 1 2 0 0 2 0 0 0 2 0 0 0 2
2 0 0 0 2 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 2 0 0 0 2
2 0 0 0 2 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 2 0 0 0 2
2 0 0 0 2 0 0 0 2 0 0 2 1 1 2 2 1 1 2 0 0 2 0 0 0 2 0 0 0 2
1 1 0 1 1 0 1 1 0 1 1 2 0 0 2 2 0 0 2 1 1 0 1 1 0 1 1 0 1 1
```
There are two ways to place two in each direction:
```
1 1 2 2 1 1
3 0 2 2 0 3
3 4 4 4 4 3
```
There are no ways to place more than two in each direction.
\$1+20+2=23 \implies a(3)=23\$
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 61 bytes
```
{+/∊{(∪≡⊢)¨(,2,/m)[M],.,⍉C[M←⍵⌂cmat≢C]}¨0,⍳≢C←,2,⌿⊢m←⍵⊥¨⍳,⍨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qHfuo76pzpHqKWl5xer/q7X1H3V0VWs86lj1qHPho65FmodWaOgY6ejnakb7xuro6Tzq7XSO9n3UNuFR79ZHPU3JuYkljzoXOcfWHlphAJTcDOIAZYFaHvXsB@rPhSrtWnpoBVAaqARIba39nwYW73vU1XxovfGjtolARwQHOQPJEA/P4P9ph1YoGCoYKRgrmAAA "APL (Dyalog Extended) – Try It Online")
Finally got how to circumvent the funky inner assignment on Extended ;-)
The difference with the one below is that `dfns` is auto-loaded under `⌂`, and a no-op is added after assignment into `m`.
I have a 68-byte Unicode and 60-byte Extended solution by rewriting from scratch; [it is left as an exercise for the reader.](https://codegolf.meta.stackexchange.com/a/18975/78410)
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~72~~ 69 [bytes](https://github.com/abrudz/SBCS)
```
⎕CY'dfns'
{+/∊{(∪≡⊢)¨(,2,/m)[M],.,⍉C[M←⍵cmat≢C]}¨0,⍳≢C←,2,⌿m←⍵⊥¨⍳,⍨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVOdI9ZS0vGJ1rmpt/UcdXdUajzpWPepc@KhrkeahFRo6Rjr6uZrRvrE6ejqPejudo30ftU141Ls1OTex5FHnIufY2kMrDIAym0EcoBRQ/aOe/bkQRY@6lh5aAZQDygOprbX/08DifY@6mg@tN37UNhFofXCQM5AM8fAM/p92aIWCoYKRgrGCCQA "APL (Dyalog Unicode) – Try It Online")
Non-recursive brute force. This works the other way around: generate all possible horizontal/vertical domino placements, generate all possible combinations of `n` horizontal and `n` vertical placements, and count the ones that don't have any duplicated cells.
### Ungolfed with comments
```
⎕CY'dfns' ⍝ Load dfns library to access function "cmat"
f←{ ⍝ Main function; ⍵←1-based index n (does not handle 0)
m←⍵⊥¨⍳,⍨⍵ ⍝ n-by-n matrix of unique integers
,⍨⍵ ⍝ [n n]
⍳ ⍝ Nested matrix having [1..n;1..n]
⍵⊥¨ ⍝ Compute n×i+j for each cell containing [i j]
R←,2,/m ⍝ Horizontal domino placements
2,/m ⍝ From the matrix m, pair horizontally consecutive cells
, ⍝ Flatten the outermost layer to make it a nested vector
C←,2,⌿m ⍝ Vertical domino placements, using ⌿ instead of /
+/(0,⍳≢R){M←⍺cmat⍵⋄+/(∪≡⊢)¨,R[M],.,⍉C[M]}¨≢R ⍝ Count the placements
(0,⍳≢R){ }¨≢R ⍝ For each ⍺←0..length(≢) of R with ⍵←R,
M←⍺cmat⍵ ⍝ Generate all combinations to use for R and C
⋄ ,R[M],.,⍉C[M] ⍝ Concatenate all combinations of R with all combinations of C
+/(∪≡⊢)¨ ⍝ Count the ones whose cell values are all unique
+/ ⍝ Sum all the counts
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~88~~ ~~84~~ 66 bytes
```
Nθ⊞υ⁰FυF×¹⁵X⁴⊖Φ×θθ﹪κθF∧¬&ικ×θ⊖θ«≔×X⁴λ⊕X⁴θη≧|ικ¿¬∨&κη№υ|κη⊞υ|κη»ILυ
```
[Try it online!](https://tio.run/##XZDPTsMwDMbP61P46EpBAgGnnsYmpElsqxAvUNqsjZoma/6wA@LZg5NCmMglsf397C9uh8a0upEh7NTZu4Of3rnBuayK2tsBPYNbep@0AfQlpPtNTNzi3SODWl9I/MBgy1vDJ64c7/BZSEfZRTUzmEsGe915qXGMUTpLp7Xq8KAdPgl3EZbHUDAYSyIyft06wfBZrNbWil79zMguJHE79SfPhcgxGOgjq31zXuBX0Q958tEwSJNJIU6QTB3Nta8x8gw22isXt5LBpRJ9/S7sf6kqvoraCOI2jXX4wlXvSEhIFcJ9uPmQ3w "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
⊞υ⁰
```
Start the list of results with an empty chequerboard of size `n`. This is represented using an integer in base 4 of `n²` digits with each digit representing an element of the array in row-major order, `0` for empty, `1` for half of a vertical domino and `3` for half of a horizontal domino. (`2` is unused, but that's code golf for you.)
```
Fυ
```
Perform a breadth-first search of chequerboards.
```
F×¹⁵X⁴⊖Φ×θθ﹪κθ
```
Consider all squares of the current chequerboard that are not on the left column, then decrement the index, giving the squares that are not on the right column, then convert to a pair of base 4 digits `33` representing a horizontal domino on those two squares.
```
F∧¬&ικ×θ⊖θ«
```
Check whether those squares are empty on the current chequerboard. If so, then consider all of the squares of the current chequerboard, except for the bottom row.
```
≔×X⁴λ⊕X⁴θη
```
Calculate the base 4 digits corresponding to a vertical domino at that square.
```
≧|ικ
```
Merge the current chequerboard with the current horizontal domino.
```
¿¬∨&κη№υ|κη⊞υ|κη
```
If the vertical domino does not overlap the merged chequerboard and the domino arrangement including the vertical domino has not yet been seen then add it to the list.
```
»ILυ
```
Output the number of arrangements found.
[Answer]
# JavaScript (ES6), ~~150 133~~ 126 bytes
```
n=>(g=(a,k=0,y=n,x,h=d=>a[(b=[...a])[y-!~d]|=m=2+d<<x,y]&m?0:g(b,k+~~d,y,-~x))=>(x%=n)||y--?h()+(y&&h(-1))+(x^n-1&&h(1)):!k)``
```
[Try it online!](https://tio.run/##FYzdisIwEEbvfYoIWmZIUuqCN9rRBymVRmPb3epEVCShP69es1fnO/Bx/szHvC7P38dbs7PXuaaZ6QANgVEdZSoQK69asnQwBZypSNPUlFgEvZxsOdCdfqTNc69CmdyP2a6Bs@rkNFkVlJ48Yoz5NTEOQ9D62AJKCEnSgt5gnP7EevOv0XbLDqtqrt0TWJDI9oJFTmIbKSWKfiHExfHL3a7pzTVQGVj1PGK8rnpZA@NY4X4xzl8 "JavaScript (Node.js) – Try It Online")
### Commented
The board is described as an array of \$n\$ bit masks. We start at \$(0,n-1)\$ and attempt to put either a horizontal domino, a vertical domino or no domino at all at each position, going from right to left and bottom to top:
$$\begin{matrix}
(n-1,0)&\cdots&(1,0)&(0,0)\\
(n-1,1)&\cdots&(1,1)&(0,1)\\
\vdots&&\vdots&\vdots\\
(n-1,n-1)&\cdots&(1,n-1)&(0,n-1)
\end{matrix}$$
For horizontal dominoes, we test the bits at \$(x,y)\$ and \$(x+1,y)\$ and set both of them if the location is available. For vertical dominoes, we only test the bit at \$(x,y)\$ and set the one at \$(x,y-1)\$ if the location is available.
The helper function \$h\$ is used to process the tests and the recursive calls to its parent function \$g\$ in the scope of which it's defined:
```
h = d => // helper function taking a direction d:
// -1 = vertical, undefined = no domino, 1 = horizontal
a[ // test a[]:
(b = [...a]) // b[] = copy of the current board
[y - !~d] |= // apply the mask m to either b[y] or b[y - 1]
m = // set m to:
2 + d << x, // 3 << x for horizontal, 1 << x for vertical,
// or 0 for no domino (NaN << x)
y // test a[y]
] & m ? // if there's a collision:
0 // do nothing and leave the final result unchanged
: // else:
g( // do a recursive call to g:
b, // use the updated board
k + ~~d, // add d to k
y, // leave y unchanged
-~x // increment x
) // end of recursive call
```
Below is the main recursive function \$g\$:
```
g = ( // main recursive function taking:
a, // a[] = board
k = 0, // k = counter which is incremented when a horizontal
// domino is put on the board and decremented when
// a vertical domino is used
y = n, x, // (x, y) = current position
h = ... // h = helper function (see above)
) => //
(x %= n) || // turn x = n into x = 0
y-- // decrement y if x = 0
? // if we haven't reached the end of the board:
h() + // try to put no domino
(y && h(-1)) + // if y > 0, try to put a vertical domino
(x ^ n - 1 && h(1)) // if x < n - 1, try to put a horizontal domino
: // else:
!k // return 1 if k = 0 (meaning that we've put as many
// horizontal dominoes as vertical ones)
```
[Answer]
# Clingo, 98 bytes
```
{v(1..n,2..n)}.{h(2..n,1..n)}.:-{v(I,J)}=C,{h(I,J)}!=C.:-I=1..n,J=1..n,2{v(I,J..J+1);h(I..I+1,J)}.
```
Wow, I'm just describing the problem, and it's still bigger than most of the more explicit solutions!
A commented version:
```
% Select some positions for vertical dominoes,
% v(I,J) is meant to also cover (I,J-1).
{v(1..n,2..n)}.
% Select some positions for horizontal dominoes,
% h(I,J) is meant to also cover (I-1,J).
{h(2..n,1..n)}.
% Constraints:
% The selections must not have different sizes:
:- {v(I,J)}=C,{h(I,J)}!=C.
% No position can be covered by two or more dominoes:
:- I=1..n,J=1..n,2{v(I,J..J+1);h(I..I+1,J)}
```
Save the program in a file `dom.lp` and give `n` as command line argument as shown below. The result is the number of models reported.
Here is an example run:
```
$ clingo -c n=5 dom.lp -q 0
clingo version 5.1.0
Reading from dom.lp
Solving...
SATISFIABLE
Models : 371500
Calls : 1
Time : 2.519s (Solving: 2.51s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 2.510s
```
`-q` stops `clingo` from printing solutions, `0` tells it to search for all solutions. Performance can be increased with the option `--config=frumpy`. With it, I was able to compute `n=6` in 48 min.
In Debian, clingo is in the `gringo` packet.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ 31 bytes
-7 bytes thanks to Jonathan Allan
```
’»1p⁸U+Ø.żƊŒPẈĠịƊpU$€ẎḅFQƑɗ€⁹S‘
```
TIO can run successfully for `n=1,2,3`, but it times out for `n>3` since this is a brute force solution. I have verified `n=4` on my computer.
[Try it online!](https://tio.run/##AUcAuP9qZWxsef//4oCZwrsxcOKBuFUrw5guxbzGisWSUOG6iMSg4buLxopwVSTigqzhuo7huIVGUcaRyZfigqzigblT4oCY////Mw)
### Commented
```
’»1p⁸U+Ø.żƊŒPẈĠịƊpU$€ẎḅFQƑɗ€⁹S‘ # main link
’ p³ # [1..n-1] Cartesian product with [1..n]
»1 # [1..n] x [1..n] if n=1 to avoid empty list output
U # reverse, yielding list of pairs from ex. [1,1] to [3,2] for n=3 (tops of vertical dominoes)
+Ø. # add [0,1] to each pair to get coordinates of bottoms of vertical dominoes
żƊ # zip with the tops list to get a list of pairs of pairs: [[[1,1], [1,2]], ...]
ŒPẈĠịƊ # take the powerset to get all possible vertical dominoes, and group these subsets by length
U # switch coordinates to get grouped horizontal domino sets
p $€ # Cartesian product of each set of horizontal dominoes with each set of vertical dominos of the same count
Ẏ # tighten to get a single list of domino sets
ḅFQƑɗ€⁹ # 1 for each set pair if it is a valid arrangement of dominoes, otherwise 0 (check for no repeat coordinates)
S‘ # sum to find the count of valid arrangements, and increment for the case where there are no 0's
```
] |
[Question]
[
The [**variable star designation**](https://en.wikipedia.org/wiki/Variable_star_designation) is an identifier for a variable star (a star that fluctuates in brightness). It consists of either a 1-2 letter code or (when the letter code is no longer sufficient) a 'V' followed by a number. This code is followed by the genitive of the star constellation the star is found in (eg. "RR Coronae Borealis", in short "RR CrB"), and each constellation has their own independent numbering.
The series of variable star designations inside one constellation is as follows:
1. start with the letter `R` and continue alphabetically through `Z`.
2. Continue with `RR`...`RZ`, then use `SS`...`SZ`, `TT`...`TZ` and so on until `ZZ`.
3. Use `AA`...`AZ`, `BB`...`BZ`, `CC`...`CZ` and so on until reaching `QZ`, always omitting `J` in both the first and second positions.
4. After `QZ` (the 334th designation) abandon the Latin script and start naming stars with `V335`, `V336`, and so on (`V` followed by the full numeric index).
Note: The second letter is never alphabetically before the first, ie. `BA` for example is an invalid designation. Single letters before `R` are unused. `J` never appears in the designation.
## Your Task
Parse a variable star designation and return its index in the series of variable star designations!
The input is a string of just the variable star designation (omitting the constellation reference that is usually included in a full variable star designation). It can be assumed to be a valid variable star designation; validation is not part of this challenge.
Output is a number representing at what index in the series the designation is. The index is 1-based.
Test cases:
* `QV` => `330`
* `U` => `4`
* `V5000` => `5000`
* `AB` => `56`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. Standard rules and loopholes apply.
[Answer]
# [Python 3](https://docs.python.org/3/), 121 bytes
```
lambda z,a='ABCDEFGHIKLMNOPQ',r='RSTUVWXYZ':int(z[1:])if z[2:]else[t+u for t in['',*r+a]for u in a+r if t<=u].index(z)-15
```
[Try it online!](https://tio.run/##Fc3LCoJAGEDhV/l34@QkWriRXGh3umqppbmYUGnAVGZGKF/ecnv44DRf@aqraV/Yj76k72dGoSPURo47XyxX6812tz8cT2cPEW4j/3INwuh2j5HFKql0iWGlmBXQJRMrzUuRJ1Jtoag5SGBVghAZcZWmQ2j/AajK4c/lzG5TjVVZ/lE6PDbMfhBiEMgLwYcAQlPXdXBcCGOIIqSJpmRSwRY0fDgLAoUiMO5/ "Python 3 – Try It Online")
## Explanation
The list comprehension `[t+u for t in['',*r+a]for u in a+r if t<=u]` evaluates to these strings:
```
t='': A B C D E F G H I K L M N O P Q R S T U V W X Y Z
t='R': RR RS RT RU RV RW RX RY RZ
t='S': SS ST SU SV SW SX SY SZ
t='T': TT TU TV TW TX TY SZ
t='U': UU UV UW UX UY SZ
t='V': VV VW VX VY VZ
t='W': WW WX WY WZ
t='X': XX XY XZ
t='Y': YY YZ
t='Z': ZZ
t='A': AA AB AC AD AE AF AG AH AI AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ
t='B': BB BC BD BE BF BG BH BI BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ
...
...
...
t='Q': QQ QR QS QT QU QV QW QX QY QZ
```
If there are any characters past the first two (`z[2:]`) then the result is `int(z[1:])`. Otherwise (i.e. if there are only one or two characters) we look the string up in the list we created and subtract 15 from the index.
[Answer]
# JavaScript (ES6), ~~104 100 98~~ 92 bytes
```
s=>+s.slice(1)||(n=parseInt(s,36))-((v=n/36|0)?250-v*~v/2+(n%36>18)+(v>18?v>26?360:35:v):26)
```
[Try it online!](https://tio.run/##XZRbayNHEEbf91fMS9Aojn1kKxbBYJuenlszl56Znu6eHvJivNqNEiEvlhEElvx1RwsJIVsvXxWnqh7P70@np@Pz6@7L2@Xh5eP2/dP9@/H@4eJ4ddzvnrfx9fLr1/hw/@Xp9bhVh7f4@NN6s1xexvHp/sB683W1fLy5XV2efvzrxM1FfPhhvXm4/mV5EZ/O8Xh6uNk8rjeru/Xt3Wl5d7NZvj@/HI4v@@3V/uVz/Cle9G6xXEbngmi9Xn34Dtt/6Df88/fQ3a5Wq28LZ/it/Z6L5L/ft5sP/8OLXw/yt@3zH7vD5@hpv4@uL/fbt7fta/R0@Bjd/Dt83B53nw9Pb7vz5V20iC6ieDFgGLE4PBOBmWFgMAwjg2VwDJ5hYggMM8ZgRozFOIzHTJiAmRlHRsvoGD3jxBgYZ6zFOqzHTtiAnXEO53ETLuBmvMdP@ICfmSamwDQTAmFmnhECkSAkIkVkiBxRIEqEQlSIGtEgWoRGdIgeMSAMYkRYhEN4xIQIiJkkIZEkKUlGkpMUJCWJIqlIapKGpCXRJB1JTzKQGJKRxJI4Ek8ykQSSGSmRKTJD5sgCWSIVskLWyAbZIjWyQ/bIAWmQI9IiHdIjJ2RAzqQpaUaakxakJakirUhr0oa0JdWkHWlPOpAa0pHUkjpSTzqRBtKZLCPLyQqykkyRVWQ1WUPWkmmyjqwnG8gM2UhmyRyZJ5vIAtlMnpMX5CW5Iq/Ia/KGvCXX5B15Tz6QG/KR3JI7ck8@kQfymaKgKCkURUVRUzQULYWm6Ch6ioHCUIwUlsJReIqJIlDMlCWloqwoa8qGsqXUlB1lTzlQGsqR0lI6Sk85UQbKGaVQFapGNagWpVEdqkcNKIMaURblUB41oQJqpqqoaqqGqqXSVB1VTzVQGaqRylI5Kk81UQWqmbqmbqhbak3dUffUA7WhHqkttaP21BN1oJ5pGpqWRtN0ND3NQGNoRhpL42g8zUQTaGballbTdrQ97UBraEdaS@toPe1EG2hntEZ36B49oA16RFu0Q3v0hA7oma6j6@kGOkM30lk6R@fpJrpAN9P39AO9oR/pLb2j9/QTfaCfF1fHL/vdW7xgsbzanravf8Zn60W7ZXT/EH2Kj@e8j3ZnFVwvo8dooatFdFZDLlR9ts373w "JavaScript (Node.js) – Try It Online")
### How?
We first test whether removing the first character of the input string leads to a numeric value. If it does, we just return that. For instance, `V5000` gives \$5000\$.
Otherwise, we convert the whole string from base-36 to decimal and store the result in \$n\$.
The index \$i\_n\$ of the star is always less than \$n\$. What we want to do is find out the difference \$d\_n\$ such that:
$$i\_n=n-d\_n$$
Let \$v\_n\$ be the higher base-36 digit:
$$v\_n=\left\lfloor\frac{n}{36}\right\rfloor$$
If \$v\_n=0\$, it means that this is a single letter designation and we just need to subtract \$d\_n=26\$ from \$n\$ to get the correct index (`R=1`, `S=2`, etc.).
Otherwise, we compute:
$$d\_n=250+t\_n+k\_n+o\_n$$
\$t\_n\$ is the term reflecting the fact the designation is triangular (`ZZ`, `YY YZ`, `XX XY XZ`, etc.):
$$t\_n={v\_n+1 \choose 2}=\frac{v\_n\cdot(v\_n+1)}{2}$$
\$k\_n\$ is the correction term for the missing `J` for the second letter:
$$k\_n=\cases{0,&\text{$n\bmod36\le18$}\\
1,&\text{$n\bmod36>18$}
}$$
Finally, \$o\_n\$ acts both as a correction term for the missing `J` for the first letter and as an offset for the 'wrapping' nature of the designation which goes first from `RR` to `ZZ` and then from `AA` to `QZ`:
$$o\_n=\cases{v\_n,&\text{$v\_n\le18$}\\
35,&\text{$18<v\_n\le26$}\\
360,&\text{$v\_n>26$}
}$$
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
≔…R¦[η≔Φα⁻κ⁹ζF﹪⁻Eζκ⁹LζF✂ζι⊞η⁺§ζικI∨⊕⌕ηθΣθ
```
[Try it online!](https://tio.run/##LY/BCsIwEETvfsXS0wbiB4inKggFi6U9egptbELTrSapSH@@bqy3ZefNMNMa5dtJuXXNQ7A9Ya2o15jVmYTsngkJRhx3f@1iXdQelYTS0hxwkHAQjCyMPCYPWE7d7Cbc1FI9cZEwiERJuGrqo8FFCAE/uHG21Ymw/KnmYNBIqBw781hQpz@blhI4v/KWIp5ViHjzWFDr9agp6o5bUZesr1SlmUfkgx286LTu3@4L "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔…R¦[η
```
Start building up a list of designations with the single letters `R` to `Z`.
```
≔Φα⁻κ⁹ζ
```
Get the alphabet without the letter `J`.
```
F﹪⁻Eζκ⁹Lζ
```
Loop over each possible first letter, but offset the value so it starts at the index of `R`, wraps around, and stops at the index of `Q`.
```
F✂ζι
```
Loop over each possible second letter.
```
⊞η⁺§ζικ
```
Push the letter pair to the list of designations.
```
I∨⊕⌕ηθΣθ
```
Output the index in the list, or if not found, the embedded number.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~35~~ 34 bytes
```
|hx-I#\J+Kr\R\[smr+dd+d\[+Kr\A\RQt
```
[Try it online!](https://tio.run/##K6gsyfj/vyajQtdTOcZL27soJigmuji3SDslRTslJhok4BgTFFjy/7@So5MSAA "Pyth – Try It Online\"hok4BgTFFjy/7@So5MSAA \"Pyth – Try It Online")
Uses string ranges to build a list of star designations, then finds the index of the input in that list.
**Explanation**
* `r\R\[` is the range from `R` to `[` (half-open range, so the range ends at `Z`) and `r\A\R` is the range from `A` to `R`
* `mr+dd+d\[` maps each character \$d\$ of a given list to the range from \$dd\$ to \$d\$`[`
(eg. "S" would map to the range "SS" to "S[")
* Hence, `+Kr\R\[smr+dd+d\[+Kr\A\R` builds the following list:
```
['R',...'Z', 'RR',...'RZ', 'SS',...'SZ', 'TT',...'TZ',... 'ZZ', 'AA',... 'AZ', 'BB',... 'BZ',...'QZ']
```
* `-I#\J` filters out items that contain a `J`
* `x ... Q` gives the index of the input in that list. If the input is not in the list, -1 is returned.
+ `h` increments that result (so if the input was not in the list, we now have 0)
* `| ... t(Q)` catches the `Vxx` case. If the previous expression evaluated to 0 (meaning the input was not in the constructed list), this returns the "tail" of the input (ie. the number after the `V`)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23 22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ØAḟ”JŒċṙ280Ḋ€ḣ9;ƲiȯḊ
```
A full program which prints the index.
**[Try it online!](https://tio.run/##ATMAzP9qZWxsef//w5hB4bif4oCdSsWSxIvhuZkyODDhuIrigqzhuKM5O8ayaciv4biK////QUI "Jelly – Try It Online")**
### How?
```
ØAḟ”JŒċṙ280Ḋ€ḣ9;ƲiȯḊ - Main Link: list of characters, V
ØA - upper-case alphabet characters
”J - character 'J'
ḟ - filter discard
Œċ - combinations with repetition = ["AA","AB",...,"AZ","BB",...]
ṙ280 - rotate left by 280 = ["RR","RS",...,"RZ","SS",..."]
Ʋ - last four links as a monad:
Ḋ€ - dequeue each = ["R","S",...,"Z","S",...]
ḣ9 - head to index 9 = ["R","S",...,"Z"]
; - concatenate these together = ["R","S",...,"Z","RR","RS",...]
i - first index of V in that (or 0 if not found)
Ḋ - dequeue V (i.e. "V5000" -> "5000")
ȯ - logical OR
- implicit print
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~92 89~~ 87 bytes
*Saved 2 bytes thanks to @ceilingcat*
Very similar to [my JS answer](https://codegolf.stackexchange.com/a/204769/58563), but without the constraint of working in base 36.
```
v;f(char*s){v=*s++-81;s=*s?s[1]?atoi(s):v*10+254+*s+v*~v/2-*s/74-(v>-8?v>0?334:9:v):v;}
```
[Try it online!](https://tio.run/##VcrLCoJAGAXgvU8xCMFcGhxvZEpKvYGLXBgtZEQTSsORv4XYozcN4SY4cD4OR/JWSq0habC8VSNVZIYDVYzxyE2UUaYu7jWrpqHDisRAXcG8MGDmAvQNjsepcnYBx5DyKINUZL4fxPsYzDdZNAxdjR5V12OCZguh59j1U4PtTY3@Y2@RmfPCJj@c1y5CIcTq42lFXq4oDUhiLfojm3vVKs1fXw "C (gcc) – Try It Online")
] |
[Question]
[
You want to find the length shortest path between two points, on an 2d ASCII "map". The roads are made up of `+` characters, and the two endpoints are represented by `#`s (not counted in the length). This road can be arranged in any way, and any other characters can be ignored. You can assume the endpoints will always connect to each other through roads.
**Examples:**
Output: 1
```
#+#
```
Output: 5
```
#+
+ +
++++++
+
#
```
Output: 8
```
++++#+++
+ +
+ +
++#+++++
```
Output: 4
```
#+++
++++
+++#
```
Output: 2
```
+++++
+ +
+# +
+++#+
+
+++
```
**Undefined output:**
```
##
```
```
# +++#
+ +
```
```
#+++#
+
+
#
```
```
#++
+
```
**Rules:**
* You can take input as a 2d array, matrix, string separated by newlines, etc.
* Output should be a number
* Can be a snippet, function, or full program
* You can represent one endpoint with a different character if necessary
[Answer]
# [Python 3](https://docs.python.org/3/), 146 bytes
```
def f(k,*s):w=k.find('\n')+1;*p,x=k.find('#'),*s;return len(k*(x in p or'#'>(k+w*' ')[x])or('+'<k[x])*s[1:])or min(f(k,*s,x+a)for a in(-1,1,-w,w))
```
[Try it online!](https://tio.run/##bZHLboMwEEX3/oqRWNhmSCXUXVIiNum2H5B2kTZGsaAGOUSQr6d@8HBojOSxr89cxuPm3l5q9ToMZ1FAwcokvvJtl5UvhVRnRj8V5Zju4ibpZy2i3FA7LdqbVlAJxcqY9SAVNFBrc7xnJXYxBcqP/RevNaNI30q7jq/HdGsl@JWK@d8lPZ54YaSTsWCbNEmTTZd0nA9SNZABpaS7yEpAuiUArb7bAFBJJcypYW4t406ShVf3JsdDYM8BM6ejvY2TRXUVE9BoqVpTigE53y1ZGbWs6H9E08Lh4/2gda190rcWp3KIMCd2GyEQNNEGN4jbgA25CU6NrI7ePFxg7lOIB8Yp90keNHPuWePivQmYDZCx2NVwh8vwO6vOBLpvNIIHzkav@ksEOWTMQwi8QzVwJxMH/31xZFbsynlSo4cqAt9x5LjU@68Pj5142gdYGjrXOVVOVh3Dqd6QXNSZhbC/T9/i6buRPw "Python 3 – Try It Online")
Uses `#` for start and `@` for end. Finds all paths along `+` and returns the shortest. Each path ends when either a space is encountered, the range is outside the box or a previous position is visited.
[Answer]
# [Python 3](https://docs.python.org/3/) (+ [numpy](https://numpy.org/)), 183 bytes
Assuming the input can be passed in as a numpy character array, here is a different approach. It works by calculating a distance matrix from the start point by repeatedly 'diffusing' distances along roads. Uses `'#'` for start and `'@'` for end.
```
from numpy import*
def f(A):
B=(A!=" ")-1+(A=="#")
for _ in nditer(A):B=pad(B,1);B+=(B==0)*stack(roll(B+(B>0),n%3-1,n%2)for n in[0,2,3,5]).max(0);B=B[1:-1,1:-1]
print(*B[A=="@"]-2)
```
[Try it online!](https://tio.run/##fVLbboMwDH3nKzzQRFLTibbaS6dMNI/7BYQmVGiHRhMUsku/vgvQDkJpjZTg2Oc4PnF11B9SrE6nnZIHEF@H6gjFoZJKz5ws38GObOjaAc7I5oG54NL5AsmGMddzqQM7qeAdCgEiK3SumlzOqjQjPFgE7laKWqdCu/SFIyOcsZDOzMn2kyhZloQj4a8hDcTjar4w65I2fMLwxWGwDFbBc0KfDukvCQ0B4/FibdKaJXGgUoXQZMbj5i6Rm8yX9OSBzmtdQym/C7Evj1BrWeYCUpFBmqWVzjNo23wrdJ07bX8Nguzp2jSaKpUeSVwW5kTJH9p2Z36a/vYJpY7TJse@h5Gf0IsHAB6CHzjQmo9msfzWer8Ng@VHZusJm3TPgmC33z/BqCvUE41Ixt6oiWsb3BGH1nlW@B@D7WcrAAgWstlH4U6UAcsojD3HFPpS9XKDcRgR7tTGM@oWelT9KuxZd5@qfbYIJ/q@rbmt@n3Nr1UbqHVRwBq64XvhVd9D7ET4Hw2T731/WiZnzczi6Q8 "Python 3 – Try It Online") (*11 bytes longer as the version of numpy on TIO requires an explicit mode parameter for pad, which is [no longer the case](https://github.com/numpy/numpy/commit/f45466d7604b645d68fd6224cba8b40dac661dd7)*)
[Answer]
# JavaScript (ES7), ~~131~~ 130 bytes
Takes input as a matrix of characters. Expects `1` for the starting point and `2` for the arrival.
```
m=>(M=g=(X,Y,n)=>m.map((r,y)=>r.map((c,x)=>(X-x)**2+(Y-y)**2^1?c^1||g(x,y,r[x]=g):1/c?c^2|M>n?0:M=n:r[g(x,y,r[x]=~-n),x]=c)))()|-M
```
[Try it online!](https://tio.run/##pZBfS8MwFMXf@yny1nuXPzVBQQvpPkHfN0oHJW5FWdORibRQ/Oo1nY416vTBvCTnx@GenPtcvVZH454OL9y2j9txp8dGZ5DrWsOKrZlFnTWiqQ4AjvVeuA9hWOcFrHiHi4WisOb99NjIpdnIYaihYz1zRVfqGlOZGI/VkGd2eZPm2qaumDneuEXmb4OIgAPPR9PaY7vfin1bww4KQkiSEBkRUgghYklVXEYlYvSj7@7s81JSEpfsDKgnITidGTgZSAjUBK7H3c@HyXDcFDiN/ANR9fmP6ym3l/Jhwjf5624eLr28NSjqV0W/NP/PssZ3 "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 65 bytes
Takes the ASCII map with `#` and `*` for end goals.
```
1 i:~&,('*'i.~,){&,"2<@#@,((,-)#:i.3)&(*@]*[:>./|.!.0)3|' +# 'i.]
```
[Try it online!](https://tio.run/##dY7NCoMwEITveYqtCyabxK3VW/qDUOipp15FehPsK1R89TQm1kN/FjJZlvmGefiMZQ9HBxIslODCKxjOt@vF72BwU26V1HLgydIzt1l1aLCxStmC0A1cU6500@nWnXg78oZLqkcJBiEgnSffg2r3fK8oZQs0WpD4vAIAGmHCFzSOiHuQX/bZoGfTTCRoXQwm/pvCSCzyL3ZtgUsX/a4SQ18 "J – Try It Online")
### How it works
```
3|' +# 'i. converts streets/goal to 1, start to 2, space to 0
((,-)#:i.3) the 4 offsets + identity
( |.!.0) shift the matrix in the directions,
[:>./ join them by taking the greatest number,
*@]* and setting spaces back to 0
<@#@, call the above function NxM times,
building up the results
('*'i.~,){&,"2 flatten the results, taking the position of the goal
1 i:~&, last place the goal was 1 (before being overwritten to 2)
```
[Answer]
# Java 8, ~~421~~ ~~408~~ ~~403~~ ~~400~~ 351 bytes
```
int M[][],v[][],l,L;m->{int i=(l=m.length)*(L=m[0].length);for(M=m,v=new int[l][L];m[--i%l][i/l]!=65;);return f(i%l,i/l,-1>>>1,-1);}int z(int x,int y,int r,int d){return x<l&y<L&x>=0&y>=0&&M[x][y]>32&v[x][y]<1?f(x,y,r,d):r;}int f(int x,int y,int r,int d){return M[x][y]>65?r>d?d:r:z(x,y-1,z(x-1,y,z(x,y+1,z(x+1,y,r,d+=v[x][y]=1),d),d),d)+(v[x][y]=0);}
```
-57 bytes thanks to *@ceilingcat*.
Input as a matrix of bytes, with `A` as start and `B` as finish.
[Try it online.](https://tio.run/##jVVdb5swFH3vr7iLtMjMQJNO7UMIVMnbpKSb1EfGA01I6wxIBE4WGuW3p9cGU1JMN4P8cX18zvW9lr0O96G1Xv45L@Iwz2EesvR4BcBSHmWrcBHBgxhKAywI1n7gB5AYDlpPVyUS5sJo7mUdmzMH4PoafoUZh80K@EsETwWPrMVmh1hCbwYGrnuAFNxzYnlHwcBcEruJHUfpM38xvpGZm/iDQI2d1SYjczcx924a/RWSfhz4s8BJfMtiX7HPruPgi3t36xhOFvFdlsKK4ISJdtMaep43xMZwTo4QexX7gIMp6kLWmayXxrFafBjH/WI86x88d9AvRNWf@4fALwLv@01/X3bHw/sVOZiFmZlLY5Q5J8Gx@ie3Irq7vc@85f1ylI1eBY01NLHFujDlmMoxHZYC1K1U3aGBcuVPiTIOcG9ngO3uKWYLyHnIsdlv2BISzCh55BlLnzFxoVGmk0c5J70JnfZkJpUBOxMKv9OetIlCe1TUH22yXNokDFq2KcClhlg5aa2mVee/rHQq9S95NZw6y7TtjUb0o2micQK90ETggwlhmv3XBTr0q778NFG5WC3aFqDMxjtTGyA/@gmDUq880QBog0PPADXHJxK1FzrApLmPDh@qMqXaOFyUjkjSTh@audCexXr/ypvWoWjkkmri0FyvBdQM0HEe2ieq935BNy8DeQLLywDy6ip4LHIeJfZmx@0tTvA4Jb0f6XbHR/XB1UByNaVulpilUQ4u5Ha@jRmec/SxwqhXgwlWhNR3uFhS3fE4X4LFVV@@CAMH2LiJwTGlldcg3xQkFY3QlUCfBfZzxKfCRip1KHVxqiEtVylphVPSayG9HjcxOEbpOuaK0V8LUgnEbslz6ozqzx0vw0qFG@KpJYad2uJZRbvRHewqmafzGw)
**Explanation:**
```
int M[][], // Matrix on class-level, starting uninitialized
v[][], // Visited matrix on class-level, starting uninitialized
l,L; // x and y dimensions on class-level, starting uninitialized
m->{ // Method with integer-matrix as input and integer as return
int i=(l=m.length) // Set `l` to the amount of rows
*(L=m[0].length); // Set `L` to the amount of columns
// And set `i` to the product of the two
for(M=m, // Set `M` to the input-matrix
v=new int[l][L]; // Create the visited-matrix filled with 0s
m[--i%l][i/l]!=65;); // Loop as long as the current cell doesn't contain an 'A'
return f( // Start the recursive method `f` with:
i%l,i/l, // The current cell as the starting x,y-coordinate
-1>>>1, // Integer.MAX_VALUE as starting minimum-distance
-1);} // And -1 as amount of steps
int z(int x,int y,int r,int d){
// Method `z` to check whether we can travel to the given cell
return x<l&y<L&x>=0&y>=0// If the x,y-coordinate is within the matrix boundaries,
&&M[x][y]>32 // and that the current cell does NOT contain a space,
&v[x][y]<1? // and we haven't visited this cell yet:
f(x,y,r,d) // Return a call to the recursive method `f` with the same arguments
: // Else:
r;} // Return the row
int f(int x,int y,int r,int d){
// Create the recursive method `f`
return M[x][y]>65? // If the current cell contains 'B':
r>d?d:r // Return the minimum of the min-distance and amount of steps
: // Else:
z(x,y-1, // Do a recursive `z`-call westward,
z(x-1,y, // do a recursive `z`-call northward,
z(x,y+1, // do a recursive `z`-call eastward,
z(x+1,y,r, // do a recursive `z`-call southward,
d+=v[x][y]=1),d),d),d)
// after we've first marked the current cell as visited
+(v[x][y]=0);} // And unmark the current cell as visited afterwards
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ ~~28~~ 27 bytes
Takes input as a list of lines. Incredibly slow.
```
œẹⱮ⁾+#ŒP;€¥/Œ!ạƝ§ṀƊ€ṂƊÞḢL_2
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ie7dj7auO5R4z5t5aOTAqwfNa05tFT/6CTFh7sWHpt7aPnDnQ3HuoCCD3c2Hes6PO/hjkU@8UYgbTsXA/VwcT3cveVwuwpQwf//ytraylwKCtraXFzKQBaQqaCsDSIVwKQ2hAQLAwA "Jelly – Try It Online")
**Comments** (slightly outdated):
```
ạƝ§=1Ạ -- helper function: is this a connected path?
ạƝ -- element-wise absolute differences of adjacent coordinates
§=1Ạ -- do all differences sum to 1?
Ɱ⁾+# -- call with right arguments '+' and '#'
œẹ -- multidimensional indices of right argument in inputs
¥/ -- call next two functions with '+'-indices on the left and '#'-indices on the right
ŒP -- all subsets of the '+'-indices
;€ -- append '#'-indices to each subset
ƊƇ -- filter; keep subsets where the following three functions yield a thruthy result
Œ! -- all permutations of the subsets
Ç€ -- call the helper function for each subset
Ẹ -- is any result truthy?
Ḣ -- take first (shortest) subset
L_2 -- length - 2
```
] |
[Question]
[
The positive rational numbers can be shown to be numerable with the following process:
1. Zero has the ordinal 0
2. Arrange the other numbers in a grid so that row a, column b contains a/b
3. Plot a diagonal zig-zag top right to bottom left
4. Keep a running tally of the unique numbers encountered along the zig-zag
Here's a picture of the zig-zag:
[](https://i.stack.imgur.com/6jm5N.png)
So, the numbers encountered are, in order
```
1/1, 2/1, 1/2, 1/3, 2/2, 3/1, 4/1, 3/2, 2/3, 1/4, 1/5, 2/4, 3/3, 4/2, 5/1, 6/1, 5/2, 4/3, 3/4, 2/5, 1/6, 1/7, 2/6, 3/5, 4/4, 5/3 ...
```
And the simplified, unique numbers encountered are
```
1, 2, 1/2, 1/3, 3, 4, 3/2, 2/3, 1/4, 1/5, 5, 6, 5/2, 4/3, 3/4, 2/5, 1/6, 1/7, 3/5, 5/3, ...
```
# Challenge:
* Given *two* greater-than-zero integers **p** and **q**, output the **ordinal number** of p/q
* p and q are not necessarily co-prime
* Shortest code wins
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?noredirect=1&lq=1) are prohibited
## Test cases:
Here are the first 24 rational numbers encountered, and the desired output for each:
```
1/1: 1
2/1: 2
1/2: 3
1/3: 4
2/2: 1
3/1: 5
4/1: 6
3/2: 7
2/3: 8
1/4: 9
1/5: 10
2/4: 3
3/3: 1
4/2: 2
5/1: 11
6/1: 12
5/2: 13
4/3: 14
3/4: 15
2/5: 16
1/6: 17
1/7: 18
2/6: 4
3/5: 19
```
And, for further test cases, here are the 200 first positive rational numbers in order:
```
1, 2, 1/2, 1/3, 3, 4, 3/2, 2/3, 1/4, 1/5,
5, 6, 5/2, 4/3, 3/4, 2/5, 1/6, 1/7, 3/5, 5/3,
7, 8, 7/2, 5/4, 4/5, 2/7, 1/8, 1/9, 3/7, 7/3,
9, 10, 9/2, 8/3, 7/4, 6/5, 5/6, 4/7, 3/8, 2/9,
1/10, 1/11, 5/7, 7/5, 11, 12, 11/2, 10/3, 9/4, 8/5,
7/6, 6/7, 5/8, 4/9, 3/10, 2/11, 1/12, 1/13, 3/11, 5/9,
9/5, 11/3, 13, 14, 13/2, 11/4, 8/7, 7/8, 4/11, 2/13,
1/14, 1/15, 3/13, 5/11, 7/9, 9/7, 11/5, 13/3, 15, 16,
15/2, 14/3, 13/4, 12/5, 11/6, 10/7, 9/8, 8/9, 7/10, 6/11,
5/12, 4/13, 3/14, 2/15, 1/16, 1/17, 5/13, 7/11, 11/7, 13/5,
17, 18, 17/2, 16/3, 15/4, 14/5, 13/6, 12/7, 11/8, 10/9,
9/10, 8/11, 7/12, 6/13, 5/14, 4/15, 3/16, 2/17, 1/18, 1/19,
3/17, 7/13, 9/11, 11/9, 13/7, 17/3, 19, 20, 19/2, 17/4,
16/5, 13/8, 11/10, 10/11, 8/13, 5/16, 4/17, 2/19, 1/20, 1/21,
3/19, 5/17, 7/15, 9/13, 13/9, 15/7, 17/5, 19/3, 21, 22,
21/2, 20/3, 19/4, 18/5, 17/6, 16/7, 15/8, 14/9, 13/10, 12/11,
11/12, 10/13, 9/14, 8/15, 7/16, 6/17, 5/18, 4/19, 3/20, 2/21,
1/22, 1/23, 5/19, 7/17, 11/13, 13/11, 17/7, 19/5, 23, 24,
23/2, 22/3, 21/4, 19/6, 18/7, 17/8, 16/9, 14/11, 13/12, 12/13,
11/14, 9/16, 8/17, 7/18, 6/19, 4/21, 3/22, 2/23, 1/24, 1/25
```
Shout out to the [inverse question](https://codegolf.stackexchange.com/questions/2497/rational-counting-function?rq=1), where the first move is down so you can't use the answers to generate additional test cases.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Probably beatable by a number of bytes using some clever mathematics...
```
:g/
ǵSRRUĖ€UÐeẎÇ€Qi
```
A monadic link accepting a list of `[p,q]` which returns the natural number assigned to `p/q`.
**[Try it online!](https://tio.run/##y0rNyan8/98qXZ/rcPuhrcFBQaFHpj1qWhN6eELqw119h9uB7MDM////RxvpmMUCAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/98qXZ/rcPuhrcFBQaFHpj1qWhN6eELqw119h9uB7MBMrqOTHu6cAWQe3QMWyQLiRw1zFHTtFB41zI38//9/dLShjmGsTrQRmDTUMQKTxmARENsYLG4CJo3BIkZgWUMdEzBpChYxAcsag1WC1JiC1ZuBSVOwiAlY1his0gisy1DHDEyag0XMwLKmsbEA "Jelly – Try It Online").
### How?
First note that the **Nth** diagonal encountered contains all of the grid's rational numbers for which the sum of the numerator and denominator equals **N+1**, so given a function which reduces a `[p,q]` pair to simplest form (`[p/gcd(p,q),q/gcd(p,q)]`) we can build the diagonals as far as need be\*, reduce all the entries, de-duplicate and find the index of the simplified input.
\* actually one further here to save a byte
```
:g/ - Link 1, simplify a pair: list of integers, [a, b]
/ - reduce using:
g - Greatest Common Divisor -> gcd(a, b)
: - integer division (vectorises) -> [a/gcd(a,b), b/gcd(a,b)]
ǵSRRUĖ€UÐeẎÇ€Qi - Main Link: list of integers, [p, q]
Ç - call last Link as a monad (simplify)
µ - start a new monadic chain (call that V)
S - sum -> the diagonal V will be in plus one
R - range -> [1,2,3,...,diag(V)+1]
R - range (vectorises) -> [[1],[1,2],[1,2,3],...,[1,2,3,...,diag(V)+1]]
U - reverse each -> [[1],[2,1],[3,2,1],[diag(V)+1,...,3,2,1]]
Ė€ - enumerate €ach -> [[[1,1]],[[1,2],[2,1]],[[1,3],[2,2],[3,1]],[[1,diag(V)+1],...,[diag(V)-1,3],[diag(V),2],[diag(V)+1,1]]]
Ðe - apply only to the even indexed items:
U - reverse each -> [[[1,1]],[[2,1],[1,2]],[[1,3],[2,2],[3,1]],[[4,1],[3,2],[2,3],[1,4]],...]
Ẏ - tighten -> [[1,1],[2,1],[1,2],[1,3],[2,2],[3,1],[4,1],[3,2],[2,3],[1,4],...]
Ç€ - for €ach: call last Link as a monad (simplify each)
- -> [[1,1],[2,1],[1,2],[1,3],[1,1],[3,1],[4,1],[3,2],[2,3],[1,4],...]
Q - de-duplicate -> [[1,1],[2,1],[1,2],[1,3],[3,1],[4,1],[3,2],[2,3],[1,4],...]
i - index of V in that list
```
[Answer]
# [Perl 6](https://perl6.org), ~~94~~ 90 bytes
```
->\p,\q{(({|(1…($+=2)…1)}…*)Z/(1,{|(1…(($||=1)+=2)…1)}…*)).unique.first(p/q,:k)+1}
```
[Test it](https://tio.run/##XY9NTsMwEIX3PsWospBN3Bjnx21TpeIQrFA3JXGliDR1mhSB2kqchkuw4yhcJMxE/Ehs8uL3vTcee3eo7XDsHDzZsFgytnuBq2JfOsiH6Wrt1bo9CXE6C/P5@iZ4kEcSf4y84Pda3mth1A8U/HzOjfwXkeGxqdqjC7fVoeuF163KHmVgLgPedNu7rocc6qpx3cd7WOx3D0Kvy0BLXIW2usPAkvl600AwptHf7g/fzekKBHCveKu4e/au6F0JEk4MoOqAniFGKhX8cgUT7jVvsz9rwi6D0SYDwyKSiBkdZRCjxBkkaEbEYmIpS0gsntCcIcPIHJNJBguUFJM36CbUjwkabEQ0NB2vMMyOSmcaGyOmVIJpLJkUyzTE4jCLOkOdoc7Rt7RNPOLFFw "Perl 6 – Try It Online")
```
{(({|(1…($+=2)…1)}…*)Z/(1,{|(1…(($||=1)+=2)…1)}…*)).unique.first($^p/$^q):k+1}
```
[Test it](https://tio.run/##XY9dSsNAFIXfZxWXMsiMiYmTn0mbEnERPokUNJ1CMG2TJhWlLbgaN@GbS3Ej8dzgD/iSkznfOXfuNG5X22HfOXqyQTkXYv1CZ@V26agYDkodjsp8vr4p6RWRxo/RJ3zP9W2ojP8DlTweC6P/RXSw31Tt3gWratf1Si6aUC5anT965jTgluvedT0VVFcb1328B@V2/aDCu6UXaqzBG90gMBdNfb8hb0zDX213382LK1IkG1@2vnTPjSt7tyRNB0FUdcRPUCPVPv1ynyYSa7T5nzURp8GEJicjIpZImDDKKYbEOSUwI2Yxs1QkLBYnmBkYIlMkk5xmkBTJS7gJ92OGBo2Ih6bjFUbYUfnMY2NgTiVIo2RSlHmIxTALzaAZdArf8jbxiGdf "Perl 6 – Try It Online")
This basically generates the entire sequence of values, and stops when it finds a match.
## Expanded:
```
{ # bare block lambda with placeholder parameters $p,$q
(
( # sequence of numerators
{
|( # slip into outer sequence (flatten)
1 # start at one
…
(
$ # state variable
+= 2 # increment it by two each time this block is called
)
…
1 # finish at one
)
}
… * # never stop generating values
)
Z/ # zip using &infix:« / » (generates Rats)
( # sequence of denominators
1, # start with an extra one
{
|( # slip into outer sequence (flatten)
1
…
(
( $ ||= 1 ) # state variable that starts with 1 (rather than 0)
+= 2 # increment it by two each time this is called
)
…
1
)
}
… * # never stop generating values
)
).unique # get only the unique values
.first( $^p / $^q ) # find the first one that matches the input
:k # get the index instead (0 based)
+ 1 # add one (1 based)
}
```
---
`({1…($+=2)…1}…*)` generates the infinite sequence of numerators (`|(…)` is used above to flatten)
```
(1 2 1)
(1 2 3 4 3 2 1)
(1 2 3 4 5 6 5 4 3 2 1)
(1 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
(1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1)
…
```
`(1,{1…(($||=1)+=2)…1}…*)` generates the infinite sequence of denominators
```
1
(1 2 3 2 1)
(1 2 3 4 5 4 3 2 1)
(1 2 3 4 5 6 7 6 5 4 3 2 1)
(1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1)
(1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1)
…
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~157~~ ~~144~~ ~~137~~ ~~134~~ ~~126~~ 125 bytes
```
def f(p,q):a=[((j-i)/(i+1.))**(j%-2|1)for j in range(p-~q)for i in range(j)];return-~sorted(set(a),key=a.index).index(p*1./q)
```
[Try it online!](https://tio.run/##RZHdaoQwEIWv26fIjZjYqDXxZ3eLTyJeCMY2FqJGd9mFsq9uM3FKITAnh2/OTMj82L4mI/a9VwMZ6MwXdunqhtIx1iyl@i1LGIsiOgax@MnYMFkyEm2I7cynonP8XLyn/72RtR9WbVdr4uc62U31dFUb7Rj/Vo@6S7Tp1Z0dhc5RlqQL2yHDzeY3yGmajBM4LSeN8FKAhMqJRCk5yREQyErPFiBzL0t0HVAh624nTHDMGWXh8HckcpwhPZxhmsAlimM1b5eH/vNhDYk4dOaYArsUGA7tJQ6F9gp15fQJmRJfJg/83LaX15fZarORMFjTYA0D/1H8xsM65Mev7fsv "Python 2 – Try It Online")
4 bytes saved due to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder);
1 byte from [Jonathon Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech).
As noted by Mr. Xcoder, we can do a bit better in Python 3 since, amongst other things, integer division defaults to float results, and we can more easily unpack `list`s:
### [Python 3](https://docs.python.org/3/), 117 bytes
```
def f(p,q):a=[((j-i)/-~i)**(j%-2|1)for j in range(p-~q)for i in range(j)];return-~sorted({*a},key=a.index).index(p/q)
```
[Try it online!](https://tio.run/##RZHdaoQwEIWv26fIjZhIslbjz@4Wn0S8EIxtLESNdtmlra9uM3FKITAnh2/OTMj0WN9HI/e9Uz3p6cRndm2rmtJBaBaLTbMookMg0u@E9aMlA9GG2Na8KTqJbfae/vcG1rxatX5aI7ZltKvq6FfU/vAP9ajakzadurOj0Cme2Q7tbia/QURdJ5zAaTipUy9TkFA5kSglJxkCKbLSsznIzMsCXQeUyLrbGRMcc0GZO/wFiQxnSA8nmJbiEvmxmreLQ//5sIZEHDozTIFdcgyH9gKHQnuJunT6jEyBL5MHfmma6/PTZLVZaRgscbCEgf8gfuNhFfLjt9i@/wI "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~157~~, ~~146~~, ~~140~~, 133 bytes
```
def f(p,q):a=[(i+i-abs(j-i-i))/(abs(j-i-i+.5)+.5)for i in range(p+q)for j in range(4*i)];return sorted(set(a),key=a.index).index(p/q)
```
[Try it online!](https://tio.run/##RZHdboQgEIXvfYq5hIq7XfGv2/gkxgsbscs2QQSadJ/eMjjdGgxnjt8Mw2gf4bYaue@zWmBhVmz8OvUD07kupg/P7oUuNOdn9gzyU83xXVYHGrQBN5lPxWy@Jev@b1Uvmo/vToVvZ8CvLqiZeRXYxMWXevTTSZtZ/fBjY/a88T0oH3w/ZMNFAK5RZEOZZIkSdwGSpBRQEVASKxNbo6ySbMiNQEtsjDqqEJk3knXEX4mo6AyZ4AtVK6mJ@mgt2c2h/3xsQxKOmRVVwV5qKo7pDR2K6S3pNuqOmIZuJg889VhiwQhVnRzHDEdtBWwCnPI48jS5awbxsU6bwJ5fRfqvsPG@jxHffwE "Python 3 – Try It Online")
won 11 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech)
won 6 more bytes and then 7 thanks to [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown)
[Answer]
# J, 41, 35, 30 bytes
*-11 bytes thanks to FrownyFrog*
```
%i.~0~.@,@,[:]`|./.[:%/~1+i.@*
```
[Try it online!](https://tio.run/##VZVPaxtBDMXv/hRDISRunM1Knr@GgKHQU0@9hkIhdah7aQ899FD81d3uTvTT7sEg2zPSe09Pmh/Xd8Pta3g6hNuwC2M4/P88DOHD508frzfn4TJehuPuuHs@fPn6d3gcng83jxe5Pw/H99ftZnP68@v08vv07WkIdxJeg2x34U4tmH5RC/ZTsLe/ogV7O6N2ZjocLUhTkOxwtiDZrbjMHC1PsuvZgmJnSDjfKpawWlAsc7KE0W6p5ZkSVguaZS52fc7cEGG0qFnquiwfjRjIslUFdLXyzarKSIQgAOj06Yd4Q7wj4xJoNFTJUmRDVSx7NVQQ7hgUDHNB@i3ecBA2K@gIe8vxhWAMwRkiS4iwBJC46zCQ4CBJ4NhjJloNokKlRPWeDfcJ9hP8J3HFIaK3M8zoXaxYNTINE474G7UEhy@0xOOCyQWXC90St7d3voCz38X9gv0F/89sXYEIW9cnw9bVq7BF2s6trnTv3PK6K4zbomcZvoyeMHviXsQW4uPnzBuYCyw7N@ZUmVNhUIUBlbxiXn3CRh9y3yTOiWHuCBXU8ygyxcoy7P@mNacEJ/daozfOKYF/Pqe@k9kByg7QcaVCxAnujgz3QrWKE1zVNxV0rbr4qll0hUkWto2wbhYO9vmmy8rGUX9g2DjqqvtcuTMX0ol7vcC/73g2kbKJ1N8oXSkbuZvRzntR0a75ZvPV9ibOYm353mpoUtc@qOjUTB13jvKOKntQ2YOapvf65fvP6et9OA86jtvwcAj2hm@u/wA "J – Try It Online")
# original 41 bytes post with explanation
```
%>:@i.~[:([:~.@;[:<@|.`</.%"1 0)~(1+i.@*)
```
## ungolfed
```
% >:@i.~ [: ([: ~.@; [: <@|.`</. %"1 0)~ 1 + i.@*
```
## explanation
```
+
| Everything to the right of this
| calculates the list
p (left arg) | create the
divided by q | diagonals. yes,
(right) | +this is a +create this list
| | ++ finally rmv ^alternately |primitive ADVERB |1..(p*q), and pass
| + the index | the boxes, |box, or |in J |it as both the left
| | of that | | and remove |reverse and | |and right arg to the
| | in the | | any dups |box, each | |middle verb, where each
| | list on | | |diagonal | |element will divide the
| | the right| | | | +----------+entire list, producing
| | plus 1 | | | | | |the undiagonalized grid
| | | | | | | |
| | | | | | | |
| | + | | | | |
┌+┬──|──────────┬─────────|─────────────|─────────────|───────|──────────|─────────────┐
│%│┌─+───────┬─┐│┌──┬─────|─────────────|─────────────|───────|────────┬─|────────────┐│
│ ││┌──┬─┬──┐│~│││[:│┌────|─────────────|─────────────|───────|─────┬─┐│┌+┬─┬────────┐││
│ │││>:│@│i.││ │││ ││┌──┬|───────┬─────|─────────────|───────|────┐│~│││1│+│┌──┬─┬─┐│││
│ ││└──┴─┴──┘│ │││ │││[:│+──┬─┬─┐│┌──┬─|─────────────|─┬─────|───┐││ │││ │ ││i.│@│*││││
│ │└─────────┴─┘││ │││ ││~.│@│;│││[:│┌|───────────┬─+┐│┌─┬─┬+──┐│││ │││ │ │└──┴─┴─┘│││
│ │ ││ │││ │└──┴─┴─┘││ ││+────────┬─┐│/.│││%│"│1 0││││ ││└─┴─┴────────┘││
│ │ ││ │││ │ ││ │││┌─┬─┬──┐│<││ ││└─┴─┴───┘│││ ││ ││
│ │ ││ │││ │ ││ ││││<│@│|.││ ││ ││ │││ ││ ││
│ │ ││ │││ │ ││ │││└─┴─┴──┘│ ││ ││ │││ ││ ││
│ │ ││ │││ │ ││ ││└────────┴─┘│ ││ │││ ││ ││
│ │ ││ │││ │ ││ │└────────────┴──┘│ │││ ││ ││
│ │ ││ │││ │ │└──┴─────────────────┴─────────┘││ ││ ││
│ │ ││ ││└──┴────────┴────────────────────────────────┘│ ││ ││
│ │ ││ │└──────────────────────────────────────────────┴─┘│ ││
│ │ │└──┴──────────────────────────────────────────────────┴──────────────┘│
└─┴─────────────┴──────────────────────────────────────────────────────────────────────┘
```
[Try it online!](https://tio.run/##VZUxbxsxDIX3/AohQBC7Sa5HWtJJ16QwUKBTpq5eCqQO6i7t0KFD4b/u9k7hx7vBAG1L5HuPj9SPy3V3@xqexnAb7kMfxv@fhy58@vL8@XLzcdyfuvNh3BzGc7f/cBgf93@7r4/vu5trCf32vJG7U7d/t71sr66Of34dX34fvz11YSPhNcj2PmzUgukXtWA3BTv7K1qwszNqZ6bD0YI0BckOZwuS3YrLzNHyJLueLRjsDAnnW4MlLBYMljlZwmi31PJMCYsF1TIPdn3OXBGht6ha6rIsH40YyLJVBXSx8tWqSk@EIABo9OmHeEO8I/0SaDRUyVJkQzVY9mKoINwwKBjmgvRbvOEgrFbQEbaW4wvBGIIzRJYQYQkgcddhIMFBksCxw0y0GkQDlRLVWzbcJ9hP8J/EFYeI3s4wo/dgxYqRqZiwx9@oJTh8oSUeF0wuuFzolri9vfMDONtd3C/YX/D/zNYViLB1fTJsXb0CW6Rt3MpK98Ytr7vCuC16luHL6AmzJ@5FbCE@fs68gnmAZePGnCpzKgyqMKCSV8yLT1jvQ@6bxDkxzA2hgnoeRaZYWYbt37TmlODkXqv0xjkl8M/n1HcyO0DZAdqvVIg4wd2R4T5QreAEV/VNBV2rLr5qFl1hkoVtI6ybhYN9vumysnHUHxg2jrrqPlfuzIV04l4f4N92PJtI2UTqb5SulI3czWjnvShoV32z@Wp7E2extnxvVTQpax8UdKqmjjtHeUeVPajsQU3Te/3y/ef09S6cOu37bXgYg73hV5d/ "J – Try It Online")
[Answer]
# Python 3, 121 bytes
```
import math
def o(x,y):
p=q=n=1
while x*q!=p*y:a=p+q&1;p+=1+a*~-~-(p<2);q+=1-~-a*~-~-(q<2);n+=math.gcd(p,q)<2
return n
```
[Answer]
# Rust, 244 bytes
I created a simple formula to find the "plain" ordinal of a "plain" zigzag, without the constraints of the puzzle, using triangular numbers formulas:
<https://www.mathsisfun.com/algebra/triangular-numbers.html> . This was modified with modulo 2 to account for the zig-zags flipping their direction each diagonal row in the puzzle. This is function h()
Then for the main trick of this puzzle: how to 'not count' certain repeating values, like 3/3 vs 1/1, 4/2 vs 2/1, in the zig-zag trail. I ran the 1-200 examples, and noticed the difference between a plain zig-zag triangular counter, and the one the puzzle wishes for, has a pattern. The pattern of "missing" numbers is 5, 12, 13, 14, 23, etc, which resulted in a hit in the OEIS. It is one described by Robert A Stump, at <https://oeis.org/A076537> , in order to "deduplicate" numbers like 3/3, 4/2, and 1/1, you can check whether GCD>1 for the x,y of all "previous" ordinals in the zigzag. This is the 'for' loops and g() which is the gcd.
I guess with some builtin gcd it would have been shorter, but I kind of couldn't find one very easily (im kind of new at Rust and Integer confused me), and I like the fact that this one uses straight up integer arithmetic, and no builtins or libraries of any kind.
```
fn f(x:i64,y:i64)->i64 {
fn h(x:i64,y:i64)->i64 {let s=x+y;(s*s-3*s+4)/2-1+(s+1)%2*x+s%2*y}
fn g(x:i64,y:i64)->i64 {if x==0 {y} else {g(y%x,x)}}
let mut a=h(x,y);
for i in 1..x+y {for j in 1..y+x {if h(i,j)<h(x,y) && g(i,j)>1 {a-=1;}}}
a
}
```
[Answer]
# JavaScript (ES6), 86 bytes
Takes input in currying syntax `(p)(q)`.
```
p=>q=>(g=x=>x*y?x*q-y*p?g(x+d,g[x/=y]=g[x]||++n,y-=d):n:g(x+!~d,y+=!~(d=-d)))(d=n=y=1)
```
[Try it online!](https://tio.run/##TZDJasMwEIbveYrJSVIst/WeGMaml0JpoQ9QcgiRY1qCd4oFIa/uSnaaKRjkT/8yY38ffg79sftqBreqVTGdcGowazHjJY6YjRudj5vW1ZsmL/noKFl@jo@o92jO/eXiOJXULiqRVqnV11cltYPrK1foKiGEOSvU6IlpKPoBEHgjoZXQCcAMjnXV1@fi4VyXnDXIwAEjs3Z@My7muhkz5qI3yRNvBG/FDRE6yIF9vDFIgb08v74zsVrZIdyTYB@xkD@TL@6auQiIAgkhOX3KBXMuulE4U0yacSaUMxdb6jTmHVFkok9kDWl8MAc9GuHTotHyEX9ivOA/1a4aUNQWhdRr941oqG2LaSXblhAmBrdkjumXBEt0J6Zf "JavaScript (Node.js) – Try It Online")
[Answer]
# Javascript, 79 bytes
```
a=(p,q)=>p*q==1?1:1+((p+q)%2?q==1?a(p-1,q):a(p+1,q-1):p==1?a(p,q-1):a(p-1,q+1))
```
(I am new to code golfing, so this can probably be improved easily)
## Explanation
```
let a = (p, q) => p * q == 1 // If they are both 1
? 1
// Do a recursive call and increment the result by 1
: 1 + (
(p + q) % 2 // If on an even-numbered diagonal
? q == 1 // If at the beginning of the diagonal
? a(p - 1, q) // Go to previous diagonal
: a(p + 1, q - 1) // Go one back
: p == 1 // rougly the same
? a(p, q - 1)
: a(p - 1, q + 1)
)
```
] |
[Question]
[
Your task is to write a computer program such that when it is cut up into lines (split on the newline character) every arrangement of the lines will output a different number between **1** and **n!** (where **n** is the total number of lines). No number should be output by two different arrangements and every arrangement should output a number on this range. Since there are **n!** ways to arrange the lines of a program this means each number should be output by one rearrangement.
For example the python program
```
print 1;"""
print 2;"""
```
Has two arrangements
```
print 1;"""
print 2;"""
```
and
```
print 2;"""
print 1;"""
```
The first outputs `1` and the second outputs `2`.
You may use whatever output formats are standard in the language you are using. You may not assume any sort of boilerplate. I think this challenge is more interesting if you have to work around whatever formats the language insists on.
## Scoring
Your score will be the number of lines in your program with a higher score being better. You may choose to output numbers from **0** to **n!-1** if you would like.
[Answer]
## [CJam](https://sourceforge.net/p/cjam), score: ∞
Each line is of the form
```
];Lx+:L{__(f<0+:+\,,(;1+:**\(;}h]:+
```
where `x` is a number from `0` to `n-1`. The result is in the range `0` to `n!-1`.
[Try it online!](https://tio.run/##S85KzP3/P9bax1Dbyqc6Pl4jzcZA20o7RkdHwxoopKUVo2FdmxFrpc0FVGNEhBoDAmr@/wcA "CJam – Try It Online") (For `n=3`.)
Credits to [jimmy23013](https://codegolf.stackexchange.com/a/34808/8478) for the code that computes the actual permutation index. I've only replaced the bit that reads the input with `];Lx+:L` which discards the result from the previous line and then adds the index of the current line to the variable `L` (which is initially an empty array).
[Answer]
# Perl: ∞
```
$z.="-1,";$_.=A;END{$m.=!!s/./{${z}B}/g,map(/B/||s/\d+\K/,/g*/(-\d*,).*\1/||($n{$_}||=$m++),sort glob),print$n{$z}if/A/}
$z.="-2,";$_.=A;END{$m.=!!s/./{${z}B}/g,map(/B/||s/\d+\K/,/g*/(-\d*,).*\1/||($n{$_}||=$m++),sort glob),print$n{$z}if/A/}
$z.="-3,";$_.=A;END{$m.=!!s/./{${z}B}/g,map(/B/||s/\d+\K/,/g*/(-\d*,).*\1/||($n{$_}||=$m++),sort glob),print$n{$z}if/A/}
```
Extend to any length you like
Will quickly run out of memory since memory usage is like O(n^n). It would however be easy to replace the permutation indexer by O(n) code, just longer. I'm just illustrating the way you can use `END{}` for this task in perl. All `END{}` blocks run at exit time, but only the first one that get called (the one last in the code) will output anything due to the `/A/` test which is only true once
Notice that the `$m` counter must count as a string because as a number it would overflow (later than the end of the universe but it's the principle that counts). For the same reason I "count" the number of lines by constructing a string of `A`s instead of using a real counter though this overflow would happen even later.
Another way to do this in perl:
```
@{$b.=A; if($a eq $b) {use bigint; $n=0;$n++for@F;$c=0;$c=$c*$n--+map{$z=$_;$a=grep$_&&$_>$z,@F;$_=0;}@F;print$c}}=()x push@F,"1".!($a.=A),
@{$b.=A; if($a eq $b) {use bigint; $n=0;$n++for@F;$c=0;$c=$c*$n--+map{$z=$_;$a=grep$_&&$_>$z,@F;$_=0;}@F;print$c}}=()x push@F,"2".!($a.=A),
@{$b.=A; if($a eq $b) {use bigint; $n=0;$n++for@F;$c=0;$c=$c*$n--+map{$z=$_;$a=grep$_&&$_>$z,@F;$_=0;}@F;print$c}}=()x push@F,"3".!($a.=A),
```
This uses that fact that in `foo = bar` `bar` is executed after `foo`. This version by the way doesn't go crazy in time and space but that makes the code longer
Yet another idea is to use `DESTROY` which has the advantage that only one of them will be executed. I'm not going to repeat the permutation indexing code of which I already gave two examples.
```
push@F,"1";bless\@F;DESTROY{print"Work out permutation index of @{$_[0]}\n" }
push@F,"2";bless\@F;DESTROY{print"Work out permutation index of @{$_[0]}\n" }
push@F,"3";bless\@F;DESTROY{print"Work out permutation index of @{$_[0]}\n" }
```
Or using `BEGIN`:
```
BEGIN{push@F,"1"} print"Work out permutation index of @F\n"; exit;
BEGIN{push@F,"2"} print"Work out permutation index of @F\n"; exit;
BEGIN{push@F,"3"} print"Work out permutation index of @F\n"; exit;
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ∞
```
;3ÇQŒ¿$⁼Q$?
;2ÇQŒ¿$⁼Q$?
;1ÇQŒ¿$⁼Q$?
```
(Example with `n=3`.)
[Try it online!](https://tio.run/##y0rNyan8/9/a@HB74NFJh/arPGrcE6hiz2VthC5giCrw/z8A "Jelly – Try It Online")
~~23~~ ~~13~~ 11 bytes per line.
For a program with `n` lines, the lines will have the format
`;` `<i>` `ÇQŒ¿$⁼Q$?`
where `<i>` represents the number literal `i` and each line has a different value for `i` ranging from `1` to `n`. (The values for `i` don't actually have to be these specific numbers, they just have to have unique positive values.) This program no longer uses `n` in the line structure.
**How?**
* Without an argument Jelly starts with `0`.
* `;1` appends `1` to `0` or the active list.
* `⁼Q$` is the conditional monad for the if statement (`?`) that checks whether the list's elements are unique. If they are, the link above is called (`Ç`) and another number is appended to the list. If they are not unique, that means we have wrapped around to the first link. The repeated element is removed from the list (`Q`) and the index of the permutation is found (`Œ¿`). Note that there is a `0` at the beginning of the list when `Œ¿` is taken but it does not affect the output since the values for `i` are all positive.
### New Jelly feature
With the newly added `Ƒ` quick, we can reduce `⁼Q$` to `QƑ`, saving a byte.
**10 bytes/line** (for single digits)
```
;1ÇQŒ¿$QƑ?
```
[Try it online!](https://tio.run/##y0rNyan8/9/a8HB74NFJh/arBB6baP//PwA "Jelly – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 3
```
(({}){})
({}())
(()(){([()()]{})()(){[()()](<{}>)}}{})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0OjulYTiLiAtIYmkNLQ1NCs1ogGUbFAcTAXwtOwqa6106ytBYr@/28AAA "Brain-Flak – Try It Online")
I posted this in chat earlier but hopefully by posting it here people can build off of it.
## Explanation
We start with the basic program
```
(({}){})
({}())
```
This scores 2 on its own. In order to step up to the next level I want to add a new line. My begining guess was
```
(()(){[()()]{}(<()>)}{})
```
This sets the TOS to `2` if it it is zero and does nothing otherwise. This actually is a good start. With the other two lines we are able to get all the numbers from `1` to `6` except `4`, because there are `2` ways to output `2`:
```
({}())
(({}){})
(()(){[()()]{}(<()>)}{})
```
and
```
({}())
(()(){[()()]{}(<()>)}{})
(({}){})
```
In order to remedy this we make our line also set `2` to be `4`. This can be done with
```
(()(){([()()]{})()(){[()()](<{}>)}}{})
```
For clarity this basically implements the Haskell function
```
f 0 = 2
f 2 = 4
f x = x
```
This fixes our problem because one of the programs that was previously outputting `2` now outputs `4` with no other program changing.
[Answer]
# Java 7, score: ∞
```
public class DerangedRearrangements implements B{public void a(){System.out.println("0");}public static void main(String[]a)throws Exception{java.util.regex.Pattern p=java.util.regex.Pattern.compile("^(?:public )?class ([\\w]+).*");java.io.BufferedReader r=new java.io.BufferedReader(new java.io.FileReader("./DerangedRearrangements.java"));String line; while((line=r.readLine())!=null){java.util.regex.Matcher m=p.matcher(line);if(m.matches()){((B)Class.forName(m.group(1)).getDeclaredConstructor().newInstance()).a();}}}}interface B{void a();}
class b1 implements B{public void a(){System.out.println(getClass().getName().substring(1));}}
```
[Try it online!](https://tio.run/##tZLJTsMwEIbvPIXJyQZh9rWKKpVFQqII0SOL5CaT1MWbHIcWVX32MElThAQcOOQ29oy/@Wd@T8W72LEOzDR9q6pEiaIg42MitVOgwYSCDBauHCuZkHcrUyIoW4w@igCa2zJw56UJytAcwmX9ljKO4b3QgFFRjouABTndZ6y3XG60@LOO8C1o1WUopPl3n2gvQlJbWAQR1vUaaXTUdHt6ESxMvJ0V5HqegAvSmsUU18jLIBX3kMOcP4gQwBvi4j8yPLHaSQU0eqX9i7Yj66@006fn59nLNuNbKKcBSMsHZZaBh/QRRAqe@NjAjPyepN9TN9ilvY74br0WXqci3NlqIKKkgR6ZTWo5tD7EHsWK9A5DythmbEql2I8ZhyIkE1SiY8f1Km5es57MqG6v0DK2oHTAGv94Zn3jnua5t6WrnasdvQIcHOVfWoOWlkmwHg3GKW7xLExSy@DoGbq8XKJV4DORAHq6NrP39bn2u/27B93ij7rFH3aLP@8Wf9ot/qQbfFV9Ag "Java (OpenJDK 8) – Try It Online")
This is can print out **0** to **n!-1**. Additional lines are of the following format (where INDEX is a number from **1** to **n!-1**):
```
class b<INDEX> implements B{public void a(){System.out.println(getClass().getName().substring(1));}}
```
This method works by reading its own source in order to determine the order classes are listed in it. Unfortunately there was no cooler method I could find by parsing the compiled file or creating a custom ClassLoader thanks to how java does JIT compilation. I suppose I could have each additional class just print out a statically defined number but this seemed more fun. That would also make it so I could remove the `B` interface but the scoring isn't based on bytes so I'll leave that in for fun.
### How it works (high level):
Reads its own source code line by line. Since each line declares a new class, we use reflection to create an instance of the new class and invoke it's `a` method which it needs to have because it implements the `B` interface.
[Answer]
# [Ruby](https://www.ruby-lang.org/), score: ∞
```
(a||=[])<<2;a.size<3?0:(p 1+a.sort.permutation.to_a.index(a))
(a||=[])<<1;a.size<3?0:(p 1+a.sort.permutation.to_a.index(a))
(a||=[])<<3;a.size<3?0:(p 1+a.sort.permutation.to_a.index(a))
```
[Try it online!](https://tio.run/##KypNqvz/XyOxpsY2OlbTxsbIOlGvOLMq1cbY3sBKo0DBUBvIzy8q0StILcotLUksyczP0yvJj0/Uy8xLSa3QSNTU5ELoNqRItzHpuv//BwA "Ruby – Try It Online")
This program has 61 bytes per line (for n<10). It has the same basic format as [dylnan's solution](https://codegolf.stackexchange.com/questions/155281/deranged-rearrangements/155300#155300); the first number in each line will be a different value between `1` and `n`, and the second number in each line will be `n`.
I was hoping to find a way to avoid including `n` in the program, but I couldn't find one.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 2 (with `-d`)
```
{}(@ltN)
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/38ZOo7o2WkMzVhNIO@SUGGpyoQsZaf7//183BQA "Brain-Flak – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score: 1,114,112
```
0ˆ¯JD{œsk
1ˆ¯JD{œsk
2ˆ¯JD{œsk
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f8HTbofVeLtVHJxdncxkhc4yROP//AwA "05AB1E – Try It Online") 0-indexed. The ˆ at the start of each line pushes the distinct characters to the global array. The rest of the code is uselessly executed except on the last line, where it concatenates the values into a string, then finds its permutation index. 1,114,112 is the number of possible Unicode characters at time of writing (code points 48-57 are the easiest to demonstrate with of course).
] |
[Question]
[
Given two *different* lists of non-negative integers, return the list that has the highest maximum (e.g. `[4, 2], [3, 3, 1] -> [4, 2]`).
If they both have the same maximum, return the list that contains more instances of this maximum (e.g. `[4, 2, 4], [4, 3, 3, 3, 1, 3] -> [4, 2, 4]`).
If, after these comparisons, they are equal, do the same comparison but with their next highest item (e.g. `[2, 3, 4, 4], [4, 4, 3, 3, 1] -> [4, 4, 3, 3, 1]`).
If, after all these comparisons, they are still considered to be equal, output the longer list (e.g. `[4, 3, 2, 1, 0], [1, 2, 3, 4] -> [4, 3, 2, 1, 0]`).
Make your code as short as possible.
### Test Cases
```
[4, 4, 4, 4, 2, 4], [4, 4, 4, 4, 3, 2] -> [4, 4, 4, 4, 2, 4]
[0], [] -> [0]
[0, 0], [0] -> [0, 0]
[1], [0, 0] -> [1]
[4, 4, 4, 4, 4, 2], [4, 4, 4, 4, 4] -> [4, 4, 4, 4, 4, 2]
[1, 0], [0, 0, 0] -> [1, 0]
```
[Answer]
# Pyth, 4 bytes
```
eo_S
```
[Try it online](http://pyth.herokuapp.com/?code=eo_S&input=%5B4%2C%204%2C%204%2C%204%2C%204%2C%202%5D%2C%20%5B4%2C%204%2C%204%2C%204%2C%203%2C%202%5D&debug=0)
### Explanation
```
eo_S
o NQ Order the inputs...
_S ... by their reversed sorted values...
e ... and take the last.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
lambda*x:max(x,key=lambda y:sorted(y)[::-1])
```
[Try it online!](https://tio.run/##XY7BCoMwDIbP@hQ5tiMDdZ4KPonroUPLZLNK7aR9@q5VO7ZBSPL9SX4yO3OfVOUlNHD1TzHeOnGybBSWWHz0rtklcGyZtOk74mjL2Lnk1MtJA3khrBQGBSTPSFsjfKIKmSP8aJcgc4pxtYiz1CNsWBxcbhDFnb8tovO/bZ3ukk@oxzVleTbrQRmQ4deV@jc "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
NÞÞṪ
```
[Try it online!](https://tio.run/##y0rNyan8/9/v8LzD8x7uXPW/2Ohw@6OmNe7//0dzKUSb6CjAkRGQjNVBFTMGCsfqABUagGQgLB0FMMcAzDMEM8FCaMaZgLWiiUH0wEwA0hCdsQA "Jelly – Try It Online")
### How it works
```
NÞÞṪ Main link. Argument: [u, v] (pair of vectors)
Þ Sort [u, v], using the link to the left as key.
NÞ Sort u (or v) by the negatives of its values.
This sorts the vector in descending order.
Ṫ Tail; select the last, lexicographically larger vector.
```
[Answer]
## Haskell, ~~37~~ 35 bytes
```
import Data.Lists
argmax$sortOn(0-)
```
The input is taken as a two element list, e.g. `( argmax$sortOn(0-) ) [[4,4,4,4,2,4], [4,4,4,4,3,2]]`.
Find the element in the input list which is the maximum after sorting by negating the values (i.e. descending order).
[Answer]
# [Clean](https://clean.cs.ru.nl), 42 bytes
```
import StdEnv
s=sortBy(>)
?a b|s a>s b=a=b
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4yr2LYYyHOq1LDT5LJPVEiqKVZItCtWSLJNtE36H1ySCFRpq2CvEG2iowBHRkAyFlXIGCga@/9fclpOYnrxf11Pn/8ulXmJuZnJxQA "Clean – Try It Online")
[Answer]
# JavaScript (ES7), 52 bytes
```
(a,b,m=d=>d.map(n=>N+=1e4**n,N=0)&&N)=>m(a)>m(b)?a:b
```
This method works *without* sorting the arrays. Instead, it calculates the sum of 10,000 raised to each array's elements. The largest sum represents the array with the highest score. (This solution assumes that neither array has more than 10,000 elements.)
**Test cases**
```
let f=
(a,b,m=d=>d.map(n=>N+=1e4**n,N=0)&&N)=>m(a)>m(b)?a:b
console.log(JSON.stringify(f([4, 4, 4, 4, 2, 4], [4, 4, 4, 4, 3, 2]))); // [4, 4, 4, 4, 2, 4]
console.log(JSON.stringify(f([0], []))); // [0]
console.log(JSON.stringify(f([0, 0], [0]))); // [0, 0]
console.log(JSON.stringify(f([1], [0, 0]))); // [1]
console.log(JSON.stringify(f([4, 4, 4, 4, 4, 2], [4, 4, 4, 4, 4]))); // [4, 4, 4, 4, 4, 2]
console.log(JSON.stringify(f([1, 0], [0, 0, 0]))); // [1, 0]
console.log(JSON.stringify(f([3], [11]))); // [11]
console.log(JSON.stringify(f([4, 3, 3, 3, 1, 3], [4, 2, 4]))); // [4, 2, 4]
console.log(JSON.stringify(f([3,3],[3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]))); //[3, 3]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 33 bytes
```
->*a{a.max_by{|x|x.sort.reverse}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf104rsTpRLzexIj6psrqmoqZCrzi/qESvKLUstag4tbb2f4FCmp5GtImOoY6JjrGOaaxOtIEOgqf5HwA "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 79 bytes
```
lambda*a:max(a,key=lambda l:sum(zip(map(l.count,s(l)),s(l)),())[::-1])
s=sorted
```
[Try it online!](https://tio.run/##XU/LDoIwELzzFXtszWoAOTXhS5BDEYjEvtKWRPz5WgoaNdnszszuTLJm8TetyjDWlyC47Hp@4EzyB@F4H5Z6k0AwN0vynAyR3BBxuupZeXREULp3QmnD2LFoaeZqp60f@jBqCxw7mBSQpkL4VBl7i/CjnaPcUoyX@braIUJi@UaLhFct0W/7mvofWe2ud0icycsyAGMn5WGMb0JHwws "Python 2 – Try It Online")
[Answer]
# [Ruby](http://www.ruby-lang.org) 149 bytes
```
->n,m{(n+m).sort.reverse.map{|i|r=((a=n.index(i))&&m.index(i)?(b=n.count(i))==(c=m.count(i))?nil:b>c ?n:m:a ?n:m);return r if r};n.size>m.size ? n:m}
```
[Try it online!](https://tio.run/##dVJBboMwELzzilUOkVFdq2k5ERkeQjkAMa1RbZAxUdLA26lxKG0cYlm72pnZWa9k1eXnsaTv43Mksbgg@SR80tZKE8WOTLWMiKy59LxXFKGMSsLlgZ0Q9/3tVixFjHJDFXUn9URRigoq/upY8q8wjwqIZSjCzCZ/r5julAQFvAQ17CVp@TeLhE0Qg9EMY@IlkAQYlvtqYopvsTcDu5jVQYqn/hdDOie5hyadC839GFyLVU@rW@nfPdI6nrsH8//vFazsGlyN7nW/89febzAHvupu53spYVnxaT4AhgpD3XsATadb2HA55XAzAcBtrBbyo9YzUyYcV@lCsFPDCs0OM1vPhDeMPw)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
►Ö_
```
[Try it online!](https://tio.run/##yygtzv7//9G0XYenxf///z862kQHBo1idRC82FgA "Husk – Try It Online")
This submission basically takes a two-element list of lists as input and retrieves the maximum (`►`), sorted by their values sorted in descending order (`Ö_`).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Σ{R}θ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3OLqoNpzO/7/j4420YFBo1gdBC82FgA "05AB1E – Try It Online")
[Answer]
## JavaScript (ES6), 98 bytes
```
(a,b,g=a=>[...a].sort((a,b)=>b-a),h=([a,...b],[c,...d])=>a==c?h(b,d):a<c|!(1/a))=>h(g(a),g(b))?b:a
```
`g` sorts a copy of its parameter in reverse order (since `sort` mutates the array), while `h` recursively performs the elementwise comparison of the arrays.
[Answer]
# [Perl 6](https://perl6.org), 17 bytes
```
*.max(*.sort(-*))
```
[Test it](https://tio.run/##bVLNioMwEL7nKea0JG4UtdJDg8WH2FvpQdpZKGvb4E@pLPvsbjI1MUIhBOfL9zNmorFtttPQITy2yUmx6wgf1/oZd/e2xzOUU5SYkkeJBXgcCTERqeqx66EEzgD4oZCQHyUcNhLMyo4Cyj3MqCdIKCynIM7MNHtAJgbxczouFolXBeYB5lM2ZGN8UyvMqLJOiypkOJVf@SrRZ@Sr0JBKDpQ1U5xrOreQOnwJzAi39esoe9OIu9EV9qaL4I7dT1vnwPyVKxSzQ/4yU1NMN/UNPmmEin3f23ma8R747gdHXl1ueuiF3D3qZkBe4VPjyTwHIeDXRF26@IyomxGWl@I14Nnmk7BEmzem2N/0Dw "Perl 6 – Try It Online") (Lambda Lambda Lambda)
* `-*` lambda that numerically negates the input
* `*.sort(-*)` lambda that uses that uses the results of applying that to compare elements
* `*.max(*.sort(-*))` lambda that finds the max of those results, and uses that to determine which input to return.
[Answer]
# J, 20 bytes
```
[:{.]\:[:#.[:>\:~&.>
```
Ungolfed:
```
[: {. ] \: [: #. [: > \:~&.>
```
Essentially the Pyth answer, translated unpithily into J.
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62q9WJjrKKtlPWirexirOrU9Oz@a3IpcKUmZ@QraNgYK5gomGoq6FoppCmA2QrWColWMFkTBQg0UjCBqkESAaqE8YwVjGBaDBQMoEqBLKASA5iEIVTYECSoYPAfAA "J – Try It Online")
] |
[Question]
[
For another challenge I am writing, I need to verify that test cases are solveable with bounded integers. Specifically, I need to verify the following, for a non-empty array of integers `A` and an integer bit width `n`:
1. All integers `a` in `A` satisfy `-2**(n-1) <= a < 2**(n-1)` (representable with `n`-bit two's complement integers).
2. The length of `A` is less than `2**n`.
3. The sum of `A` satisfies `-2**(n-1) <= sum(A) < 2**(n-1)`.
4. All combinations of elements in `A` satisfy all of the above conditions.
Naturally, I've decided to outsource this problem to you!
Given an array of integers `A` and a positive integer bit width `n`, verify that `A` satisfies the conditions above.
## Test Cases
```
[0, 0, 0], 2: True
[0, 0, 0, 0], 2: False (violates #2)
[1, 2, 3, 4, 5], 8: True
[1, 2, 3, 4, 5], 2: False (violates all conditions)
[1, 2, 3, 4, 5], 5: True
[-3, 4, 1], 4: True
[10, 0, -10], 4: False (violates #1 and #4)
[27, -59, 20, 6, 10, 53, -21, 16], 8: False (violates #4)
[-34, 56, 41, -4, -14, -54, 30, 38], 16: True
[-38, -1, -11, 127, -35, -47, 28, 89, -8, -12, 77, 55, 75, 75, -80, -22], 7: False (violates #4)
[-123, -85, 6, 121, -5, 12, 52, 31, 64, 0, 6, 101, 128, -72, -123, 12], 12: True
```
## Reference Implementation (Python 3)
```
#!/usr/bin/env python3
from itertools import combinations
from ast import literal_eval
def check_sum(L, n):
return -2**(n-1) <= sum(L) < 2**(n-1)
def check_len(L, n):
return len(L) < 2**n
def check_elems(L, n):
return all(-2**(n-1) <= a < 2**(n-1) for a in L)
A = literal_eval(input())
n = int(input())
OUTPUT_STR = "{}, {}: {}".format(A, n, "{}")
if not (check_elems(A, n) and check_len(A, n) and check_sum(A, n)):
print(OUTPUT_STR.format(False))
exit()
for k in range(1, len(A)):
for b in combinations(A, k):
if not check_sum(b, n):
print(OUTPUT_STR.format(False))
exit()
print(OUTPUT_STR.format(True))
```
[Try it online!](https://tio.run/##hVFBasMwELzrFUtOcrBL3PYUmkMuPQVaWudUSlAcuRGWV0aWS0vI212tGhM7oVRYYGZmd2ZX9bfbG7zrusKaCpST1hmjG1BVbayD3FRbhcIpgw0LEtG4ntQkF3ojP4VmjO1kAfle5uWmaSu@igGjOQOw0rUWIbmdTjkmaQQPCwgC/wc9OCrXEq/KA3aqwJFaalk1V3qhNR9ZioEbFMZ6QCGsyHkJi9EsXGHdOh5FDD2j0J2Bp3X2vM42r9mLZyaHYwyH49zfyY1vWQnHlz5HTMzEd1YFoHHAh0FJEIHA3WDYS4zWE7AwUW0pwtm5t3oUupE@E4D8Uj4dYzRWSWNZgR@Sp3FY2/K3DZFbIodvSjZloAFOac8Rtv1O6fyfgk6f5C91Zlsv7rq3dBaD/5J09s7ufwA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
Max[x=2Tr/@Subsets@#,-x-1,Tr[1^#]]<2^#2&
```
[Try it online!](https://tio.run/##dY/BasNADETv/Q1DTyO60q68G2jAPxAIJDfjgFtSmkNycBwwBH@7o01ONi1oWdCMRk/ntv89ntv@9N1OP7fLetq0Qz2sZd99VLvb1/XYX6sCNBBj39V8KJrmUw6FvE/b7nTpK5up7wyBR4COSM3b34L8J@hMoNzlEWFud3Agdsu@RJCuIA4lzKMeJAwulxzkbVWJwKBgOfY0wDv4NJp7YU3msLKcHO/VZiIkIa1AWRPECFXEZ1EyMpERcR7DYjBJM5ghkdoHtaMZZcCLN2@wwCh4utlCWJrpAQ "Wolfram Language (Mathematica) – Try It Online")
Condition 1 is implied by checking condition 3 for all subsets, including the one-element ones. So we take the max of
* twice the sum of each subset,
* one less than twice the negative of the sum of each subset, and
* the length of the whole set
and check if that's less than `2^#2` (where `#2` is the bit-width input).
At the cost of only 6 more bytes, we can replace `Subsets@#` with `GatherBy[#,Arg]`, which is much more efficient because it computes only the two worst-case subsets: the subset of all nonnegative values, and the subset of all negative values. (This works because `Arg` has a value of `0` on the former and `π` on the latter.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
ŒPS€;⁸L¤ḟ⁹’2*$ŒRṖ¤Ṇ
```
[Try it online!](https://tio.run/##bU8rDkIxEPScogIBpA10230t4QoIApI8iSFcAAcIDoAgQWFIMByAZyEchHeRMttHUCT97ezszHS5WK3WKb0Ok1m9u43q7X38uLzv53pb1ZsT9dqvw/RdHYFV@/S89kFKad7qzK1WpJXTymvFpVaxq/@g9BfljJoGsAB8QxtohWXs4AdRQM1DzKNRgIyLMWcImrb4@Ron0iB44MaLiByMw2HExVLoX2qUtmzRyA6OZQovQi/CzmQOQgeAjG74bhMlIRH0QiNnSfJEbvJJLsPywJx8GnXh879y/Gwp4oGyg5NawlG3VX4A "Jelly – Try It Online")
It suffices to check that `mapped sum of powerset + length of set` is in the required range.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ ~~12~~ 11 bytes
Saved 1 byte thanks to *Mr. Xcoder*
```
æO·D±¹gMIo‹
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8DL/Q9tdDm08tDPd1zP/UcPO//@jjcx1FHRNLXUUjAx0FMx0FAyBlKkxUMzIEMgxi@WyAAA "05AB1E – Try It Online")
**Explanation**
```
æ # powerset of first input
O # sum each subset
· # multiply each element by 2
D # duplicate
± # bitwise negation of each element in the copy
¹g # push length of first input
M # get the maximum value on the stack
Io # push 2**<second input>
‹ # compare
```
[Answer]
## JavaScript (ES6), ~~75~~ ~~63~~ 58 bytes
```
a=>n=>!a.some(e=>(a.length|2*(e<0?l-=e:u+=e))>>n,u=0,l=-1)
```
The sum of any subset of `a` lies between the sums of the negative and nonnegative elements, so checking the two sums suffices for everything except case 2. Edit: Saved ~~12~~ 17 bytes thanks to @Arnauld.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 bytes
```
»0,«0$S€~2¦Ḥ;LṀ<2*Ɠ¤
```
[Try it online!](https://tio.run/##ZVHBbhMxEL37K0ZRJULllbLebLJAhcQBDohT4RbtwXQnilPHXna9TXpBgSO9UPUKh0oVHOADiipxSKT@R/IjYexEVFWttT3jN@/Ns3eMWp9uNoubDl/86uy9XX/@/VEsfqyur569Wf2ZH4j924vF1WY9/8ZezkotjXTKGhjaCtwIabcOq6eMHaIstDII0hSAJ1IzeFGW@hSW5zhzQNAxyBokTKyRBbRf@74wrWQZMEIq25iCg5b1rpyBqqkJLXjXmUNtYfkTCou1eeRgaqvjxwxoHGKJ0sGBMmXjnoNTE6yhPVQV6Zlm8h4rr7eL7BAcEnAka6y3fBqr6y/4ocEGoV3hxJ7Q/QIdNU7QOA7TkToaeZnOfw6xbs5MgTNQxtnwKFrRm0gNg9a7qsEWh9YrqWts5Xec@2NslYGpcqN7dE9k6/l3xm4vlud7sPy6uPQWfUP6H16btiBNVTBef/rLYRPHbNDhsPtyJrZpCGIOgkPCocshzVn24ORhTcoG0TaJc9YleCscxZ2Qij7F6RPi0GGPimhLqT4SpBP3Qo8o8VIEduks6nqyX1JaEipPspzFPV@WechPzw3KSeoZFAnCMmoThRoy2KfDlND@bkaZdyVEzvokFQvvIUu3nryXKPUBcfzlKO91wz2C5dDOC/dFUE98TqbEPw "Jelly – Try It Online")
Linear time complexity solution. Turns out that I over-estimated the time complexity
>
> [in The Nineteenth Byte, 2017-12-11 13-15-03Z,](https://chat.stackexchange.com/transcript/240?m=41665393#41665393) by user202729
>
>
>
> >
> > @NewSandboxedPosts "Real" subset sum problem are much harder. This one can be done in linearithmic time...
> >
> >
> >
>
>
>
because now I realize sorting the array is completely unnecessary.
---
Explanation:
```
»0,«0$S€~2¦Ḥ;LṀ<2*Ɠ¤ Main link. Example list: [-1, 0, 1]
»0 Maximize with 0. Get [0, 0, 1]
, Pair with
«0$ minimize with 0. Get [-1, 0, 0]
S€ Sum €ach. Get [1, -1]
~ Inverse
¦ at element
2 2. (list[2] = ~list[2]) Get [-1, 2]
Ḥ Unhalve (double, ×2). Get [-2, 4]
; Concatenate with
L Length (3). Get [-2, 4, 3]
Ṁ Maximum of the list (4).
< ¤ Still less than
2 two
* raise to the power of
Ɠ eval(input())
```
[Answer]
# JavaScript (ES6), 114 bytes
Takes input in currying syntax `(A)(n)`. Returns a boolean.
```
A=>n=>!(A.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).some(a=>(s=eval(a.join`+`),s<0?~s:s)>>n-1)|A.length>>n)
```
### Test cases
```
let f =
A=>n=>!(A.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).some(a=>(s=eval(a.join`+`),s<0?~s:s)>>n-1)|A.length>>n)
console.log('[Truthy]')
console.log(f([0, 0, 0])(2))
console.log(f([1, 2, 3, 4, 5])(8))
console.log(f([1, 2, 3, 4, 5])(5))
console.log(f([-3, 4, 1])(4))
console.log(f([-34, 56, 41, -4, -14, -54, 30, 38])(16))
console.log(f([-123, -85, 6, 121, -5, 12, 52, 31, 64, 0, 6, 101, 128, -72, -123, 12])(12))
console.log('[Falsy]')
console.log(f([0, 0, 0, 0])(2)) // violates #2
console.log(f([1, 2, 3, 4, 5])(2)) // violates all conditions
console.log(f([10, 0, -10])(4)) // violates #1 and #4
console.log(f([27, -59, 20, 6, 10, 53, -21, 16])(8)) // violates #4
console.log(f([-38, -1, -11, 127, -35, -47, 28, 89, -8, -12, 77, 55, 75, 75, -80, -22])(7)) // violates #4
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 20 bytes
```
>EleS++KyMsMyQmt_dKl
```
**[Try it here!](https://pyth.herokuapp.com/?code=%3EEleS%2B%2BKyMsMyQmt_dKl&input=%5B27%2C+-59%2C+20%2C+6%2C+10%2C+53%2C+-21%2C+16%5D%0A8&debug=0)**
[Answer]
## Clojure, ~~121~~ 117 bytes
```
#(let[l(int(Math/pow 2(dec %2)))](every?(set(range(- l)l))(cons(count %)(for[i(vals(group-by pos? %))](apply + i)))))
```
Well that was a bit dumb, splitting into positive and negative values is a lot better than sorting. Original, but surprisingly not much longer:
```
#(let[l(int(Math/pow 2(dec %2)))S(sort %)R reductions](every?(set(range(- l)l))(concat[(count S)](R + S)(R +(into()S)))))
```
This works by checking prefix sums of the sequence in ascending and descending order, I think it isn't necessary to generate all combinations of elements in `A`.
`(into () S)` is in effect same as `(reverse S)`, as lists grow from the head. I couldn't figure out a way to use `cons` instead of `concat` when there are two lists to `cons` to. :/
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
ŒPS€Ḥ;~$;LṀl2<Ɠ
```
[Try it online!](https://tio.run/##y0rNyan8///opIDgR01rHu5YYl2nYu3zcGdDjpHNscn//1v8jzYy11HQNbXUUTAy0FEw01EwBFKmxkAxI0MgxywWAA "Jelly – Try It Online")
### Explanation
```
ŒPS€Ḥ;~$;LṀl2<Ɠ ~ Monadic full program.
ŒP ~ Powerset.
S€ ~ The sum of each subset.
Ḥ ~ Double (element-wise).
;~$ ~ Append the list of their bitwise complements.
;L ~ Append the length of the first input.
Ṁ ~ And get the maximum.
l2 ~ Base-2 logarithm.
<Ɠ ~ Is smaller than the second input (from stdin)?
```
Saved 1 byte thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) (reading the second input from STDIN instead of CLA).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
≥Lḋ▲ṁ§eLöa→DΣṖ
```
Going with brute force by looping over all sublists, since splitting into positive and negative parts takes more bytes.
[Try it online!](https://tio.run/##AUIAvf9odXNr///iiaVM4biL4pay4bmBwqdlTMO2YeKGkkTOo@G5lv///1syNywtNTksMjAsNiwxMCw1MywtMjEsMTZd/zg "Husk – Try It Online")
## Explanation
```
≥Lḋ▲ṁ§eLöa→DΣṖ Implicit inputs, say A=[1,2,3,4,5] and n=5
Ṗ Powerset of A: [[],[1],[2],[1,2],..,[1,2,3,4,5]]
ṁ Map and concatenate:
Argument: a sublist, say S=[1,3,4]
Σ Sum: 8
D Double: 16
→ Increment: 17
öa Absolute value: 17
§eL Pair with length of S: [3,17]
Result is [0,1,1,3,1,5,2,7,..,5,31]
▲ Maximum: 31
ḋ Convert to binary: [1,1,1,1,1]
L Length: 5
≥ Is it at most n: 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~72~~ ~~71~~ 70 bytes
```
def f(x,n):t=2*sum(k*(k<0)for k in x);max(2*sum(x)-t,~t,len(x))>>n>0>_
```
Output is via [presence/absence of an error](https://codegolf.meta.stackexchange.com/a/11908/12012).
[Try it online!](https://tio.run/##bU9Nb4JAED3rr5iLEcxuAgsr1FZuemwvvRljaLtEgiJZlxQv/ev2DbRc2oSd3TfvY4bm5o6XWt3vH6agwutE7a/cWi2u7dmrFl71FPjFxVJFZU2d/3jOO28gO1868eXEydR4@1lWZ0F2uH8ey5OhV9ua1XTi7A114o7mUNZN62hN/e356Da2rB3NZzJRV6KZamlOMxq1ApLCW4x4tHgcDmS6d9M42rxsN9ZeLA96syavRuY5P5uRGqzb/HQ1/n0XCOJvL0hNf8GIQ1RBkaBYkEYr/dv6R6WnOzmgECiGYAiVYTBglQDoB9jQXUKGS8MhFaLC5TBIRhwHNkZTxmznolEi6KN0z1rWpczxYXefHWm24KXApRgkew22TNDUYJOfI1NeTCmEJcgKFa@R6mEtXkdqfsDEvwi8jPt/6bfu53Fyovr4iDGvpb4B "Python 2 – Try It Online")
] |
[Question]
[
We have objects that oscillate between two integer points, `[l, r]`, at the speed of one unit per time unit, starting at `l` on `t=0`. You may assume `l < r`. For example, if an object oscillates on `[3, 6]`, then we have:
```
t=0 -> 3
t=1 -> 4
t=2 -> 5
t=3 -> 6
t=4 -> 5
t=6 -> 4
t=7 -> 3
t=8 -> 4
```
Etc. But objects oscillate continuously, so we also have `t=0.5 -> 3.5` and `t=3.7 -> 5.3`.
Given two objects oscillating between `[l1, r1]`, `[l2, r2]`, determine if there is ever a time `t` such that the two objects share the same position. You make take `l1, r1, l2, r2` in any convenient format, and output any truthy/falsy values.
---
Truthy inputs:
```
[[3, 6], [3, 6]]
[[3, 6], [4, 8]]
[[0, 2], [2, 3]]
[[0, 3], [2, 4]]
[[7, 9], [8, 9]]
```
Falsy inputs:
```
[[0, 3], [3, 5]]
[[0, 2], [2, 4]]
[[5, 8], [9, 10]]
[[6, 9], [1, 2]]
[[1, 3], [2, 6]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
l,r,L,R=input()
d=r-l;k=1
while(R-L)*k%d:k+=1
print r-L>=k%2*d/k<=R-l
```
[Try it online!](https://tio.run/##TYzdCoJAEIXv9ykGQfBnltRVK2t7Aq@8Da9SUHYxWTaqp99GjQgOh/nmnJn5bYf7lLnnMOoe0qp/9TfP85xGgzU2cpzmhw1C1knD9UnJlK3NoOF1GCm/q1RMu9mMkwXD64tUfhZ1O3WWDddu@XQVCCXC4i37Qo5wIEgQslViA7FCTrBHOFKH/JeQiv@bpVZsHYQ0ISq3kdL2Aw "Python 2 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
VEΣUẊeTmȯ…¢mD
```
Takes input in format `[[l,r],[L,R]]`.
Returns `0` for falsy instances and a positive integer for truthy instances.
[Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/Ya7nFoc@3NWVGpJ7Yv2jhmWHFuW6/P//PzraWMcsVgdMxnLBeCY6FmCegY4RkGekYwzlGYN5JmCeuY4lkGcBJBFyxjqmKPogKk2BpulEW@oYGoC5ZmCNhkAlsQA "Husk – Try It Online")
## Explanation
The main ideas are
1. A collision can only happen at an integer or half-integer coordinate.
2. It's enough to simulate the system until a repetition of two consecutive states is encountered.
Here's the code annotated.
```
VEΣUẊeTmȯ…¢mD Implicit input, say [[0,2],[2,3]]
mȯ For both pairs do:
mD Double each: [[0,4],[4,6]]
¢ Cycle: [[0,4,0,4..],[4,6,4,6..]]
… Rangify: [[0,1,2,3,4,3,2,1,0,1,2..],[4,5,6,5,4,5,6..]]
T Transpose: [[0,4],[1,5],[2,6],[3,5],[4,4],[3,5],[2,6]..
Ẋe Adjacent pairs: [[[0,4],[1,5]],[[1,5],[2,6]],[[2,6],[3,5]],[[3,5],[4,4]]..
U Prefix of unique elements: [[[0,4],[1,5]],[[1,5],[2,6]],[[2,6],[3,5]],[[3,5],[4,4]]..[[1,5],[0,4]]]
Σ Concatenate: [[0,4],[1,5],[1,5],[2,6],[2,6],[3,5],[3,5],[4,4]..[1,5],[0,4]]
VE Index of first pair whose elements are equal (or 0 if not found): 8
```
[Answer]
# JavaScript (ES6), ~~104~~ 100 bytes
A naive implementation that just runs the simulation. Takes **(a, b, c, d)** as 4 distinct variables.
```
(a,b,c,d)=>(g=(X,Y)=>x==y|x+X==y&(y+=Y)==x||(x+=X)-a|y-c&&g(x>a&x<b?X:-X,y>c&y<d?Y:-Y))(1,1,x=a,y=c)
```
### Test cases
```
let f =
(a,b,c,d)=>(g=(X,Y)=>x==y|x+X==y&(y+=Y)==x||(x+=X)-a|y-c&&g(x>a&x<b?X:-X,y>c&y<d?Y:-Y))(1,1,x=a,y=c)
console.log('Truthy')
console.log(f(3, 6, 3, 6))
console.log(f(3, 6, 4, 8))
console.log(f(0, 2, 2, 3))
console.log(f(0, 3, 2, 4))
console.log(f(7, 9, 8, 9))
console.log('Falsy')
console.log(f(0, 3, 3, 5))
console.log(f(0, 2, 2, 4))
console.log(f(5, 8, 9, 10))
console.log(f(6, 9, 1, 2))
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~77~~ ~~69~~ 61 bytes
```
If[#>#3,#0[##3,#,#2],(z=GCD[x=#-#2,#3-#4])Mod[x/z,2]<=#2-#3]&
```
A pure function taking the four arguments `l1, r1, l2, r2` as input: e.g., `[0,3,2,4]` when the intervals are `[0,3]` and `[2,4]`.
[Try it online!](https://tio.run/##XY5BC4JAEIXv/YqFgSh4ku6qKWQERtEh6L7sQSpJaBVEQYx@@6aURl3m8c28eTM6qW5XnVTZOTFpnUfmkEpakwDZknoBcYVZG@3jrWwisoiDhEWumh@Li2wWLbhaRcQtEmpqTmWWV5u4uNc63xWllpNHlyoFfLCuKEzYyC6CgW1wMA7xZdGzO/ASIViA8Gcu4P3tj34PAVgIxx4afh/gdK9@2Hkf8NVTmRc "Wolfram Language (Mathematica) – Try It Online")
### How it works
To get a point in `[a,b]` close to a point in `[c,d]`, assuming `a<c<b<d`, we want an odd multiple of `b-a` within `b-c` of an even multiple of `d-c`. If `b-a` has more factors of `2` than `d-c`, we can make this happen exactly: there will be a time when the first point is at `b` and the second point is at `c`, and then we're in good shape. If not, then the best we can do is the GCD of `b-a` and `d-c`.
[Answer]
## JavaScript (ES6), 89 bytes
```
(a,b,c,d)=>[...Array((b-=a)*(d-=c)*4)].some((g=e=>i/e&2?e-i/2%e:i/2%e,i)=>a+g(b)==c+g(d))
```
Takes `l1,r1,l2,r2` as separate arguments. Explanation: The simulation is guaranteed to repeat after `(r1-l1)*(r2-l2)*2` time units (or a factor thereof); `g` calculates the offset of the appropriate object after `i/2` time units, so `i` needs to range up to `(r1-l1)*(r2-l2)*4`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ ~~10~~ 14 bytes
*+4 bytes to handle negative ranges*
Return 0 if falsy, or a positive integer otherwise
Use [Zgarb's idea](https://codegolf.stackexchange.com/a/146129/73296) of doubling values to make same position detection easier
Thanks to @Zacharý for pointing out my mistakes
```
ÄZU\·εXиŸ}øüQO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cEtUaMyh7ee2RlzYcXRH7eEdh/cE@v//Hx2ta2hgYKBjGKsTDSJjAQ "05AB1E – Try It Online")
**Explanations:**
```
ÄZU\·εXиŸ}øüQO
ÄZU\ Store in X the largest absolute number in the lists
· Double lists ([3,6],[4,8] => [6,12],[8,16])
ε } For each...
X Push X
и List-repeat that much times ([6,12]*12 => [6,12,6,12,6,...])
Ÿ Rangify ([6,12,6,...] => [6,7,8,9,10,11,12,11,...])
ø Zip lists ([6,7,8,...],[8,9,10,...] => [6,8],[7,9],[8,10],...)
üQ 1 if both elements of a pair are equal, 0 otherwise
O Sum result list (=0 if the same position is never shared)
Implicit output
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 81 bytes
```
(l,r,L,R)->{int d=r-l,k=0;for(;(R-L)*++k%d>0;);return(r-L<R-l?r-L:R-l)>=k%2*d/k;}
```
[Try it online!](https://tio.run/##jZBPb4IwGIfvfor3YtLqC0NRp@tgt53YBY9mh8ofg9RCSjFZCJ@dFfRe0zS/pH36/Npe@Z07VZ3Ja1oOdXsWRQKJ4E0DP7yQ0M0ACqkzlfMkg2/o4FxVIuMScmLWQeC4DeoR0SNiyqA3B5@6RnNt4l4VKdyMlBy1KuTl9AtcXRo6dYBx58FABCqMMKZO2I2mNFCOwDLwWF4pwkjsRHSxXJbzNPQYZSrTrZJEOdFn7Igvkx8maRiU8/UifStZP7BJfvxrdHZzq1a7tenWQpLczYmPOzSTUiu1wb2F8nBthm@lfENtLNQ7HnCPhxdcPm5fupetcTv24cqzYLsRwrWFWk2PfH5rP@uHfw "Java (OpenJDK 8) – Try It Online")
Reusing [xnor's Python algorithm](https://codegolf.stackexchange.com/a/146113/16236).
] |
[Question]
[
Anyone here a die-hard Bethesda fan? Maybe you prefer Obsidian Entertainment? Well, if you're either of those things than the following picture should be relatively familiar to you.
[](https://i.stack.imgur.com/rn77P.jpg)
I've taken the liberty of preparing a rather unique ASCII-Art challenge, so here's the first clue as to what I'm going to have you do:
```
_____________________________________________________
/ \
| _____________________________________________ |
| | | |
| | Welcome to ROBCO Industries (TM) Termlink | |
| | Password Required | |
| | Attempts Remaining: | |
| | | |
| | 0x01 | 0x0D | |
| | 0x02 | 0x0E | |
| | 0x03 | 0x0F | |
| | 0x04 | 0x10 | |
| | 0x05 | 0x11 | |
| | 0x06 | 0x12 | |
| | 0x07 | 0x13 | |
| | 0x08 | 0x14 | |
| | 0x09 | 0x15 | |
| | 0x0A | 0x16 | |
| | 0x0B | 0x17 | |
| | 0x0C | 0x18 | |
| |_____________________________________________| |
| |
\_______________________________________________________/
\_______________________________________/
```
This is a very basic (blank) template for the RobCo Fallout terminal design in pure ASCII, your job will be to:
* First, generate this template.
* Then, given a list of strings `l` and a number `0 <= n <= 4` to fill it up!
The two dynamic parts of a fallout hacking terminal are:
# The Number of Attempts
* The number of attempts you have remaining (indicated by space delimited boxes.
+ For the purpose of this challenge you will be using `X` instead of `■`.
# The Passwords
* The passwords, defined by `l`, are interspersed with random printable ASCII symbols.
* The passwords, as you can tell by the example, can wrap multiple rows (`NAMES`).
* All passwords in the terminal screen should have an equal chance of being anywhere.
* All passwords can be expected to be of equal length, though this doesn't matter.
* The list of symbols usable to separate passwords are: `!"#$%&'()*+/:;<=>?@[\]^_{|}`.
* All passwords in `l` must be of equal length.
* PASSWORDS MUST HAVE THE POTENTIAL TO WRAP BETWEEN BOTH COLUMNS.
+ This also goes for rows, but only to a higher byte address (0x18->0x01 is invalid).
* The display space for passwords on either side is 15 wide (with a space on either side).
+ You may assume no words in `l` will be longer than this.
* Passwords are alphabetical only, meaning only letters.
---
Example:
`l = ["SMART","ENACT","SWORE","PITYS","SMELL","CARTS","RACES"]`, `n = 4`
```
_____________________________________________________
/ \
| _____________________________________________ |
| | | |
| | Welcome to ROBCO Industries (TM) Termlink | |
| | Password Required | |
| | Attempts Remaining: X X X X | | # N = 4 drives these X's.
| | | |
| | 0x01 $?_/%$ENACT||"} | 0x0D TYS"_'$\#|^%&{} | |
| | 0x02 }:!*@{/_<"[]#>; | 0x0E #{!"^&\]'|}_[$% | |
| | 0x03 $%&'()*+/:;<\_' | 0x0F }|[(%SMELL/_$@( | |
| | 0x04 ^SMART(!@$*'^_@ | 0x10 []_#!"{|}'%$\&^ | |
| | 0x05 (*@#%}*(!%)^(_! | 0x11 %$}[!\#'^&_]{|" | |
| | 0x06 $%&'()*+/:;<_@) | 0x12 \SWORE|%'_!}\^" | |
| | 0x07 "/')=*%!&>#<:$+ | 0x13 ^{['&$|!_]%\"#} | |
| | 0x08 ;'*$&"(<%!#)RAC | 0x14 ']!|^#[$"_\}&{% | |
| | 0x09 ES:($&';%#+"<*/ | 0x15 @)($!CARTS*!@$_ | |
| | 0x0A ;'*$&"(<%!#)/+: | 0x16 !#%${"'}&[]^|_\ | |
| | 0x0B |'_!}$\%["#^{&] | 0x17 ]"_#$&}^%[{|\'! | |
| | 0x0C #{!"^&\]'|}_[PI | 0x18 _![&#{$%\^'|}"] | | # Notice how PITYS wrapped.
| |_____________________________________________| |
| |
\_______________________________________________________/
\_______________________________________/
```
If `n = 2` on the same example:
```
_____________________________________________________
/ \
| _____________________________________________ |
| | | |
| | Welcome to ROBCO Industries (TM) Termlink | |
| | Password Required | |
| | Attempts Remaining: X X | | # N = 2 drives these X's.
| | | |
| | 0x01 $?_/%$ENACT||"} | 0x0D TYS"_'$\#|^%&{} | |
| | 0x02 }:!*@{/_<"[]#>; | 0x0E #{!"^&\]'|}_[$% | |
| | 0x03 $%&'()*+/:;<\_' | 0x0F }|[(%SMELL/_$@( | |
| | 0x04 ^SMART(!@$*'^_@ | 0x10 []_#!"{|}'%$\&^ | |
| | 0x05 (*@#%}*(!%)^(_! | 0x11 %$}[!\#'^&_]{|" | |
| | 0x06 $%&'()*+/:;<_@) | 0x12 \SWORE|%'_!}\^" | |
| | 0x07 "/')=*%!&>#<:$+ | 0x13 ^{['&$|!_]%\"#} | |
| | 0x08 ;'*$&"(<%!#)RAC | 0x14 ']!|^#[$"_\}&{% | |
| | 0x09 ES:($&';%#+"<*/ | 0x15 @)($!CARTS*!@$_ | |
| | 0x0A ;'*$&"(<%!#)/+: | 0x16 !#%${"'}&[]^|_\ | |
| | 0x0B |'_!}$\%["#^{&] | 0x17 ]"_#$&}^%[{|\'! | |
| | 0x0C #{!"^&\]'|}_[PI | 0x18 _![&#{$%\^'|}"] | | # Notice how PITYS wrapped.
| |_____________________________________________| |
| |
\_______________________________________________________/
\_______________________________________/
```
*These examples were manually crafted, so the distribution is not randomized, sorry.*
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count will be the accepted winner. I will bounty this after 3 days if no answers have been submitted for a total of 250 REP.
[Answer]
## JavaScript (ES8), ~~575~~ ~~568~~ 564 bytes
*Saved 3 bytes thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)*
Takes input in currying syntax `(r)(a)`, where ***r*** is the number of remaining attempts and ***a*** is the array of passwords.
```
r=>a=>[...C=`!"#[]^$%&'*+;<{}=`].reduce((s,c)=>(x=s.split(c)).join(x.pop()),` "%%__
/;;# \\
[ "} $Welcome to ROBCO Industries (TM) Termlink'!Password Required#}'!Attempts Remaining:${" X".repeat(r).padEnd(9)};[$^1=^D<2=^E<3=^F<4*0<5*1<6*2<7*3<8*4<9*5<A*6<B*7<C*8='+"[|
|;;#'|
\\"{_/
}'\\&%/= ]]]]] | }' {%%%<='+ ^#}}}+|
[|*=0x1' "{{{%___$+;#}} !^0x0]ZZZ[|}#;}"&{![+ `).replace(/Z/g,(c,i)=>a.join``[(i%58>>5?y++:x++)%L],x=(R=n=>Math.random()*n|0)(L=360),y=x+180,[...Array(L-(n=a.sort(_=>R(3)-1).length)*a[0].length)].map(_=>a[R(n)]+=(C+`>?@()/:\\_|`)[R(27)]))
```
*Syntax highlighter disabled on purpose. It has no clue what to do with that.*
### Demo
```
let f =
r=>a=>[...C=`!"#[]^$%&'*+;<{}=`].reduce((s,c)=>(x=s.split(c)).join(x.pop()),` "%%__
/;;# \\
[ "} $Welcome to ROBCO Industries (TM) Termlink'!Password Required#}'!Attempts Remaining:${" X".repeat(r).padEnd(9)};[$^1=^D<2=^E<3=^F<4*0<5*1<6*2<7*3<8*4<9*5<A*6<B*7<C*8='+"[|
|;;#'|
\\"{_/
}'\\&%/= ]]]]] | }' {%%%<='+ ^#}}}+|
[|*=0x1' "{{{%___$+;#}} !^0x0]ZZZ[|}#;}"&{![+ `).replace(/Z/g,(c,i)=>a.join``[(i%58>>5?y++:x++)%L],x=(R=n=>Math.random()*n|0)(L=360),y=x+180,[...Array(L-(n=a.sort(_=>R(3)-1).length)*a[0].length)].map(_=>a[R(n)]+=(C+`>?@()/:\\_|`)[R(27)]))
O.innerText = f(3)(["SMART","ENACT","SWORE","PITYS","SMELL","CARTS","RACES"])
```
```
<pre id=O>
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 225 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
R“EC"+w╗─║Z⁰2BΥø‘▓"▲╔⁸‘'²∙+"⅟Δλ≤LK⅟ΗΠ.JN║«⁸⅟‘▓+╬⁷"№D↓tι▲‛Q─Ρδν∙υ4Ρψ▲¦‽↑√Ε┐Ζ5↔‛⅟≤š▼¦⁾○ΔΡ%³‘ū91 tž85ž.ΖX Ο'⁹7žø]Xe@*c{leκψI1ž}_:@øŗ⁄c∑⁄≠}l{"T-)⅞↑°Χpjζ⅓īa0ε+Μ‛⁶ρ\=↔⅟¹‘ψ}¹K@Gŗ'¹nο²²Z+8«m«ο+I{@∑"0x0”Κ}¹6«n_'⁷1ž'⁵16«┐∙ž'⁸4 19∙ž89╬5
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTkyJTIyUiV1MjAxQ0VDJTIyK3cldTI1NTcldTI1MDAldTI1NTFaJXUyMDcwMkIldTAzQTUlRjgldTIwMTgldTI1OTMlMjIldTI1QjIldTI1NTQldTIwNzgldTIwMTglMjclQjIldTIyMTkrJTIyJXUyMTVGJXUwMzk0JXUwM0JCJXUyMjY0TEsldTIxNUYldTAzOTcldTAzQTAuSk4ldTI1NTElQUIldTIwNzgldTIxNUYldTIwMTgldTI1OTMrJXUyNTZDJXUyMDc3JTIyJXUyMTE2RCV1MjE5M3QldTAzQjkldTI1QjIldTIwMUJRJXUyNTAwJXUwM0ExJXUwM0I0JXUwM0JEJXUyMjE5JXUwM0M1NCV1MDNBMSV1MDNDOCV1MjVCMiVBNiV1MjAzRCV1MjE5MSV1MjIxQSV1MDM5NSV1MjUxMCV1MDM5NjUldTIxOTQldTIwMUIldTIxNUYldTIyNjQldTAxNjEldTI1QkMlQTYldTIwN0UldTI1Q0IldTAzOTQldTAzQTElMjUlQjMldTIwMTgldTAxNkI5MSUyMHQldTAxN0U4NSV1MDE3RS4ldTAzOTZYJTIwJXUwMzlGJTI3JXUyMDc5NyV1MDE3RSVGOCU1RFhlQCpjJTdCbGUldTAzQkEldTAzQzhJMSV1MDE3RSU3RF8lM0FAJUY4JXUwMTU3JXUyMDQ0YyV1MjIxMSV1MjA0NCV1MjI2MCU3RGwlN0IlMjJULSUyOSV1MjE1RSV1MjE5MSVCMCV1MDNBN3BqJXUwM0I2JXUyMTUzJXUwMTJCYTAldTAzQjUrJXUwMzlDJXUyMDFCJXUyMDc2JXUwM0MxJTVDJTNEJXUyMTk0JXUyMTVGJUI5JXUyMDE4JXUwM0M4JTdEJUI5S0BHJXUwMTU3JTI3JUI5biV1MDNCRiVCMiVCMlorOCVBQm0lQUIldTAzQkYrSSU3QkAldTIyMTElMjIweDAldTIwMUQldTAzOUElN0QlQjk2JUFCbl8lMjcldTIwNzcxJXUwMTdFJTI3JXUyMDc1MTYlQUIldTI1MTAldTIyMTkldTAxN0UlMjcldTIwNzg0JTIwMTkldTIyMTkldTAxN0U4OSV1MjU2QzU_,inputs=JTVCJTIyU01BUlQlMjIlMkMlMjJFTkFDVCUyMiUyQyUyMlNXT1JFJTIyJTJDJTIyUElUWVMlMjIlMkMlMjJTTUVMTCUyMiUyQyUyMkNBUlRTJTIyJTJDJTIyUkFDRVMlMjIlNUQlMEE0)
Expects array input on the stack and the number input an an input, so `→"` is added in the online program for ease-of-use.
[Answer]
# [Perl 5](https://www.perl.org/), ~~588~~ 560 + 1 (-a) = ~~589~~ 561 bytes
*Cut 28 bytes with the suggestions Dom pointed out*
```
$,=$/;$_=" X"x pop@F;say" "."_"x53," /".$"x53 ."\\",$q="| ".'_'x45 ." |",$e=($b="| |").$"x45 .$b,"$b Welcome to ROBCO Industries (TM) Termlink $b
$b Password Required".$"x27 .$b,"$b Attempts Remaining:$_".$"x(25-length).$b,$e;map{$s.=(grep/[^\w,.`-]|_/,map{chr}33..125)[rand 27]}1..360;($t=substr$s,$r=rand 360-($l=length),$l,$_)=~/[a-z]/i&&(substr$s,$r,$l,$t)&&push@F,$_ while$_=pop@F;@o=$s=~/.{15}/g;printf"$b 0x0%X %s | 0x%02X %s $b\n",$_,$o[$_-1],$_+12,$o[$_+11]for 1..12;say$b.'_'x45 .$b,$q=~y/_/ /r,$q=" \\"."_"x54 ."/",$"x6 .$q=~s/_{15}//r
```
[Try it online!](https://tio.run/##TVFhb9owEP2@X3GyDpqoiZ0E0kpDlsoQlSqVURGkdgKWJcWFaCEJdhB0hf70ZU6oqvnTO733znf3CiFTv6rQ4sh6GHICT@QARV7c3PZU9EoACCUhOfgdiwAjFGsIlMznxMItJ0eoH6EX4cWh62uiqY@aFNzA@ENwJGbtrAUYWwRjeBTpc74RUOYwGX8bjOEuW@5UKROhwJiOTJgKuUmT7Ld2Y/xFOx4ipfa5XMJEbHeJFMtmGO/6s2W/LMWmKJUWbKIkS7LVVwwbkeH5diqyVbk2azGK3iYq3lBRbqykKNjs53xv0V/24hgyq6ae1/LU6VDqer45k1G2BO96cXIp7Vw5PQNLrnaxHhaVhZI3vCZsA1P@8Y2FqYWhyd/ZLLL/LFjSbhv/eRq6NNvtYqfWN7daCvt1kgodwPn0NzlHpd30zfVPbNUrZJKVL/WWzsFpPUFLwVHDluM1GON5pk8eWpjPMLTdhcaXrncuL1138ZJLcOt96lAx/oyrvsaWv7@ykAGTTaKgoz1H3tVxMt2WHK60UssUC5t5mKyqYNSfTGH4vT@YQvA4ngzh4W76I4BgNLy/h4EmA5j0B8MAun/zokzyTFX2yKeO61R29A8 "Perl 5 – Try It Online")
*Previously:*
```
$,=$/;$_=" X"x pop@F;say" "."_"x53," /".($"x53)."\\",$q="| ".('_'x45)." |",$e=($b="| |").($"x45).$b,"$b Welcome to ROBCO Industries (TM) Termlink $b
$b Password Required".($"x27).$b,"$b Attempts Remaining:$_".($"x(25-length)).$b,$e;$s=join'',map{(split//,'!"#$%&\'()*+/:;<=>?@[]^_{|}\\')[int rand 27]}1..360;while($_=pop@F){if(($t=substr$s,$r=rand 360-($l=length),$l,$_)=~/[a-z]/i){substr$s,$r,$l,$t;push@F,$_}}@o=$s=~/.{15}/g;printf"$b 0x0%X %s | 0x%02X %s $b\n",$_,$o[$_-1],$_+12,$o[$_+11]for 1..12;say$b.('_'x45).$b,$q=~y/_/ /r,$q=" \\".("_"x54)."/",($"x6).$q=~s/_{15}//r
```
[Try it online!](https://tio.run/##TVJtb5swGPy@X/HMcwYsgIGGVirzlixKpUrNUoVI7RQyBIuTuCNAMFHT5eWnjxlSbePT4buz7nnOOSsSt6qwTjHxcEgRPKId5FnevfFE9IIAkIlCtHMvdAQEmSqusWaiIEA63lB0gPqThBIqu44rmebgIFlGVRy/Kg5Ia7y1Asc6wjE8sORHtmZQZjAefemP4Dadb0VZcCZAnQw1mLBinfD0p7Tj@I103EdCPGfFHMZss@UFm5/zOFd/7@yVJVvnpZCKdcRTni6vcXhWqY5rJCxdliutkWPmYUGfMp4qir6O8r0q8oSXhOjKW/QOt94Hiqp9aJNr7yP99Lk7nX0P94djECjalKclFFE6B@dqdrRN8@LS8p5XPGGq3GCzO23PF6qKSyq2sRwJCx0XtLFIraHihL5G0XGi41CjJzKNjF8zwrX9f5aGLb18K1bdG6k7HrsZlalPxNzb7pEsvbyQYRb16NbOaj1CS8BBwpblNBjHQSqbCHWcTXFo2DOJ27Zz/m3b9myRFSAnsJ26bRz/q7He0IaeXkhIgBRN1SA7N9XmNXRkzwTp9V4vpVYKBQmbSKSoKn/YG09g8LXXn4D/MBoP4P528s0Hfzi4u4O@JH0Y9/oDHzq/s7zkWSoqY@ialm1VRvQH "Perl 5 – Try It Online")
Input is on one line, space separated: first the strings, then the number
**How?**
```
$,=$/; # delimiter between fields is newline
$_=" X"x pop@F; # set number of attempts left
say # output the header
" "."_"x53,
" /".($"x53)."\\",
$q="| ".('_'x45)." |",
$e=($b="| |").($"x45).$b,
"$b Welcome to ROBCO Industries (TM) Termlink $b
$b Password Required".($"x27).$b,
"$b Attempts Remaining:$_".($"x(25-length)).$b,
$e;
$s=join'',map{(split//,'!"#$%&\'()*+/:;<=>?@[]^_{|}\\')[int rand 27]}1..360; # create random string long enough for entire screen
while($_=pop@F){ # for each given string
if(($t=substr$s,$r=rand 360-($l=length),$l,$_) # attempt to insert it
=~/[a-z]/i) # but check if it overlaps another string
{substr$s,$r,$l,$t; # if it does, take it out
push@F,$_}} # and put it back in line
@o=$s=~/.{15}/g; # split "memory dump" into chunks
printf"$b 0x0%X %s | 0x%02X %s $b\n",$_,$o[$_-1],$_+12,$o[$_+11]for 1..12; #output the grid
say # output the footer
$b.('_'x45).$b,$q=~y/_/ /r,
$q=" \\".("_"x54)."/",
($"x6).$q=~s/_{15}//r
```
[Answer]
# [Python 3](https://docs.python.org/3/), 585 bytes
```
from random import*
def f(l,n,r=range):
u,c='_ ';a=[choice('!"#$%&\'()*+/:;<=>?@[\\]^_{|}')for i in c*360];L=len(l[0]);i={*r(360-len(l[0]))};p=lambda x:'0x%02X'%x+c+''.join(a[15*x:][:15])
for q in l:s=choice([*i]);a[s:s+L]=q;i-={*r(s+~L,s+-~-~L)}
return''' %s
/%s\\
|# %s #|
?%s?
? Welcome to ROBCO Industries (TM) Termlink ?
? Password Required ######?
? Attempts Remaining:%-25s?
?%s?
%%s?%s?
|%s|
\%s/
# \%s/'''.replace('?','|#|').replace('#',c*4)%(u*53,c*53,u*45,c*45,' X'*n,c*45,u*45,c*55,u*55,u*39)%('| | %s | %s | |\n'*12)%sum([(p(x),p(x+12))for x in r(12)],())
```
[Try it online!](https://tio.run/##RVLRbpswFH0uX3EXxmwDadKmTBqMZVmUh0p0qZJI7QSsYsRp3YEhNmhMpfn1zs6qjYdz7jnX18cY6t/NQ8UnLy87UZUgMr5VxMq6Eo1tbOkOdrhwuStC1bqnxDdOWjcP0R2gIAvj/KFiOcXozcB8a71LECa2M/KDj@Gn6ec4SdLvd0/9MyK7SgADxiG3J@/HaRCFBeW4iMcpCVj4ZAus7OE/jzwHdVhk5Y9tBp2Pxp01Pr9FVufkDkKnjxXjOIvPPLvz09g/81JinOiEvU4ofBm@niq2mdo/i6UvnSgN9wEbHrOkc4hc6QwPw0NEno0TQZtWcIQQgCUNGFkySYzeVALM3phacmpM4YYWeVVSaCpYLb/Ml3DJt61sBKMS8OaKwIaKsmD8JwDo9deZlL8qsYUV3bdM0K3yzeOju7OmoWXdSNUtM8YZv/et4bmnk3ScpUBzb8neSCw5Mkw1rgt1ylNB6yLTtz5FLurNHpH/lonc3L4gFm5tb6JKBa194WnTcxHcIpv/rV9dT1dHmHxQU6hXOdDrV38FLROO7LNzYsm2xDGucUdcBY6yjl@20/cusJKpiwl5qQXjDVb/DYQQD9ZXs9Vm4A4WX2dzzeub5Wqh@Ppy822t9dUiihTP1TKtV7P5Yj1IXeBq/EJt9wc "Python 3 – Try It Online")
-70 bytes thanks to Jonathan Allan
-9 bytes thanks to myself (finally!)
-72 bytes thanks to notjagan
[Answer]
# JavaScript (ES8), 639 bytes
```
(w,n,r=i=>Math.random()*i|0,s=b=>{for(i=b[k];i;i--)[b[i-1],b[j]]=[b[j=r(i)],b[i-1]]},a=Array(360-w[k="length"]*--w[0][k]),m=[...a].map((j,i)=>~(j=d.slice(0,w[k]).indexOf(i))?w[j]:`!"#$%&'()*+/:;<=>?@[\\]^_{|}`[r(27)],s(w),s(d=[...a.keys()])).join``.match(/.{15}/g).map((v,i)=>"0x"+(i+1).toString(16).padStart(2,0)+" "+v))=>` _53
/ 53\\
| 5_45 5|
${["","Welcome to ROBCO Industries (TM) Termlink","Password Required","Attempts Remaining:"+" X".repeat(n),"",...m.slice(0,12).map((x,i)=>x+" | "+m[i+12])].map(x=>"| 4| "+x.padEnd(43)+" | 4|").join`
`}
| 4|_45| 4|
| 55|
\\_55/
7\\_39/`.replace(/[_ ]([1-9]+)/g,(m,n)=>m[0].repeat(n))
```
The hex labels are in lowercase; if uppercase was required, that would be an additional 14 bytes for `.toUpperCase()`.
## Test Snippet
Better viewed over on [CodePen](https://codepen.io/justinm53/pen/EvgWPP).
] |
[Question]
[
## Rules
1. No cell range references (`A2:B3`).
2. Maximum 9 rows and 9 columns.
3. No circular references or formula errors.
4. Empty cells evaluate to `0`.
5. Data are numbers only, but may be taken as strings.
6. Formulas are strings.
## Implementation choices
You must state your choices in these matters:
7. Require formulas to be prefixed with any single character, e.g. `=` – or not.
8. The leftmost cell of the second row is `A2` or `R2C1`, as per the two conventions used by Excel et al.
9. Require any single-character pre- or suffix in cell references, e.g. `$` – or not.
10. One of null, empty string, empty list, etc., (but not `0`) to represent empty cells.
11. Language of your submission (spreadsheet managers are not allowed).
12. Language for the formulas (may differ from the above).\*
13. Brownie points or cookies for explaining your solution.
## Examples
Choices: 7: `=`; 8: `A2`; 9: none; 10: `""`; 12: Excel Formula Language
### In:
```
[[ 2, 3],
["=A1+B1",""]]
```
### Out:
```
[[2,3],
[5,0]]
```
### In:
```
[[ 2,"=A1+B2"],
["=A1+B1", ""]]
```
### Out:
```
[[2,2],
[4,0]]
```
### In:
```
[[ 3, 4,"=A1*B1"],
[ 2, 5,"=A2*B2"],
["","","=C1+C2"]]
```
### Out:
```
[[3,4,12],
[2,5,10],
[0,0,22]]
```
### In:
```
[["","=2*B2*B3" ,""],
[ 3,"=A1+(A2+C2)/2", 2],
[ 1,"=C1+(A3+C3)/2", 5]]
```
### Out:
```
[[0,15, 0],
[3, 2.5,2],
[1, 3 ,5]]
```
---
\* The formula language must be [PPCG admissible](https://codegolf.meta.stackexchange.com/a/2073/43319), but you only have to support cell references plus criteria 3 and 4 there, wiz. addition and primeness determination.
[Answer]
# JavaScript, ~~125~~ ~~112~~ 105 bytes
To use, add `f=` at the beginning and invoke like `f(argument)`.
```
a=>a.map(b=>b.map(p=>+p?p:p?eval(p.replace(/[A-I][1-9]/g,m=>`a[${m[1]-1}][${(m.charCodeAt(0)-65)}]`)):0))
```
### Choices:
7. Does not require `=`.
8. The left most cell of second row is `A2`.
9. Does not require any prefix or suffix.
10. `""` (Empty String) to denote empty cell.
11. JavaScript.
12. JavaScript.
13. Cookies. üç™üç™üç™
### Explanation:
This solution iterates over all the cells of the worksheet (each element of the sub-arrays of the given array) and if non-empty String is found, replaces its cell references with the corresponding references in terms of the given array and evaluates the expression with `eval()` (yeah, [that evil thing that haunts you in your nightmares](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea)). This solution assumes that the constants provided in the input array are of Integer type.
### Test Cases
```
f=a=>a.map(b=>b.map(p=>+p?p:p?eval(p.replace(/[A-I][1-9]/g,m=>`a[${m[1]-1}][${(m.charCodeAt(0)-65)}]`)):0))
console.log(f([[1,2,3],["A1+B1+C1",10,11]]));
console.log(f([[1,2,5,4,6,89,0],[0,1,2,3,"A2+A1",5,6]]));
console.log(f([[1,2,4,5],["A1/B1*C1+A1+Math.pow(5,B1)",2,3,4]]));
```
[Answer]
# PHP, ~~265 263 259 258 257 240 224 222 213 202~~ 196 bytes
featuring [`array_walk_recursive`](http://php.net/array_walk_recursive), a [recursive anonymous function](https://stackoverflow.com/a/2480242/6442316) and [`preg_replace_callback`](http://php.net/preg_replace_callback):
```
function f(&$a){array_walk_recursive($a,$p=function(&$c)use($a,&$p){eval('$c='.preg_replace_callback("#R(.)C(.)#",function($m)use($a,&$p){$d=$a[$m[1]-1][$m[2]-1];$p($d);return$d;},$c?:0).';');});}
```
or
```
function f(&$a){array_walk_recursive($a,$p=function(&$c)use($a,&$p){eval('$c='.preg_replace_callback("#R(.)C(.)#",function($m)use($a,&$p){return$p($a[$m[1]-1][$m[2]-1]);},$c?:0).';');return$c;});}
```
operates on input: call by reference. [Test it online](http://sandbox.onlinephpfunctions.com/code/c57d5272bbf563f7197a056a308249f0f96b4432).
* no expression prefix
* reference format `R2C1`, no prefix
* anything falsy for empty cell
* evaluates any (lowercase) PHP expression, including all arithmetics
**breakdown** (first version)
```
function f(&$a)
{
array_walk_recursive($a, # walk through elements ...
$p=function(&$c)use($a,&$p){ # use array $a and recursive $p
eval('$c='. # 3. evaluate expression
preg_replace_callback('#R(.)C(.)#', # 2. replace references with ...
function($m)use($a,&$p){
$d=$a[$m[1]-1][$m[2]-1]; # $d=content of referenced cell
$p($d); # recursive evaluation
return$d; # return $d
},$c?:0) # 1. replace empty with 0
.';'
);
}
);
}
```
[Answer]
## Clojure, ~~263~~ 281 bytes
Oh damn without that `apply map vector` the result is in transpose, as `A2` is alphabetically before `B1`.
```
#(apply map vector(partition(count(% 1))(for[v(vals(loop[C(into{}(mapcat(fn[i r](map(fn[j v][(str j i)(or v"0")])"ABCDEFGHI"r))(rest(range))%))P[]](if(= C P)C(recur(into(sorted-map)(for[[k v]C][k(reduce(fn[r[K V]](clojure.string/replace r K V))v C)]))C))))](eval(read-string v)))))
```
Examples:
```
(def f #(...))
(f [["2" "3"]["(+ A1 B1)" nil]])
([2 3] [5 0])
(f [[nil ,"(* 2 B2 B3)" ,nil],
["3" ,"(+ A1 (/ (+ A2 C2) 2))" ,"2"],
["1" ,"(-> A3 (+ C3) (/ 2) (+ C1))","5"]])
([0 15N 0] [3 5/2 2] [1 3 5])
```
7. Formulas are S-expressions
8. `A2`
9. No, `(+ A1 A2)` is fine
10. `nil` and `false` work as empty cells, but empty string do not
11. Clojure
12. S-expressions (Clojure + any built-in macros)
An example of thread first macro:
```
(macroexpand '(-> A3 (+ C3) (/ 2) (+ C1)))
(+ (/ (+ A3 C3) 2) C1)
```
Starting value of `C` in the loop is a hash-map, keys are cell names and values are original values. Then all cell references are replaced by contents of referenced cells until we have converged (`P`revious = `C`urrent), then cells are evaluated and the flat structure is partitioned back into a nested list.
Would be cool to find a solution where `A1`, `A2` etc. are actually callable functions, then `(* 2 B2 B3)` could be rewritten to `(* 2 (B2) (B3))` and executed.
[Try it online!](https://tio.run/nexus/clojure#ZVE7T8MwEN7zK05Gle4gpSQRI0iteYqlE4vlwUqcKm2II8eJhBC/vZxTFsrJw935e1k@YmVrqOECTd@3n/BhephsGZzH3vjQhMZ1WLqxC7iAjAhr59WEk2kHbJ3rlcSmC@7rG5lZmoB1pxrwOo6x38OkFQ7Bwx4aQudhEjeCNIn1Rj48Pj2/vArPst4OAb3pdpZoQbRVWmNT4x1I2JLk63L0sxMOzgdbLVn/FEYd2EJqdWBQNZY2unr1Bu@sULZuP3p7zf5Nt1t527emtOCBr4kmkByEJHFptPwmljDV8oSGieZKkgR7XoS2A6xBKZELEIXQSuAVrDPYZCSga1rNWmdQ3kIq8BJy2PApGHhWaSSmyZ@dYvVIm9VxBbHJQeYEOf0qpBziPy2bact7WBeRJAuKdObFgT9PpOJWxJjH4w8)
[Answer]
## Mathematica, ~~119~~ ~~115~~ 95 bytes
```
(m=#/.""->0)//.s_String:>ToExpression@StringReplace[s,"R"~~x_~~"C"~~y_:>"m[["<>{x,",",y,"]]"}]&
```
Choices:
7. No prefix.
8. `R2C1` style.
9. No prefix or suffix.
10. `""` for empty cells.
11. Mathematica.
12. Mathematica. Arbitrary arithmetic expressions that don't use variables of the form `RxCy` and don't have side effects should work.
### Explanation
```
(m=#/.""->0)
```
We start by replacing all empty strings in the input (`#`) with zeros and storing the result in `m`, because we'll need this again in another place.
```
...//.s_String:>...
```
*Repeatedly* replace any remaining string `s` with the following...
```
...StringReplace[s,"R"~~x_~~"C"~~y_:>...]
```
Match any substrings of the form `RxCy` in `s` and replace them with...
```
..."m[["<>{x,",",y,"]]"}
```
Which gives `m[[x,y]]`, which uses `x` and `y` as indices into the matrix `m`.
```
...ToExpression@...
```
Finallz, evaluate this string as a Mathematica expression.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 51 bytes
```
⍎¨({((⍴⍵)↑⍉⎕A∘.,1↓⎕D),¨'←',¨⍵}{0::⍵⋄×≢⍵:⍕⍎⍕⍵⋄0}¨)⍣≡
```
7. None
8. `A2`
9. None
10. Empty string
11. APL
12. APL
[Try it online!](https://tio.run/##tVKxjhMxEO33K0bbOCsMXHZFc10IkRCKALG5Kkrhy04Soz1vZDt3iaJ0KCKCjUAoOhqKu2vyAYeoaHJ/4h8J480VFJTcyPaMx0@e98YW4/xxNhN5MdzvB275xZXr3bY2r9VceevKn5FbfnXlyq03Dffx@xNed8tvtHkR8d2WEZyRJ9hifnR8TN59@nB36VbXFNJ2Q5dVq88fLXbbyJU3bnW137vyB9gRgsKppUAjQi4VGkAlTnM8nMk@wmkxxQwyaca5mAVRvxjPwIjcBvPFAZo22p2gR0wICYUKghgSos5epW9eM2Dpy1arQ/5dKz1pdxh3n38T/cOA/2JeCp6LfCIs3kvB6VijMbJQBoTKQGgt1LBSdQZSgYChlhlcSDvyOalhhCKTamiC96ZQvq3dbhjyML67fO5nElIhHoY9zniNmJ80U6gnEWfQhcTDfrly@@hpI4ZmHHKI/4Wr/4VLoJkQ7lmvx@4VaHEBvmWBGSFa/w/o3dcbnwLPCR7CfOF@oc5R26o42AIab9twJqyW02AAFRl4WKvUT1T15QYT1bf0bH8A "APL (Dyalog Unicode) – TIO Nexus")
`⍎¨` Evaluate each cell of the result from
`(`…`)⍣≡` continuous application of the following two functions until nothing more changes
`{` first anonymous function to be applied…
`0` on any
`::` error:
`‚çµ` return the argument unmodified
`⋄` now try;
`‚çµ` if the argument's
`≢` tally:
`√ó` is positive
`:` then:
`‚çï` stringify
`‚çé` the evaluated
`‚çï` stringified
`‚çµ` argument
`⋄` else;
`0` return zero
`}¨` … to each cell
`{` second anonymous function to be applied…
`'←',¨` prepend an assignment arrow to each cell of
`‚çµ` the argument
`(`…`),¨` prepend the following to each cell of that
`1‚Üì` drop the first of
`‚éïD` the string of all **D**igits (i.e. zero)
`‚éïA` With all the letters of the **A**lphabet going down,
`‚àò.,` make a concatenation table (with the remaining digits going right)
`‚çâ` transpose (to get increasing numbers down, progressing letters right)
`(`…`)↑` take the upper left submatrix with the size of…
`⍴` the size of
`‚çµ` the argument
`}` … to the the previous function's result.
[Answer]
# [Python 2](https://docs.python.org/2/) 273,265,263, 259 bytes
```
import re
def g(m):x=m.group();return's[%d][%d]'%(int(x[1])-1,ord(x[0])-65)
e=enumerate
while'='in`s`:
for x,i in e(s):
for i,j in e(i):
try:s[x][i]=0if not j else float(eval(re.sub('\w\d',g,str(j)).strip('=')))
except:pass
```
[Try it online!](https://tio.run/nexus/python2#VY/RaoQwEEXf/YohsJjU1K7K9sHiw9bPyAbWrqONqAlJ7Nqvt5Gl0A4zzOUeGO64SghCOKnyp/fQBYG9OCGSCyiCf84Ses6TOmcvOeGQSw4CsgDqHRRJXTzAScpNTUZbDxajFjvo6cTKtZrS3urFUPZm0S92jp04tHKf@EDV7OkqMsmeM65tG/Qx6NcTi7DCeZnQNh6j@6caMa5iNV/dtYz2hJ22sHIFagakjj3MX6D48ADqD9jL2@/SiVUKJauj6mDWHgbA0SF0o248xa9mpBZTt3zQ@HK/tDHvufOWDoylYStDQw7G2L@zuN7Q@NI0zm3Ghp/AbdsP "Python 2 – TIO Nexus")
**Choices:**
7. =
8. A2
9. none
10. ""
11. Python 2.7
12. Python expressions
**Basic explanation:**
For every formula in the sublist, substitute it with the corresponding list (that is, for B1 s[0][1]) index and evaluate the result!
* -4 bytes by changing str() to backticks!
] |
[Question]
[
This challenge is inspired by [Mathematics is fact. Programming is not](https://codegolf.stackexchange.com/questions/109248/mathematics-is-fact-programming-is-not).
---
The mathematical notation for a factorial, or a **fact** is an exclamation mark **`!`**. The exclamation mark is also a common symbol for **`not`** in many programming languages.
### Challenge:
Take a string, containing numerals, and the characters: **`+ !`** as input and output the following:
Everything in front of an exclamation mark should be evaluated as a mathematical expression, so `2+2` would be `4`.
Everything after a single exclamation mark should be appended as accessories to whatever is in front of it, so: `2+2!5` should give `45`, because `2+2=4`, and `5` is an accessory. `2+2!5+5` should give `410`.
Since `!` also means `not`, anything that's **not** an accessory after the fact should **not** be appended. So, `2+2!!5` should give `4`, since `5` is not an accessory. Now, `not(not(true))==true`, so `2+2!!!5` should give `45`. `2+2!!5!5+5` should give: `410`, because `2+2=4`, then followed by a factorial and `!5!5+5`. The first `5` is not a fact, but `5+5` is after another exclamation mark, and is therefore a fact, yet again.
**Clarifications:**
* The exclamation marks will not be adjacent to a **`+`** on either side.
* There will not be leading `+` for numbers (it's `5`, not `+5`).
* You may optionally include a leading zero if that's the result of the expression in front of the first `!`. Both `4` and `04` are accepted output for input: `0+0!4`
**Executive summary:** evaluate each sum (treating `!` as separators). Then discard all numbers that appear after an even number of `!` (counting from the start of the string). Then remove all `!`.
**Test cases:**
```
!
<- Empty string
5
5
12!
12
!87
87
!!5
<- Empty string
5+5!2+2
104
5+5!!2+2
10
1!2!3!4!5!6!7!8!9
12468
10+10!!2+2!!3+3!4+4
208
2!!3!5
25
2!!3!5!7
25
10!!!!!!!5
105
```
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes (in each language) wins!** Explanations are strongly encouraged!
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~35~~ ~~31~~ 29 bytes
Saved 4 bytes by taking some inspiration from [ETHproductions](https://codegolf.stackexchange.com/a/110419/8478).
Thanks to Leo for saving another 2 bytes.
```
\d+|\+
$*
1+
$.&
1`!
!\d*!?
```
[Try it online!](https://tio.run/nexus/retina#HYkxDoMwEAT7/cVIJIo4KeIMF5OKkk@4cOFn5O8OeIvd0c7jddZemv2KaZrlV7@f8opEaTOHekchT4g9C0JhQbI0doCTWNkIPmR2vvLFfBkSVrucbbqPkfgD "Retina – TIO Nexus")
[Answer]
## JavaScript (ES6), ~~58~~ 56 bytes
Saved two bytes thanks to [Martin Ender](https://codegolf.stackexchange.com/a/110420/42545).
```
let f =
x=>x.replace(/[^!]+/g,eval).replace(/!(\d*)!?\d*/g,"$1")
```
```
<input value="2+2!5+5" oninput="try{O.value=f(value)}catch(e){}"><br>
<input id=O value="410" disabled>
```
Might be improved somehow...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ṣ”!µḢW;m2$VṾ$L¡€
```
[Try it online!](https://tio.run/nexus/jelly#@/9w5@JHDXMVD219uGNRuHWukUrYw537VHwOLXzUtOb/4XYgmfWoYY6SjoISUBkQKVlbg8j//6OVFJV0lEyB2NAIxFK0MAeRiiARU21TRSNtIygLyjRUNFI0VjRRNFU0UzRXtFC0BIkZaBsagBUoKhprA2W1TYCiIA7YHAhD0RysUhECTJViAQ "Jelly – TIO Nexus")
## Explanation
The key observation here is that we can run the steps "out of order"; instead of evaluating the sums then ignoring the ones we don't like, we can ignore the sums in invalid positions, then evaluate the rest.
```
ṣ”!µḢW;m2$VṾ$L¡€
ṣ”! Split input on '!'
µ Set as the new default for missing arguments
Ḣ Take the first element, removing it from the default
W; $ Cons with
m2 every odd-numbered element of {the tail of the !-split input}
€ For each remaining element
VṾ$ Evaluate and de-evaluate it
L¡ a number of times equal to its length
```
Evaluating a sum like `"10+10"` will evaluate it to a number, e.g. `20`, then de-evaluate it to a string, `"20"`. Repeating that process has no additional effect (it's idempotent). Thus, we effectively evaluate every element of the string, *except* the null string, which remains unevaluated because it has a zero length.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ”!µḊm2;@ḢW$LÐfVṾ€
```
**[Try it online!](https://tio.run/nexus/jelly#@/9w5@JHDXMVD219uKMr18ja4eGOReEqPocnpIU93LnvUdOa/0f3HG4H0pFAnPWoYc6hbYe2ATX8/x@trqiuo6BuCiIMjcBsRQtzMKUIFjTVNlU00jaCMWFsQ0UjRWNFE0VTRTNFc0ULRUuwoIG2oQFYiaKisTZQWtsEJAziQQyDsBTNIYoVIQBit7ahooG2AQo21AYrUY8FAA)**
### How?
```
ṣ”!µḊm2;@ḢW$LÐfVṾ€ - Main link: string
ṣ”! - split on '!' characters
µ - monadic chain separation (call that x) e.g. ['1+1','0+0','0+0','0+0','','1+0','','','']
Ḋ - dequeue x (all but the leftmost entry of x) e.g. ['0+0','0+0','0+0','','1+0','','','']
m2 - modulo 2 index into that result e.g. ['0+0', '0+0', '1+0', '']
$ - last two links as a monad
Ḣ - head x (the leftmost entry of x) e.g. '1+1'
W - wrap e.g. ['1+1']
;@ - concatenate with reversed arguments e.g. ['1+1','0+0', '0+0', '1+0', '']
Ðf - filter keep:
L - length (keep that have non-zero length) e.g. ['1+1','0+0', '0+0', '1+0']
V - eval as jelly code (vectorises) e.g. [ 2, 0, 0, 1]
Yes, addition is just + and decimal numbers are just strings of digits in Jelly believe it or not!
Ṿ€ - uneval €ach (creates a string from each one)e.g. [ '2', '0', '0' ,'1']
without the € it would uneval the list and hence yield commas too)
- implicit print (prints the resulting list [of characters and possibly
lists of characters] as if it were all one string.)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 90 bytes
```
def f(s,e=1,r=''):
for x in s.split('!'):
if x:r+=str(eval(x))*e
else:e=1-e
return r
```
[Try it online!](https://tio.run/##bcxBCsIwEIXhfU8xXWViqmDFTSCHKTjBQEjDTCzx9DF1Jdjl/z14@V2ea7q19iAPHmUid53YKaXtAH5lqBASyEVyDAXV@HUIHqpl46Qw0rZErFqfqA8UhWy/OPdgKi9OwC1zSAU9qtnMSuvht8f7nxzRsZld2wc "Python 3 – Try It Online")
* -8 thanks to 97.100.97.109
* -1 thanks to Steffan
### Explanation
```
def f(s,e=1,r=''):
```
Define a function, `f`, which takes in a string, `s`.
`e` is whether to evaluate the next expression, and `r` is the return string.
```
for x in s.split('!'):
```
Iterate through the string, split by `'!'`s.
```
if x:r+=str(eval(x))*-e
```
If `x` is not empty, and `e` is True, evaluate `x` and add to the return string.
```
else:e=1-e
```
Otherwise, set `e` to `not e`
```
return r
```
Return the final value of `r`
---
# [Python 3.8+](https://docs.python.org/3/), 74 bytes
```
lambda s,e=1:''.join(e*str(eval(x))for x in s.split('!')if x or(e:=1-e)*0)
```
(Suggested by 97.100.91.109)
[Attempt this online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3vXISc5NSEhWKdVJtDa3U1fWy8jPzNFK1ikuKNFLLEnM0KjQ10_KLFCoUMvMUivWKC3IySzTUFdU1M9OAYvlARVa2hrqpmloGmlAT4wqKMvNKNNI01I20jdQ1NbmQ-YqmGCLYhLCLaYNEIbYsWAChAQ)
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 20 bytes
```
r'!/{_{'+/1b}&}%(\2%
```
[Try it online!](https://tio.run/nexus/cjam#HYkxDoNADAR7/2IKAsIF2OAcKfOPRJHyAAra0739gJtmRzu5Hj1T/uVeJ/uXR@mGj3f1u5f3WJEQc4QtCYSEBq7etonhLKwETxIbL7FZbW4RFr2arnIfjTgB "CJam – TIO Nexus") (Linefeed-separated test suite.)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~58~~ 56+1 = ~~59~~ 57 bytes
Uses the `-p` flag. -2 bytes from [Tutleman](https://codegolf.stackexchange.com/users/64834/tutleman).
```
i=0;$_=' '+$_;gsub(/!?([^!]*)/){eval$1if(2>i+=1)||i%2<1}
```
[Try it online!](https://tio.run/nexus/ruby#JYvRCoJAFETf71fs0EbaFtdd3TTM@pAoSbBYCAlFIbJvN7V5mQNzZliA26bmwlVcVp2o2@Itti9yWZDKPFuJlZJ5@mjawmOcvPMVl7XP/qfsbk@p3d0zR6cy7fe9W5qD/tJoCpa8kTwMIEvagJDEBFiyysIoM/cMGgYhIljsECPBnnSgdDCPQKjGTUU04fj@F2KahDn2Bw "Ruby – TIO Nexus") (An extra line of code was added so that it would take all of the input lines and print the output in different lines.)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 18 bytes
I think this is the shortest it gets... although I said that about three iterations ago too.
```
{VaX++v%2+!v}Ma^'!
```
Takes input as command-line argument. [Try it online!](https://tio.run/nexus/pip#@18dlhihrV2maqStWFbrmxinrvj//39DA21DA0VFI20jRUVjbWNFE20TAA "Pip – TIO Nexus")
### Explanation
```
a is 1st cmdline arg; global variable v is -1 (implicit)
a^'! Split a on !
{ }M Map this function to the resulting list (note that inside function,
a is the function arg):
++v Increment v (so that v tracks the 0-based index of the current
element)
%2 We want to keep the elements where v%2 is 1...
+!v ... and also v=0, where v%2 is 0, but adding !v makes it 1
aX String-multiply the argument by the above quantity (turning elements
we don't want into empty string)
V Eval it (eval'ing empty string gives nil, but that's okay because
nil doesn't output anything)
Autoprint the resulting list, concatenated together (implicit)
```
[Answer]
## Batch, ~~192~~ 184 bytes
```
@echo off
set/ps=
call:c . "%s:!=" "%"
echo(%s%
exit/b
:c
set s=
if not %2=="" set/as=%2
:l
shift
shift
if "%1"=="" exit/b
if %1=="" goto l
set/at=%1
set s=%s%%t%
goto l
```
Having to handle the empty strings is inconvenient.
[Answer]
# R, 95 bytes
```
function(x)for(e in strsplit(gsub('!([^!]*)![^!]*','\\1!',x),'!')[[1]])cat(eval(parse(text=e)))
```
There is probably some room for improvement but at the moment it is the best I can come up with.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
q'! kϩYvãOxX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=cSchIGvPqVl2w6NPeFg&input=IjIrMiEhNSE1KzUi)
You can also [Try all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cSchIGvPqVl2w6NPeFg&footer=cQ&input=WwoiISIsCiI1IiwKIjEyISIsCiIhODciLAoiISE1IiwKIjUrNSEyKzIiLAoiNSs1ISEyKzIiLAoiMSEyITMhNCE1ITYhNyE4ITkiCiIxMCsxMCEhMisyISEzKzMhNCs0IiwKIjIhITMhNSIsCiIyISEzITUhNyIsCiIxMCEhISEhISE1IgpdLW1S), with a slight modification in the footer since the `-mR` flag that is used to run on multiple test cases conflicts with the `-P` flag that formats the output in the main version.
```
q'! kϩYvãOxX
q'! # Split the string on "!"
k à # Remove elements where:
Ï # The index is non-zero
©Yv # And the index is divisible by 2
£ # For each remaining element:
OxX # Evaluate it as Javascript
-P # Concatenate the elements and print
```
] |
[Question]
[
Because of this, families from all over the world are building Christmas trees.
But this normal tree can get boring after a while, so let's make an ASCII tree!
Leafs are represented by `#` and must be arranged as shown in the example output. We have 5 balls (`O`) and 5 candy canes (`J`), which we place randomly around the tree. We also have a candle on top.
**Input:** none
**Output:**
```
^
|
###
##O##
#######
#####
####J##
#########
####O######
#############
###J###
#########
####O###J##
#######O#####
###J########O##
###########J#####
###
###
```
### Rules (if it's not in the rules, assume you can)
* Balls and candy canes must be randomly placed on the tree and must have at least one leaf between them, not counting diagonals.
* Each leaf must have a non-zero chance of getting a ball or a candy cane.
* There may be leading or trailing spaces on each line, as long as the tree has the proper shape.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in characters wins.
[Answer]
# CS-Script - 306 bytes
```
var c=new string(' ',342).ToCharArray();var r=new Random();int e=18,i,j,w;for(;i<e;i++){c[i*e+e]='\n';w=i<5?i:i<10?i-2:i<16?i-6:2;for(j=1;j++<w*2;)c[i*e+8-w+j]='#';}for(i=0;i<10;){j=37+r.Next(288);if(c[j]=='#'&c[j+1]<42&c[j-1]<42&c[j+e]<42&c[j-e]<42)c[j]=i++<5?'J':'O';}c[8]='^';c[27]='|';Console.Write(c);
```
Once more with formatting and comments:
```
// create 'char bitmap' filled with spaces
var c=new string(' ',342).ToCharArray();
// Random for placing ornaments
var r=new Random();
int e=18,i,j,w;
// once for each row
for(;i<e;i++)
{
// add new lines
c[i*e+e]='\n';
// determine width of tree for this row
w=i<5?i:i<10?i-2:i<16?i-6:2;
for(j=1;j++<w*2;)
// add leaves
c[i*e+8-w+j]='#';
}
for(i=0;i<10;)
{
// select random location
j=37+r.Next(288);
if( // check we have a leaf
c[j]=='#' &
// check surrounding to be leaf/space/new-line
c[j+1]<42 & c[j-1]<42 & c[j+e]<42 & c[j-e]<42)
// add ornament if location is valid
c[j]=i++<5?'J':'O';
}
// light candle
c[8]='^';
c[27]='|';
// print
Console.Write(c);
```
It's basically C#, but using [CS-Script](https://github.com/oleg-shilo/cs-script) allows me to skip all the boiler-plate.
[Try it here!](https://dotnetfiddle.net/nMfpa5)
**Notes:**
This currently outputs another line of white spaces below the tree to make sure the that 'checking for existing ornaments below' does not throw an IndexOutOfBoundsException. Other solutions would be:
* Checking if it is the last line before checking below (adds a few more character)
* Not adding ornaments to the 'stem' of the tree (Same byte count, but seems to me to be against rules)
I'll leave it to the OP if this should be changed.
Lastly, this is my first golf, so any feedback is appreciated. ;)
[Answer]
## JavaScript (ES6), 148 bytes
Hopefully, this should comply with the 'random enough' condition.
```
_=>[...'887656543254321077'].map(n=>' '.repeat(n)+'#'.repeat(17-2*n)).join`
`.replace(/#/g,_=>'OJ^|#'[++i<4?i:i>133|++j%13?4:j/13&1],i=1,j=new Date)
```
### Demo
```
let f =
_=>[...'887656543254321077'].map(n=>' '.repeat(n)+'#'.repeat(17-2*n)).join`
`.replace(/#/g,_=>'OJ^|#'[++i<4?i:i>133|++j%13?4:j/13&1],i=1,j=new Date)
console.log(f())
```
[Answer]
# TSQL, ~~556~~ ~~532~~ ~~494~~ 476 bytes
This script needs to be executed on the master database
**Golfed:**
```
DECLARE @ varchar(max)='',@h INT=0,@w INT=0WHILE @h<18SELECT
@+=space(9-@w)+REPLICATE(char(IIF(@h<2,94+30*@h,35)),@w*2+1)+space(9-@w)+CHAR(10),@h+=1,@w+=CHOOSE(@h,0,1,1,1,-1,1,1,1,1,-2,1,1,1,1,1,-8,0)WHILE
@h>7WITH C as(SELECT*,substring(@,number,1)v,number/20r,number%20c
FROM spt_values WHERE type='P'and number<358)SELECT @=stuff(@,number,1,CHAR(74+@h%2*5)),@h-=1FROM
c d WHERE v='#'and not exists(SELECT*FROM c WHERE abs(d.c-c)+abs(d.r-r)<2and'A'<v)ORDER BY newid()PRINT @
```
**Ungolfed:**
```
DECLARE @ varchar(max)='',@h INT=0,@w INT=0
WHILE @h<18
SELECT @+=
space(9-@w)+REPLICATE(char(IIF(@h<2,94+30*@h,35)),@w*2+1)
+space(9-@w)+CHAR(10),
@h+=1,
@w+=CHOOSE(@h,0,1,1,1,-1,1,1,1,1,-2,1,1,1,1,1,-8,0)
WHILE @h>7
WITH C as
(
SELECT*,substring(@,number,1)v,number/20r,number%20c
FROM spt_values
WHERE type='P'and number<358
)
SELECT @=stuff(@,number,1,CHAR(74+@h%2*5)),@h-=1
FROM c d
WHERE v='#'and not exists(SELECT*FROM c WHERE abs(d.c-c)+abs(d.r-r)<2and'A'<v)
ORDER BY newid()
PRINT @
```
**[Try it out](https://data.stackexchange.com/stackoverflow/query/949979/christmas-tree)**
[Answer]
# Python 3 - ~~450~~ 427 bytes
I know `450` is too much for python. But, but.....
```
from random import randint as r
t=lambda o,g:(o*g).center(19,' ')+';';s,z='','#';s+=t(z,3)*2
for h,w in zip([6,5,3],[17,13,7]):
for i in range(h):s+=t(z,w);w-=2
s+=t('|',1)+t('^',1);s=[list(i)for i in s.split(';')]
for o in'O'*5+'J'*5:
while 1:
h,w=r(2,15),r(1,16)
m=s[h]
C,m[w]=m[w],o
P=s[h-1][w]+s[h+1][w]+m[w-1]+m[w+1]
if not('O'in P or'J'in P)and C!=' ':break
m[w]=C
print (*[''.join(i)+'\n'for i in s][::-1])
```
If the `for i in'O'*...` is turned into a *better recursive function* then lots of bytes can be cut down.
[Try it here](https://repl.it/ErvH/2)
**Edit**:
Saved 2 bytes by using `;` as delimiter and several bytes by taking newline byte count as 1 byte.
[Answer]
# JavaScript, 204 bytes
```
f=(s='^|1232345634567811'.replace(/./g,x=>(y=x|0,' '.repeat(8-y)+(y?'#'.repeat(y*2+1):x)+`
`)),o=5,j=5,r=(Math.random()*56|0)*4,k)=>j?f(s.replace(/###/g,(_,i)=>i-r?_:k=o?'#O#':'#J#'),k?o-!!o:o,k?j-!o:j):s
console.log(f());
```
```
.as-console-wrapper{max-height:100%!important;top:0}
```
[Answer]
# PHP, 200 bytes
might be shorter with a more sophisticated approach; but I´m in a hurry.
```
for(;$c="^|2343456745678922"[$i++];)$s.=str_pad(+$c?str_pad("",2*$c-1,"#"):$c,17," ",2)."
";for(;$n++<10;)$s[$p=rand(0,288)]!="#"|($s[$p-18]|$s[$p+18]|$s[$p-1]|$s[$p+1])>A?$n--:$s[$p]=OJ[$n&1];echo$s;
```
requires PHP 5.6 or 7.0. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/d8d5952aa2544df1c7d4f2c75f9a9a2cb1c2bce3).
[Answer]
# Scala, 329 bytes
```
var r=scala.util.Random;var z=r.nextInt(2);def t{print(new StringBuilder({"^|234345645678922".map(x=>{val t=if(x>57)8 else(57-x);" "*t+{if(x>57)""+x else "#"}*(17-(t*2))+" "*t+" \n"})}.mkString)match{case e=>{var w=0;while(w<10){{val b=(r.nextInt(e.size/2)*2)+z;if(e.charAt(b)=='#'){e.setCharAt(b,if(w<5)'O'else'J');w+=1}}};e}})}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 101 bytes
```
↑¯9↑¨'^|'
f←{⍵×(≢⍵)⍴2?2}
{(5/'OJ')@(x[10?≢x←⍸↑f¨f¯2↓↓'#'=⍵])⊢⍵}↑{' #'/⍨⍵,17-2×⍵}¨⍎¨'7656543254321077'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@P2qbeGi9JYhcoR5Xo86VBpSqftS79fB0jUedi4AMzUe9W4zsjWq5qjVM9dX9vdQ1HTQqog0N7IHSFUDFj3p3AHWnHVqRdmi90aO2yUCkrqxuC9QZq/moC2RCLVC@Wl1BWV3/Ue8KIF/H0FzX6PB0kMwhIL8PaLO5mamZqYmxEQgbGpibq/8HOu5/GgA "APL (Dyalog Unicode) – Try It Online")
A full program which returns the tree.
Tree creation algorithm borrowed from Arnauld's answer.
## Explanation
**Displaying the top**
```
↑¯9↑¨'^|'
'^|' string
¯9↑¨ pad each with 8 spaces
↑ convert to matrix
```
---
**Distancing the ornaments**
```
f←{⍵×(≢⍵)⍴2?2} store the following lambda as f:
2?2 generate 0 1 or 1 0 (random)
(≢⍵)⍴ reshape to the length of the input
⍵× multiply the input with it(vectorizes)
```
---
**Display the tree**
```
↑{' #'/⍨⍵,17-2×⍵}¨⍎¨'7656543254321077'
⍎¨'7656543254321077' create an array of digits from the string
{ }¨ for each digit x:
⍵,17-2×⍵ array [x,17-2*x]
' #'/⍨ replicate spaces and hashes as per that
↑ convert to matrix
```
---
**Add the ornaments:**
```
{(5/'OJ')@(x[10?≢x←⍸↑f¨f¯2↓↓'#'=⍵])⊢⍵} apply the following to the tree:
'#'=⍵ boolean matrix for the tree
↓ convert to 2d array
¯2↓ remove trunk rows
f¨f convert to swiss cheese with function f
⍸↑ get the indices of all 1s
x← and store in x
10?≢ pick 10 random indices in length(x) range
x[ ] and take those from x
@( )⊢⍵ replace those coordinates with:
(5/'OJ') 5 instances of 'O' and 5 instances of 'J'
```
] |
[Question]
[
Palindromic prime problems are pretty common, but that's not what this question is about. In this challenge, the number doesn't have to be a palindrome, its prime factors do.
# Task
Your code has to take a single positive integer as input. Then check if any of the permutations of the prime factors of that integer are palindromic when concatenated. If so, output one of them (the list of factors, not the concatenated string). Else, you have to output `-1`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
# Test Cases
```
11 -> [11]
4 -> [2, 2]
39 -> [3, 13]
6 -> -1
1207 -> [17, 71]
393 -> -1
2352 -> [2, 2, 7, 3, 7, 2, 2]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
Òœ.ΔJÂQ
```
[Try it online!](https://tio.run/##yy9OTMpM/W/u5vn/8KSjk/XOTfE63BT4v1bnv6EhlwmXsSWXGZehkYE5kGXMZWRsagQA "05AB1E – Try It Online")
Explanation:
```
Ò # prime factorization of the input
œ # permutations
.Δ # find the first one such that
J # concatenated
ÂQ # is a palindrome
```
(`.Δ` conveniently defaults to -1, so no extra work needed)
[Answer]
# Pyth, 14 bytes
*-2 bytes by @FryAmTheEggman*
```
h+f_IjkT.pPQ_1
```
Explanation:
```
h first element of
+ (append a -1 to the end in case the filter is empty)
f filter by lambda T:
_I is invariant under reversing
jkT stringified list
.p over permutations of
P Q prime factors of Q with duplicates
_1 -1
```
Thanks @FryAmTheEggman for reminding me about `I`. I don't think I've used it before.
[Test suite](https://pyth.herokuapp.com/?code=h%2Bf_IjkT.pPQ_1&test_suite=1&test_suite_input=0%0A11%0A4%0A39%0A6%0A1207%0A393%0A2352&debug=1)
[Answer]
# CJam - 17 bytes
*Thanks to Martin Büttner for saving me **10** bytes!*
```
Wqimfe!{s_W%=}=p;
```
My first time writing in CJam! Explanation:
```
W # Push a -1 onto the stack
q # Get input
i # Convert to integer
mf # Find prime factorization
e! # Find all permutations
{...}= # Find permutation which...
s # Convert to string
_ # Copy string
W% # Get inverse
= # Check if inverse == original
p; # Print top of stack and discard the rest
```
[Answer]
## Ruby, 89+7=96 ~~102+7=109~~
```
->n{n.prime_division.flat_map{|*a,b|a*b}.permutation.find{|x|x.join==x.join.reverse}||-1}
```
+7 for the `-rprime` flag.
*Sigh*, some Ruby builtins have such long names... at least that makes the code fairly self-explanatory.
The `flat_map` bit is because `prime_division` returns ex. `[[2, 2], [3, 1]]` for input `12` (which represents `2231`).
Thanks to [@histocrat](https://codegolf.stackexchange.com/users/6828/histocrat) for 13 bytes!
[Answer]
# Julia, ~~132~~ 122 bytes
```
n->(x=filter(p->(q=join(p))==reverse(q),permutations(foldl(vcat,[[repeated(k,v)...]for(k,v)=factor(n)]))))==[]?-1:first(x)
```
This is a lambda function that accepts an integer and returns either an array or -1. To call it, assign it to a variable.
Ungolfed:
```
function f(n::Int)
# Construct an array of all prime factors of n
P = foldl(vcat, [[repeated(k, v)...] for (k, v) in factor(n)])
# Filter the set of permutations of this array to only
# those such that the string constructed by concatenating
# all elements is a palindrome
x = filter(p -> (q = join(p)) == reverse(q), P)
# If x is empty, return -1, otherwise get the first array
# in the collection
return x == [] ? -1 : first(x)
end
```
Saved 10 bytes thanks to Glen O!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
ḋp.cX↔X∨_1
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GO7gK95IhHbVMiHnWsiDf8/z/a0FDHRMfYUsdMx9DIwBzIMtYxMjY1igUA "Brachylog – Try It Online")
```
. The output is
p a permutation of
ḋ the prime factorization of
the input
c such that concatenated
X it is the variable X
↔ which reversed
X is still X;
∨ if this is not possible,
the output is
_1 -1.
```
Initially, I had expected that having to output `-1` instead of being allowed to fail would be at a fairly large byte cost, but since the output in the case of success can't be concatenated, it only costs the two bytes necessary to write `_1` (if we removed those, it would leave the output unconstrained defaulting to `0`, and if we additionally changed the `∨` to `∧`, the predicate would fail instead), because we need to break unification with the implicit output either way. (If the concatenation was the output for success but `-1` was still the output for failure, we'd have `ḋpc.↔|∧_1` or `ḋpc.↔.∨_1`. In the shortest case, where the output is concatenated and the predicate can fail, the whole thing is only five bytes: `ḋpc.↔`. Although not outputting the actual factors gives it more of a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") feel...)
[Answer]
## Haskell, 122 bytes
```
import Data.Numbers.Primes
import Data.List
f x=head$[p|p<-permutations$primeFactors x,s<-[show=<<p],s==reverse s]++[[-1]]
```
Usage example: `f 39` -> `[3,13]`.
The obvious brute force approach. Iterating over all permutations of the prime factors and check for palindroms. Pick the first one. If there are none, the list is empty and the appended `[-1]` jumps in.
[Answer]
# [Perl 6](http://perl6.org), 100 bytes
```
{$/=$_;map(->\f{|({$/%f||($//=f)&&f}...^*!==f)},2..$_).permutations.first({.join.flip eq.join})||-1}
```
```
{
# store copy of argument in $/
$/ = $_;
# uses $/ so that I don't have to declare a variable
# find the prime factors
map(
->\f{
# Slip so that outer list of all prime factors is flat
|(
{
$/ % f # return modulus
|| # or
($/ /= f) # factor the prime out of $/
&& # and
f # return factor
}
# produce a list of them and
# stop when it returns something other than the factor
# also ignoring the last non-factor value
...^ * !== f
)
},
# find the factors out of the values from 2
# up to the original argument
2..$_
# don't need to skip the non-primes as their
# prime factorization will have already be
# factored out of $/
)
# try all permutations of the prime factors
.permutations
# find the first palindromic one
.first({ .join.flip eq .join })
# return -1 if .first returned Nil or empty list
|| -1
}
```
Usage:
```
# give it a lexical name
my &prime-palindrome = {...}
say prime-palindrome 1; # -1
say prime-palindrome 2; # (2)
say prime-palindrome 11; # (11)
say prime-palindrome 13; # -1
say prime-palindrome 39; # (3 13)
say prime-palindrome 93; # (31 3)
say prime-palindrome 6; # -1
say prime-palindrome 1207; # (17 71)
say prime-palindrome 393; # -1
say prime-palindrome 2352; # (2 2 7 3 7 2 2)
say prime-palindrome 2351; # -1
say prime-palindrome 2350; # -1
```
---
About half of it (53 bytes) is taken up with the prime factorization code.
```
$/=$_;map(->\f{|({$/%f||($//=f)&&f}...^*!= f)},2..$_)
```
If there were a `prime-factorize` method the whole thing could be significantly shorter.
```
{.prime-factorize.permutations.first({.join.flip eq.join})||-1} # 63
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ÆFŒṙŒ!VŒḂ$ƇḢ¹-¹?
```
Longer than I expected, both in the byte count and the time it took to write.
[Try it online!](https://tio.run/##y0rNyan8//9wm9vRSQ93zjw6STEMyNjRpHKs/eGORYd26h7aaf///39DIwNzAA "Jelly – Try It Online")
**Explanation:**
```
ÆFŒṙŒ!VŒḂ$ƇḢ¹-¹?
ÆFŒṙ Get the prime factors (gets them as exponents then run-length decodes).
Œ! Get the permutations.
Ƈ Filter (keep) the ones that...
ŒḂ$ ...are palindromic when...
V ...joined.
Ḣ Take the first.
¹? If the value is truthy...
¹ ...return the value...
- else return -1.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-F-1`](https://codegolf.meta.stackexchange.com/a/14339/), 9 bytes
```
k á æ_¬êS
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LUYtMQ&code=ayDhIOZfrOpT&input=MjM1MgoKLVE)
[Answer]
# Japt, 18 bytes
*Almost* as short as CJam...
```
Uk á f_¬¥Z¬w} g ªJ
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=VWsg4SBmX6ylWqx3fSBnIKpK&input=MjM1Mg==)
### How it works
```
// Implicit: U = input, e.g. 2352
Uk // Factorize the input. [2,2,2,2,3,7,7]
á // Take permutations. [[2,2,2,2,3,7,7],[2,2,2,2,7,3,7],[2,2,2,7,2,3,7],...]
f_ } // Filter to only the ones that return truthily to this function:
Z¬¥Z¬w // Return Z.join('') == Z.join('').reverse().
// [[2,2,7,3,7,2,2],[2,7,2,3,2,7,2],[7,2,2,3,2,2,7]]
g // Take the first item. [2,2,7,3,7,2,2]
ªJ // If falsy, resort to -1. [2,2,7,3,7,2,2]
```
[Answer]
# JavaScript (ES6), ~~256~~ ~~244~~ ~~208~~ 187 bytes
*Saved 36 bytes thanks to @Neil*
```
x=>eval("for(a=[],i=2;x>1;x%i?i++:(a.push(i),x/=i));p=-1,f=(z,t=[])=>z[0]?z.map((u,i)=>f([...z.slice(0,i),...z.slice(i+1)],[...t,u])):(y=t.join``)==[...y].reverse().join``&&(p=t),f(a),p")
```
Defines an anonymous function; prepend e.g. `F=` to use it. It's actually quite fast on input of 2352, only taking ~150 milliseconds to finish on my computer.
[Answer]
# APL(NARS), 169 chars, 338 bytes
```
∇r←F w;i;k;a;m;j
r←⊂,w⋄→0×⍳1≥k←↑⍴w⋄a←⍳k⋄j←i←1⋄r←⍬⋄→C
A: m←i⊃w⋄→B×⍳(i≠1)∧j=m⋄r←r,m,¨∇w[a∼i]⋄j←m
B: i+←1
C: →A×⍳i≤k
∇
G←{F⍵[⍋⍵]}
f←{∨/k←{⍵≡⌽⍵}¨∊¨⍕¨¨v←Gπ⍵:↑k/v⋄¯1}
```
G would be the function find the permutations and f is the function of this exercise; test:
```
⎕fmt f¨11 4 39 6 1207 393 2352
┌7───────────────────────────────────────────────────┐
│┌1──┐ ┌2───┐ ┌2────┐ ┌2─────┐ ┌7─────────────┐│
││ 11│ │ 2 2│ │ 3 13│ ¯1 │ 17 71│ ¯1 │ 2 2 7 3 7 2 2││
│└~──┘ └~───┘ └~────┘ ~~ └~─────┘ ~~ └~─────────────┘2
└∊───────────────────────────────────────────────────┘
```
] |
[Question]
[
The aim is simple: given the string of resistance values, draw the part of "electrical circuit" of those resistors. Examples follow.
1. Input: `3`. Output:
```
--3--
```
2. Input: `1,2,3`. Output:
```
--1----2----3--
```
Next, the resistors can be joined parallel (by 2 or 3 resistors per join), but the required depth of parallel joins is only 1.
3. Input: `1|2`. Output:
```
|--1--|
-| |-
|--2--|
```
4. Input: `1|2|3`. Output:
```
|--1--|
-|--2--|-
|--3--|
```
**Note**, that `--2--` resistor is now centered.
5. Input: `1|2,3|4|5`. Output:
```
|--1--| |--3--|
-| |--|--4--|-
|--2--| |--5--|
```
Combined joins:
6. Input: `1,2,3|4,5,6|7|8,9`. Output:
```
|--3--| |--6--|
--1----2---| |---5---|--7--|---9--
|--4--| |--8--|
```
If it would be more convenient, the input can be a two-dimensional array. I.e. the input for the last example would look like this: `[1,2,[3,4],5,[6,7,8],9]`.
Some notes:
* No other forms of (in|out)puts are allowed.
* The resistance of each resistor can vary in the range from 1 to 9. Other values, like `-`, `42` or `0` are disallowed.
* The joins like `1|2|3|4` are invalid. As already mentioned, max 3 per parallel join. Empty joins, i.e. `...,|,...` or `...,,...` are invalid.
* Oh, and this is code golf :)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 64 bytes
```
ƛI⁼[h\-dpømð5*:‟W|ƛ`|--`pøm;:L2=[÷`| `øm$W]];DvhṄ,ƛ1i;\-j,vtṄ,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C6%9BI%E2%81%BC%5Bh%5C-dp%C3%B8m%C3%B05*%3A%E2%80%9FW%7C%C6%9B%60%7C--%60p%C3%B8m%3B%3AL2%3D%5B%C3%B7%60%7C%20%20%20%60%C3%B8m%24W%5D%5D%3BDvh%E1%B9%84%2C%C6%9B1i%3B%5C-j%2Cvt%E1%B9%84%2C&inputs=%5B1%2C%5B2%2C3%5D%5D&header=&footer=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ 42 bytes
```
ε€…--ÿDgið.ø.BëÁð3ת3£À'|ì… - SδìÅ\]€.ºøJ»
```
[Try it online!](https://tio.run/##AWMAnP9vc2FiaWX//8614oKs4oCmLS3Dv0RnacOwLsO4LkLDq8OBw7Azw5fCqjPCo8OAJ3zDrOKApiAtIFPOtMOsw4VcXeKCrC7CusO4SsK7//9bMSxbNyw4XSwyLFszLDQsNV0sNl0 "05AB1E – Try It Online")
[Answer]
## Python 2, 195 bytes
```
a=b=c=''
B=' '*5
H='--'
S=' |'+H;E=H+'| '
for x in input():
if x>9:a+=S+`x[0]`+E;c+=S+`x[-1]`+E;b+='-|'+[B,H+`x[1]`+H][len(x)>2]+'|-'
else:b+=H+`x`+H;a+=B;c+=B
print[b,a+'\n'+b+'\n'+c]['|'in a]
```
Takes input as:
```
[1,2,[3,4],5,[6,7,8],9]
```
Output:
```
|--3--| |--6--|
--1----2---| |---5---|--7--|---9--
|--4--| |--8--|
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 149 bytes
```
n=>(H=M=>n.map(e=>(T=e[M]||e[1])?` |${(G=e=>`--${e}--`)(T)}| `:' ').join``)(0)+`
${n.map(e=>+e?G(e):`-|${e[2]?G(e[1]):' '}|-`).join``}
`+H(2)
```
[Try it online!](https://tio.run/##lZDNbsIwEITveQofIrEm61BC6Q@SwzG5cAo3y5IjaioQ2KhUvcR59tSuAioICbG3Wc@M1t@2/qmPq6/N4ZsZ@6G7Ne8Mz6HkC56bdF8fQHu55FospHNajCWdK@LiBgruXxRjcaNbxhSFJW0dUbMBCTOg6dZujPL7J5qoKG7ObYmeF6DpTDFfo0UmgwzFp2jrfF0fbyOVlJDRbmXN0e50urOfsAYxxgzFBJ8lTlG84Cu@SXyXlEb/fZeqT03uuoJN/rXjVAb3aEjAYMX7@/Dq63ifVnGiU5258Lx8AE11CwoZjrpf "JavaScript (Node.js) – Try It Online")
No need to overcomplicate things, just keep it simple
[Answer]
# [Haskell](https://www.haskell.org/), 132 bytes
```
foldr(zipWith(:))e.(>>=g)
a=" - "
b="|||"
s%c=[a,b,c,c,s,c,c,b,a]
g[x]=[a,a,' ':x:" ",a,a]
g[x,y]=[x,' ',y]%"- -"
g z=z%"---"
e=[]:e
```
[Try it online!](https://tio.run/##JYnNCoJAFEb38xSXS6LCTNB/CeMT1KpFC3MxmqOS2qAGJj570634@A4HTqG6e1ZVVsur1Y/q1npjaS5lX3iB72dzLwxl7jMlEQQgSyRO04Ssc1IZKZ7wlNb9mHAVszwa4m9Q3AU3GAIEJP8H/qI0fAOZgwIEshxGOZIL8kxGcZDZWpUNSKiVOYF59ue@PTYwAw0RLpDjkr5aEzb07W5PPGBs36muVN5ZkRrzAQ "Haskell – Try It Online")
Takes input as a `[[Char]]` and outputs a list of lines.
[Answer]
# [Julia 1.5](http://julialang.org/), 129 bytes
```
s=" "^5
+x="--$x--"
!x=map(*,[" |","-|"," |"],x,["| ","|-","| "])
-x=[[s,.+x,s],![+x[1],s,+x[(l=end;)]],!.+x][l]
~x=map(*,.-x...)
```
[Try it online!](https://tio.run/##TVBBTsMwELznFVvDwSZrpyEN0KJw4Ij4gWUkt00bV4kT1Q4yUtSvh6SoEpfZ2Rnt7GpPfW10GsZGd/SAQQjBoIB37UrxJ0kj001jrGn6htalPfpK0MCYgkN7BgPGQlDXsTvwLTTa7ypIRR7Dtqz0t2n7M9DK@85tkuRofNVvxa5tko958ae2x@Q0s8Q415cuybJstWSjKwiQrzyKQ0E4vw@ck2gRivmkB5QEBoKEzzAxhWGSBpi6gc8ARLGIh0JKhyIO6BQuZBxkqtDhVGldlHb/ytSkT76StYout3DBr08YLzLFR5QZrhTmKJ/wGV8UrhUMb7A3rqv1T9SdjfW1pSy60OVmzf554y8 "Julia 1.0 – Try It Online")
output is a list of lines
] |
[Question]
[
You have a number of polynomials who are lonely, so make them some companions (who won’t threaten to stab)!
For a polynomial of degree `n`, there is an `n by n` companion cube [matrix](https://en.wikipedia.org/wiki/Companion_matrix) for it. You need to make a function that accepts a list of coefficients for a polynomial in either ascending (`a + bx +cx^2 + …`) or descending (`ax^n + bx^(n-1) + cx^(n-2)+…`) order (but not both) and output the companion matrix.
for a polynomial `c0 + c1x + c2x^2 + ... + cn-1x^(n-1) + x^n`,
its companion matrix is
```
(0, 0, 0, ..., -c0 ),
(1, 0, 0, ..., -c1 ),
(0, 1, 0, ..., -c2 ),
(...................),
(0, 0, ..., 1, -cn-1)
```
note that the coefficient for `x^n` is 1. For any other value, divide all the rest of the coefficients by `x^n`'s. Additionally, the 1's are offset from the diagonal.
If the language you’re using already contains a function or module that does this, you can’t use it – you must write your own.
For instance, if you had `4x^2 – 7x + 12`, the coefficients in ascending order are `(12, -7, 4)` and descending order `(4, -7, 12)`. The function or program should output `[(0, -3.0), (1, 1.75)]` for either order. Specify which order your code accepts. Minimum polynomial should be a quadratic. Coefficients are restricted to real numbers.
Below are examples – your output does not have to match the pretty formatting but it should output the rows (in the `()`) of the matrix in order.
Ascending order:
```
input:
[3., 7., -5., 4., 1.]
output:
[(0, 0, 0, -3.),
(1, 0, 0, -7.),
(0, 1, 0, 5.),
(0, 0, 1, -4.)]
input:
[-4., -7., 13.]
output:
[(0, 0.30769231),
(1, 0.53846154)]
input:
[23., 1., 92., 8., -45., 88., 88.]
output:
[(0, 0, 0, 0, 0, -0.26136364),
(1, 0, 0, 0, 0, -0.01136364),
(0, 1, 0, 0, 0, -1.04545455),
(0, 0, 1, 0, 0, -0.09090909),
(0, 0, 0, 1, 0, 0.51136364),
(0, 0, 0, 0, 1, -1. )]
```
Descending order:
```
input:
[1., 4., -5., 7., 3.]
output:
[(0, 0, 0, -3.),
(1, 0, 0, -7.),
(0, 1, 0, 5.),
(0, 0, 1, -4.)]
input:
[13., -7., -4.]
output:
[(0, 0.30769231),
(1, 0.53846154)]
input:
[88., 88., -45., 8., 92.,1., 23.]
output:
[(0, 0, 0, 0, 0, -0.26136364),
(1, 0, 0, 0, 0, -0.01136364),
(0, 1, 0, 0, 0, -1.04545455),
(0, 0, 1, 0, 0, -0.09090909),
(0, 0, 0, 1, 0, 0.51136364),
(0, 0, 0, 0, 1, -1. )]
```
---
[Dennis](https://codegolf.stackexchange.com/a/59601/34315) wins with 20 bytes!
[Answer]
# CJam, ~~23~~ 20 bytes
```
{)W*f/_,,_ff=1f>\.+}
```
This is a function that pops the input (ascending order) from the stack and pushes the output in return.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%20e%23%20Read%20and%20evaluate%20input.%0A%0A%7B)W*f%2F_%2C%2C_ff%3D1f%3E%5C.%2B%7D%0A%0A~p%20e%23%20Call%20function%20and%20print.&input=%5B3.%207.%20-5.%204.%201.%5D).
### How it works
```
) e# Pop the last element from the input array.
W* e# Multiply it by -1.
f/ e# Divide the remaining array elements by this product.
_, e# Push a copy of the array and compute its length (L).
,_ e# Push [0 ... L-1] twice.
ff= e# For each I in [0 ... L-1]:
e# For each J in [0 ... L-1]:
e# Push (I==J).
e# This pushes the L x L identity matrix.
1f> e# Discard the first element of each row, i.e., the first column.
\ e# Swap the result with the modified input.
.+ e# Vectorized append; append the input as a new column.
```
[Answer]
# CJam, ~~32~~ ~~31~~ 28 bytes
```
0q~)f/f-_,(_,\0a*1+fm<~]W%z
```
[Try it online](http://cjam.aditsu.net/#code=0q~)f%2Ff-_%2C(_%2C%5C0a*1%2Bfm%3C~%5DW%25z%60&input=%5B23.%201.%2092.%208.%20-45.%2088.%2088.%5D)
This takes the input in ascending order, using the CJam list format. Sample input:
```
[-4.0 -7.0 13.0]
```
Explanation:
```
0 Push a 0 for later sign inversion.
q~ Get and interpret input.
) Pop off last value.
f/ Divide all other values by it.
f- Invert sign of values.
_, Get count of values, which corresponds to n.
( Decrement by 1.
_, Create list of offsets [0 1 ... n-1] for later.
\ Swap n-1 back to top.
0a* Create list of n-1 zeros.
1+ Append a 1. This is the second-but-last column [0 0 ... 0 1].
fm< Apply rotation with all offsets [0 1 ... n-1] to column.
~ Unwrap the list of 0/1 columns.
] Wrap all columns
W% Invert their order from last-to-first to first-to last.
z Transpose to get final matrix.
` Convert to string for output.
```
[Answer]
# APL, ~~40~~ 30 bytes
```
{(-n↑⍵÷⊃⊖⍵),⍨⍉1↓⍉∘.=⍨⍳n←1-⍨≢⍵}
```
Accepts input in ascending order.
Explanation:
```
{
n←1-⍨≢⍵ ⍝ Define n = length(input)-1
∘.=⍨⍳ ⍝ Create an n×n identity matrix
⍉1↓⍉ ⍝ Drop the leftmost column
,⍨ ⍝ Append on the right:
(-n↑⍵ ⍝ n negated coefficients,
÷⊃⊖⍵) ⍝ divided by the n+1st
}
```
[Try it online](http://tryapl.org/?a=%7B%28-n%u2191%u2375%F7%u2283%u2296%u2375%29%2C%u2368%u23491%u2193%u2349%u2218.%3D%u2368%u2373n%u21901-%u2368%u2262%u2375%7D%203%207%20%AF5%204%201&run)
[Answer]
# Julia, 43 bytes
```
c->rot180([-c[2:(n=end)]/c[] eye(n-1,n-2)])
```
This uses descending order for the input. It constructs the matrix rotated 180 degrees, in order to enable more efficient use of "eye", then rotates the matrix into the right orientation.
[Answer]
# Julia, ~~64~~ 44 bytes
```
c->(k=c[n=end];[eye(n-=1)[:,2:n] -c[1:n]/k])
```
Accepts a vector of the coefficients in ascending order.
Ungolfed:
```
function f(c::Array)
# Simultaneously define k = the last element of c and
# n = the length of c
k = c[n = end]
# Decrement n, create an n×n identity matrix, and exclude the
# first column. Horizontally append the negated coefficients.
[eye(n-=1)[:,2:n] -c[1:n]/k]
end
```
[Try it online](http://goo.gl/aFl1Ol)
Saved 20 bytes thanks to Glen O!
[Answer]
# R, ~~71~~ 59 bytes
Takes input in ascending order.
```
function(x)cbind(diag(n<-length(x)-1)[,2:n],-x[1:n]/x[n+1])
```
Ungolfed:
```
f <- function(x) {
# Get the length of the input
n <- length(x)-1
# Create an identity matrix and exclude the first column
i <- diag(n)[, 2:n]
# Horizontally append the negated coefficients divided
# by the last one
cbind(i, -x[1:n]/x[n+1])
}
```
[Answer]
# Matlab, 66 bytes
```
function y=f(c)
n=numel(c);y=[[0*(3:n);eye(n-2)] -c(1:n-1)'/c(n)];
```
It uses ascending order for the input, with format `[3., 7., -5., 4., 1.]` or `[3. 7. -5. 4. 1.]`.
[Try it online](http://ideone.com/YDjCef) (in Octave).
Example (in Matlab):
```
>> f([23., 1., 92., 8., -45., 88., 88.])
ans =
0 0 0 0 0 -0.261363636363636
1.000000000000000 0 0 0 0 -0.011363636363636
0 1.000000000000000 0 0 0 -1.045454545454545
0 0 1.000000000000000 0 0 -0.090909090909091
0 0 0 1.000000000000000 0 0.511363636363636
0 0 0 0 1.000000000000000 -1.000000000000000
```
---
*If a program is valid (instead of a function), with stdin and stdout:*
# Matlab, 59 bytes
```
c=input('');n=numel(c);[[0*(3:n);eye(n-2)] -c(1:n-1)'/c(n)]
```
[Answer]
# Octave, ~~45~~ 44 bytes
Assuming `c` is a column vector with the coefficient of the highest power of `x` at the end.
```
@(c)[eye(n=rows(c)-1)(:,2:n),-c(1:n)/c(end)]
```
Old version:
```
@(c)[eye(n=numel(c)-1)(:,2:n),-c(1:n)/c(end)]
```
High five, [Julia!](https://codegolf.stackexchange.com/a/59595/24877)
[Answer]
# Python 2, 141 bytes
My own attempt:
```
def C(p):
c,r=p.pop(0),range;d=[-i/c for i in p];n=len(d);m=[[0]*n for i in r(n)]
for i in r(n-1):m[i][i+1]=1
m[-1]=d[::-1];return zip(*m)
```
Takes a list of the coefficients in descending order and first builds the transpose of the companion matrix - known for stabbing and being talkative. The return uses zip to produce the transpose of this transpose to get the actual matrix.
```
>>> C([1., 4., -5., 7., 3.])
[(0, 0, 0, -3.0), (1, 0, 0, -7.0), (0, 1, 0, 5.0), (0, 0, 1, -4.0)]
```
[Answer]
# JavaScript (ES6) 85
Ascending order.
Test running the snippet below in any EcmaScript 6 compliant browser.
```
f=c=>alert(c.map((v,i)=>c.map((x,j)=>++j-i?j-c.length?0:-v/m:1),m=c.pop()).join(`
`))
// test
// redefine alert to write into the snippet body
alert=x=>O.innerHTML+=x+'\n'
function test() {
v=I.value.match(/\d+/g)
I.value=v+''
alert(v)
f(v)
}
test()
```
```
<input value='23.,1.,92.,8.,-45.,88.,88.' id=I><button onclick="test()">-></button>
<pre id=O></pre>
```
[Answer]
# TI-BASIC, 50 bytes
```
Ans→X
List▶matr(ΔList(Ans-cumSum(Ans)),[A]
dim(Ans
augment(augment(0randM(Ans-2,1),identity(Ans-2))ᵀ,[A]∟X(Ans)⁻¹
```
Takes input in ascending order. Note that this will not work for polynomials of degree <2, because TI-BASIC does not support empty matrices or lists. Pending a ruling from OP, I can fix this at the cost of a few bytes.
First, we store the list into `∟X` to use the last element later; then, we calculate `ΔList(Ans-cumSum(Ans))`, which is just the negated list with the last element chopped off, and convert it to a column vector. Since `List▶matr(` doesn't modify `Ans`, we can use the next line to take the dimension of the list, which we use thrice. TI-BASIC doesn't have vertical concatenation, so we need to take transposes and horizontally concatenate. In the last line, `[A]/∟X(Ans` wouldn't work because matrices can be multiplied by scalars but not divided.
An aside: To generate the row vector of zeros, we take advantage of the rarely useful `randM(` command. `randM(` creates a random matrix, but its entries are always random integers between -9 and 9 (!), so it's really only useful to create zero matrices.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes
```
p->concat(matid(#p-1),-p[^#p]~/p[#p])[,^1]
```
[Try it online!](https://tio.run/##FYrBCoMwEER/ZdBLAruUqKXxUH8kRAgWS6C1i@TSS3893RyGmfcYSWfmp9Qdd1ThZfscWyrmnUp@mF7YWWIJay/xd5GgZQOtLtYk8voaAS@QMx9FZ9egw27EWkIII@FG4CthIrioinWwOjc2GvTgCPNA8OonPXrfEqOtfw "Pari/GP – Try It Online")
] |
[Question]
[
Clem is a minimal stack-based programming language featuring first-class functions. Your objective is to write an interpreter for the Clem language. It should properly execute all examples included in the reference implementation, which is available [here](http://www.orbitaldecay.com/code/clem.zip).
* As usual, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply.
* Smallest entry by byte count wins.
## The Clem language
Clem is a stack based programming language with first-class functions. The best
way to learn Clem is to run the `clem` interpreter with no arguments. It will
start in interactive mode, allowing you to play with the available commands. To
run the example programs, type `clem example.clm` where example is the name of
the program. This brief tutorial should be enough to get you started.
There are two main classes of functions. Atomic functions and compound
functions. Compound functions are lists composed of other compound functions and
atomic functions. Note that a compound function cannot contain itself.
## Atomic Functions
The first type of atomic function is the *constant*. A *constant* is simply an
integer value. For example, -10. When the interpreter encounters a *constant*,
it pushes it to the stack. Run `clem` now. Type `-10` at the prompt. You should
see
```
> -10
001: (-10)
>
```
The value `001` describes the position of the function in the stack and `(-10)` is the *constant* you just entered. Now enter `+11` at the prompt. You should see
```
> +11
002: (-10)
001: (11)
>
```
Notice that `(-10)` has moved to the second position in the stack and `(11)` now
occupies the first. This is the nature of a stack! You will notice that `-` is also the decrement command. Whenever `-` or `+` precede a number, they denote the sign of that number and not the corresponding command. All other atomic functions are *commands*. There are 14 in total:
```
@ Rotate the top three functions on the stack
# Pop the function on top of the stack and push it twice
$ Swap the top two functions on top of the stack
% Pop the function on top of the stack and throw it away
/ Pop a compound function. Split off the first function, push what's left,
then push the first function.
. Pop two functions, concatenate them and push the result
+ Pop a function. If its a constant then increment it. Push it
- Pop a function. If its a constant then decrement it. Push it
< Get a character from STDIN and push it to the stack. Pushes -1 on EOF.
> Pop a function and print its ASCII character if its a constant
c Pop a function and print its value if its a constant
w Pop a function from the stack. Peek at the top of the stack. While it is
a non-zero constant, execute the function.
```
Typing a command at the prompt will execute the command. Type `#` at the prompt
(the duplicate command). You should see
```
> #
003: (-10)
002: (11)
001: (11)
>
```
Notice that the (11) has been duplicated. Now type `%` at the prompt (the drop
command). You should see
```
> %
002: (-10)
001: (11)
>
```
To push a command to the stack, simply enclose it in parenthesis. Type `(-)` at
the prompt. This will push the decrement operator to the stack. You should see
```
> (-)
003: (-10)
002: (11)
001: (-)
>
```
## Compound functions
You may also enclose multiple atomic functions in parenthesis to form a compound
function. When you enter a compound function at the prompt, it is pushed to the
stack. Type `($+$)` at the prompt. You should see
```
> ($+$)
004: (-10)
003: (11)
002: (-)
001: ($ + $)
>
```
Technically, everything on the stack is a compound function. However, some of
the compound functions on the stack consist of a single atomic function (in
which case, we will consider them to be atomic functions for the sake of
convenience). When manipulating compound functions on the stack, the `.` command
(concatenation) is frequently useful. Type `.` now. You should see
```
> .
003: (-10)
002: (11)
001: (- $ + $)
>
```
Notice that the first and second functions on the stack were concatenated, and
that the second function on the stack comes first in the resulting list. To
execute a function that is on the stack (whether it is atomic or compound), we
must issue the `w` command (while). The `w` command will pop the first function
on the stack and execute it repeatedly so long as the second function on the
stack is a non-zero constant. Try to predict what will happen if we type `w`.
Now, type `w`. You should see
```
> w
002: (1)
001: (0)
>
```
Is that what you expected? The two numbers sitting on top of the stack were
added and their sum remains. Let's try it again. First we'll drop the zero and
push a 10 by typing `%10`. You should see
```
> %10
002: (1)
001: (10)
>
```
Now we'll type the entire function in one shot, but we'll add an extra `%` at
the end to get rid of the zero. Type `(-$+$)w%` at the prompt. You should see
```
> (-$+$)w%
001: (11)
>
```
(Note this algorithm only works if the first constant on the stack is positive).
## Strings
Strings are also present. They are mostly syntactic sugar, but can be quite useful. When the interpreter encounters a string, it pushes each character from last to first onto the stack. Type `%` to drop the 11 from the previous example. Now, type `0 10 "Hi!"` on the prompt. The `0` will insert a NULL terminator and the `10` will insert a new-line character. You should see
```
> 0 10 "Hi!"
005: (0)
004: (10)
003: (33)
002: (105)
001: (72)
>
```
Type `(>)w` to print characters from the stack until we encounter the NULL terminator. You should see
```
> (>)w
Hi!
001: (0)
>
```
## Conclusions
Hopefully this should be enough to get you started with the interpreter. The
language design should be relatively straight-forward. Let me know if anything is terribly unclear :) A few things have been left intentionally vague: values must be signed and *at least* 16 bits, the stack must be large enough to run all reference programs, etc. Many details haven't been carved out here because a full blown language specification would be prohibitively large to post (and I haven't written one yet :P). When in doubt, mimic the reference implementation.
[The esolangs.org page for Clem](http://esolangs.org/wiki/Clem)
[The reference implementation in C](http://www.orbitaldecay.com/code/clem.zip)
[Answer]
# Python, ~~[1684](https://gist.githubusercontent.com/csaftoiu/20fe5fdcb897bb50193f/raw/f8c6401e5a113ff88782cabe522825dc673d5024/clemint.py%20-%20gold)~~ [1281](https://gist.githubusercontent.com/csaftoiu/20fe5fdcb897bb50193f/raw/19d77b8a2942d0de046c0f76415bcf6174fe7360/clemint.py%20-%20gold) characters
Got all the basic golf stuff done. It runs all the example programs and matches the output character-for-character.
```
import sys,os,copy as C
L=len
S=[]
n=[S]
Q=lambda:S and S.pop()or 0
def P(o):
if o:n[0].append(o)
def X():x=Q();P(x);P(C.deepcopy(x))
def W():S[-2::]=S[-1:-3:-1]
def R():a,b,c=Q(),Q(),Q();P(a);P(c);P(b)
def A(d):
a=Q()
if a and a[0]:a=[1,a[1]+d,lambda:P(a)]
P(a)
def V():
a=Q();P(a)
if a and a[0]-1and L(a[2])>1:r=a[2].pop(0);P(r)
def T():
b,a=Q(),Q()
if a!=b:P([0,0,(a[2],[a])[a[0]]+(b[2],[b])[b[0]]])
else:P(a);P(b)
def r():a=os.read(0,1);F(ord(a)if a else-1)
def q(f):
a=Q()
if a and a[0]:os.write(1,(chr(a[1]%256),str(a[1]))[f])
def e(f,x=0):f[2]()if f[0]+f[1]else([e(z)for z in f[2]]if x else P(f))
def w():
a=Q()
while a and S and S[-1][0]and S[-1][1]:e(a,1)
def Y():n[:0]=[[]]
def Z():
x=n.pop(0)
if x:n[0]+=([[0,0,x]],x)[L(x)+L(n)==2]
D={'%':Q,'#':X,'$':W,'@':R,'+':lambda:A(1),'-':lambda:A(-1),'/':V,'.':T,'<':r,'>':lambda:q(0),'c':lambda:q(1),'w':w,'(':Y,')':Z}
def g(c):D[c]()if L(n)<2or c in'()'else P([0,1,D[c]])
N=['']
def F(x):a=[1,x,lambda:P(a)];a[2]()
def E():
if'-'==N[0]:g('-')
elif N[0]:F(int(N[0]))
N[0]=''
s=j=""
for c in open(sys.argv[1]).read()+' ':
if j:j=c!="\n"
elif'"'==c:E();s and map(F,map(ord,s[:0:-1]));s=(c,'')[L(s)>0]
elif s:s+=c
elif';'==c:E();j=1
else:
if'-'==c:E()
if c in'-0123456789':N[0]+=c
else:E();c in D and g(c)
```
**Testing**:
Gather [clemint.py](https://gist.github.com/csaftoiu/20fe5fdcb897bb50193f), [clemtest\_data.py](https://gist.github.com/csaftoiu/c55fc6faf93f9439cb18), [clemtest.py](https://gist.github.com/csaftoiu/1d2b87d4870cd0d65c64), and a compiled `clem` binary into a directory and run `clemtest.py`.
**Expanation**:
The most ungolfed version is [this one](https://gist.github.com/csaftoiu/20fe5fdcb897bb50193f/acee3127e6bf0e1d483d5fe1f30bae8f733c0a91). Follow along with that one.
`S` is the main stack. Each item of the stack is a 3-list, one of:
```
Constant: [1, value, f]
Atomic: [0, 1, f]
Compound: [0, 0, fs]
```
For the constants, `f` is a function which pushes the constant onto the stack. For the atmoics, `f` is a function which executes one of the operations (e.g. `-`, `+`). For the compounds, `fs` is a list of items.
`xec` executes an item. If it's a constant or an atomic, it just executes the function. If it's a compound, if there has been no recursion yet, it executes each function. So executing `(10 20 - 30)` will execute each of the functions `10`, `20`, `-`, and `30`, leaving `10 19 30` on the stack. If there has been recursion, then it just pushes the compound function onto the stack. For example, when executing `(10 20 (3 4) 30)`, the result should be `10 20 (3 4) 30`, not `10 20 3 4 30`.
Nesting was a bit tricky. What do you do while reading off `(1 (2 (3 4)))`? The solution is to have a stack of stacks. At each nesting level, a new stack is pushed on the stack of stacks, and all push operations go onto this stack. Further, if there has been nesting, then atomic functions are pushed instead of executed. So if you see `10 20 (- 30) 40`, `10` is pushed, then `20`, then a new stack is created, `-` and `30` are pushed onto the new stack, and `)` pops off the new stack, turns it into an item, and pushes it onto the stack one level down. `endnest()` handles `)`. It was a bit tricky since there's a special case when only one item has been pushed and we're pushing back onto the main stack. That is, `(10)` should push the constant `10`, not a composite with the one constant, because then `-` and `+` don't work. I'm not sure whether this is principled but it's the way it works...
My interpreter is a character-by-character processor - it doesn't create tokens - so numbers, strings, and comments were somewhat annoying to deal with. There's a separate stack, `N`, for a currently-being-processed-number, and anytime a character which isn't a number is processed, I have to call `endnum()` to see whether I should first complete that number and put it on the stack. Whether we're in a string or a comment is kept track of by boolean variables; when a string is closed it pushes all the innards on the stack. Negative numbers required some special handling as well.
That's about it for the overview. The rest was implementing all the built-ins, and making sure to do deep copies in `+`, `-`, and `#`.
[Answer]
# C 832
**Thanks to @ceilingcat for finding a much better (and shorter) version**
This treats everything as simple strings - all stack items are strings, even constants are strings.
```
#define Q strcpy
#define F(x)bcopy(b,f,p-b);f[p-b x]=!Q(r,p);
#define C(x,y)Q(S[s-x],S[s-y]);
#define N[99]
#define A Q(S[s++]
#define D sprintf(S[s++],"%d"
#define G(x);}if(*f==x){
#define H(x)G(x)s--;
#define R return
#define Z(x)T(t,u,v)-1||putchar(x)H(
z=1,*y;char S N N;s;c;T(b,f,r,p)char*b,*f,*r,*p;{strtol(b+=strspn(b," "),&p,0);if(p>b){F()R 1;}if(c=*b==40){for(p=++b;c;p++)if(z^=*p==34)c+=*p-41?*p==40:-1;F(-1)R-1;}p++;F()*r*=!!*b;R 0;}*P(char*p){R*p-34?y=P(p+1),D,*p),y:++p;}E(int*x){char*p,c N,f N,r N,t N,u N,v N;for(Q(c,x);*c;Q(c,p)){Q(t,S[s-1]);if(T(c,f,p=r))A,f);else{{G(64)C(0,1)C(1,2)C(2,3)C(3,0)G(35)A,t)G(36)C(0,2)C(2,1)C(1,0)H(37)H(47)T(t,u,v);*v&&A,v);A,u)H(46)strcat(strcat(S[s-1]," "),t)H(43)D,atoi(t)+1)H(45)D,atoi(t)-1)G(60)D,getchar())H(62)Z(atoi(u))99)Z(*u)119)for(Q(u,t);atoi(S[s-1]);)E(u)G(34)p=P(p);}}}}
```
[Try it online!](https://tio.run/##fVLbTuMwEH3nK9zQohnHWcVNKCqWgYrrU0ULT9Cu1ISGrcS2Vi7QEvrt3XFCC7xsJI/H5xw7c4u95zjebPafpslsPmUDluVpbFZ7W@AKlhjFC7OCSCTCeBGq5JE2thzrxgBSYVDtxOewFCscwN1j5i3Hwm6r8Te@/9jtjnenHquUrvsFXbDMpLN5nnwSwmk9OTv2mmJR61kCPNF6ieWOuCHCkpnnff1syNJpXqTzHfBAinvIRSFe0ZMfH6bI4z@TlNAb2HvXUvCVsgC7Y33WV5mK1X2VtU3SEjwSPBE8FdyokuqUL14gcjV5mZmT0mEOigMjfFQUpDmJsLwCHDJZBR1rHmkd@lgmixSMdt2I/mBcF4l8/6250ToIMXbJ80J5as@hf@xJdQWexCE5a1LTCXnKdaPBIzVkvlrzW6iiM1gO6WoQnq70LRhXorigUFGsjl3XqPUlUGU51a1Wi5j1RUIrpZXTKmi9UuI2vAHEgorNY2U9g1gOqHK2oXJcZXdPMM2DThF7IkE1fcmmZXkNnRDPwReSrBRtsm0RkA2oKNcQHJI4t06nUtV8rfWpC8ERmfBo1yXFXw8OetbpicJSHbTjOcnhc6sDqgufW0GAF2KSL2aQI@VPwOEXQEWk@HwCnqd155EUnTY@QKUoELtdOvACpexiXYaC3lUVvU0eL0lJKYRobJlpIunb/J3M5kAjydjnADsj52bWGDnsmIJThF@C4zPpsy0OJ/hWM9sb0l@25Xc9qQnwz6B5tk/GbXr41jqrbOvn1VY2mjvUH8/Lxj@IQWFH/9ubMHJQ@s39IGxSDiz0q0DwF32y@fZf0r6x3vwD "C (gcc) – Try It Online")
A less golfed version of my original (unlike the golfed version this one prints the stack when it ends if it is not empty and takes a -e parameter so you can specify the script on the command line instead of reading from a file):
```
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define FIRST_REST(x) memcpy(first, b, p - b); first[p - b - x] = '\0'; strcpy(rest, p);
#define COPY(dest,src) strcpy(stack[size + dest], stack[size + src]);
char stack[9999][9999]; int size = 0;
int token(char *b, char *first, char *rest)
{
while (*b == 32) b++;
char *p; int x = strtol(b, &p, 0);
if (p > b) { FIRST_REST(0) return 1; }
if (*b == '(') { int c = 1; for (p = ++b; c; ++p) c += (*p == '(') - (*p == ')'); FIRST_REST(1) return -1; }
p++; FIRST_REST(0) if (!*b) *rest = '\0'; return 0;
}
char *push(char *pointer)
{
if (*pointer == '\"') return pointer+1;
char *result = push(pointer+1);
sprintf(stack[size++], "%d", *pointer);
return result;
}
void eval(char *x)
{
char program[9999], first[9999], rest[9999], tos[9999], tmp1[9999], tmp2[9999];
char *pointer;
for (strcpy(program, x); *program; strcpy(program, pointer))
{
*stack[size] = '\0';
strcpy(tos, stack[size-1]);
if (token(program, first, rest))
{
pointer = rest;
strcpy(stack[size++], first);
}
else
{
pointer = rest;
if (*first == '@'){
COPY(0, -1) COPY(-1, -2) COPY(-2, -3) COPY(-3, 0) }
if (*first == '#')
strcpy(stack[size++], tos);
if (*first == '$'){
COPY(0, -2) COPY(-2, -1) COPY(-1, 0) }
if (*first == '%')
size--;
if (*first == '/'){
size--; token(tos, tmp1, tmp2); if (*tmp2) strcpy(stack[size++], tmp2); strcpy(stack[size++], tmp1); }
if (*first == '.'){
size--; strcat(stack[size - 1], " "); strcat(stack[size - 1], tos); }
if (*first == '+'){
size--; sprintf(stack[size++], "%d", atoi(tos) + 1); }
if (*first == '-'){
size--; sprintf(stack[size++], "%d", atoi(tos) - 1); }
if (*first == '<')
sprintf(stack[size++], "%d", getchar());
if (*first == '>'){
size--; if (token(tos, tmp1, tmp2) == 1) putchar(atoi(tmp1)); }
if (*first == 'c'){
size--; if (token(tos, tmp1, tmp2) == 1) printf("%s", tmp1); }
if (*first == 'w'){
size--; strcpy(tmp1, tos); while (atoi(stack[size - 1])) eval(tmp1); }
if (*first == '\"')
pointer=push(pointer);
}
}
}
int main(int argc, char **argv)
{
char program[9999] = "";
int i = 0, comment = 0, quote = 0, space = 0;
if (!strcmp(argv[1], "-e"))
strcpy(program, argv[2]);
else
{
FILE* f = fopen(argv[1], "r");
for (;;) {
char ch = fgetc(f);
if (ch < 0) break;
if (!quote) {
if (ch == '\n') comment = 0;
if (ch == ';') comment = 1;
if (comment) continue;
if (ch <= ' ') { ch = ' '; if (space++) continue; }
else space = 0;
}
if (ch == '\"') quote = 1 - quote;
program[i++] = ch;
}
fclose(f);
}
eval(program);
for (int i = 0; i < size; i++) printf("%03d: (%s)\r\n",size-i,stack[i]);
return 0;
}
```
[Answer]
# Haskell, ~~931~~ ~~921~~ 875
this isn't fully golfed yet but it will probably never be. Still, it is already shorter than all other solutions.
~~I will golf this more soon.~~ I don't feel like golfing it any more than this.
probably has a few subtle bugs because I didn't play with the C reference implementation.
this solution uses the type `StateT [String] IO ()` to store a "runnable" clem program. most the program is a parser which parses the "runnable program".
in order to run this use `r "<insert clem program here>"`.
```
import Text.Parsec
import Control.Monad.State
import Control.Monad.Trans.Class
import Data.Char
'#'%(x:y)=x:x:y
'%'%(x:y)=y
'@'%(x:y:z:w)=y:z:x:w
'$'%(x:y:z)=y:x:z
'/'%((a:b):s)=[a]:b:s
'+'%(a:b)=i a(show.succ)a:b
'.'%(a:b:c)=(a++b):c
_%x=x
b=concat&between(s"(")(s")")(many$many1(noneOf"()")<|>('(':)&((++")")&b))
e=choice[s"w">>c(do p<-t;let d=h>>= \x->if x=="0"then a else u p>>d in d),m&k,s"-">>(m&(' ':)&k<|>c(o(\(a:b)->i a(show.pred)a:b))),s"c">>c(do
d<-t
i d(j.putStr.show)a),o&(++)&map(show.ord)&between(s"\"")(s"\"")(many$noneOf"\""),(do
s"<"
c$j getChar>>=m.show.ord),(do
s">"
c$do
g<-t
i g(j.putChar.chr)a),m&b,o&(%)&anyChar]
k=many1 digit
i s f g|(reads s::[(Int,String)])>[]=f$(read s::Int)|0<1=g
t=h>>=(o tail>>).c
c n=return n
a=c()
h=head&get
(&)f=fmap f
m=o.(:)
o=modify
u=(\(Right r)->r).parse(sequence_&many e)""
r=(`runStateT`[]).u
s=string
j=lift
```
[Answer]
# Scala, ~~1014~~ 1009 bytes
```
import util._
val n="([+-]?\\d+)(.*)".r
def c(z:String):(String,String)=z.trim match{
case s"($x"=>var i,b=0
while(-1<b&i<x.size){if(x(i)=='(')b+=1
if(x(i)==')')b-=1
i+=1}
(x.slice(0,i-1),x drop i)case n(x,t)=>(x,t)case x=>x.slice(0,1)->x.tail}
def f(z:String,r:List[String]=Nil):List[String]="\"([^\"]*)\"".r.replaceAllIn(z.trim,m=>m.group(1).reverse.flatMap(" " + _.toInt + " "))match{case ""=>r
case s"($x"=>val(a,b)=c(z.trim);f(b,a::r)case n(x,t)=>f(t,""+x.toInt::r)case s"@$t"=>val a::b::c::d=r
f(t,b::c::a::d)case s"#$t"=>f(t,r.head::r)case s"$$$t"=>val a::b::c=r
f(t,b::a::c)case s"%$t"=>f(t,r.tail)case s"/$t"=>val(a,b)=c(r.head.trim)
f(t,a::b.trim::r.tail)case s".$t"=>val a::b::c=r
f(t,s"$a$b"::c)case s"<$t"=>f(t,Try{""+io.StdIn.readChar}.getOrElse("-1")::r)case s">$t"=>Try{print(r.head.toInt.toChar)}
f(t,r.tail)case s"c$t"=>Try{print(r.head.toInt)}
f(t,r.tail)case s"w$t"=>var h::u=r
while(u.head!="0")u=f(h,u)
f(t,u)case x=>f(x.tail,""+(Try{r.head.toInt+s"${x(0)}1".toInt}getOrElse-1)::r.tail)}
```
[Try it online](https://scastie.scala-lang.org/onZ6ikT7SWimTwrgKBsS6Q)
Wow, this got long. I'll add an explanation later.
[Ungolfed](https://scastie.scala-lang.org/XCHfB8STSyuPct9RW624xg)
] |
[Question]
[
Golfers.
Together, we have banded together to produce code that is concise, is functionally beautiful and is uglier then the Phantom of the Opera from the original novel.
The time has come for us to bring beauty back to the world of programming. With color. In a way that is concise, functionally beautiful is uglier then the Phantom of the Opera from the original novel.
We're gonna be coding a colorful syntax highlighter. In the shortest amount of code possible.
You will receive via an input file or Stdin a valid C file. The C file will use the line convention of your choice, and will only contain ASCII characters 32-126. You have to turn it into a HTML file that displays correctly at least in Chrome, that shows the source code with syntax highlighting. The output may be in a file or to Stdout.
You must highlight:
* All strings and characters (including the quote characters) in Green (#00FF00). The strings may contain escaped characters.
* All C reserved words in Blue (#0000FF).
* All comments in Yellow (#FFFF00).
* All C preprocessor directives in Pink (#FF00FF).
The output when displayed in Chrome must:
* Be in a fixed-width font
* Display new lines wherever they appeared in the original source
* Accurately reproduce whitespace. A tab character should be taken as being 4 spaces.
**Bonuses**
* x 0.9 if you include line numbers. Line numbers must be able to reach at least 99999. All source must still be aligned - so, source code with smaller line numbers should still start at the same position as source code with higher line numbers
* x 0.8 if background of each line is alternated between light gray (#C0C0C0) and white (#FFFFFF)
* x 0.9 if your source code is written in C, and can correctly format itself.
**Scoring**
This is code golf. Your score is the amount of bytes of your source code multiplied by any bonuses. The winner is the golfer with the lowest score.
[Answer]
## Perl 769 chars \* 0.9 \* 0.8 = 554
Probably still some improvements to be made on some of the regexes, but it's slowly getting there!
```
$_=join"",<>;$s="<tt class";$c="</tt>";$d=counter;$e=color;s/\t/ /g;s!<!<!g;s!>!>!g;s!^#.+(?=$|
)!$s=d>$&$c!gm;s!//.+!$s=c>$&$c!g;s|(['"]).*?(?<!\\)(\\\\)*\1|($h=$&)=~s!/!/!g;"$s=s>$h$c"|smeg;s!/\*.*?\*/!$s=c>$&$c!smg;s!\b(_Packed|(au|go)to|break|c(ase|har|onst|ontinue)|d(efault|o|ouble)|e(lse|num|xtern)|f(loat|or)|if|int|long|re(gister|turn)|short|(un)?signed|s(izeof|tatic|truct|witch)|typedef|union|vo(id|latile)|while)\b!$s=r>$&$c!g;s!=(\w)>.+?$c!join"$c
$s=$1>",split$/,$&!smeg;s!
!<tr><td>!g;print"<style>body{font:10px monospace;$d-reset:n}td{white-space:pre}tr:nth-child(even){background:#c0c0c0}tr:before{$d-increment:n;content:$d(n)}.d{$e:#f0f}.r{$e:#00f}.c{$e:#ff0}.s{$e:#0f0}tt tt{$e:inherit!important}</style><table cellspacing=0><tr><td>$_"
```
Slightly less obfuscated version with comments:
```
$_=join"",<>; # slurp file
$s="<tt class"; # used later - use <tt/> instead of <span/>, fewer chars!
$c="</tt>";
$d=counter;
$e=color;
s/\t/ /g; # convert tabs to spaces
s!<!<!g; # htmlentity < and >
s!>!>!g;
s!^#.+(?=$|\n)!$s=d>$&$c!gm; # directives
s!//.+!$s=c>$&$c!g; # inline comments
s|(['"]).*?(?<!\\)(\\\\)*\1|($h=$&)=~s!/!/!g;"$s=s>$h$c"|smeg; # strings, might have 0 length - thanks @Einacio; work-around string that contain /* by converting them to HTML entities
s!/\*.*?\*/!$s=c>$&$c!smg; # multi-line comments
s!\b(_Packed|(au|go)to|break|c(ase|har|onst|ontinue)|d(efault|o|ouble)|e(lse|num|xtern)|f(loat|or)|if|int|long|re(gister|turn)|short|(un)?signed|s(izeof|tatic|truct|witch)|typedef|union|vo(id|latile)|while)\b!$s=r>$&$c!g; # reserved words, don't optimise this too much! - thanks @bwoebi
s!=(\w)>.+?$c!join"$c
$s=$1>",split$/,$&!smeg; # any multi-line string/comment, ensure <span/>s are repeated
s!\n!<tr><td>!g; # strip newlines, replace with <tr><td>, don't need </td> _or_ </tr> - thanks @xfix!
print"<style>
body{font:10px monospace;$d-reset:n} /* init counter */
td{white-space:pre} /* preserve whitespace */
tr:nth-child(odd){background:#c0c0c0} /* alternating rows */
tr:before{$d-increment:n;content:$d(n)} /* place counter */
.d{$e:#f0f} /* highlights */
.r{$e:#00f}
.c{$e:#ff0}
.s{$e:#0f0}
tt tt{$e:inherit!important} /* ignore reserved words/comments in strings */
</style><table cellspacing=0><tr><td>$_"
```
Now successfully highlights @xfix's entry.
Borrowed the idea to drop `</tr>` from @xfix's entry, thank you!
[Example of output for @xfix's solution](http://jsfiddle.net/ydMc9/3/).
[Answer]
# C - ~~1605~~ 1200 chars \* 0.9 \* 0.8 \* 0.9 = 777 chars
Definitely too long, but whatever. 264 used by list of keywords itself. The long one liner version. Doesn't use memory allocations, so the memory usage is very low (and everything is global, so the stack is not really used). [Sample HTML on JSFiddle](http://jsfiddle.net/LgfJ9/). In my opinion, comments support was most complex thing in the code.
```
char*k[]={"auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","int","long","register","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while"},b[9];c;p;e;p;l=1;q;s;i;main(){printf("<style>tr:nth-child(2n){background:#C0C0C0}</style><table style=font-family:monospace;white-space:pre-wrap><tr><td>1<td>");while(~(c=getchar())){if(!e&&q){if(q==c){printf("%c</span>",c);q=0;continue;}}else if(isalpha(c)&&p<8){b[p++]=c;continue;}else if(b[0]){for(i=0;i<32;i++){s!=2&&!strcmp(k[i],b)&&(printf("<span style=color:#00F>%s</span>",b),b[0]=0);}printf("%s",b);memset(b,0,9);}p=0;switch(c){case'<':printf("<");goto e;case'&':printf("&");goto e;case 92:putchar(c);e^=1;goto e;case'/':q||1==s?putchar('/'):3==s?(printf("*/"),s=0):(s=1);break;case'*':if(s==1){s=2;printf("<span style=color:#FF0>/*");}else if(s==2){s=3;}else{goto d;}break;case 39:case'"':e||q||(q=c,printf("<span style=color:#0F0>"));e=0;goto d;case 10:l+=1;printf("<tr><td>%d<td>",l);if(p&&e){case'#':e=0;q||(p=1,printf("<span style=color:#F0F>"));}else{p=0;}default:d:10!=c&&putchar(c);e:s=s/2*2;}}puts(b);}
```
And the longer version (which is as readable as real program, aside of few code golf tricks I didn't think I could apply easily while golfing the program.
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define ARRAY_SIZE(array) (sizeof(array) / sizeof *(array))
/* Sample comment. */
int main(void) {
const char *keywords[] = {
"auto", "break", "case", "char", "const",
"continue", "default", "do", "double", "else",
"enum", "extern", "float", "for", "goto",
"if", "int", "long", "register", "return",
"short", "signed", "sizeof", "static", "struct",
"switch", "typedef", "union", "unsigned", "void",
"volatile", "while",
};
int character;
int preprocessor = 0;
int escape = 0;
char buffer[9] = {0};
int pos = 0;
int line = 1;
int quote = 0;
int comment_state = 0;
printf("<style>tr:nth-child(2n){background:#C0C0C0}</style><table style=font-family:monospace;white-space:pre-wrap><tr><td>1<td>");
while ((character = getchar()) != EOF) {
if (!escape && quote) {
if (quote == character) {
printf("%c</span>", character);
quote = 0;
continue;
}
}
else if (isalpha(character) && pos < 8) {
buffer[pos] = character;
pos += 1;
continue;
}
else if (buffer[0]) {
int i;
for (i = 0; i < ARRAY_SIZE(keywords); i++) {
if (comment_state != 2 && strcmp(keywords[i], buffer) == 0) {
printf("<span style=color:#00F>%s</span>", buffer);
buffer[0] = 0;
}
}
printf("%s", buffer);
memset(buffer, 0, 9);
}
pos = 0;
switch (character) {
case '<':
printf("<");
goto e;
case '&':
printf("&");
goto e;
case '\\':
putchar(character);
escape ^= 1;
goto e;
case '/':
if (quote || comment_state == 1) {
putchar('/');
}
else if (comment_state == 3) {
printf("*/");
comment_state = 0;
}
else {
comment_state = 1;
}
break;
case '*':
if (comment_state == 1) {
comment_state = 2;
printf("<span style=color:#FF0>/*");
}
else if (comment_state == 2) {
comment_state = 3;
}
else {
goto d;
}
break;
case '\'':
case '"':
if (!escape && !quote) {
quote = character;
printf("<span style=color:#0F0>");
}
escape = 0;
goto d;
case '\n':
line += 1;
printf("<tr><td>%d<td>", line);
/* Execute next only if conditions match. */
if (preprocessor && escape) {
case '#':
escape = 0;
if (!quote) {
preprocessor = 1;
printf("<span style=color:#F0F>");
}
}
else {
preprocessor = 0;
}
/* fallthru */
default:
d:
if (character != '\n') putchar(character);
e:
comment_state = comment_state / 2 * 2;
}
}
printf("%s</table>", buffer);
}
```
[Answer]
## PHP 606 bytes × 0.9 × 0.8 = 436
```
<style>li:nth-child(odd){background:#f5f5f5}pre{tab-size:4;-moz-tab-size:4}</style><pre><ol><li><?php $p='preg_match';preg_match_all('_\w+|("|\')(\\\\?.)*?\1|#(.(?!/[/*]))*|//.*|(?s)/\*.*?\*/|.+?_',stream_get_contents(STDIN),$m);foreach($m[0]as$t)echo'</font><font color=#',$t[0]=='#'?'d0d':($p('_^/[/*]_',$t)?'bb0':($p('/"|\'/',$t)?'0d0':($p('/^(auto|break|(cas|continu|doubl|els|volatil|whil)e|char|(cons|defaul|floa|in|shor|struc)t|do|enum|extern|for|goto|if|long|register|return|sizeof|static|switch|typedef|union|(un|)signed|void)$/',$t)?'00f':0))),'>'.preg_replace("/\r?\n/",'<li>',htmlentities($t));
```
Formatted:
```
<style>li:nth-child(odd){background:#f5f5f5}pre{tab-size:4;-moz-tab-size:4}</style>
<pre><ol><li><?php
$p='preg_match';
preg_match_all('_\w+|("|\')(\\\\?.)*?\1|#(.(?!/[/*]))*|//.*|(?s)/\*.*?\*/|.+?_',
stream_get_contents(STDIN),$m);
foreach($m[0]as$t)
echo'</font><font color=#',
$t[0]=='#'?'d0d':(
$p('_^/[/*]_',$t)?'bb0':(
$p('/"|\'/',$t)?'0d0':(
$p('/^(auto|break|(cas|continu|doubl|els|volatil|whil)e|char|'.
'(cons|defaul|floa|in|shor|struc)t|do|enum|extern|for|goto|if|long|register|'.
'return|sizeof|static|switch|typedef|union|(un|)signed|void)$/',$t)?'00f':
0))),
'>'.preg_replace("/\r?\n/",'<li>',htmlentities($t));
```
* Reads from stdin and writes to stdout.
* Accepted line endings are \n and \r\n.
* Does line numbers and line color alternation.
* I used *slightly* different colors so I could bear to look at it, though not in a way that affects the byte count.
* I don't have Chrome to test it although it's fine in Firefox.
[Answer]
## C++ - 5067 bytes4612 \* 0.9 \* 0.8 = 3320 (\* 0.9 = 2988 if being able to format itself counts - it's written in C++)
I realize that this is larger than the solutions already presented here, but I've decided to post this anyway because I started working on my version before the C solution by xfix was posted.
* It works with multiline comments
* It outputs HTML that has errors (but it displays correctly in Chrome)
* It reads out of input.c and produces output.html
A half of this is the large array of C and C++ keywords.
```
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <locale>
#define B break
#define Z(a,b)if(s[i]==a){z=b;o+=OP+p(s[i]);i++;B;}
#define V(a,b)if(e(s,i,a)){z=b;o+=OC+p(s.substr(i,2));i+=2;B;}
#define N(a) if(s[i]=='\n'){a;o+=nl();i++;B;}
#define Q(a)if(e(s,i,"\\")){o+=p(s.substr(i,2));i+=2;B;}if(s[i]==a){z=0;o+=p(s[i])+CL;i++;B;}
#define C case
using namespace std;string k[]={"__abstract","__alignof","_Alignas","_alignof","and","and_eq","__asm","_asm","asm","__assume","_assume","auto","__based","_based","bitand","bitor","bool","_Bool","__box","break","__builtin_alignof","_builtin_alignof","__builtin_isfloat","case","catch","__cdecl","_cdecl","_Complex","cdecl","char","class","__compileBreak","_compileBreak","compl","const","const_cast","continue","__declspec","_declspec","default","__delegate","delete","do","double","dynamic_cast","else","enum","__event","__except","_except","explicit","__export","_export","extern","false","__far","_far","far","__far16","_far16","__fastcall","_fastcall","__feacpBreak","_feacpBreak","__finally","_finally","float","for","__forceinline","_forceinline","__fortran","_fortran","fortran","friend","_Generic","__gc","goto","__hook","__huge","_huge","huge","_Imaginary","__identifier","if","__if_exists","__if_not_exists","__inline","_inline","inline","int","__int128","__int16","_int16","__int32","_int32","__int64","_int64","__int8","_int8","__interface","__leave","_leave","long","__multiple_inheritance","_multiple_inheritance","mutable","namespace","__near","_near","near","new","_Noreturn","__nodefault","__nogc","__nontemporal","not","not_eq","__nounwind","__novtordisp","_novtordisp","operator","or","or_eq","__pascal","_pascal","pascal","__pin","__pragma","_pragma","private","__probability","__property","protected","__ptr32","_ptr32","__ptr64","_ptr64","public","__raise","register","reinterpret_cast","restrict","__restrict","__resume","return","__sealed","__serializable","_serializable","short","signed","__single_inheritance","_single_inheritance","sizeof","static","static_cast","_Static_assert","__stdcall","_stdcall","struct","__super","switch","__sysapi","__syscall","_syscall","template","this","__thiscall","_thiscall","throw","_Thread_local","__transient","_transient","true","__try","_try","try","__try_cast","typedef","typeid","typename","__typeof","__unaligned","__unhook","union","unsigned","using","__uuidof","_uuidof","__value","virtual","__virtual_inheritance","_virtual_inheritance","void","volatile","__w64","_w64","__wchar_t","wchar_t","while","xor","xor_eq"};string OS="<font color=\"#00FF00\">";string OC="<font color=\"#FFFF00\">";string OK="<font color=\"#0000FF\">";string OP="<font color=\"#FF00FF\">";string CL="</font>";string NL[]={ "<li class=\"li l1\">","<li class=\"li l2\">" };bool lo=1;string nl() {lo=!lo;return "</li>"+NL[lo];}bool r(char c,string s) {for (size_t i=0; i<s.size(); i++)if (c==s[i])return 0;return 0;}bool is(string s,int i) {return !(i<0||i>=s.size())&&((s[i]=='_')||isalpha(s[i]));}bool ic(string s,int i){return !(i<0||i>=s.size())&&(is(s,i)||('0'<=s[i]&&s[i]<='9'));}bool e(string a,int s,string b) {return !(a.size()-s<b.size())&&a.substr(s,b.size())==b;}string p(char c) {switch (c) {C '&':return "&";C '\"':return """;C '\'':return "'";C '<':return "<";C '>':return ">";}stringstream s;s<<c;return s.str();}string p(string s) {string ans="";for (size_t i=0; i<s.size(); i++) {ans+=p(s[i]);}return ans;}string h(string s) {int z=0;size_t i=0;string o ="<html><body><style type=\"text/css\">.l{list-style-type: decimal;margin-top:0;margin-bottom:0;} .li{display:list-item;word-wrap:B-word;} .l1{background-color:#FFFFFF;} .l2{background-color:#EEEEEE;} .cd{white-space:pre;}</style><code class=\"cd\"><ul class=\"l\">";o+=NL[1];for (; i<s.size();) {switch (z) {C 0:{Z('#',6)Z('"',3)Z('\'',2)V("//",4)V("/*",5)N()for (size_t j=0; j<201; j++)if (e(s,i,k[j])&&!ic(s,i+k[j].size())) {o+=OK+p(k[j])+CL;i+=k[j].size();B;}if (is(s,i)) {z=7;o+=p(s[i]);i++;if (i+1==s.size()||!ic(s,i+1)) {z=0;}B;}o+=p(s[i]);i++;B;}o+=p(s[i]);i++;B;C 2:Q('\'')C 3:Q('"')C 4:{N(z=0)o+=p(s[i]); i++;B;}C 5:{if (e(s,i,"*/")) {z=0;o+=p(s.substr(i,2))+CL;i+=2;B;}N()o+=p(s[i]);i++;B;}C 6:{if (s[i]=='\n') {int j=i-1;for (; j>=0&&r(s[j],"\n\t "); j--);if (j<0||s[j] != '\\') {z=0;o+=CL+nl();i++;B;}o+=nl();i++;B;}o+=p(s[i]);i++;B;}C 7:{if (i+1==s.size()||!ic(s,i+1)) {z=0;}o+=p(s[i]);i++;B;}}}o+="</ul></code>";return o;}int main() {ifstream i("input.c");ofstream o("output.html");string cCode((istreambuf_iterator<char>(i)),istreambuf_iterator<char>());o<<h(cCode)<<endl;}
```
Readable version:
```
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
//The 201 keywords from C and C++. Not sure if all of them are listed here!
const size_t NUMBER_OF_KEYWORDS = 201;
string keywords[] = { "__abstract", "__alignof", "_Alignas", "_alignof", "and",
"and_eq", "__asm", "_asm", "asm", "__assume", "_assume", "auto",
"__based", "_based", "bitand", "bitor", "bool", "_Bool", "__box",
"break", "__builtin_alignof", "_builtin_alignof", "__builtin_isfloat",
"case", "catch", "__cdecl", "_cdecl", "_Complex", "cdecl", "char",
"class", "__compileBreak", "_compileBreak", "compl", "const",
"const_cast", "continue", "__declspec", "_declspec", "default",
"__delegate", "delete", "do", "double", "dynamic_cast", "else", "enum",
"__event", "__except", "_except", "explicit", "__export", "_export",
"extern", "false", "__far", "_far", "far", "__far16", "_far16",
"__fastcall", "_fastcall", "__feacpBreak", "_feacpBreak", "__finally",
"_finally", "float", "for", "__forceinline", "_forceinline",
"__fortran", "_fortran", "fortran", "friend", "_Generic", "__gc",
"goto", "__hook", "__huge", "_huge", "huge", "_Imaginary",
"__identifier", "if", "__if_exists", "__if_not_exists", "__inline",
"_inline", "inline", "int", "__int128", "__int16", "_int16", "__int32",
"_int32", "__int64", "_int64", "__int8", "_int8", "__interface",
"__leave", "_leave", "long", "__multiple_inheritance",
"_multiple_inheritance", "mutable", "namespace", "__near", "_near",
"near", "new", "_Noreturn", "__nodefault", "__nogc", "__nontemporal",
"not", "not_eq", "__nounwind", "__novtordisp", "_novtordisp",
"operator", "or", "or_eq", "__pascal", "_pascal", "pascal", "__pin",
"__pragma", "_pragma", "private", "__probability", "__property",
"protected", "__ptr32", "_ptr32", "__ptr64", "_ptr64", "public",
"__raise", "register", "reinterpret_cast", "restrict", "__restrict",
"__resume", "return", "__sealed", "__serializable", "_serializable",
"short", "signed", "__single_inheritance", "_single_inheritance",
"sizeof", "static", "static_cast", "_Static_assert", "__stdcall",
"_stdcall", "struct", "__super", "switch", "__sysapi", "__syscall",
"_syscall", "template", "this", "__thiscall", "_thiscall", "throw",
"_Thread_local", "__transient", "_transient", "true", "__try", "_try",
"try", "__try_cast", "typedef", "typeid", "typename", "__typeof",
"__unaligned", "__unhook", "union", "unsigned", "using", "__uuidof",
"_uuidof", "__value", "virtual", "__virtual_inheritance",
"_virtual_inheritance", "void", "volatile", "__w64", "_w64",
"__wchar_t", "wchar_t", "while", "xor", "xor_eq" };
// Different states
const int NONE = 0;
const int WHITESPACE = 1;
const int CHAR_UNCLOSED = 2;
const int STRING_UNCLOSED = 3;
const int LINE_COMMENT_UNCLOSED = 4;
const int MULTILINE_COMMENT_UNCLOSED = 5;
const int PREPROCESSOR_UNCLOSED = 6;
const int IDENTIFIER = 7;
//Different elements
const string OPEN_STRING = "<font color=\"#00FF00\">";
const string CLOSE_STRING = "</font>";
const string OPEN_COMMENT = "<font color=\"#FFFF00\">";
const string CLOSE_COMMENT = "</font>";
const string OPEN_KEYWORD = "<font color=\"#0000FF\">";
const string CLOSE_KEYWORD = "</font>";
const string OPEN_PREPROCESSOR = "<font color=\"#FF00FF\">";
const string CLOSE_PREPROCESSOR = "</font>";
//Alternating background
const string NEW_LINE[] = { "<li class=\"li l1\">", "<li class=\"li l2\">" };
bool lineOdd = true;
string getNewLineHTML() {
lineOdd = !lineOdd;
return "</li>" + NEW_LINE[lineOdd];
}
//Check if the character is in the string chars
bool inRange(char c, string chars) {
for (size_t i = 0; i < chars.size(); i++)
if (c == chars[i])
return true;
return false;
}
//Check if the character is the start of an identifier
bool isIdentifierStart(string input, int i) {
if (i < 0 || i >= input.size())
return false;
return (input[i] == '_') || ('a' <= input[i] && input[i] <= 'z')
|| ('A' <= input[i] && input[i] <= 'Z');
}
//Check if the character is the continuation of an identifier
bool isIdentifierCont(string input, int i) {
if (i < 0 || i >= input.size())
return false;
return ('0' <= input[i] && input[i] <= '9') || isIdentifierStart(input, i);
}
//Check if a[start + i] == b[i], i<b.size()
bool eqRange(string a, int start, string b) {
if (a.size() - start < b.size())
return false;
return a.substr(start, b.size()) == b;
}
//Escape the sourcecode for HTML
string escape(char c) {
switch (c) {
case '&':
return "&";
case '\"':
return """;
case '\'':
return "'";
case '<':
return "<";
case '>':
return ">";
}
//Is there a better way to do this?
stringstream strm;
strm << c;
return strm.str();
}
string escape(string str) {
string ans = "";
for (size_t i = 0; i < str.size(); i++) {
ans += escape(str[i]);
}
return ans;
}
string highlight(string input) {
//The current state
int state = NONE;
//The current position
size_t i = 0;
//Styles
string output =
"<html><body><style type=\"text/css\">.l{list-style-type: decimal; margin-top: 0; margin-bottom: 0;} .li{ display: list-item; word-wrap: break-word;} .l1{background-color: #FFFFFF;} .l2{background-color: #EEEEEE;} .cd{white-space: pre;}</style><code class=\"cd\"><ul class=\"l\">";
output += NEW_LINE[1];
for (; i < input.size();) {
switch (state) {
case NONE: {
if (input[i] == '#') { //Start a preprocessor statement
state = PREPROCESSOR_UNCLOSED;
output += OPEN_PREPROCESSOR + escape(input[i]);
i++;
break;
}
if (input[i] == '"') { //Start a string
state = STRING_UNCLOSED;
output += OPEN_STRING + escape(input[i]);
i++;
break;
}
if (input[i] == '\'') { //Start a character
state = CHAR_UNCLOSED;
output += OPEN_STRING + escape(input[i]);
i++;
break;
}
if (eqRange(input, i, "//")) { //Start a single line comment
state = LINE_COMMENT_UNCLOSED;
output += OPEN_COMMENT + escape(input.substr(i, 2));
i += 2;
break;
}
if (eqRange(input, i, "/*")) { //Start a multi-line comment
state = MULTILINE_COMMENT_UNCLOSED;
output += OPEN_COMMENT + escape(input.substr(i, 2));
i += 2;
break;
}
if (input[i] == '\n') { //New lines are special!
output += getNewLineHTML();
i++;
break;
}
for (size_t j = 0; j < NUMBER_OF_KEYWORDS; j++) //Iterate through keywords
if (eqRange(input, i, keywords[j])
&& !isIdentifierCont(input, i + keywords[j].size())) { // The keyword can't be a prefix of an identifier, so test for that
output += OPEN_KEYWORD + escape(keywords[j])
+ CLOSE_KEYWORD;
i += keywords[j].size();
break;
}
//Treat identifiers separately because we need to separate identifiers from keywords.
if (isIdentifierStart(input, i)) {
state = IDENTIFIER;
output += escape(input[i]);
i++;
//If the next character is not a part of the identifier, go to the NONE state
if (i + 1 == input.size() || !isIdentifierCont(input, i + 1)) {
state = NONE;
}
break;
}
//Other characters
output += escape(input[i]);
i++;
break;
}
case CHAR_UNCLOSED: {
if (eqRange(input, i, "\\")) { //Treat escape sequences inside quotes
output += escape(input.substr(i, 2));
i += 2;
break;
}
if (input[i] == '\'') { //Close quote
state = NONE;
output += escape(input[i]) + CLOSE_STRING;
i++;
break;
}
output += escape(input[i]); //Other characters go into the literal
i++;
break;
}
case STRING_UNCLOSED: {
if (eqRange(input, i, "\\")) { //Treat escape sequences inside quotes
output += escape(input.substr(i, 2));
i += 2;
break;
}
if (input[i] == '"') { //Close quote
state = NONE;
output += escape(input[i]) + CLOSE_STRING;
i++;
break;
}
output += escape(input[i]); //Other characters go into the literal
i++;
break;
}
case LINE_COMMENT_UNCLOSED: {
if (input[i] == '\n') { //Close comment with new line
state = NONE;
output += CLOSE_COMMENT + getNewLineHTML();
i++;
break;
}
output += escape(input[i]); //Comment body
i++;
break;
}
case MULTILINE_COMMENT_UNCLOSED: {
if (eqRange(input, i, "*/")) { //Close multiline comment
state = NONE;
output += escape(input.substr(i, 2)) + CLOSE_COMMENT;
i += 2;
break;
}
if (input[i] == '\n') { //New lines are special!
output += getNewLineHTML();
i++;
break;
}
output += escape(input[i]); //Comment body
i++;
break;
}
case PREPROCESSOR_UNCLOSED: {
if (input[i] == '\n') { //Close preprocessor statement or go to next line
int j = i - 1;
for (; j >= 0 && inRange(input[j], "\n\t "); j--)
//Seek las non-whitespace character
;
if (j < 0 || input[j] != '\\') { //Check if the last non-whitespace character is a backslash
state = NONE; //... If it isn't, close the preprocessor statement
output += CLOSE_PREPROCESSOR + getNewLineHTML();
i++;
break;
}
output += getNewLineHTML(); //... If it is, we need to extend the preprocessor statement to the next line
i++;
break;
}
output += escape(input[i]);
i++;
break;
}
case IDENTIFIER: {
//If the next character is not a part of the identifier, go to the NONE state
if (i + 1 == input.size() || !isIdentifierCont(input, i + 1)) {
state = NONE;
}
output += escape(input[i]);
i++;
break;
}
}
}
output += "</ul></code>";
return output;
}
int main() {
ifstream input("input.c");
ofstream output("output.html");
std::string cCode((std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>());
output << highlight(cCode) << endl;
}
```
] |
[Question]
[
[Manchester coding](http://en.wikipedia.org/wiki/Manchester_code) is a telecom protocol used in radio communications that guarantees bit transitions at a regular interval so a receiver can recover the clock rate from the data itself. It doubles the bitrate, but is cheap and simple to implement. It is widely used by amateur radio operators.
The concept is very simple: at a hardware level, the clock and data lines are simply XORed together. In software, this is portrayed as converting an input stream of bits into a double-rate output stream, with each input '1' translated to a '01' and each input '0' translated to a '10'.
This is an easy problem, but open to a lot of implementations because of its bitstream nature. That is, the encoding is conceptually a bit-by-bit process instead of a byte-by-byte process. So we all agree on endianness, the least significant bits of the input become the least significant byte of the output.
Golfing time! Write a function that, given an arbitrary length array of bytes, returns an array of that data manchester encoded.
Input and output should be considered little-endian, least significant byte first, and least significant BIT first in the bit stream.
**ASCII bitstream drawing**:
```
bit # 5 4 3 2 1 0 5 4 3 2 1 0
IN ------- 1 0 1 0 1 1 ---> [manchester encoder] --- 01 10 01 10 01 01 ----> OUT
```
**Examples**:
```
Example 1 (hex):
LSB MSB <-- least sig BYTE first
IN : [0x10, 0x02]
OUT: [0xAA, 0xA9, 0xA6, 0xAA]
Example 1 (binary):
msb lsb msb lsb <-- translated hex, so msb first
BIN: [00010000, 00000010] <-- least sig NIBBLE...
BIN: [10101010, 10101001, 10100110, 10101010] <-- becomes least sig BYTE
LSB MSB
Example 2
IN : [0xFF, 0x00, 0xAA, 0x55]
OUT: [0x55, 0x55, 0xAA, 0xAA, 0x66, 0x66, 0x99, 0x99]
Example 3
IN : [0x12, 0x34, 0x56, 0x78, 0x90]
OUT: [0xA6, 0xA9, 0x9A, 0xA5, 0x96, 0x99, 0x6A, 0x95, 0xAA, 0x69]
Example 4
IN : [0x01, 0x02, 0x03, 0xF1, 0xF2, 0xF3]
OUT: [0xA9, 0xAA, 0xA6, 0xAA, 0xA5, 0xAA, 0xA9, 0x55, 0xA6, 0x55, 0xA5, 0x55]
```
**Rules**:
* Solution only requires algorithm to convert input to output.
* Acquiring input and printing output are NOT a required part of the solution, but may be included. You are encouraged to provide your test/print code if not included in your solution.
* Input is an array of 8-bit bytes (whatever that may mean in your language of choice), NOT a text string. You can use strings as the storage format if convenient in your language, but non-printable characters (i.e. 0xFF) must be supported. Input can also take a length if necessary.
* Memory for output must be allocated by your routine, not provided. **edit: unnecessary requirement**
* Output is also an array of 8-bit bytes, and a length if necessary.
* Must support at least 16KB input
* Performance must not be too horrible: < 10s for 16KB
* Least-significant byte first in memory.
**Side-channel challenge**:
* Challenge another user's answer by proving your code is faster, more memory efficient, or produces a smaller binary!
## **Get golfing! Shortest code wins!**
[Answer]
## GolfScript 28 characters
```
{2{base}:|~4|43691-~256|~\}%
```
Equivalent version without obfuscating optimization:
```
{2base 4base 43691-~256base~\}%
```
The code accept input as an array of integers, and return ditto.
For each number in the array the number is converted to base 2 array form, it is then converted back to a number as if it was base 4, this has the effect of spacing out the bits with a 0 in between each. 43691 is then subtracted from the number, and the result is binary inverted, this is equivalent to subtracting the number from 43690 (43690 = 0b1010101010101010). The number is then split into two parts by converting it to a base 256 array, the array is decomposed and the order of the two resulting numbers is inverted.
Example input:
```
[1 2 3 241 242 243]
```
Example output:
```
[169 170 166 170 165 170 169 85 166 85 165 85]
```
[Answer]
## c -- 224 characters
I believe that this is functional, including the allocation of memory requirement since dropped.
```
#include <stdlib.h>
int B(char i){int16_t n,o=0xFFFF;for(n=0;n<8;++n)o^=((((i>>n)&1)+1))<<(2*n);
return o;}char* M(char*i,int n){char*o=calloc(n+1,2),*p=o;do{int r=B(*i++);
*p++=0xFF&r;*p++=(0xFF00&r)>>8;}while(--n);return o;}
```
The working part of the code is a loop over the bits of each character, noting that ((bit+1) exclusive-or 3) is the output bit pair, and applying lots of shifting and masking logic to get everything to line up.
As is c's wont, it works on the data as characters. The test scaffold won't accept 0 bytes (because c treats them as string ending), but the working code has no such limitation.
It might be golfed little more by copy the byte conversion work inline.
Test run (with improved test scaffold):
```
$ gcc -g manchester_golf.c
$ ./a.out AB xyz U
'AB':
[ 0x41, 0x42 ]
[ 0xa9, 0x9a, 0xa6, 0x9a ]
'xyz':
[ 0x78, 0x79, 0x7a ]
[ 0x6a, 0x95, 0x69, 0x95, 0x66, 0x95 ]
'U':
[ 0x55 ]
[ 0x99, 0x99 ]
```
Commented, less machine dependent, and with test scaffold
```
/* manchester.c
*
* Manchester code a bit stream least significant bit first
*
* Manchester coding means that bits are expanded as {0,1} --> {10, 01}
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdint.h>
#include <string.h>
/* Caller must insure that out points to a valid, writable two byte
buffer filled with 0xFF */
int16_t manByte(char i){
int16_t n,o=0xFFFF;
printf("Manchester coding byte 0x%hx...\n",i);
for(n=0; n<CHAR_BIT; ++n)
o ^= (
(
(
(i>>n)&1) /* nth bit of i*/
+1) /* +1 */
) <<(2*n) /* shifted up 2*n bits */
;
printf("\tas 0x%hx\n",o);
return o;
}
char* manBuf(const char*i, int n){
char*o=calloc(n+1,2),*p=o;
do{
int16_t r=manByte(*i++);
*p++= 0xFF&r;
*p++=(0xFF00&r)>>8;
} while(--n);
return o;
}
void pbuf(FILE* f, char *buf, int len){
int i;
fprintf(f,"[");
for(i=0; i<len-1; i++)
fprintf(f," 0x%hhx,",buf[i]);
fprintf(f," 0x%hhx ]\n",buf[len-1]);
}
int main(int argc, char**argv){
int i;
for(i=1; i<argc; i++){
int l=strlen(argv[i]);
char *o=manBuf(argv[i],l);
printf("'%s':\n",argv[i]);
pbuf(stdout,argv[i],l);
pbuf(stdout,o,l*2);
free(o);
}
return 0;
}
```
[Answer]
# J, 36
```
,@:(3 :'#.2 8$,(,.~-.)4|.y#:~8#2'"0)
```
Outline of explanation (See [J Vocabulary](http://www.jsoftware.com/help/dictionary/vocabul.htm) for reference):
* `,@:(3 :'...'"0)` applies the ... to each input "byte" as y, resulting in two bytes (integers) each. The result is flattened by `,`.
* `y#:~8#2` is equivalent to `2 2 2 2 2 2 2 2 #: y`, or vector of the 8 least significant base-2 digits of y.
* `4|.` swaps the front and back 4 bits by rotating by 4 positions.
* `(,.~-.)` is equivalent to `3 :'(-. y) ,. y'`, or not of the argument 'stitched' to the argument (taking on shape 8 2).
* `#.2 8$,` flattens the result giving the bitstream, reshapes to 2 rows of 8, and converts from base 2.
Example usage (J, interactive):
```
,@:(3 :'#.2 8$,(,.~-.)4|.y#:~8#2'"0) 1 2 3 241 242 243
,@:(3 :'#.2 8$,(,.~-.)4|.y#:~8#2'"0) 1 2 3 241 242 243
169 170 166 170 165 170 169 85 166 85 165 85
```
Speed information (J, interactive):
```
manchester =: ,@:(3 :'#.2 8$,(,.~-.)4|.y#:~8#2'"0)
manchester =: ,@:(3 :'#.2 8$,(,.~-.)4|.y#:~8#2'"0)
data =: 256 | i. 16384
data =: 256 | i. 16384
100 (6!:2) 'manchester data'
100 (6!:2) 'manchester data'
0.243138
```
Mean time for 16kb is just under .25s, Intel Core Duo 1.83Ghz or similar.
[Answer]
## Haskell, 76 characters
```
import Bits
z a=170-sum[a.&.p*p|p<-[1,2,4,8]]
y a=[z a,z$a`div`16]
m=(>>=y)
```
Test runs:
```
> testAll
input [10, 02]
encoded [AA, A9, A6, AA]
pass
input [FF, 00, AA, 55]
encoded [55, 55, AA, AA, 66, 66, 99, 99]
pass
input [12, 34, 56, 78, 90]
encoded [A6, A9, 9A, A5, 96, 99, 6A, 95, AA, 69]
pass
input [01, 02, 03, F1, F2, F3]
encoded [A9, AA, A6, AA, A5, AA, A9, 55, A6, 55, A5, 55]
pass
```
Performance is well within spec. at 1MB in ~1.2s on my oldish laptop. It suffers because the input is convert to and from a list, rather then processed as a `ByteArray`.
```
> dd bs=1m count=1 if=/dev/urandom | time ./2040-Manchester > /dev/null
1+0 records in
1+0 records out
1048576 bytes transferred in 1.339130 secs (783028 bytes/sec)
1.20 real 1.18 user 0.01 sys
```
The source, [2040-Manchester.hs](https://bitbucket.org/mtnviewmark/haskell-playground/src/a662b5b357e7/golf/2040-Manchester.hs), includes the code, tests, and main function for a command line filter.
[Answer]
# OCaml + Batteries, 138 117 characters
```
let m s=Char.(String.(of_enum[?chr(170-Enum.sum[?d land
p*p|p<-List:[1;2;4;8]?])|c<-enum s/@code;d<-List:[c;c/16]?]))
```
**Tests:**
With
```
let hex s = String.(enum s/@(Char.code|-Printf.sprintf "%02x")|>List.of_enum|>join" ")
```
The results are:
```
m "\x12\x34\x56\x78\x90" |> hex;;
- : string = "a6 a9 9a a5 96 99 6a 95 aa 69"
m "\x10\x02" |> hex;;
- : string = "aa a9 a6 aa"
m "\xFF\x00\xAA\x55" |> hex;;
- : string = "55 55 aa aa 66 66 99 99"
m "\x12\x34\x56\x78\x90" |> hex;;
- : string = "a6 a9 9a a5 96 99 6a 95 aa 69"
m "\x01\x02\x03\xF1\xF2\xF3" |> hex;;
- : string = "a9 aa a6 aa a5 aa a9 55 a6 55 a5 55"
```
As a benchmark, with:
```
let benchmark n =
let t = Unix.gettimeofday() in
assert(2*n == String.(length (m (create n))));
Unix.gettimeofday() -. t
```
I get:
```
# benchmark 16_384;;
- : float = 0.115520954132080078
```
on my MacBook.
[Answer]
## Python, 87 chars
`M` is the function requested in the problem. It calls `N` for each nybble and splices everything back into a list.
```
N=lambda x:170-(x&1|x*2&4|x*4&16|x*8&64)
M=lambda A:sum([[N(a),N(a>>4)]for a in A],[])
print map(hex,M([0x10,0x02]))
print map(hex,M([0xff,0x00,0xaa,0x55]))
print map(hex,M([0x12, 0x34, 0x56, 0x78, 0x90]))
print map(hex,M([0x01, 0x02, 0x03, 0xF1, 0xF2, 0xF3]))
```
generates
```
['0xaa', '0xa9', '0xa6', '0xaa']
['0x55', '0x55', '0xaa', '0xaa', '0x66', '0x66', '0x99', '0x99']
['0xa6', '0xa9', '0x9a', '0xa5', '0x96', '0x99', '0x6a', '0x95', '0xaa', '0x69']
['0xa9', '0xaa', '0xa6', '0xaa', '0xa5', '0xaa', '0xa9', '0x55', '0xa6', '0x55', '0xa5', '0x55']
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 22 bytes
```
∊(⌽(2⍴256)⊤43690-4⊥⊤)¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FHl8ajnr0aRo96txiZmmk@6lpiYmxmaaBr8qhrKZCjeWjF/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NwVDBSMFYwcgESJsYAbExAA "APL (Dyalog Extended) – Try It Online")
Port of the GolfScript answer.
```
∊(⌽(2⍴256)⊤43690-4⊥⊤)¨ Monadic train:
⌽(2⍴256)⊤43690-4⊥⊤ Define a helper function taking an integer n:
⊤ Convert n to base 2. Monadic ⊤ is an Extended feature.
4⊥ Convert the result from base 4.
This puts the 1 digits of n
in odd indices of the intermediate result.
43960- Subtract from 43690.
(2⍴256)⊤ Convert to 2 base-256 digits, corresponding to
nibbles of n.
⌽ Reverse the order of these bytes.
( )¨ Call the helper function for each element of the input
∊ and flatten the results into a list.
```
[Answer]
# C, 164 bytes
Takes in a series of hex bytes and converts to manchester binary stream.
```
#include <stdio.h>
main(int c,char **v){int i,b,x,j=0;while(++j<c{sscanf(v[j],"%x",&b);x=b^0xff;for(i=9;--i;){printf("%d%d",x&1,b&1);x=x>>1;b=b>>1;}printf("\n");}}
```
---
```
#include <stdio.h>
main(int c,char **v){
int i,b,x,j=0;
while(++j<c){
sscanf(v[j],"%x",&b);
x=b^0xff;
for(i=9;--i;){
printf("%d%d",x&1,b&1);
x=x>>1;b=b>>1;}
printf("\n");}}
```
---
Test:
```
./a.out 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 10 20 30 40 50 60 70 80 90 a0 b0 c0 d0 e0 f0
```
Output:
```
1010101010101010
0110101010101010
1001101010101010
0101101010101010
1010011010101010
0110011010101010
1001011010101010
0101011010101010
1010100110101010
0110100110101010
1001100110101010
0101100110101010
1010010110101010
0110010110101010
1001010110101010
0101010110101010
1010101010101010
1010101001101010
1010101010011010
1010101001011010
1010101010100110
1010101001100110
1010101010010110
1010101001010110
1010101010101001
1010101001101001
1010101010011001
1010101001011001
1010101010100101
1010101001100101
1010101010010101
1010101001010101
```
---
16kb test data set generator:
test\_data.c:
```
#include <stdio.h>
void main()
{
int i=16*1024;
while(i--)
{
printf("0x%02x ", i&0xFF);
}
printf("\n");
}
```
---
```
cc test_data.c -o test_data
```
1.6G i5dual core time trial:
```
time ./a.out `./test_data` > test.out
real 0m0.096s
user 0m0.090s
sys 0m0.011s
```
[Answer]
# PHP, 156 bytes
```
function f($i){foreach($i as$n){$b=str_split(str_replace([0,1,2],[2,'01',10],
str_pad(decbin($n),8,0,0)),8);$o[]=bindec($b[1]);$o[]=bindec($b[0]);}return$o;}
```
Given the input `[0, 1, 2, 3, 4, 5]`, it returns:
```
[170, 170, 169, 170, 166, 170, 165, 170, 154, 170, 153, 170]
```
It encodes 16 KiB of data in 0.015 seconds and 1 MiB of data in about 0.9 seconds.
The ungolfed code, another implementation (longer and about twice slower) and the test cases can be found on [my code-golf solutions page](https://github.com/axiac/code-golf/blob/master/manchester-encode-a-data-stream.php) on Github.
] |
[Question]
[
In Haskell (and probably some other languages or something) `zip` is a function which takes two lists, and produces a list of tuples by pairing elements at the same index:
```
zip [1,2,3] [6,5,4] = [(1,6),(2,5),(3,4)]
```
If there are extra elements on one of the input lists those are trimmed off and don't appear in the result:
```
zip [1,2,3] [6,5,4,3,2,1] = [(1,6),(2,5),(3,4)]
```
A ragged list is like a list, but instead of just containing one type of thing it can contain two types of things, one being itself. For example:
```
[1,[2,3,[2]]]
```
This is a ragged list of integers. It contains integers and ragged lists of integers.
You can easily imagine zipping ragged lists which have a similar enough structure. For example:
```
zip [1,[2,3,9],3] [2,[3,4,5,6]] = [(1,2),[(2,3),(3,4),(9,5)]]
```
But things get a little tricky when you have to combine an element (e.g. an integer) with a structure (e.g. a ragged list of integers). To do this we are going to *distribute* the element across the structure. Some examples:
```
zip [1] [[2,3,[5,4]]] = [[(1,2),(1,3),[(1,5),(1,4)]]]
zip [1,2] [3,[4,5]] = [(1,3),[(2,4),(2,5)]]
zip [[2,3],4] [1,[6,7]] = [[(2,1),(3,1)],[(4,6),(4,7)]]
```
This whole behavior can be captured by this Haskell program:
```
data Ragged a
= Ragged (Either a [Ragged a])
zip' :: Ragged a -> Ragged b -> Ragged (a, b)
zip' (Ragged x) (Ragged y) = Ragged $ go x y
where
go :: Either a [Ragged a] -> Either b [Ragged b] -> Either (a,b) [Ragged (a,b)]
go (Left x) (Left y) =
Left (x, y)
go (Left x) (Right ys) =
Right $ (zip' $ Ragged $ Left x) <$> ys
go (Right xs) (Left y) =
Right $ (flip zip' $ Ragged $ Left y) <$> xs
go (Right xs) (Right ys) =
Right $ zipWith zip' xs ys
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVPLToQwFI1bvuIumtgmzEJHjZno7Ny5GhcuJixKKNCIQACd4q-4mY3xm_RP3BgvlJaxoCtuzz33nNMHr-8prx9Elu33b09NvLj8PPqOeMNhw5NERMA9gGuzoDeySUUFHLamHTAkRKKSzzJP4C4tdp73IstjWK2sBCzWpg4Pasp9CJlm0wFTzJYtG40JJAUoaNFrhwEEfqGD0GQmUucxwKGFw0MYrUNmW_0qMJr0VsRNH6Qvuhh9C6BfU-UjNiVvZJIiux7pGiFA-x2ScS9m5oqsccBKab6qZ5ytVJzJEmb1Wq2nZvX-Doda93gmWlPVyNHP4OPrkcscbyAqcKKsZD6wx7sig8j2d5ATHxwCcSmnvhN-GQTsH91ZnzNX5DyYODsjy8mIC1xgEH0A5n_4AQ)
## Task
Take as input two ragged lists of positive integers and output their `zip` as defined above. The output should be a ragged list of integer tuples. You may represent ragged lists and tuples in any reasonable way. The definition of ragged lists given here implies there is always a list at the top level, (e.g. `1` is not a ragged list of integers) so you may assume that this is the case for your inputs, but you may also support integers at the top level if its more convenient.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
[Answer]
# [Whython](https://github.com/pxeger/whython), 53 bytes
```
z=lambda a,b:map(z,[+a]*len(b)?a,[+b]*len(a)?b)?(a,b)
```
Takes two lists; returns `map` iterators instead of lists. [Attempt This Online!](https://ato.pxeger.com/run?1=TZFBboMwEEXVrU8xS7udLoBAm0hRVFU5AdlZVmQaoyARg8ColKt0k03VM7Wn6WBKxMqa_98fy9-f3-_nD3eu7PX61bn88fknHralvmQnDRqzzUXXfED5oNV9aSzPxE7TlE2TFjsSOHFiCv_erQ_79PD6ku5T2IJkwGWAIUYKQSYY4wojGgMlcLIkebhWExCijIiIMVEzMMqekZRVNxnD0SCV6FmU_prVaNDeBJ-8oRg7mRzoGUdXHcuidbwXGwZFDkVb2NZp-2Z4j-C6ujSjA41xXWOhZ2DK1iwUnx4LWWxD6IVgLK8abwfojxAKC7cmaEXdFNYtc3zgS16I_wbnb_gD)
### Explanation
Partly inspired by [97.100.97.109's Python answer](https://codegolf.stackexchange.com/a/258140/16766).
```
z=lambda a,b:
```
Define `z` as a function of two arguments `a` and `b`.
```
map(z,...,...)
```
Map `z` over corresponding items from the following two iterables:
```
[+a]*len(b)?a
```
If `a` is an integer and `b` is a list, convert `a` to a list by putting it into a single-element list and then repeating it a number of times equal to the length of `b`. Otherwise, the first expression errors, either because `+a` is an error when `a` is a list, or because `len(b)` is an error when `b` is an int. In this case, catch the error with `?` and use just `a` instead.
```
[+b]*len(a)?b
```
The second iterable is the same thing but for `b` instead of `a`.
If either or both of `a` and `b` are lists, the `map` will get two lists as arguments and will succeed. However, if they are both ints, the `map` will get two ints as arguments and will error. Thus:
```
?(a,b)
```
If the `map` errors, return a tuple containing `a` and `b` instead.
[Answer]
# [Haskell](https://www.haskell.org/), ~~100~~ 92 bytes
```
data R a=I a|L[R a]
I a%I b=I(a,b)
L x%L y=L$zipWith(%)x y
a%L y=L$map(a%)y
L x%b=L$map(%b)x
```
[Try it online!](https://tio.run/##VY47j4MwEIR7/4otgoSlTcErqbjeElWuuMJyYS5IoEsICkiBe/x2bmwQl3Ox2hl/s5ra9h/V5TLPZztYOpHNFdnvQmMzAmugqMxVaLmUoqAxKGjKi91n0701Qx0GcqRJ2NW92i60gZw8WK5GUMpxbtp@sO17ReFrfXuQlZS/kF/Dk1OPurpXgvB6byoagSxifPKLf7742gs0oYh0zAnrjFNj8K3DiGPJmIlkJzIvUmmM5zW@DWkkUs62hGdjUIyZbaw7bXDYpfSBjwvvyAhkgmmQS/kAlfLR5fY/Qlxt0wI83wR196YdaEcKRQMqtKKYFSXstgwbSv9BzoxgouDCLlwKy1V9BrdLxh9Z@cjzB1ioOv8C "Haskell – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 58 bytes
```
{$[&/i:`i=@:'(x;y);x,'y;|/i;x o'y;o'/#/:/|1(&/#:')\(x;y)]}
```
[Try it online!](https://ngn.codeberg.page/k#eJx1jDEKg0AQRfs9xYLBnQFh0Lga5hPIIeySQCphK9sVzd0zbhHSpPu89/izbqd7LUlf6XrTQBkrIzdhxS4J2S+2liCVqOwt1VJp4Eepnm/nJiWiltFQhzMoomdm5703io5BBnvELzwytgimacD4T9CIC/9cFW2ynB2vEUPxbpYwuQ9h+yjJ)
[Answer]
# JavaScript, 76 bytes
```
z=(a,b,f=c=>c.shift?.()??c)=>a<z|b<z?[]:a+b>z?[z(f(a),f(b)),...z(a,b)]:[a,b]
```
```
z=(a,b,f=c=>c.shift?.()??c)=>a<z|b<z?[]:a+b>z?[z(f(a),f(b)),...z(a,b)]:[a,b]
console.log(JSON.stringify(z([1,2,3], [6,5,4]))); // [(1,6),(2,5),(3,4)]
console.log(JSON.stringify(z([1,2,3], [6,5,4,3,2,1]))); // [(1,6),(2,5),(3,4)]
console.log(JSON.stringify(z([1,[2,3,9],3], [2,[3,4,5,6]]))); // [(1,2),[(2,3),(3,4),(9,5)]]
console.log(JSON.stringify(z([1], [[2,3,[5,4]]]))); // [[(1,2),(1,3),[(1,5),(1,4)]]]
console.log(JSON.stringify(z([1,2], [3,[4,5]]))); // [(1,3),[(2,4),(2,5)]]
console.log(JSON.stringify(z([[2,3],4], [1,[6,7]]))); // [[(2,1),(3,1)],[(4,6),(4,7)]]
```
Code with comment:
```
zip = (a, b) => {
if (isEmptyArray(a) || isEmptyArray(b)) return [];
if (isNonEmptyArray(a) || isNonEmptyArray(b)) {
return [zip(pop(a), pop(b)), ...zip(a, b)];
}
return [a, b];
};
isEmptyArray = a => a < zip;
isNonEmptyArray = a => a > zip;
pop = a => Array.isArray(a) ? a.shift() : a;
```
[Answer]
# [Python](https://www.python.org), ~~101~~ 91 bytes
*-10 bytes thanks to @DLosc*
```
g=lambda a,b:(a,b)*(a*0==0==b*0)or map(g,a*0!=0and a or[a]*len(b),b*0!=0and b or[b]*len(a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nZFLTsMwEIbF1qcYxMa2Bilt2gKVcgt2lhdj4qaREjtyXCTOwqYbuBOchknCa4eEZVnW9__jefj5dXjKxxjO55dTPlzfvpmm6qh3NQGh20s-lJaki6ri7XShYoKeBtkgw8uqoFADQUyGrO58kE6h-xbcJLhFIKWWFO8X6grujx5G6j08xNoDjUAuPnoEd8rQZp8ot6EBRgkyWznjKP6uzOj_lmaF6KACI4CXNCs0ayzxzmJpEfhuStzgFnfWKlw8q5mXaLa4-aEcuZ4imLP_F5-8lp2s8eM7vGFNWHHgcXIn0Abo9rN1SG3Ispn7-5zY1-d8AA)
Takes in input as a tuple.
# [Python](https://www.python.org), ~~97~~ 87 bytes
```
g=lambda a,b:(a,b)*(a*0==0==b*0)or map(g,a*(a*0!=0)or[a]*len(b),b*(b*0!=0)or[b]*len(a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nZFLasMwEIbpVqeYUgqSmEISJ2kS0C0CXQgtRo3iGGzZ2EogZ8kmm_ZO7Wk6tvvaFSoGIb75ZzSPy2tzToc6Xq8vx7R_WL095aakyu8ICP1G8qW0JD0xhs3riapbqKiROdLAb02PLDldhii9Qq-l_8Z-xKTUmP795v4OtocAHVUBnutdAOqAfH0KCP6YoEihpVTEHBi1kFjKv3Xi76qs_k9ZTogSDFgBfKSdop1hhmuHmUPgt81wjgtcOqdw1EwHnqFd4PyHcuSsj2DO-l-81zpWso-TL_GRfcKJPY-Ru4AiQrkZpE1bxCTzobfPaX0t5QM)
Same as above, except it also assumes that the integers are never zero.
[Answer]
# Rust, ~~294~~ ~~284~~ 271 bytes
```
#[derive(Clone)]
enum A{b(i32),c(Vec<A>)}fn f(x:(A,A))->A{A::c(match x{(A::c(i),A::c(j))=>i.into_iter().zip(j).map(f).collect(),(y,A::c(j))=>j.into_iter().map(|k|f((y.clone(),k))).collect(),(A::c(i),z)=>i.into_iter().map(|k|f((k,z.clone()))).collect(),w=>vec![w.0,w.1]})}
```
[Playground Link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4cfc3dc86ba617f46b3f54b5cf91f6b6)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes
```
⊞υθFυF⊙ι⁼κ⁺κ⟦⟧«≔⮌E²⊟ιηUMη⎇⁼λ⁺λ⟦⟧λE§η¬μλFE⌊EηLλEη§νλ«⊞ιλ⊞υλ»»⭆¹θ
```
[Try it online!](https://tio.run/##NVDLasMwEDzbX7HHNajQ9wOfTOmh0BTT9mZ8EIlqieqRSFZoKPl2daU4AmlmV7OjXa0l92vHdUp9DBIjg13T1t/OA8YGCnb2gIrByy5yHfCHQa9jwWFsaMFfXXUhqMnih9gLHwSu@BavSee2qEjBQJJnRdlnZwy3G5QMvoS33B9wsdWLrT7ZMiCSbbr51W7Eb654dzOactVku9JblqyUVSaawkn2Juw0S9Tl4SV3drGl@NRzVQZWOdOeo7hEx/pY917ZGT9nginbXOWvadqUhmG4ZEDhQDPejIS3Yz7vaN8zeCD@SPRppJUu9vof "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a pair list of ragged lists, and outputs using pair lists as tuples. Explanation:
```
⊞υθFυ
```
Start a breadth-first search with the pair of input lists.
```
F⊙ι⁼κ⁺κ⟦⟧«
```
If at least one corresponding entry from the pair is a list, then:
```
≔⮌E²⊟ιη
```
Extract the pair into a new list so that they can be replaced by their zipped entries.
```
UMη⎇⁼λ⁺λ⟦⟧λE§η¬μλ
```
If one of the entries is an integer then repeat it for the length of the other list.
```
FE⌊EηLλEη§νλ«
```
Loop over the transpose of the entries.
```
⊞ιλ⊞υλ
```
Push the new pairs back to the list that held the pair being processed but also to the list of lists to be processed so that they will themselves be zipped.
```
»»⭆¹θ
```
Pretty-print the final list because the default output format doesn't work well for ragged lists.
[Answer]
# JavaScript, 90 bytes
Expects input like `z(list1, list2)`. Supports integer inputs
```
z=(a,b)=>a>z?a.flatMap((x,i)=>b[i]?[z(x,b[i])]:b>z?[]:[z(x,b)]):b>z?b.map(x=>z(a,x)):[a,b]
```
**Ungolfed version**:
```
z=(a,b)=>{
if (a>z) return a.flatMap((x,i)=>b[i]?[z(x,b[i])]:b>z?[]:[z(x,b)])
if (b>z) return b.map(x=>z(a,x))
return [a,b]
}
```
Try it:
```
z=(a,b)=>a>z?a.flatMap((x,i)=>b[i]?[z(x,b[i])]:b>z?[]:[z(x,b)]):b>z?b.map(x=>z(a,x)):[a,b]
;[
[
[1, 2], '[1,2]'
],
[
[1, [2,3]], '[[1,2],[1,3]]'
],
[
[1, [2,[3]]], '[[1,2],[[1,3]]]'
],
[
[[2,3], 1], '[[2,1],[3,1]]'
],
[
[[1,2,3], [4,5,6]], '[[1,4],[2,5],[3,6]]'
],
[
[[1,2], [4,5,6]], '[[1,4],[2,5]]'
],
[
[[1,2,3], [4,5]], '[[1,4],[2,5]]'
],
[
[[1], [[2,3,[4,5]]]], '[[[1,2],[1,3],[[1,4],[1,5]]]]'
],
[
[[1,2], [3,[4,5]]], '[[1,3],[[2,4],[2,5]]]'
],
[
[[[1,2],3], [4,[5,6]]], '[[[1,4],[2,4]],[[3,5],[3,6]]]'
],
].forEach(([[a,b],c])=>console.log(JSON.stringify(z(a,b)), JSON.stringify(z(a,b)) === c))
```
## UPD 126 -> 98
Thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh) for the [tip](https://codegolf.stackexchange.com/questions/258133/zip-ragged-lists/258150?noredirect=1#comment570166_258150) to reduce bytes count
[Answer]
# [Elm](https://elm-lang.org/), ~~159~~ 155 bytes
*4 bytes saved thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)!*
```
type R a=I a|L(List(R a))
z v u=case(v,u)of
(I x,I y)->I(x,y)
(L x,L y)->L(List.map2 z x y)
(_,L y)->L(List.map(z v)y)
(L x,_)->L(List.map(\n->z n u)x)
```
Elm's pattern matching is not very golfy, and given the nature of the language, it is hard to squeeze out bytes in the case branches themselves. We define a recursive type `R` to encapsulate the ragged structures used in the challenge, since Elm does not natively support ragged lists. The function itself `z` is called on two such structures (of `Int`s), and returns a structure (of pairs of ints `(Int, Int)`). We must also fully qualify such structures to pass it to the program, as is the nature of Elm:
```
z
(L[I 1, L[I 2, I 3, I 9], I 3])
(L[I 2, L[I 3, I 4, I 5, I 6]])
```
corresponds to `zipRagged [1,[2,3,9],3] [2,[3,4,5,6]]`. In the testing harness below, I've defined a `parseCase` function which allows the function to be called as `z (parseCase "[1,[2,3,9],3]") (parseCase "[2,[3,4,5,6]]")`.
## Testing
You can try it [here](https://elm-lang.org/try) with the following test program:
```
import Html exposing (..)
-- begin code golf
type R a=I a|L(List(R a))
z v u=case(v,u)of
(I x,I y)->I(x,y)
(L x,L y)->L(List.map2 z x y)
(_,L y)->L(List.map(z v)y)
(L x,_)->L(List.map(\n->z n u)x)
-- end code golf
-- z : R Int -> R Int -> R (Int, Int)
-- display
showResult : R (Int, Int) -> String
showResult res =
case res of
I (x, y) -> "(" ++ (String.fromInt x) ++ "," ++ (String.fromInt y) ++ ")"
L list -> "[" ++ (List.map showResult list |> String.join ", ") ++ "]"
-- zip [1,[2,3,9],3] [2,[3,4,5,6]] = [(1,2),[(2,3),(3,4),(9,5)]]
parseCase : String -> R Int
parseCase str = str |> String.split "" |> parseCaseHelper
type alias ParseState =
{ depth : Int
, build : R Int
, number : String
, stack : List (R Int)
}
pushNumber : ParseState -> ParseState
pushNumber state =
if state.number == "" then state
else
let
parsedNumber = state.number
|> String.toInt
|> Maybe.withDefault -1
pushed = case state.build of
I x -> I parsedNumber
L v -> L (v ++ [I parsedNumber])
in
{ state
| number = ""
, build = pushed }
parseCaseHelper : List (String) -> R Int
parseCaseHelper =
List.foldl
(\el state ->
if el == "[" then
{ state
| stack = state.build :: state.stack
, build = L []
}
else if el == "," then
pushNumber state
else if el == "]" then
let nextState = pushNumber state
in
case nextState.stack of
head :: rest ->
{ nextState
| stack = rest
, build = case (nextState.build, head) of
(L b, L h) -> L (h ++ [nextState.build])
_ -> L [I -2] -- never occurs. "error"
}
_ -> state -- unbalanced. "error"
else if "0" <= el && el <= "9" then
{ state | number = state.number ++ el }
else state
)
{ depth = 0, build = L [], number = "", stack = [] }
>> .build
>> (\x -> case x of
L ((L inner) :: rest) -> L inner
_ -> x
)
cases =
[
( "[1,[2,3,9],3]"
, "[2,[3,4,5,6]]"
)
,
( "[1]"
, "[[2,3,[5,4]]]"
)
,
( "[1,2]"
, "[3,[4,5]]"
)
,
( "[[2,3],4]"
, "[1,[6,7]]"
)
]
overTuple : (a -> b -> c) -> (a, b) -> c
overTuple fn (left, right) = fn left right
main = cases
|> List.map
(Tuple.mapBoth parseCase parseCase >> overTuple z >> showResult)
|> List.map (\str -> Html.p [] [ text str ] )
|> Html.div []
```
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
*Inspired by <https://xkcd.com/835>*
In the midst of his mid-life crisis, Santa has impulsively purchased a Sports Sleigh™ for present delivery this year. The only problem is that this sleigh has a specially designed Infinite Present Trunk with rigid sides instead of a present bag with flexible ones. This means Santa must pack the presents optimally so there is as little empty space as possible.
## The Challenge
Write a program that takes as input a list of positive integers (representing the widths of the presents) and outputs a list of lists of positive integers (representing rows of presents) where each row follows these two rules:
* There are never *fewer* presents in each row than the one before it
* The *total width* of each row is the same as the width of the widest present
Your program must return any constant value if it is impossible to fulfill these rules. There may be multiple valid solutions; your program may output any of them.
## Examples
```
Input: [5, 1, 2, 6, 4, 3, 3]
Possible output: [[6], [5, 1], [2, 4], [3, 3]]
Visualization:
vvvvvv
+++++=
xx----
___ooo
Input: [9, 4, 2, 4, 5, 3]
Possible output: [[9], [4, 5], [3, 4, 2]]
Visualization:
+++++++++
vvvv=====
xxxoooo--
```
*I don't actually know if there exist any inputs with multiple possible outputs; it doesn't seem like it to me, but if you can prove there are or aren't please leave a comment! (I'm not counting trivial differences with different orderings of presents on a single row.)*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
æʒO¹àQ}éæ.Δ˜ÃQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8LJTk/wP7Ty8ILD28MrDy/TOTTk953Bz4P//0aY6CoY6CkY6CmY6CiY6CsZAFAsA "05AB1E – Try It Online")
Explanation:
```
æʒO¹àQ}éæ.Δ˜ÃQ
æ # powerset
ʒ } # filter:
O # sum
¹à # maximum of input
Q # are equal
é # sort by length
æ # powerset
.Δ # first where the following is true:
˜ # flatten
à # intersect with implicit input
Q # is equal to implicit input
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
```
ṖvøṖÞf'Ṡ?G=A;hÞṡ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwi4bmWdsO44bmWw55mJ+G5oD9HPUE7aMOe4bmhIiwiIiwiWzUsIDEsIDIsIDYsIDQsIDMsIDNdIl0=)
Extremely inefficient. Simply brute-forces it.
```
ṖvøṖÞf'Ṡ?G=A;hÞṡ
Ṗ # All permutations
vøṖ # For each, get a list of all ways to partition the list
Þf # Shallow flatten
' # Filter:
Ṡ # Sum each
?G=A # All are equal to the max of the input?
; # End filter
h # First item
Þṡ # Sort by length
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒPS⁼¥ƇṀŒPFṢ⁼ɗƇṢṪ
```
A monadic Link that accepts a list of integers and yields a list of lists of integers representing the present rows, or the integer `0` if not possible.
**[Try it online!](https://tio.run/##y0rNyan8///opIDgR417Di091v5wZwOQ5/Zw5yKgwMnpIIFFD3eu@v//f7SpjoKhjoKljoKxjoKJjoIZmA1kGAFRLAA "Jelly – Try It Online")**
### How?
```
ŒPS⁼¥ƇṀŒPFṢ⁼ɗƇṢṪ - Link: list of integers, Widths
ŒP - power-set (Widths) (results are ordered by length, ascending)
Ṁ - maximum (Widths)
Ƈ - filter (the sets) keeping those for which:
¥ - last two links as a dyad - f(set, max_width):
S - sum (set)
⁼ - (that) equals (max_width)?
ŒP - power-set (those)
Ṣ - sort (Widths)
Ƈ - filter (the sets of valid-sum sets) keeping those for which:
ɗ - last three links as a dyad - f(set_of_sets, sorted_widths):
F - flatten (the set_of_sets)
Ṣ - sort (that)
⁼ - (that) equals (sorted_widths)?
Ṫ - tail
```
[Answer]
# JavaScript (ES2020), 140 bytes
Returns `0` if there's no solution.
```
f=(a,m=Math.max(...a),t,o=[],...p)=>a.some((v,i)=>f(a.filter(_=>i--),m,~~t+v,o,...p,v),t^m|p[o[0]?.length]||(o=[p,...o],p=t=[]))?O:a+p?0:O=o
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBdisIwEH73FHmc4DRo3YoKaU-weIDSlaiJFppOsLHsQ_EEe4N98cE9lLfZWPVFhGHg4_sb5vdS01afz39Hb6LZ9cdIUGjlp_J7YdU3CCEUR48k8wIDcFymSjRkNUCLZUAGlDBl5fUBVjIto4ijxdPJD1uk3oFtCPiyncspHxWZqHS98_ui6yCEupuECnTShwbOs-VCDV02WiwlPW5ab6huqNKioh0YyBNkY2QxsimyD2STMME4eFHNezLud_JekvR8HJh70_ML_w)
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input array
m = Math.max(...a), // m = highest value in a[]
t, // t = sum of the current sub-array
o = [], // o[] = array of sub-arrays
...p // p[] = current sub-array
) => //
a.some((v, i) => // for each value v at index i in a[]:
f( // do a recursive call:
a.filter(_ => i--), // remove the i-th element from a[]
m, // pass m unchanged
~~t + v, // add v to t
o, // pass o[] unchanged
...p, v // append v to p[]
), // end of recursive call
// loop initialization:
t ^ m | // do nothing if t is not equal to m
p[o[0]?.length] || // or p is longer than o[0] (which is either the
( // previous sub-array or still undefined)
o = [p, ...o], // otherwise, insert p[] at the beginning of o[]
p = t = [] // and start with p[] empty and t zero'ish
) //
) ? // end of some(); if truthy:
O // return the solution O[]
: // else:
a + p ? // if either a[] or p[] is non-empty:
0 // incomplete or invalid solution: do nothing
: // else:
O = o // save the solution in O[]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Returns `undefined` if there is no result.
```
n
à f@̶XxÃà æ@eXÔc n
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bgrgIGZAzLZYeMPgIOZAZVjUYyBu&input=WzksIDQsIDIsIDQsIDUsIDNdCi1R)
```
n\nà f@̶XxÃà æ@eXÔc n :Implicit input of array U
n :Sort
\n :Reassign to U
à :Combinations
f :Filter by
@ :Passing each X through the following function
Ì : Last element of U
¶ : Is equal to
Xx : X reduced by addition
à :End filter
à :Combinations (in descending order of length)
æ :First element to return true
@ :When passed through the following function as X
e : U is equal to
XÔ : Reverse X (mutates the original)
c : Flatten
n : Sort
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18 bytes
```
MfqSsTSGyHlDhgQgeS
```
[Try it online!](https://tio.run/##K6gsyfj/3zetMLg4JNi90iPHJSM9MD01@P//aEsdBRMdBSMwaaqjYKyjYAYkYwE "Pyth – Try It Online")
Returns an index error when there is no solution.
Somehow only used alphabetical characters as well, which is neat.
### Explanation
Power set is the poor man's partition. This solution is brute force, but a rather elegant one, I think. First we take the power set of the input and filter for elements whose sum is equal to the desired width. This means we now have a list of all possible rows (often with duplicates). Then we take the power set of the rows, and filter for elements which use the exact same elements as the input. This will give us all sets of rows that are valid solutions. From here it's simple, just pick any set and sort the rows by number of elements. The beauty comes from the fact that both of these steps look the same if you squint, and so by being clever we can write a single "power set and filter" function and just apply it twice.
```
MfqSsTSGyHlDhgQgeSQQ # implicitly add QQ to the end
# implicitly assign Q = eval(input())
M # define g(G, H):
f yH # filter powerset(H) on lambda T
qSsTSG # when H is a list and G is a number, this will check if T sums to G
# but when H is a list of lists and G is a list, this will check if T and G use the same elements
lD # sort using length as the key
h # the first element of
gQ # power set filter Q,
geSQQ # power set filter max(Q), Q
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 58 bytes
```
W⁻E⊟ΦEXLθLθΦEθΦθ⁼ν﹪÷κXLθπLθμ⬤κ⁼Σμ⌈θ⁺⟦Lκ⟧κυF№ι⌊ι⊞υ⌊ι⭆¹Eυ✂λ¹
```
[Try it online!](https://tio.run/##ZU/LasMwELz3K/a4AvUQSA8lp9I2EKjB4KPxQThqvHgt@SEl/XtlFdzQ0MOyM8PMrNR2Zm694ZQuHbEFLMjFBQszYulH3BMHO6/0IujLulPocFIa7lDwH990Z4I@p2h4Qaeh8MfIHg8ufNCZjhZ7Df8qR/XQqzIdZN6Ys39tq@KAWS3MDw2Cf50ly8vrNd6rRkOf5agUfPsZ8N1HF5AkSO4WJIlBGZcO44O4eypnEmsVZJ3ypzb52phtFVNrkTVs8tFdSnX9qmGr4aVp0vOZrw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Lots and lots of brute force (takes minutes on the examples) so link only has three presents.
61 bytes for a slightly less inefficient version that can just about complete the examples on TIO:
```
≔E⊟ΦEXLθLθΦEθΦθ⁼μ﹪÷ιXLθξLθλ⬤ι⁼Σλ⌈θ⁺⟦Lι⟧ιηW⁻ηυF№ι⌊ι⊞υ⌊ι⭆¹Eυ✂λ¹
```
[Try it online!](https://tio.run/##ZY8xa8MwEIX3/IobT6AOadqheApNC4UYDB6NB@G41sFZsi0pyb9XpeCGhg46vXf67nHqtFo6qzjGvXM0GCzVhJWd8JPY98tqL0kdezN4jbOQcJdJ/@Hmu0vqYw6KHY4SSnsKbPHL@AOd6dQjSfgXeRUPuSJbTmfPnPk1rQ4j5m6prjQm/UtWHBw26ziJVgLlthbF5qKJe8CSTEK0hCAEfNsF8N0G43N2erqFpREBVXAaw0Oz2FQLJbT26RryR7d5gyljNVPXI0vY5kWKGJvmTcKLhOdbfZWwa9v4dOYf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Calculates all `nⁿ` permutations of `n` presents in `n` rows, filters for valid answers, picks one, then sorts it. (But unlike the first version, it doesn't perform the calculation each pass of the sorting loop.)
65 bytes for a slightly less inefficient version:
```
≔÷Σθ⌈θη≔E⊟ΦEXηLθΦEθΦθ⁼μ﹪÷ιXηξηλ⬤ι⁼Σλ⌈θ⁺⟦Lι⟧ιηW⁻ηυF№ι⌊ι⊞υ⌊ι⭆¹Eυ✂λ¹
```
[Try it online!](https://tio.run/##VU/BboMwDL33K3x0pOzQdTtMnKp1kyYVCYkj4oBoRiwZAoS0/XvmUFa1h8R@8Xt@L7WtxtpVPM9776np8KebDnSmk8E8tDgoDWl1pXbpBViVbFZmWvWYuR6/iSczrvAindVwNF0z2ZvkYT7ckXRfQ6jYYysO7hTYPViThvuq681WxcJy9sxxvqpjSH4OuTAzDh6LNQapUgP9x79YYgOYUicUMQhKwa8bAT9d6Ka4W0bLMpEoyIK3GJ4ek002klDzSUoTP7aNCfpIy5lqg6xhG4Mk81wUHxreNLwu97uGXVnOL2f@Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Still exponential time, but since we know the width of each row then we can calculate the number of rows, and take the `n`th power of that instead.
71 bytes for a version that's less inefficient for a large enough number of rows:
```
≔⟦⟦⟧⟧ηFθ≔ΣEηE⊞OκυΦEκ⎇⁼νπ⁺ξ⟦ι⟧ξξη≔E⊟Φη⬤ι⁼Σλ⌈θ⁺⟦Lι⟧ιηW⁻ηυF№ι⌊ι⊞υ⌊ι⭆¹Eυ✂λ¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVC7TsQwEBTtfcXqqrXkK8JLoFQnBNWdOCl0losQ5WILXx5-QPgWmitA8EvwNaydUCCtvPbueGZ2374qVdqqK83x-BH8fnX1c7JZO6ebFoWQkoNi-WLfWcCBwdwowgG3ZY-KQ0y74NR9X9vSdxafOATG4U4bX9uEospDbdvSvuLtEErjsOXQE2ZngsORg9CSXiObjpii5qyVBLoeZ0KSXBuDmsPMFb0YFo2M-kD3gU0UiVxs6rbxCjWjQfQf84vSpgbc6pYgKvplkCa86ULrIze1Ehl9YRDHw_CvmC92VhO08JSaaDGbVkGwwuiqRsMhi0byd_dYuXm1n2K5ejZL-Q1CXHOguORwweE8xRmH0xSZlBP-Fw) Link is to verbose version of code. Explanation: Uses dynamic programming to generate integer partitions directly instead of filtering permutations, so `O(A000110(n))` instead of `O(kⁿ)`. This means that it can handle the example in @JonathanAllan's comment.
72 bytes for a version that's somewhat efficient for a small enough number of rows:
```
≔⟦E÷Σθ⌈θυ⟧ηFθ≔ΣEηΦEκEκ⎇⁼νπ⁺ξ⟦ι⟧ӧμν⌈θη≔E⊟η⁺⟦Lι⟧ιηW⁻ηυF№ι⌊ι⊞υ⌊ι⭆¹Eυ✂λ¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLSwMxEMZrf8XQ0wTSw_pC6an4omBlod6WPcRt2gym2TaPuv4WLz0o-pf015ik7aEwMJnhe00-fholbNMKvd1-BT8fXP2d1CPnaGGwmogVjo2_pQ3NJE7DEteMw0R0tMzvOARWc1Bs2Ju3FuIK9twETnTF4Z60lzZPr4md27O0Rth3vFsHoR0aDquoVurgsONQUR2njiWHp9bjg5UiaSTVkR-bmexwycGw4zgsE1KafYpkVrYxxUG7epRm4RVSik0H9JsiLQEnZCJEpaMY5Htu2mA8UjQhk00ihUEZnMJwtBz2SksROvWxLZJtsTs1wqaaGomaQ5HyDT_dS-P2f_1d9Qcb3a9_oaquOcS65HDB4TzXGYfTXEVd7_D_) Link is to verbose version of code. Explanation: Based on the third version but using dynamic programming to to generate only matching integer partitions, but still generates all permutations of all integers in all rows.
85 bytes for an efficient version:
```
≔⟦υ⟧ηFθ≔ΣEη⁺ΦEκEκ⎇⁼νπ⁺ξ⟦ι⟧ξ⬤쬛Σξ⌈θ…⟦⁺κ⟦⟦ι⟧⟧⟧‹Lκ÷Σθ⌈θη≔E⊟η⁺⟦Lι⟧ιηW⁻ηυF№ι⌊ι⊞υ⌊ι⭆¹Eυ✂λ¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZE7TgMxEIZFm1OMUo0lpwgvgVJF4SGkBK0UutUWy-LEVhxv1o-wuQF3oEkBgivBaRg7S4GQRn6Mfn__zPj1s5KlrepS7_fvwS8GF99HL2Pn1NJgHgoOko16i9oCNgy6_DyscVZuUHLIdHB4o7QXNqVWHLrtQVhT2h1eN6HUDg2HDev0LYdcFXRrGaN1rDWuOdzXHm-tKCMqOrQsslq1pnPDWJJOdpUWE1lvME8k8skJVTAqdCqcw6kwSy9xRdo746_UVj2JRGv-0SIvNtc1FcvOCCx_q8w7lopw9at-lkoLwJkyJKEBBMYgjWdSB-NRkYsyyYWeMMiCkxj-JEe9zCqSzj1ty2g7PAyNZHOtKoGawzDWN3pzj5XrvuUj7w-2ul98UceXHCjOOZxxOE1xwuE4xbAoDvof) Link is to verbose version of code. Explanation: Combination of the previous two so it avoids considering multiple empty rows for the same integer.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 167 bytes
```
f=(x,i=z=[],...y)=>z=x.map((v,j)=>f(j=x.filter(_=>j--),[...i,v],...y)|f(j,[v],i,...y),L=[i,...y])+x?z:L.some((e,j)=>e.length<(y[j-1]||i).length|eval(e.join`+`)!=i)?z:L
```
[Try it online!](https://tio.run/##bYxdDoIwEITfPUV924ZtE/An0Vi9ADdoiBAt2KZSI4QA4e5YwCdjstnszH4zJmuy6vbWr5qV7q7GMRfQoha9kAlyzjsqzr1o@TN7ATRovMzBeCPXtlZvuIqzYYyi9KzG5psZPIPSK71ojIVczoQG7aU/xrxyTwWg5kbFrSqL@nGCThoWJsOg6dcaVJNZUNw4XaZBStdC0yk/3lxZOeuTroAc5A5JiCRCskeyRbLxk1C6@qEO8zOa9@4/srRsp8/4AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 43 bytes
```
@(DNa=DNFL_FI(Ma=$+_FIaCB_MF,#a)CB_MF,#a)|0
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJAKEROYT1ETkZMX0ZJKE1hPSQrX0ZJYUNCX01GLCNhKUNCX01GLCNhKXwwIiwiIiwiWzk7NTsxXSBbNTsxOzI7Njs0OzM7M10gIFs5OzQ7Mjs0OzU7M10gIiwiLXggLXAiXQ==)
Pip doesn't have a command for powersets (that I could find), so I had to construct them manually. Explanation:
```
Ma=$+_FIaCB_MF,#a
```
All combinations of the input list where the sum of the combination equals the input max i.e. all possible row combinations
```
DNa=DNFL_FI( )CB_MF,#a
```
All valid combinations of all possible row combinations, determined by comparing the sorted flattened combination with the sorted input
```
@()|0
```
Outputs the first valid combination, or `0` if no combination is found. No reordering is required, as the combination operator `aCBb` in pip automatically orders lists by ascending length.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
àÅœéæʒ˜œ€Qà
```
Extremely slow. Will output all possible results (replace filter `ʒ` with find\_first `.Δ` to only output one - although that will still timeout for the second test case).
[Try it online.](https://tio.run/##yy9OTMpM/f//8ILDrUcnH155eNmpSafnHJ38qGlN4OEF//9Hm@ooGOooGOkomOkomOgoGANRLAA)
**Explanation:**
```
à # Get the maximum of the (implicit) input-list
Ŝ # Get lists of all positive integers that sum to this maximum
é # Sort those lists by length (shortest to longest)
æ # Get the powerset of this list of lists
ʒ # Filter this list of lists of rows by:
˜ # Flatten the list of rows to a single list
œ # Get all permutations of this flattened list
€Q # Check for each permutation whether it's equal to the (implicit) input
à # Check if any is truthy
# (after which the filtered list is output implicitly)
```
] |
[Question]
[
You have a line with two endpoints `a` and `b` (`0 ≤ a < b`) on a 1D space. When `a` or `b` has a fractional value, you want to round it to an integer.
One way to do this is to round `a` and `b` each to its nearest integer, but this has a problem that the length of the rounded range (`L`) can vary while `b - a` stays the same. For example,
```
b - a = 1.4
(a, b) = (1, 2.4) -> (1, 2), L = 1
(1.2, 2.6) -> (1, 3), L = 2
```
We want to find a way to round `(a, b)` so that `L` always has the same value `⌊b - a⌋` while the rounded pair `(ra, rb)` is closest to `(a, b)`.
With `(a, b) = (1.2, 2.6)`, we can consider two candidates of `(ra, rb)` with `L = ⌊2.6 - 1.2⌋ = 1`. One is `(1, 2)` and the other is `(2, 3)`. `(1, 2)`'s overlapping range with `(a, b) = (1.2, 2.6)` is `(1.2, 2)`, while `(2, 3)` overlaps at `(2, 2.6)`. `(1, 2)` has a larger overlapping range (`(1.2, 2)` vs `(2, 2.6)`), so in this case we choose `(1, 2)`.
Sometimes there are two options with the same overlapping length. For example, `(0.5, 1.5) -> (0, 1), (1, 2)`. In such cases, either could be, but one should be, chosen.
### Examples
```
0 ≤ a < b
b - a ≥ 1
(a, b) -> (ra, rb)
(1, 2) -> (1, 2)
(1, 3.9) -> (1, 3)
(1.1, 4) -> (2, 4)
(1.2, 4.6) -> (1, 4)
(1.3, 4.7) -> (1, 4) or (2, 5)
(1.4, 4.8) -> (2, 5)
(0.5, 10.5) -> (0, 10) or (1, 11)
```
[Answer]
# [Python](https://www.python.org), 44 bytes
```
lambda a,b:(m:=(a+b+1-(l:=int(b-a)))//2,m+l)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY5NCsIwEIX3PcXgasamVav4U6gncZNii4E0CbUKLryFOzeC6J28jR0jWt1kHt97eTPnuzs0G2su1zJb3XZNGc0fQssqX0uQIk-xSjOUYR6OItRppkyDeSSJaDBIRBVqev85lrYGDcqAdYXBIcV1IddamWKLlAaghIUMdLx1WjXYg2gJPQqAof3AtoKhEn3mlXRY7KUWyIBaw9W8X4kS-4r8-9r4PuLyOOFIQELc7lXwGvHiF8WtGHuUsGKUcG76l2O3A31yzMlZJ8l3f4smbM877f64Jw)
## Old [Python](https://www.python.org), 50 bytes
```
lambda a,b:(m:=(a+b+~(l:=int(b-a))%2)//2-l//2,m+l)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY5BbsIwEEX3OcUICWmGOKEY1NJI4STdOCJRLU1sKwQkFu0puusGqaJ34jbNYETTbsaj97___M_vcOxfvTt9NeXLed832fqi2bTV1oBRVYFtUaJJq_QduSit67HKDNFU03yuMx6GalOm28-3xnfAYB34UDt8oLyrzZatq3dIRQJWeSiB811g2-MEsg1MKAGB_g6HCIFWzYS3JmB9MKxQAA1C6KSGVQ3OLMV5vXgrcbp84EKBJkmPW3J98ue_KB-WZURaNkFafI__fKKOYHQuxfk0ckrv36CVyOtReiz3Aw)
## Old [Python](https://www.python.org), 56 bytes
```
lambda a,b:((m:=(a+b+~(l:=int(b-a))%2)//2)-l//2,m--l//2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY5BasMwEEX3PsUQKMwkktPIIXEN7kmykYlNBLIkHLfQRXuK7roJlOZOuU09VkjdbGaG97--_tc5vPUH707fTbn7eekbmV9yq9tqr0GLqkBsixL1olp8oC1K43qspCZ6ULRcKpJ2mKKV46br-_fGd2DBOPChdvhIaVfrvTWuPiIVCRjhoQSbHoM1Pc5APsOMEmDob3CIYGjEnHmrA9av2gpkQIMQOu5iRINzQ3GOP15LnC6fuBKgiNPjlYwrffqP0uHIIlJ8MVLs29z5WJ3A6MzYuZ04ufdf0JrlfJIey_0C)
## How?
The basic idea is: If the required length `l` is even round the midpoint and move `l/2` in both directions. If `l` is odd round the midpoint to the nearest half integer instead.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
O>I`αï©-2÷D®+‚
```
-2 bytes porting [*@loopyWalt*'s Python answer](https://codegolf.stackexchange.com/a/246945/52210); make sure to upvote him as well!
[Try it online](https://tio.run/##ASgA1/9vc2FiaWX//08@SWDOscOvwqktMsO3RMKuK@KAmv//WzEuMiwyLjZd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/f7vKhHMbD68/tFLX6PB2l0PrtB81zPqv8z862lDHKFYHROpZgmg9Qx1jMG0EFDEDs4yBLHMwywTIsgCyDPRMdQz1TGNjAQ).
**Explanation:**
```
O # Sum the (implicit) input-pair
> # Increase it by 1
I # Push the input-pair again
` # Pop and push both values separated to the stack
α # Take the absolute difference between both
ï # Cast it to an integer to floor it
© # Sort this value in variable `®` (without popping)
- # Subtract it from the earlier sum+1
2÷ # Integer-divide it by 2
D # Duplicate this
®+ # Add `®` to the copy
‚ # Pair the two values together
# (after which it is output implicitly as result)
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 44 bytes
```
[ 2dup - ⌊ -rot 1 + + over - 2 /i tuck + ]
```
[Try it online!](https://tio.run/##VdBLCsIwEAbgfU/xIxSUWDX1rQcQN27ElbooMbGlmpQ83IgXEE/pRWq0iDYDw8zHvxgiEmaVLjfr5WoxQ2KMYgY515KfcE5s@mkdJzOmDhwmdUKcOITS3m0mj5gHwTWAf1fEoLh9ZzLt0t4f9EEJfdMvMfokSFzXcaX9uk4qHfwr7ZHhex9WeAvKLeKDKxDh@bgj0sr6A4gvdeHaa4xuButY7mnvw41m6NoIXWsnGyh0Jq3AHkydC2V49RkRT1havgA "Factor – Try It Online")
Takes input as `b a`. Port of loopy walt's [Python answer](https://codegolf.stackexchange.com/a/246945/97916).
[Answer]
# [Desmos](https://desmos.com/calculator), 62 bytes
```
f(a,b)=(A,\floor(b-a)+A)+\{\ceil(b)-b<a-A,0\}(1,1)
A=floor(a)
```
Takes input as function parameters and returns a point `(ra,rb)`
[Try it on Desmos!](https://www.desmos.com/calculator/vc9xlo3gjp)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
After messing around trying to find an arithmetic solution I came up with the following:
```
Nθ≔E⁺N⟦±θ⊕θ⟧⌊ιηI÷⟦↨η±¹Ση⟧²
```
[Try it online!](https://tio.run/##TYy7CoMwFIZ3nyLjOZAKcSo49YLgUBE6ikOqBxOI0ebi66cpdOj2Xz6@SUk3bdKk1No9hi6uL3Lwxrq4eK8XCw@5Q2@ih/8fORs6WmSgjHLW2snRSjbQnPuYl8ZsmwONOars6p22AW7Sh6wJd33omWC4Sk@gOPuZxJd@xhUUjpxViFinJEpRVOU5nQ7zAQ "Charcoal – Try It Online") Link is to verbose version of code.
Rather than trying to be clever with vectorised arithmetic, I rewrote it to use variables instead. It still came out at 26 bytes:
```
NθNη≔⌊⁻ηθζ≧⁺⊕θηI÷⟦⁻ηθ⁺ηζ⟧²
```
[Try it online!](https://tio.run/##TYw9C4MwFEV3f0XG9yAVdCo4lZZCBkW6lg6pBhOIT82Hg38@Vbq43cO993Raum6SNiVBcwxNHL/KwYJVdma98817MxA87TQ5qA1FD5qzBZGzba9rOf8XLzPoAK2NnjNBnVOjoqD63cnZ4WmdoQB36QMICg@zml7B@yTk7DgfecMPZyUiVikVeZGV@TVdVvsD "Charcoal – Try It Online") Link is to verbose version of code.
A direct port of @loopywalt's Python answer turns out to also be 26 bytes:
```
NθNη≔⌊⁻ηθζ≔÷⁻⊕⁺ηθζ²εI⟦ε⁺εζ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5DsWF2em52m45eTnF2n4ZuaVFmtk6CgUamrqKFQhpD3zSlwyyzJTUqFKPPOSi1JzU/NKUlM0AnJQ9OgoGAFxKlBvQFFmXomGc2JxiUZ0qo4CWF0qSEmspqb1//@GeoZcRnoW/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Note that because it does the integer division by 2 earlier it doesn't need to explicitly close the output list, saving a byte.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 34 bytes
```
f(a,b)=[m=(a+b+1-l=(b-a)\1)\2,m+l]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc5BCsIwEAXQqwxZJWQSTFq1LupF2iBToVJISyjtwrO46UY8k7cxMbqZ_wYG_jxegebhcgvb9lyXXlVv1nPCTtTNWHOSnTTK17xTJFojWouj9O53uVII_s4J1BnCPExLJEsLgyt5z3sEEgKhaQyCdRExC336SkeXWTZKH7KL5GN2mVwl7_QewcTpnMjl_3c_)
A port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/246945/97916).
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 48 bytes
```
f(a,b)=[a,b]\1+if(a%1>b%1,[1,0],[t=a%1+b%1>1,t])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc7NCoMwDADgVwmCYDEWq25zB_siXRlx4BCKFKmHPcsuXsaeaW-zdM5L8iWQn-fb0zxe735dX0sYivZTDhlhLzrD0V5UPnKdKt2nCo3C0qIJHTdybmiFwYr_3ELeu0dGUGjw8zgFZhKLBG7kXDYgkBAIhrdAZRmca3n-SbKbTRVLHjfX0afNTXQbXcoDguJo9-P7818)
] |
[Question]
[
The Caesar cipher is a simple and famous cipher, where the letters of the alphabet are rotated by some secret amount. For example, if our secret rotation is `3`, we would replace `a` with `d`, `b` with `e`, `w` with `z`, `x` with `a` and so on.
Here is an example (rotation amount: 10):
```
Robo sc kx ohkwzvo
```
This cipher is very weak, because short common English words like "I", "a", "is", "an", "if", etc. are easy to detect. Your task is to crack a Caesar cipher, that is, recover the rotation amount from the ciphertext. As additional input, you are given a list (or set) of words, which the plaintext can contain. It is guaranteed that there is only one answer.
# Examples
```
"Ifmmp Xpsme!", ["world", "banana", "hello"]
-> 1
"Nc cd, Kadcn?", ["cogito", "et", "ergo", "tu", "sum", "brute"]
-> 9
"boring", ["boring"]
-> 0
"bccb foo", ["abba", "gpp", "cddc"]
-> 25
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", ["zabcdefghijklmnopqrstuvwxy"]
-> 1
"bcsbdbebcsb", ["abracadabra", "za", "aq"]
-> 1
```
# IO rules
The ciphertext can contain any printable ascii characters. The dictionary (list of words) contains strings made of lowercase letters (a-z). Words are separated by non-letters. Only letters are rotated (punctuation is ignored). You will output an integer in the range `[0,25]`
[Answer]
# [Ruby](https://www.ruby-lang.org/), 66 bytes
Curried function that takes the dictionary first and the ciphertext second.
```
->w{f=->s{s=~/^([^a-z]|#{w*?|})*$/i?0:1+f[s.tr'a-zA-Z','ZA-Y'*2]}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGidNulpSVpuhY3nXTtyqvTbHXtiquLbev04zSi4xJ1q2JrlKvLtexrajW1VPQz7Q2sDLXToov1SorUgZKOulHqOupRjrqR6lpGsbW1UJOOFpSWFCukR0crlecX5aQo6SgoJSXmASGIlZGak5OvFBsbreSZlptboBBRUJybqqgUywXXlJyfnlmSD1KbWgImi9LBvJJSEFlcmgs2sKi0JBVsjF-yQnKKjoJ3Ykpynj2yOUn5RZl56WA1MCZCMjEpCeyc9IICEJWckpIMUZmcnKSQlg90IcQzCxZAaAA)
From the dictionary a regex can be generated that only matches decoded text:
```
irb> w
=> ["world", "banana", "hello"]
irb> /^([^a-z]|#{w*?|})*$/i
=> /^([^a-z]|world|banana|hello)*$/i
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 99 bytes
*Saved 1 byte thanks to @l4m2*
Expects `(string)(dictionary)`, where the dictionary is a set.
```
s=>g=(d,k=25)=>s.match(/[a-z]+/gi).some(s=>!d.has(Buffer(s).map(c=>(c%32+k)%26+97)+''))&&1+g(d,k-1)
```
[Try it online!](https://tio.run/##hdBNS8MwGAfwu58iC2xL6JutTNkhFbyJ4MWLMHZIn7y0rmlKkzrwy9e2etnm8AnkjYffP@SDf3IHXdX6qLFCDooNjuWaEREeWLahLHex4R5Kkux49LUPEl3R2Fkjydi3EHHJHXnqlZIdcXRsbQmwnMDyLgsOdJndB9sHGqzXlK5WaaAnNkrpALZxtpZxbTUJFMHPypgWvbfOyAWmpJFH9CY92eGj7WqBQ4QL3oxj2pWyri3eU0rRH5UkKL05518BgQjRCxfQPJ74YHXl7cRKP8@dnk@@n2bXmzm76738SRz57QVf2K5q9In7e3Xtlddq5G8veYACKWtPAnhRzL@h23ZaQAj4P23ks83wDQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~19~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[DIlÐáмS¡åP#ADÀ‡}N
```
First input is the list of words, second the sentence.
[Try it online](https://tio.run/##MzBNTDJM/f8/2sUz5/CEwwsv7Ak@tPDw0gBlR5fDDY8aFtb6AeWUkvPTM0vylXQUlFJLwGRROphXUgoii0tzQVRSUWlJqlIsl1@yQnKKjoJ3Ykpynj0A) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWVC6P9ol4icwxMOL7ywJ/jQwsNLA5QdXQ43PGpYWOv3X@d/dHS0Unl@UU6Kko5SUmIeEAIZGak5OflKsTpKnmm5uQUKEQXFuamKQL4CUHFyfnpmST5QUWoJiChKB7FLSoFEcWkuyJCi0pJUkF6/ZIXkFB0F78SU5Dx7qOak/KLMvHSQLJwFEk5MSgJZm15QACSTU1KSwSqSk5MU0vKB7ogFAA).
Uses the legacy version of 05AB1E because of three reasons, each saving a single byte:
1. `‡` works on a list of strings, whereas the new version requires a map around it - `ADÀ‡}` would have been `εADÀ‡]` in that case;
2. `N` outputs the last index outside of a loop, whereas this is just `0` in the new version and we would have to use the counter variable - `N` would have been `¾`, and `¼` would have to be added after the `#`;
3. `¡` in the new version would keep empty strings as items, and we would have to remove them - so an additional `á` would have to be added after the `¡` to only keep the words.
**Explanation:**
```
[ # Loop indefinitely:
D # Duplicate the current list
# (which will be the first implicit input-list in the first iteration)
I # Push the second input-sentence
l # Convert it to lowercase
Ð # Triplicate it
á # Only leave the letters of the top copy
м # Remove all those letters from the second copy
S # Convert the non-letters to a list of characters
¡ # Split the lowercase sentence on these non-letters
å # Check for each word if it's in the list
P # Check if this is truthy for all of them
# # If it is: stop the infinite loop
ADÀ‡ # Caesar Cipher the words in the list once:
A # Push the lowercase alphabet: "abcdefghijklmnopqrstuvwxyz"
DÀ # Duplicate, and rotated once: "bcdefghijklmnopqrstuvwxyza"
‡ # Transliterate the words in the list
}N # After the loop: push the last 0-based index
# (which is output implicitly as result)
```
[Answer]
# [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal), 19 bytes
```
λ?⇩⌈Ǎka:nǓ$vĿ?vcA;ṅ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BB%3F%E2%87%A9%E2%8C%88%C7%8Dka%3An%C7%93%24v%C4%BF%3FvcA%3B%E1%B9%85&inputs=%22bccb%22%0A%5B%22bccb%22%2C%20%22gpp%22%2C%20%22cddc%22%5D&header=&footer=)
Basically, try a cipher of each rotation and output the rotation number where all the words are in the dictionary.
2 can play at the legacy version saving bytes game.
## Explained
```
λ?⇩⌈Ǎka:nǓ$vĿ?vcA;ṅ
λ ;ṅ # Find the first integer n, such that
?⇩ # the lowercase input
⌈ # split on spaces
Ǎ # and with all non-alphabet letters removed
?vcA # contains all words from the input after
vĿ # being transliterated according to the mapping:
ka:nǓ$ # lowercase alphabet → lowercase alphabet rotated left n times
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 83 bytes
```
T`L`l
[^a-z¶]+
@
^
¶
{ms`\A(#*)¶@?((\w+\b)(?=.*¶\3$)@?)+$.*
$.1
^\B
#
T`l`zl`^.*¶.*
```
[Try it online!](https://tio.run/##Fco9CsIwAAbQ/TtFoR2SVAPiLKmuilM3Y0ibhlLoD6QpQr1XDpCLRXzzc9YPc5NSrR96xEs1xz2Gd4kKCjHgO61aXknOaAyVIER@StlSIi6cxSDPBa0ELQvOUPATlLwhR61HvY9a/QdnKT1NZrpDdm86MwuYpR/8AuthXb/Ab1i3Ca3bvP0B "Retina 0.8.2 – Try It Online") Takes input as a line of ciphertext followed by each dictionary entry on a separate line. Explanation:
```
T`L`l
```
Lowercase everything.
```
[^a-z¶]+
@
```
Change non-letters to a marker to simplify matching.
```
^
¶
```
Prepend a blank line to hold the result.
```
{`
```
Repeat until the result is found.
```
ms`\A(#*)¶@?((\w+\b)(?=.*¶\3$)@?)+$.*
$.1
```
If all the words in the ciphertext are in the dictionary then replace the whole buffer with the result.
```
^\B
#
```
If the result has not been found then increment the rotation amount.
```
T`l`zl`^.*¶.*
```
If the ciphertext is still present then rotate it.
[Answer]
# [R](https://www.r-project.org/), ~~99~~ 103 bytes
*Edit: Thanks to pajonk for bug-spotting, which unfortunately cost +4 bytes (also thanks to pajonk)*
```
f=function(x,d)`if`(all(x%in%d),0,1+f(gsub("[^a-z]","",chartr("a-zA-Z","za-za-y",scan(t=x,,x))),d))%%26
```
[Try it online!](https://tio.run/##hVDZVtswEH3nKxSlLhLIJQl7S1haaFkK3dgKgUaL7bjYkpFlMKbw68FySpqH9HB0zszV6N6rmdF9rQw1oZLtvt/2M8ktRjkRuBv6XUSjCOVOKB2BSYM0p30UpBlD8PySusUFJBAS3qPaaATLwoZ7VpaKElH3DpKUU4lMOyckxxiXlthxWgvDHxHc8eM4AadJGns1SABH8FbpSJQQMirLY1HPiyIFMQZ14K6C5sQ/@QEHXBCwRwWXawM9V0FolJV5poo6qG4mszHN4spbZ8YbOi6PODKlQxkMrP7iZ1pjlMY5A75SAyJlrGo0SBKbuBB8qGrNj8hArQPrr5zXkwhPTRP3zUyj2Zqdm19YXFp@@26lvbq2vvH@w@bWx0/bO7t7n/cPvnz99v3H4dHxyenPs/NO5wLUL391KePC84Ne@PsqiqVKrnVqspvb/K64//PwOOio@C9p7B4ZT5lgnk3PE2nKqbDJTlRUkV6PF1drqr24M6kMGLNeYh9GBP0n "R – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 132 bytes
```
y=>f=x=>eval(`/(?<![a-z])(?!${y}(?![a-z]))[a-z]/i`).test(x)&&f(x.replace(/[a-z]/ig,t=>(t=parseInt(t,36)-1,t-9?t:35).toString(36)))+1
```
[Try it online!](https://tio.run/##LYvLasMwEEV/xTElmaGyTQgt9CF7FyiFbroMAavyRCi4kpHGwenj213HzeYcLod7VCcVdbAdZ843NG7leJblQQ6ypJNqoS6gel7sVPa1R6gWN9/n30n/G2cVtsacKTIMuFweYMgDda3SBMW1G8GyBJadCpFeHAOLzT1ma8HZQ8WPm7vp7985WGdgCoi36/FJexd9S3nrDWxhl2pvLPtUJCnxzGDmxf2Fsf@86CP0TOk@P3rr6p8aYfWmE92I5FU12lUrxPEP "JavaScript (Node.js) – Try It Online")
As always, long part adding 1 to letter
[Answer]
# [Python](https://www.python.org), 120 bytes
```
f=lambda s,d,t=-1:~-any([chr((ord(c)%32+t)%26+97)for c in w]in d for w in re.findall(r'\w+',s))and-~f(s,d,~-t)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZBNasMwEIX3OcUgCJFqqdAU-gehBwj0Ao4XimQlAlsy4xFONj5D991kk96pt2nk_lC6ecNjZr43zNt7d6R9DKfTOZFTDx8Ht2p0u7UaemklrdTN06h0OPLS7JHziJYbMb9dFiTmy7vi8V64iGDABxiqi1jIfsge62vng9VNw3GxGYqF7IXQwarR8QwfFYmZb7uIdJn9zn_t0AfijrMXA8ZKWGtrwjOT5VWrO974nmTJTNx5ikwCq2lS3E2OUtY-tblsMVHNKlEJMful1gSUJEy9_9TMmhB_V7_u-vnPJw)
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
Related to [AoC2018 Day 8](https://adventofcode.com/2018/day/8).
---
The license file for an imaginary software system is defined as follows:
* The entire file is a sequence of non-negative integers.
* The entire file defines a *tree* of nodes.
* Each node in the tree has the following fields in the order:
+ Header, a single number indicating the number of child nodes.
+ Zero or more child nodes, as specified in the header.
+ Zero or more metadata entries (each being a single integer), as specified in the footer.
+ Footer, a single number indicating the number of metadata entries.
Hmm, does it really work? It should, because it is your job to validate the given license file!
An example of a valid license file:
```
2 0 10 11 12 3 1 0 99 1 2 1 1 1 2 3
A----------------------------------
B----------- C-----------
D-----
```
A has two children (B, C) and three metadata entries. B has no children and three metadata entries. C has one child and one metadata entry, and so on. It is well-formed, so it is valid.
How about this?
```
2 1 0 0 1 1 0 0 1 1 0
```
The root node has 2 children and 0 metadata. Then we need to divide `1 0 0 1 1 0 0 1 1` into two nodes. But:
* `1 0 0` is not a valid node: it has 1 child and 0 metadata, but single 0 is not a valid node.
* `1 0 0 1` is not valid either: it has 1 child and 1 metadata, but again we are left with single 0.
* `1 0 0 1 1` is valid (1 child, 1 metadata, `0 0` being the child), but the rest `0 0 1 1` is not a valid node.
* `1 0 0 1 1 0` is not a valid node because `0 0 1 1` isn't.
* The first child cannot be longer than that because the second must have 1 metadata.
Therefore, the second example is not a valid license file.
Given a license file as an array of non-negative integers, determine if it is valid. You can choose to
* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Truthy:
```
[0, 0]
[1, 0, 0, 0]
[0, 99, 99, 99, 3]
[2, 0, 10, 11, 12, 3, 1, 0, 99, 1, 2, 1, 1, 1, 2, 3]
```
Falsy:
```
[]
[0]
[0, 1]
[1, 1]
[0, 0, 0, 0]
[1, 0, 2, 3, 2]
[3, 0, 1, 0, 0, 1, 0, 0, 1, 2, 3, 2]
[2, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~85~~ 80 bytes
```
f=->l{a,*l,b=l;q=l.size;a==0?b==q:(1..q).any?{|x|f[l[0,x]]&&f[[a-1,*l[x,q],b]]}}
```
[Try it online!](https://tio.run/##XY7RDoIgFIbvewqvshowwCtz5IOwcwFbbm2sZeamqc9OCKPIjQMfP//hP89ej9Y2Al/MpNDJIC1M1QpDutv7WikhaK2FaM8HRkh7JOo@1tM8zI00kqIBYL9vpFSYuVY5oBaQBlgW@8icTFFGAXaemeOwouK4LH9VRJ17G1vLNTF3LdzhxdXniPudRfad/avLcoxxHj75hiRpLJmFJfpmrhAVYnkUizBUNKewcfL/1y0D2A8 "Ruby – Try It Online")
### Let me explain:
The license is valid if:
* the first element is zero and the last element is the length of the list minus 2
or
* we can create 2 valid licenses by splitting the list in 2, removing the head from the first part and prepending it (minus 1) to the second part. A license in the format `a x x x x x x y y y y y y y` is valid if both `x x x x x x` and `a-1 y y y y y y y` are.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 121 bytes
```
f=lambda a,l=1:any(f(a[:i])*f(a[i:],l-1)for i in range(len(a)))if l>1else[[]==a,a>[]<(s:=a[:~a[-1]])and f(s,s.pop(0))][l]
```
[Try it online!](https://tio.run/##lVDLbsMgELz3KziyEam8oEqNVfIjhMNWMQkSxcjOJZf@uoNt5YEbRarEwjA7s7uQzqdjG9Vn6gandzkC/XzviZEIGmuKZ@44mdpbWI3A11aENYJrO@aZj6yjeGh4aCInAPCOhS02oW@MsVqToK2xX7yvda7xS2aN1gLFPXO8F/17ahOvAKwJdkidj6fczFSCVRbg7UZgJuZV0JnYbO6hiqScDDhGtmO@qnxM5CjOSE47XvFkv/vLTsu@uJwPnww895RFRs1jXR/0CJ7JZSlZ4nJkWVZVD/o/f6f@of14rX1dZrgA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 49 bytes
```
f(0:x++[l])|length x==l=1
f(a:x++y)|a>0=f$a-f x:y
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9Nw8CqQls7OidWsyYnNS@9JEOhwtY2x9aQK00jESRTqVmTaGdgm6aSqJumUGFV@T83MTNPwVYhTSHaSEfBQEfBEIQNgRjINQZSYEFLSzDLCEwawtjGsf8B "Curry (PAKCS) – Try It Online")
A port of [@G B's answer](https://codegolf.stackexchange.com/a/239887/9288).
This returns `1` if the license is valid, and nothing otherwise.
Though Curry has a Haskell-like syntax, its pattern matching is so powerful that this answer looks more similar to the [Mathematica answer](https://codegolf.stackexchange.com/a/240016/9288) than the [Haskell one](https://codegolf.stackexchange.com/a/239996/9288).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes
```
⊞υ⟦θ⟧Fυ¿ι«≔⊟ιη¿η«≔§η⁰ζ¿‹ζ⁼§η±¹⁻Lη²⊞υι¿ζF…³Lη⊞υ⁺ι⟦✂η¹κ¹⁺⟦⊖ζ⟧✂ηκ⟧»»P¹
```
[Try it online!](https://tio.run/##TU9BasMwEDzHr9ijBCrU9inkFGgOhSaY9mh8EM7GElHlxJJCccnb1ZWoQwQSq53ZmdleyakfpYmxCU6xIKC9dnxTnMYJWOCgT8A0h99itXVOD5Y144UaAhSRVglVGV3grX@3R/xhSsArsebEyrQPdI7NAnbXII175h1wkB5ZyYm/1zY44trBK1IWUHE6sGTTWQ6Nwxxs5pBzfko7IKsFPAafZhpDipr2@jK6x2RYCjjTy/@x9g37Cb/RejySZCfgwTxz3vHkeS/uRbbdB@P1ZdLWU@BNjG1b0aakli4Jl/StswU11utcVfktl7ruuvhyM38 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the licence is valid, nothing if not. Explanation:
```
⊞υ⟦θ⟧
```
Start by checking the whole licence as a list of one sublicence.
```
Fυ
```
Loop over the lists of sublicences.
```
¿ι«
```
If there are still sublicences to check:
```
≔⊟ιη
```
Remove one sublicence.
```
¿η«
```
If this sublicence is not trivially illegal, then:
```
≔§η⁰ζ
```
Get the number of its sublicences.
```
¿‹ζ⁼§η±¹⁻Lη²
```
If this is a valid licence with no sublicences, then...
```
⊞υι
```
... push the remaining sublicences to the list to scan.
```
¿ζ
```
Otherwise if this licence has sublicences, then:
```
F…³Lη
```
For each potential first sublicence:
```
⊞υ⁺ι⟦✂η¹κ¹⁺⟦⊖ζ⟧✂ηκ⟧
```
Append the first sublicence and the licence adjusted for the removal of the first sublicence to the list of licences to scan.
```
»»P¹
```
Otherwise, all sublicences validated and so this licence is valid.
[Answer]
# JavaScript (ES6), ~~94~~ 92 bytes
This is using [GB's great insight](https://codegolf.stackexchange.com/a/239887/58563).
Returns **0** or **1**.
```
f=a=>a[a[n=a.length,0]+n-!!n]==n-2|a.some((_,i)=>f(a.slice(1,i))&&f([a[0]-1,...a.slice(i)]))
```
[Try it online!](https://tio.run/##dVFBDsIgELz7Cr20EIEUevKAR1/grRJDKtUaBNNWExP/XrdtGluDCQuzszub2XDVT13nVXlvqPMn07aF1HKrM505qZk17txcSKLWjq5WTknpqHhrVvubQehISiy3BYLclrlBHHIcRQUCdaIoJ4yxsVZihXGbe1d7a5j1ZxRn@@rRXF4qxospD/KELBNo/6U50MMJFIHebL6RBlpEL@ZdwCgOaQpPT3YSQKK/@Yj7IbMp8cFlO23rkOuQqbBRHl6Oh7v/7zx4H/YQgXo6LDyOmIL/IjFv/MXdN34A "JavaScript (Node.js) – Try It Online")
[Answer]
# TypeScript Types, 378 bytes
```
//@ts-ignore
type a<T,N,C=[],P=[],Q=[...P,C]>=T extends[infer A,...infer R]?a<R,N,[...C,A],P>|a<R,N,[A],Q>:N extends Q["length"]?Q:[N,Q]extends[0,[[]]]?T:never;type b<D,N,M=[]>=N extends M["length"]?D:D extends[...infer D,{}]?b<D,N,[...M,0]>:never;type c<C>=C extends(infer C)[]?0 extends M<C>?0:1:0;type M<D>=D extends[infer C,...infer I,infer M]?1 extends c<a<b<I,M>,C>>?1:0:0
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgDlKBhAXgG0BdSgBWbYEVmA6Ae3osAfA3KF0AD3DpEAE0hNYiAGbpUhAIKUBfFes0AlFgH4yRmpSZ66lLW3YiAPhatMHlbiIBc1STJyioTcTABEADZy8OAAFmFm3D5MtNws0rIKSgAM1qwsZuQ+iOgAbhoA3LgEhABGpAAiVgCyXGL+GUGQhM3hUYgx8WYNPg0BmYo2AgYahE0A3gC+ZvVNtFN8zZTZosVlldVEAMakdGJ0410AFDOadACUrKbZl1k9pyLPPgCMPtlV+CIzUaYjGnSyyjUszseluhAAkpQ4c0zN9XsETmR6ojmiJ6CJPr9sn9MNhAYRyC8GO8mLlCDsRJgQIQWQA9UxkmrkNHU4FMb6UemCukMpnAFmEdmcojkABMhF5pFpgoAnCrVerCGrBQBmURiiVSw4UnUKmmy4WC75074CwjfC2EHVWy1azV2x12r2Cx16xnMtkc6WEABiVJp+oDko5xpDPJpoqjRvJIfliuV9sj4sDwZDpvTXqzhpjKYALGa+SLXYns9HcwBWCtKu1030+os52MANibTGdQvt1ZdA5tPt17f9teTNRDAHZe56h4Pl1Xly2O3WgA)
## Ungolfed / Explanation
```
// Returns all the ways an array can be chunked into Count subarrays
type Chunkify<Unchunked, Count, CurChunk=[], PrevChunks=[], AllChunks=[...PrevChunks,CurChunk]> =
// Get the first element of Unchunked
Unchunked extends [infer El, ...infer Rest]
// Return a union of:
?
// Continue this chunk
| Chunkify<Rest, Count, [...CurChunk, El], PrevChunks>
// Start a new chunk
| Chunkify<Rest, Count, [El], AllChunks>
// Unchunked is empty.
// If AllChunks.length == Count,
: Count extends AllChunks["length"]
// Return AllChunks
? AllChunks
// Otherwise, if Count == 0 and AllChunks == [[]],
: [Count, AllChunks] extends [0, [[]]]
// Return []
? Unchunked
// Invalid chunking
: never
type RemoveMetadata<
Data,
MetadataCount,
RemovedCount=[]
> =
// If RemovedCount == MetadataCount,
MetadataCount extends RemovedCount["length"]
// Return Data
? Data
// Otherwise, pop the last element off of Data
: Data extends [...infer Initial, {}]
// Recurse, incrementing RemovedCount
? RemoveMetadata<Initial, MetadataCount, [...RemovedCount, 0]>
// Data is empty, but we still need to strip more metadata; return never
: never
type ValidateLicenses<Chunkifications> =
// Map over Chunkifications, extracting the chunks as a union
Chunkifications extends (infer Chunks)[]
// Return 0 if any of Chunks are invalid licenses
? 0 extends ValidateLicense<Chunks> ? 0 : 1
// Invalid
: 0
type ValidateLicense<Data> =
Data extends [infer ChildCount, ...infer InnerData, infer MetadataCount]
// Return 1 if any of the ways to chunk RemoveMetadata<InnerData, MetadataCount> into ChildCount chunks are valid lists of licenses
? 1 extends ValidateLicenses<Chunkify<RemoveMetadata<InnerData, MetadataCount>, ChildCount>> ? 1 : 0
// Invalid
: 0
type T0 = ValidateLicense<[0, 0]>
// ^?
type T1 = ValidateLicense<[1, 0, 0, 0]>
// ^?
type T2 = ValidateLicense<[0, 99, 99, 99, 3]>
// ^?
type T3 = ValidateLicense<[2, 0, 10, 11, 12, 3, 1, 0, 99, 1, 2, 1, 1, 1, 2, 3]>
// ^?
```
```
[Answer]
# [Rust](https://www.rust-lang.org/), 156 bytes
```
fn f(a:&[usize])->bool{let l=a.len();l>1&&((a[0]<1&&a[l-1]==l-2)||a[0]>0&&(2..l).any(|i|f(&a[1..i])&&f(&{let mut z=a[i..].to_vec();z.insert(0,a[0]-1);z})))}
```
[Try it online!](https://tio.run/##hVLdboMgFL7vU5z2wsCCBOxV29k9iCENWzAhodgpblnVZ@@O2nZdMzsi@HG@nwA5ZV2FU@5hr60nFJoe50Svo6yu7NEoGm9fi8I1zgRwqebOoGzjtjKKCNGZUM@IdOZiqdLUxQlt2766FcgnnDvKtf8irW1zgjLJuVU0inAzJO7rAMdUZ5ZzxUOx@zBvmH7k1lemDESwPiuWWOoopd0JcORFCcT6Qx0YaF99mpKC9RBlMzgPgjHzTDAQikEoa0PZHSeRG78pBXKr1c9cTumSIUb2E0Mlbpf4G4q9D1EyrPKCJ5OwnmtX/XGUaQZDJ0n5iBS3DzDpF@OJcZ1ULcf7X@JuwX/W5Lf8Ht/5FDRX/6G0Pjg/J4tm/dItGAztQDdXga76/tmZ9znBVhtZBk/ndhl13aw7fQM "Rust – Try It Online")
Making use of @G B's approach.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 81 bytes
```
f(a)=#a&&if(a[1],sum(i=2,#a,f(a[2..i])*f(concat(a[1]-1,a[i+1..#a]))),a[#a]+2==#a)
```
[Try it online!](https://tio.run/##XU3RCoMwDPyVoiB21mLqkw/uR0ofguAobK647WFf3yWtMjdomrvkchdw9e0lxDjXKMcSq8oTsuDU43Wr/WhUiYonRmvv5Gmup/sy4TNpWlBofQNal@iklMQINGYkIxkxhOu7RtGeRVj9QieiYFIIzpJKWNsp0TkCQD0/ZtSH4Vs9z0xaAxeJgWhPLQ1ZQ8ikH3acrpLbZglbEGz8EJh9sqfhQZ/TdtERHFTmd/OPnZPxAw "Pari/GP – Try It Online")
A port of [@G B's answer](https://codegolf.stackexchange.com/a/239887/9288).
[Answer]
# Haskell, ~~101~~ 93 bytes
This uses [G B](https://codegolf.stackexchange.com/a/239887/)'s observation.
```
h(x:y)|x>0=or[h$take n y|n<-[0..l y],h$x-1:drop n y]
h y@(0:_)=last y==l y-2
h _=1<0
l=length
```
-8 bytes thanks to alephalpha
[Try it Online!](https://tio.run/##XU1BCoMwELz3FXvwoKCSxJNiSv8RggQqTTFGUQ8G/LvdGMS2kM3O7MzOajV3rTH7ruO1csm23gkfJqGjRXUtWHCbrTNB8tyAk6mO1oxWz2kYvSRvGtwjJlWTcKPmBRznaMsYzhtOa3Iz3LT2tei9V28LHMbpbReIezWCBiFICkSmgmILDwm2sryqwBE7ROoLrRRpge0Yegsidvz0xH7JR4U4Gk7QwK5LISGkMeRFOHNavsFlYr/CP5Yy2T8)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~44~~ 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"ćUX_iRćsgQë.œ2ùεεNiX<š}}}εε®.V}0ìP}à"©.V
```
Port of [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/239887/52210).
Results in `1` for truthy and `0`/`""` for falsey (only `1` is truthy in 05AB1E).
[Try it online](https://tio.run/##yy9OTMpM/f9f6Uh7aER8ZtCR9uL0wMOr9Y5ONjq889zWc1v9MiNsji6sra0FcQ6t0wurNTi8JqD28AKlQyv1wv7/jzbUMQBCw9j/urp5@bo5iVWVAA) or [verify (almost) all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/pSPtoRHxmUFH2ovTAw@v1js62ejwznNbz231y4ywObqwtrYWxDm0Ti@s1uDwmoDawwuUDq3UC/uv8z862kDHIFZHIdpQx0AHyjTQsbSEImMI3xCIDHUMjSB8kFKgnKGOkY4hiA9WA1UIkTeE8ODmwZkQWwxhTKCBOkYgDtAkiAwyDZIwBnMMkEiIntj/urp5@bo5iVWVAA) (the largest truthy test case times out because of `.œ`).
**Explanation:**
```
"..." # Push the string below
© # Store it in variable `®` (without popping)
.V # Execute it as 05AB1E code
# (after which the result is output implicitly)
```
```
ć # Head extracted; pop and push remainder-list and first item separately
U # Pop and store this first item in variable `X`
X_i # If `X` is 0:
R # Reverse the remainder-list
ć # Extract head again (or extract tail actually)
s # Swap so the remainder-list is at the top
g # Pop and push the length of this remainder-list
Q # Check if it's equal to the extracted tail
ë # Else:
.œ # Get all possible partitions of the remainder-list
2ù # And only keep those consisting of two partition-parts
ε # Map over each partition:
ε # Inner map over both partition-parts:
Ni # If it's the second part:
X< # Push `X` and decrease it by 1
š # Prepend it in front of the partition-part
} # Close the if-statement
} # Close the inner map
} # Close the outer map
ε # Map over the partitions again:
ε # Inner map over both partition-parts again:
® # Push string `®`
.V # And execute it as 05AB1E code as recursive call
} # After the inner map:
0ì # Prepend a 0 in front of each result
P # Get the product of this result to check if all were truthy
} # After the outer map:
à # Get the maximum to check if any were truthy
```
Some notes:
* 05AB1E lacks any recursive methods, but with `"..."©.V` and `®.V` we can mimic this behavior.
* You may be wondering why we first close the maps and then do the exact same maps again at `}}εε`? We do this to first create the correct partitions, before we do the recursive calls, otherwise variable `X` will be incorrectly overwritten by the inner recursive call. In *@GB*'s Ruby answer, the variables `a` and `b` are within scope of the function, whereas in my full program, the `X` (which is basically variable `a`) would be overwritten in the inner calls.
* `ć` results in an empty string if the list is empty, which is why we use the `0ì` before the `P` to convert all empty strings to `0`, while keeping all other integers the same.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes
-3 bytes thanks to @att.
```
_f=1<0
f[0,x___,l_]:=l==Tr[1^{x}]
f[a_,x__/;f@x,y__]:=f[a-1,y]
```
[Try it online!](https://tio.run/##XU1BCsMgELznFUKgJ0Ncc0pbi0/oobdgJZRKA0kPIYcE8e12VaRpwdXZmXFm6pfXc@qX4dF7r42AMytMx@iqtaajVkcxCnGbO7jb1SmUeh20@mTkSjcdDMhVQDflr/PwXrqSVBdiiJSkVAdSy8JaRglztCAWEKQTVwRt@50mkjwaIAzaAdcGn0gGEyIeb8g4fUuBORZyHWRm35vSUjKPTJNKs20P9jb@K/1j5/wH "Wolfram Language (Mathematica) – Try It Online")
A port of [@G B's answer](https://codegolf.stackexchange.com/a/239887/9288).
] |
[Question]
[
Output a sequence of all the primes that are of the following form:
`123...91011...(n-1)n(n-1)..11109...321`. That is, ascending decimal numbers up to some `n`, followed by a descending tail, all concatenated.
## Background
Recently, Numberphile [posted a video](https://www.youtube.com/watch?v=vKlVNFOHJ9I) about primes that follow this pattern.
## Output
```
1 -> 12345678910987654321 (n=10)
2 -> 123...244524462445...321 (n=2446)
```
No more terms are known, but it's likely that there are infinitely many.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
∞η€ûJʒp
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8c9sfNa05vNvr1KSC//8B "05AB1E – Try It Online") Times out on TIO without printing a single number because the [primality test](https://github.com/Adriandmen/05AB1E/blob/f34df35b53d2b8d82c7e8132fe0f03c72107598d/lib/commands/int_commands.ex#L196) is too slow. Takes 77 seconds locally for the first number and will never† get to the second number.
```
∞η Prefixes of [1, 2, 3, ...]
€û Palindromize each prefix
J Join each into a number
ʒp Filter: keep primes
```
Local output:
```
05AB1E git:master ❯ ./osabie programs/mwp.abe
["12345678910987654321"
```
† in the lifetime of the universe, the test is \$\mathcal{O(\sqrt{n} \log{}n})\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒḄV©ẒƊ#®
```
[Try it online!](https://tio.run/##ARsA5P9qZWxsef//xZLhuIRWwqnhupLGiiPCrv///zE "Jelly – Try It Online")
By [default sequence I/O rules](https://codegolf.stackexchange.com/tags/sequence/info), this inputs a value `k` and outputs the prime corresponding to `k`.
This is a monadic link `f(k)` that returns the prime. It also outputs the `n` value for that prime as a side effect - this should be considered a function that returns the prime. I've included a 9 byte version that doesn't output anything extra below.
```
ŒḄV©ẒƊ#ṛ®
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//xZLhuIRWwqnhupLGiiPhuZvCrv//MQ "Jelly – Try It Online")
---
Both can handle \$k = 1\$ on TIO, can't handle \$k = 2\$ or above.
## How they work
```
ŒḄV©ẒƊ#® - Main link. Takes k on the left
Ɗ# - Find the first n such that the following is true:
ŒḄ - Bounced range of n; [1, 2, ..., n, ..., 2, 1]
V - Evaluated as an integer: 12...n...21
© - Save this in the register
Ẓ - Is this prime?
® - Print n and return the register
```
The second uses `ṛ®` instead of `®`. The `ṛ` causes the program to discard the value of `n` rather than printing it, and then `®` returns the register.
[Answer]
# [Python 3](https://docs.python.org/3/), 213 bytes
```
def A(n):return int(''.join(str(d)for d in range(1,n+1))+''.join(str(d)for d in range(n-1,0,-1)))
i=5
w=0
y=int(input())
while 1:
p=n=1;exec("p*=n*n;n+=1;"*~-A(i))
if p%n==1:w+=1
if w==y:print(A(i));break
i+=1
```
[Try it online!](https://tio.run/##fYxLDoIwFEXHdhUNieGVj6ExTkregKWgFKmaR1NLKhO3XgsLcHjPPTl29dNM5xgHPfIOSCin/eKIG/KQ56fHbAje3sEgxtnxIXHuerprkBWVUojyr0S1rJqqTp5gBi8sYMNW3NqG7OIh4TCZl@ZSsYNFQtnqj75BZgukgloqE8mKb92BSe7BjNweCVGqkJ59B8RVWbc1d6m9Ot0/05WEGOUP "Python 3 – Try It Online")
Probably should be correct. If you find bugs then comment the answer.
Upvote [Lynn solution of prime checking](https://codegolf.stackexchange.com/a/57682/106959)!
[Answer]
Here I used the Miller-Rabin Primality Test to approximate if the number is in fact prime.
```
import math
import random
def miller_rabin(n, k):
# Implementation uses the Miller-Rabin Primality Test
# The optimal number of rounds for this test is 40
# See http://stackoverflow.com/questions/6325576/how-many-iterations-of-rabin-miller-should-i-use-for-cryptographic-safe-primes
# for justification
# If number is even, it's a composite number
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
a = random.randrange(2, n - 1)
x = pow(a, s, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
print(_)
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
def constructNumber(n):
numberArray = []
for i in range(n):
numberArray.append(str(i+1))
for i in range(n-1):
numberArray.append(str((n-1)-i))
return int(''.join(numberArray))
if __name__ == "__main__":
print(miller_rabin((constructNumber(10)),40))
```
[Miller-Rabin Python Source](https://gist.github.com/Ayrx/5884790)
] |
[Question]
[
## Background
Zeckendorf representation is a numeral system where each digit has the value of Fibonacci numbers (1, 2, 3, 5, 8, 13, ...) and no two consecutive digits can be 1.
[Nega-Zeckendorf representation](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem#Representation_with_negafibonacci_numbers) is an extension to this system that allows encoding of all integers, not just positive ones. Its base values are nega-Fibonacci numbers (regular Fibonacci numbers with alternating sign; 1, -1, 2, -3, 5, -8, 13, -21, ..., also derived by extending regular Fibonacci sequence to negative indices).
Donald Knuth proved that every integer has a unique representation as a sum of non-consecutive nega-Fibonacci numbers (0 is an empty sum). Therefore, the corresponding nega-Zeckendorf representation is unique for every integer. 0 is represented as an empty list of digits.
## Challenge
Given an integer (which can be positive, zero, or negative), compute its nega-Zeckendorf representation.
The output must consist of zeros and ones, either as numbers or characters. Output in either least-significant first or most-significant first order is acceptable (the latter is used in the test cases).
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
-10 = 101001
-9 = 100010
-8 = 100000
-7 = 100001
-6 = 100100
-5 = 100101
-4 = 1010
-3 = 1000
-2 = 1001
-1 = 10
0 = (empty)
1 = 1
2 = 100
3 = 101
4 = 10010
5 = 10000
6 = 10001
7 = 10100
8 = 10101
9 = 1001010
10 = 1001000
-11 = (-8) + (-3) = 101000
12 = 13 + (-1) = 1000010
24 = 34 + (-8) + (-3) + 1 = 100101001
-43 = (-55) + 13 + (-1) = 1001000010
(c.f. negafibonacci: 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, ...)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
0BUJNÆḞḋƲ=ʋ1#ḢȯRB
```
[Try it online!](https://tio.run/##AT4Awf9qZWxsef//MEJVSk7DhuG4nuG4i8ayPcqLMSPhuKLIr1JC/zEwxZJSICzDh8WS4bmYJCTigqwgS@KCrFn//w "Jelly – Try It Online")
+3 bytes (`ḢȯR`) to output `[]` instead of `0`
I'm sure this can be beaten by some clever mathematical trick; this just counts up in binary, converts from nega-Zeckendorf and stops when it equals the input
## How it works
```
0BUJNÆḞḋƲ=ʋ1#ḢȯRB - Main link. Takes n on the left
ʋ - Group the previous 4 links into a dyad f(k, n):
B - Convert k to binary
U - Reverse the bits
Ʋ - Group the previous 4 links into a monad g(bin(k)):
J - Indices
N - Negate
ÆḞ - nth Fibonacci number
ḋ - Dot product with bin(k)
= - Does g(bin(k)) equal n?
0 1# - Find the first integer k such that f(k, n) is true
Ḣ - Extract k
ȯR - If k = 0, replace with []
B - Convert to binary
```
[Answer]
# [Python 3](https://docs.python.org/3/), 89, 87 bytes
```
f=lambda n,a=-1,b=1,i=0:0<b*n<=b*b-i%2and f"1{f(n+a):0>{i}}"or n and f(n,b,a-b,i+1)or""
```
[Try it online!](https://tio.run/##TVDRToQwEHznKzYkBnpXki6cnpLr/Yj6QKHkGrUQqIlK@HZckIJNpp3uzO622367W2Ozaarle/GhqgIsL2SCXEnkRopcXNTBXqQ6qMTcpYWtoA5xqGN7LFguroMZx7DpwMIixZYrXiSKmyOypgvDyene9SAhTlBwSJ4Ij4Qz4YFwTzgRMkJKQA5ko50uFCOJHGQkP6VRNgoW6K9Wl05Xc9kIBQqBEQdiRIRnYmdexS2GPrb7vfJ3zvvC1vDq3tK32ltjX89b/5lxb0syC8qbLt90tzz/5TM9n8pZnxlmJNc0T8c1GAs/po2XCXLwn2Z5ALTmmdaxY8ul7Yx1cR0OboTkCtHQjxEMa5tnLWX/OoZs@gU "Python 3 – Try It Online")
[Old version](https://tio.run/##TVDRToQwEHznKzY8SHtXku7d6Sm53o@oDxRKrlELgZqohG/HBSnYZNrpzuxuu823v9XuOI6Ves8/dJmDE7lKUWiFwiqZyYveuYvSO50ye4c8dyVUMfYVc/ucZ/La22GI6xYczBJzQos81cLukddtHI/edL4DBSxFKSB9IjwSzoQHwj3hRDgSDgQUQDba6UIxkshBRvJTGmWj5JH5akzhTTmVTVCilJgIIEZEBiY3FlRcYxhimz8of@e0z2wJL@41fa29Ng71gvWfGbe2JPOouJnizbTz818@D@dTMekTwyPJFc3TCwPWwY9t2DxBAeHTPIuA1jTTink@X5rWOs@quPcDpFdI@m5IoF/aPBulutch5uMv "Python 3 – Try It Online")
Uses the fact that each negative term in the negbonacci equals minus the sum of all preceding positive terms and, similarly, each positive term is 1 minus the sum of all preceding negative terms.
This is used to set up a direct recursion.
Test bed "borrowed" from @Noodle9.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞bõš.ΔRSƶÅfāÉ·<*OQ
```
[Try it online](https://tio.run/##ASkA1v9vc2FiaWX//@KInmLDtcWhLs6UUlPGtsOFZsSBw4nCtzwqT1H//y0xMA) or [verify all test cases](https://tio.run/##ATwAw/9vc2FiaWX/VChUxbh2ecKpPyIg4oaSICI//@KInmLDtcWhLs6UUlPGtsOFZsSBw4nCtzwqT8KuUf99LP8).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,4,5,...]
b # Convert each to a binary string
õš # Prepend an empty string (for edge case 0)
.Δ # Find the first value which is truthy for:
R # Reverse the binary string
S # Convert it to a list of bits
ƶ # Multiply each by its 1-based index
Åf # Get the n'th Fibonacci number for each
ā # Push a list in the range [1,length] (without popping)
É # Check for each whether it's odd: [1,0,1,0,1,...]
· # Double each: [2,0,2,0,2,...]
< # Subtract each by 1: [1,-1,1,-1,1,...]
* # Multiply it to the Fibonacci numbers at the same positions
O # Sum them together
Q # And check if it's equal to the (implicit) input-integer
# (after which the found result is output implicitly)
```
[Answer]
# JavaScript (ES6), 74 bytes
Output format: least-significant first.
```
f=(n,k)=>(g=(k,a,b)=>k&&k%2*a+g(k>>1,b-a,a,s+=k%2))(k,1,s='')^n?f(n,-~k):s
```
[Try it online!](https://tio.run/##FU1LDoIwFNx7ircR@uS1schKUowLT2HQFATUYkuoMTFGr45lMcl8M3f90r4eb8OTW3dppqlVzJJBVbBOMUOaqsBNFJllutJJx0xRSKq4DolPVHARQ02SV3GMJ7trw5z/DG79lB@FEDP246jfLJVYioceGDsTWARVgAUOco0EXEoCmRKkWRDZphStGw@6vjI79z4LgNpZ7/pG9K4LFxB@EPPFF6c/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~137 129~~ 119 bytes
```
n=->x{x<2?x:n[x-2]-n[x-1]}
z=->x,u=0{i,y=0,u.to_s(2)
y.bytes.sum{|b|b%2*n[y.size+i-=1]}!=x||y=~/11+/?z[x,u+1]:y[0..-2]}
```
[Try it online!](https://tio.run/##RY/dbsIwDIXv/RQZEhI/SYjT8qsFHqSrpnXrtF7QIdpKCS17deaWBG6ST7bPOfa5ydztVhqxt6191Qe7KxMrdCr6D9MrXPoWb4xqC@6M4o2sf9@riZ6Ck5mr80pWzbHtsi4b61mZOFkVl3xeCEPiF2O7zpm/BeJ8cbgk5DPHdOcSJSVlXG/JTCAxKi4QOWquYy7iKJX5x@dP29nudC7K@puNxtEXM3s23lRv5Ygzyxm5kQHJmWGoUCkEsR2YUIHYeFbE68A0s7oz9vVlYKrH3gdE5KdBaN8HgQNBHzbJj6faTWEogR@BuwghDpawDKGwCmvBOiwLG08I28cSCvw16h6PGMapox83KNDxUzPsHj1l9PwD "Ruby – Try It Online")
* Saved 8 Bytes thanks to @ovs suggestion to use =~(find) instead of match
* probably not the golfiest but at least I solved this complicated task.
n=->x{..} # nega-fib(x)
z=->x,u=0{ # starts from 0
y=u.to\_s 2 # binary representation
we convert y to an array of nega+fibs or 0.
If that sum is ==x and if no 1's are next to each other we return y with last bit removed, else we try next u
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 83 bytes
```
t=>(h=i=>i&i/2|t-(g=(i,p=0,q=1)=>i&&g(i>>1,q,p-q)+i%2*q)(i)?h(++i):i)``.toString(2)
```
[Try it online!](https://tio.run/##FYxNDoIwFAav4kbynm0RWAqvHsILQJCfz5CWQuPKu1fYzGKSmU/37fZ@wxqN8@8hjZKiWJoFYpHhXv2ioUkIepVCByn59NlEsLbUQa8msMK1ugUm8HMmpcAPcNvm0b/iBjdRxWn0G0FMWdRo5KRS3Hu3@2XIF3/c9GU8eq7THw "JavaScript (Node.js) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 20 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╘ïâ_h╒m*fh╒¥∞(m*Σk=▼
```
Outputs in least-significant first order (so the test cases in reversed).
[Try it online.](https://tio.run/##y00syUjPz0n7///R1BmH1x9eFJ/xaOqkXK00EHVo6aOOeRq5WucWZ9s@mrbn/39dQwMuXUsuXQsuXXMuXTMuXVMuXRMuXWMuXSMuXUMuAy5DLiMuYy4TLlMuMy5zLgsuSy5DAwA)
**Explanation:**
```
▼ # Do-while false with pop:
╘ # Discard everything from the stack
ï # Push the 0-based loop-index
â # Convert it to a binary-list
_ # Duplicate it
h # Push the length of this list (without popping)
╒ # Pop and push a list in the range [1,length]
m* # Multiply the integers at the same positions together
f # Get the n'th Fibonacci number for each
h╒ # Push a [1,length] ranged list again (without popping)
¥ # Modulo-2 on each
∞ # Double each
( # Subtract each by 1
m* # Multiply the integers at the same positions again
Σ # Sum this list together
k= # Check whether it's equal to the input-integer
# (after which the entire stack is output implicitly as result,
# which is the binary-list we've duplicated)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes
```
NθF²⊞υ±ιW∧θ⁼›θ§υ±³›θ§υ±¹⊞υ↨…⮌υ²±¹W›Lυ²¿⁼›θ§υ±³›θ⊟υ0«1≧⁺§υ±¹θ
```
[Try it online!](https://tio.run/##nVBLa8JAED7rrxg8zUAKjT16ilKK0ErwH2zjmF1YN8k@1FL87evGF@1BD87xm@81U0lhq0boGOemDX4RNt9ssaPJcN1YwDFBGZzEkMGCa@EZFaXdTirNgIVZYZfBexeEdvhhORFsjxR@bla8/yN7I6IMHlJyOs0tcCoc4@yn0jyTTYtL3rJNSEg@Y/qnuhW6@n@yqb28UAnUGvCpkmXKDedSVhmPo9dRCmPtGH6HgwuW99jgS7SFc6o2S1VLj6UO7s6RGfTvPcSY5/Flq48 "Charcoal – Try It Online") Link is to verbose version of code. Based on the algorithm in the linked Stack Overflow question. Explanation:
```
Nθ
```
Input the integer.
```
F²⊞υ±ι
```
Start building up the negated nega-Fibonacci sequence with `0, -1`.
```
W∧θ⁼›θ§υ±³›θ§υ±¹
```
Until enough terms have been generated to calculate the nega-Zeckendorf representation...
```
⊞υ↨…⮌υ²±¹
```
Push the difference between the last two terms to the sequence.
```
W›Lυ²
```
While sufficient terms of the sequence remain:
```
¿⁼›θ§υ±³›θ⊟υ0
```
If the integer does not fall between the third last and the last term (removing the last term as we go), then output a `0`.
```
«1≧⁺§υ±¹θ
```
Otherwise output a `1` and add the (originally second) last term to the integer, which brings it closer to zero (since it has the opposite sign; see the linked question to explain why this works).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~125~~ ~~97~~ 93 bytes
```
f=lambda n,k=0:n-g(k)and f(n,k+1)or bin(k)[2:-1]
g=lambda k,a=0,b=1:k and k%2*a+g(k>>1,b-a,a)
```
[Try it online!](https://tio.run/##TVDtToMwFP3PU9wsMVBXkl42nZJ0LzL3o7CyEbQjUBN12bPjAVcmySm35@NeuO23P53dahgq/W4@ioMhJxutcpcek0YYd6AqAbNkce6oqB3IXZanvI@OIdBIo5UsNOcNjYHmIXs0S8S3W5ZFaqQRg7e970lTkrKSlL4CL8AGeAaegDWwAjKAJcGGExdwkOCAEX7EkGYlIvvV2tLbw9g2ZsVKcSwJFQoVKnWvgsozx4G7@4Py9x7PqbrRN/ccn3vPg0O/YP1n5vtYyCIqT7ZsbDd9/ttntlmXoz5WvIJcYeFeWqod/dRtMm1QUvhpkUeEZ9xplXgxXdqudj6pFhd/pXRL8aW/xnS5jdlZrfv9dSGGXw "Python 3 – Try It Online")
*Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/236677/9481).*
Outputs most-significant first.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 19 bytes
```
ḟö=⁰ṁ_z*z*İ_İf↔ΘmḋN
```
[Try it online!](https://tio.run/##AWcAmP9odXNr/21vc@KCgf/huJ/Dtj3igbDhuYFfeip6KsSwX8SwZuKGlM6YbeG4i07///9bLTEwLC05LC04LC03LC02LC01LC00LC0zLC0yLC0xLDAsMSwyLDMsNCw1LDYsNyw4LDksMTBd "Husk – Try It Online")
```
mḋ # get the binary digits of each number in
N # the infinite list of integers
Θ # and prepend an empty list of no digits;
ḟö # now, return the first set that satisfies:
↔ # the digits reversed
z* # zipped by multiplication with
z*İ_İf # the negative negafibonacci sequence
# (=fibonacci sequence zipped by multiplication
# with powers of -1)
ṁ_ # all negated and summed
=⁰ # is equal to the input
```
[Answer]
# Excel, 240 bytes
```
=LET(q,SEQUENCE(1,18),d,SEQUENCE(2^18-1),x,DEC2BIN(INT(d/2^9),9)&DEC2BIN(MOD(d,2^9),9),y,FILTER(x,ISERROR(FIND(11,x))),IF(A1,XLOOKUP(A1,MMULT(MID(y,q,1)*1,TRANSPOSE(-1*ROUND((-((1+5^0.5)/2)^(19-q))/5^0.5,0))),REPLACE(y,1,FIND(1,y)-1,)),""))
```
## Explanation
```
=LET(q,SEQUENCE(1,18), # q = [1..18] horizontal
d,SEQUENCE(2^18-1), # d = [1..2^18-1] vertical
x,DEC2BIN(INT(d/2^9),9)&DEC2BIN(MOD(d,2^9),9), # x = 18 digit binary representations of d
y,FILTER(x,ISERROR(FIND(11,x))), # y = x with all items containing "11" removed
IF(A1, # if A1 <> 0 then
XLOOKUP(A1, # match A1 to
MMULT( # the matrix multiplication of
MID(y,q,1)*1, # the digits of y times
TRANSPOSE(-1*ROUND((-((1+5^0.5)/2)^(19-q))/5^0.5,0))),
# the first 18 digits if the nega-Fibonacci series
REPLACE(y,1,FIND(1,y)-1,)), # return the corresponding y with leading zeros removed
"")) # else ""
```
Lists all valid binary representations upto 18 digits and finds the match to the number in A1. Works for [-4180 .. 2584].
[Answer]
# [Python 3](https://docs.python.org/3/), 111 bytes
```
f=lambda x:x<0 or f(x-2)-f(x-1)
g=lambda a,n=0:a-sum(f(i)for i in range(n)if n>>i&1)and g(a,n+1)or bin(n)[2:-1]
```
[Try it online!](https://tio.run/##XY1BCsIwEEX3PcXQhcxgAkndBdOLiIuUNnHATktaoZ4@xoUbV3/x3uOv7/2xyKWU6J9hHsYAhzuuBpYMEQ/dkf6OpSb9eFDijQt6e80YkSlWlYEFcpA0oRBHkL7nk6UgIySswdlStQaWim@d0/Ze/jJtjbKGXANrZtmRVev7VuVpzZjqC1H5AA "Python 3 – Try It Online")
] |
[Question]
[
[Try it online!](https://tio.run/#) currently has 680 listed languages, all of which are searchable. For most of those languages, when searching for it, you don't have to enter the entire string. For example, entering `lega` results in just [05AB1E (legacy)](https://tio.run/#05ab1e) appearing, and entering `d+` results in only [Add++](https://tio.run/#addpp). However, for some languages, there is no such string that results in *only* that languages, e.g. `Jelly` returns both `Jelly` and `Jellyfish`
We will call the length of the shortest string required to return *only* a specific language on TIO the *TIO uniqueness* of that language. The TIO uniqueness of a language for which this is impossible is undefined. Note that TIO ignores case when searching, so `bri` results in [Brian & Chuck](https://tio.run/#brian-chuck) and `SOM` results in [Somme](https://tio.run/#somme).
You are to take the name of a programming language on Try it online!, exactly as spelt in the search function, and return that language's TIO uniqueness. If the language's TIO uniqueness is undefined, you may instead return any value which is not a positive integer (or could reasonably be interpreted as a positive integer). This value need not be consistent between such languages. Your program should handle all 680 languages currently on TIO.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, especially internet access. You may also not access the file system of TIO. Essentially, your program should work whether it's run on TIO or locally.
## Test cases
All test cases include the TIO uniqueness string in lowercase, as TIO is case insensitive in its search, and use 0 for undefined TIO uniquenesses
```
"Arcyóu" -> 1 ("ó")
"Befunge-98 (PyFunge)" -> 13 ("befunge-98 (p")
"Cauliflower" -> 3 ("cau")
"Shove" -> 3 ("hov")
"Funky" -> 0
",,," -> 2 (",,")
"Agony" -> 0
"Starry" -> 4 ("tarr")
"Add++" -> 2 ("d+")
"ATS2" -> 3 ("ts2")
"F# (.NET Core)" -> 5 ("f# (.")
"Dyvil" -> 2 ("yv")
"Python 3.8 (pre-release)" -> 2 ("3.")
```
The [full list of names](https://gist.github.com/cairdcoinheringaahing/a3a9bad0aae27415890d628c9f4a9f5e) and the [full list of test cases](https://gist.github.com/cairdcoinheringaahing/504bd72c948aa83e0817f400dc53aee3)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~819~~ 779 bytes
Returns `0` for undefined TIO uniqueness.
```
s=>(B=Buffer)('J .!> . 8 " . . 0 L"0"c$E"~~~="8"~1 Y$^"~~~j S$x"P S$;"7 @ Z G"/$8$A :%X!T%A G M$c*h"d"L!Q$8"~F$.$>"s$@"`"E 3 1$r"U">"8 F&~Y"="z"~Q"F"E"g |"R%m!c$"~N"~?$Q 1 ~W B$k"F ="d$> U"7%"""F"X%Y%s"S$E"<-O$b _"]"?$3 <$B i"0"~A"W">$6 L `"I%2"1"?$6"M "A _$2"A ="; T"t @$:"q"N i"["V&~= z"5"1 I!N"8"Z ` ~~B 4"1 }"#"2$."e P F ;!A"W$K G">$9$K"T M*W #"8 < 0"A ]""~~J Z""m"0"V!; ~~[ h+$2$~^"1"3$1"3 A$}"D"~i"9 H%N"~3 9 K"~4"; C%C"Q"3"/ X ^"D"9$4 4 /"7 J":$$0*o"~<"Z 9"T"I"~D$5"@ 1"j ". ~c"O$4"3 O ~X 6$K"I ~8 F d$T } 6"#"V"W";$I$0 H$R"x$"[$6 j i"U"~M L"K$~~h W$L O"0%="Z 4"F$X"6!?$;"4"M"~0$~1%r"k"6"K"^"2 5$V v"4"J"z 1"1 H$;$W"#">!i"."V"V$e"6$~~<*~C!~/"7 8!/ q$3"U /"."? t"Y"J!<$4 i"~P K"Y'.replace(/[.-~]/g,c=>'#'.repeat(B(c)[p=0]-44))[B(s).map(c=>p=(p*79^c)>>>0)|p%12635])[0]-32
```
[Try it online!](https://tio.run/##lVJrU9paFP1@f8XOcqcmKuGRiCAkCigtID4qPpDBSkN4KAoN4C1OPX@qP6E/zLu5czt1CnXmZpIzSc5ae6299rltPbbGftgfTSIPw3bw0nFfxq5n5N38tNMJQtNYLZOleWRRiiCr3DE6QAw@70Mp5SIFFac6X8@/bumUv@JY1gy2aJeu6D2inOIcbeuXWk3P0Xuqsr/WQxsH2gkLt8gWexjzLm6wTzbFOcQZPKSo@E7V4eIJ6gRF7KNL3/BRv9d8hjqE2uETojipC8rzHYrkos0enWFLBwR/qdf1MU7FZTZyxJ/pE5rYYZuynKe@@Fc5XMDjJB3QDUp6AnHZTqJKyNEnTsjqIkM1TGiXt/EFh8Jq4PydcukJm4hTSTuU3q/ohpTKkyN/nrGCBFsI6JiKlNFEgSuSgMdprqBG1bULWpHGshST8k1IYmW6Au7FzrmWkToN6q1zgtW1uLFZHsrxM/ag@kjTB126tilNFShHvBX0Ak5gI0qXdC2gNDvkUFSCL2ObObY2hMqKwTRqKEHt8SZ2KY5bgkXKxxE7Uv@I1CUlxV6JlERO1OYaPVNSWjmXgDJc4hh94I/4ymhIWrcSwxlUVc5AhZXq0QUf0BFiuitKDop8iaS2I@N3UIWKsYrrIe6QRAXXSNAmn9Oj7JXxJFbiUjnDF6LlaX1YonjOAZJSN7umCpqa95LSovSFbZxJZxZ2aII6ylpWeu1DHUsW9VUrDEaDlh8Y0YYVUc1od8N3vdWVf/8HrYmRN3yzMXJjzYjjmGYjb4xN6741MgQ1co3R2lb62jc9z4uZ30Z6PJG0N5tmQ9B24sUfPoyHg8AaDLtGx0Au9Gc/vk9BC5dpUjQqx9HAj@8w//qNlw8604duEEmnyDieFefvJl7RbOF9foUZLZYotKaDfmcw/DsIsUR5XsFvTRd5p73hY7DE8CueIBZ5YvJu9mde7Hf8xsbGMvRPfILmkEWZXHf48H9kTietMJz9cQCOyMwRS4Ta7fV1vOmvvb6EVjtNgN6MbzJOLIlvhQzrcL9GhWH436xf8zaF15lDFpl7s8f@4G2jsyXzOp5NesMHsq358QmDSBgMgtZYpH/RbFF7@Qc "JavaScript (Node.js) – Try It Online") (test cases)
[Try it online!](https://tio.run/##jVvbUhtJmr7vp0jKclvYlhAHY9w2uCWBQCBARsK07elDqiqlSlRVWa4DqNhuPcFG7M3eTMTu/dxPzMReT8e8yLzAPkLv//9VlVnQ7oiNsCHzy7/y@J8zueY3PLYjGSaNQDnit@nub/HuXr2z20mnUxGt1p8cs@bKHmuyHWbBT/jXYgOrZdm1A2u5XO5aO9ZynX2o/YC1azaqLawh/HxtvWTfso/s0Fqr7dTa7JvH362MH7fZITut2U9dy7EGK@9q8G2v1qztWXHtW@sn64BtsvVaZF1ae9YO6329/GDtWnfW8p3Vsw6sGfvZunjsr9g1a3lmLd/W3jG2zpZXrFObWz22azm1PXZpvXxsWUD/3eMPj2NrBLN80zivTdiP1vfW29ome1PrMAnzX7atK2uvts0G7Cer/3jDWofmbeuUWW32Y20Dfu5ar9nYSti3tW@sz9YZfPXJev/1cpfdWS@sddZfOYO1f2Q/seWyw7YA@cV6ZG3UmpZgQ9Zjr1dghNoJ7MBe7VXtxBqz06dX7BEs7A1rQfffW7Bjx@yjZfkwnfcrr6GfT8x9VtuoLX@A2WzW4D9r136x9q2ltF6xo8ew6k32ip1Yyy2YW/dx13pnbVpr7Dv2AxC9qm2xLbYGG39sfVOrtZ4qa/kGJvjKGlt9a7lfe2F9y9ata2Y12dK2zmtb0P85W37HtmF6fbaELWfMqY3ZL2wblvIeNuh1rV9rsaPahbWoWZ9gt65hGy6t5SnwwEltuXTZVW3Azq3W410Yacvq1b6ztlfewvFvWafWslVbrj@OrLm1bZ1YP1gb7EXtPbuBtmPrDqayDj2/rl3BWHsr0mrCiO9rwtqGft88XXZXlriWnZU19rm2aV3CyprWW5ZYH6zjlTewVmkth7AXH540IxF63Bb1tU/NxvL7tdlze3fvySPCBU/qnbq9@incbX3f2NpaXf3UqcerTZ@HdaAKd@vh05evfrBX9/b2Wqs/h4/XN7Y3X3y/@gmoNzd@i8TnVEai/mQaP1mF/rjTk54YZYFdb602EzVKIhnM6qvNOPRkUrf@FFirzamKDrjt1mO2u8f@7SvGPv34nMXPWfA922UxDJ1A41q9@XSVNfZY/U/Os9W11ddAZ6sgVp5oemoGHz9jT7D9CRSmMGWqY6VOtd1dFrC37Mn//s9//Ou//hN@PmHfsCf/@u9/f7IKff2y@lvrRbuzfsDqnphxO6OhNlndWhfMWv1qffAjR6SFpfZ5v2z9kSto3djvpfa8xDacKWIDrG9g3cNqzCee0FAM0OZm3uPmDY/Khs0baNjK8Zf5r1evysZXr6CRN2YR90uINwBqs6GALsaREOUcOAuxodPN@4BCg8ex8GEOeiybvrXtlRWNrBAiElX2A2WCkpR7XqbRJEXU4ax@eNYe672aBTzHw6SEoEyQ8@xZOYrzDJH948vRWEPXCM0cXgIzhwAVZMUCXGAlLG7h4qCCza5IJauLWCUqFHoSgGKjZ7vCl7GeCNQRHhyeD9j2DkxcBDL/CMfb3qFvpC2K8aj4NeuoSdkBVDXN6cCgPqGhyzsi4eUUJ1AucSgnksUhn7lUKpfoFgQV1oEKgakvA32UHmJjV7C2H4hYcpv1IuWzUxnE87IzP8DvgkToPYIyckuQTeVCdxVkSDYcsPp@xkFq2GUgbTBj5gRZ@oCi6wHjSLtCYT@gOFgkInCEUyERJYlzx6XP16Cst9q5KxuDWbDGQ09/BzVsCkNPxEI4eotj6u6iMzjQC4kmCEW2e8tLDskrG@Uw2UZOkf361xSxdcB@/SthgfKcbknnEafFtpT7KolLVEpER0NxIb/Tg8bEyrkYZazOQUUttrees4EM0oVeX53fo5ry2P8dHXYHLfcIZ7b9xf7s5/fIjq@@1CESXt/eIwz@cOBcSsejjRJJYtqsJAEtbFRIQqKfTkQ0k4GBU9r6q5Ny2Ns58tlClfUFasQOt@cuD5wSnLsExm5@WBM7/92Rya2MBetmNsgVG/MZ66QJu4JDvVJRLP6fVBvNlpFHXEpH5CqSEO7nSFD0BqWRKzyvFBWoxzlFEkgtUUlAmIhvuZafiRAETtNgJhqvNssOdb3e63T6q2XHUJ/ep6@fjnv32v0H7cOsh2UieYEqH7CwSrNd6YNswna19WWldb1FMy5bqmQ7Dya682CiO/cnsr5Z7WmnmJFM9OnAv@PUD/XWIYdMJFjt4rSpWIdfDVdPPGloonrsymliTC5U8wG6wEKz3GDhNIGWFw3ACZojEzvLUWKSfE7g3sxhRI/Pda9QIbKARxkbcH8C1qbLPTv10ljTSDp1pYpulPKmFfUMFZy0ytmY9DyU6YuEHQRVMZkolJ5OBBKVoZK8WTfa8eZeSz4SVMHP0TLv5yTSM8uEcgEGjR4sTH8og0khWKREJ7jMCcEwfQOr8uueV5wV4VOvJC9XWnQ6g7Vrqpm6P3adykewy3p/AS1pPHVjph3oaY9Cbms8IG0KeKL3EsoESRDVr1m3ahgnEbFEpGxbeVL7ITZNK52AWzNLtcRPSEV10gjsyOfUHEkaEXx315N3d@VW300rzINunIgyo0ywscvqtgeMuJpvTpdUtakktjGOUMEPOOx8rMe1@YTAuTBug81Ra9rAfqw@Hp8YqZgTaQBBpjHaN4RFDrCuPk@o5Sgc8ddsn99o35I5eUOk9M7aUCMwtrlTmVdMYOLCloIrrR0o5RGeenLqqdtc/vIPkP27IhKx8Q@pYwGcHBgM5RFk1/gwUM6hyC81m40VAsXUuG7TnAyk3gMOLOeP1bwhFHoHwhKLbFXZF2IJ6LTkZSqCM9HVHik5MAA7Do/MyLRrrtSCAUVE@uCnnKpAMShoD3rVyCTyfFcGAfdhAw4ND9qkSWy58LRdpOkeG9/dRqcX3CtfH5NHpqrrFbYqx8jX7Q76w5HB8rkpHwcdyFhPGgDqQF2nkT5nqCF43gHPF/z1S81s6Sr1AnJXkkKZIOCGVHvOtqINU9OpECNKfTCtzKD4sM14FWSKnz9/Xo73/HkxaxEkPFF68xOSe2qIbFk9S@IaFThSTwYqOXYjFgYjCVHKMVOmfVAQgJabhmXahitDhA5TFwKTinwjKQJlS0XUhx/0lyFyuP0uhYVol9H@jN9EPKtIQkRDRlmYGE0MtRyMk8pSM5LFR6zePDsYM5y59gFsRIvW9zKGSIxBEbYrlCUvbuMxMyC0f0fXh0AAjEsiQUPc@waHfcRk8QHxOBTsh92qarclFflPlV5o8iOj3WLi9XQi7WrYCNUCNh6VXBAUedk0kkbfQz3HQRnXh@2T7khz7dw2LSNPJa7RvvmwRUCAPoIKdECENWjdzxv3dZzgIJPu82keaSIyDQiJtPoEPZEQZKysQ7rTKdzYfQhOpzJ2l2WgsURyYUPo45UU3s/@z0nZ/jO1g@9q4mRBs5NRordL5qNCNJ5GhgwxZ6ZnP0OS887BoF0MlJfrjpqAEJutcah75Situh2FkrSPORrQ6FO92FxO9iNgmEY/YFcycNStPheJorZfiHrZU2wTmHBzgE6MExXcNjwOFYSKlMTKt49qj3/4@ml99cdn5bZ8i@12GLJnrGJl8Vtms0pbVTDzVkwp7Gc3UmvbDOeZx5Ctrw5mwnj7uS058ASqIa0jBWreg0GP1Rc722tfiK6mjL6SC6kPA4r00fvTRv9Cr9LDkQ98bsf3VDPUCSflZ/bEp3F9dS2LqWKRUjx@YQCRDKCSDMN11mq@MBzB7jWZXrpQjbQSwQpuia8SWfVpoZZ/n8hA@VU/AKrQUq@vmtC2jqSBV0mrCHLvDiJUoJiLIcZYNWKMvJS7CzCr0fnw8uxEu/kKFeHBuODcgzR0Ffh@bNMksTaRoMS3DL6FvVZOW9CeL0JPGfdGLKj7IjnBOtrFHWehYH3jDkxysohrFwEqgE15mQ3qgf5UOgwBHHm71x6MTELCw9Pt8SBR2gWY8oCwKIhvVZS4Bsfee@DhaDU4JZ7sieisfbavk28iog4OLg0ZOmC9/qlJpvnI@Xtv9vKJohIqpizjWKrgfmWjXAJWsCdwJCbGtk49SaDiiQm6wAXkOToJTJ5yQjNTJsqe5lTn3fagsa0zlo1tIlOGShEQzYSx6NEsx@Ym5QPlHDMJLSwXGESMsyn@1nwGUNEWgetUPyxKhg/pQHugSKVxZ6eKdvOi3R1ftM9MbpNIv2iJp4Ul7hWm8F4DCksvFSbemKY04TSwZWKkCsoFmiipU5pYy@F5Yb7yonamMnKmelmQad0xzfAQDrnU7tuM3OxDrhLDIAkyyGF7mPd6KHxDTTrvUCgD4BwOvQwEriDPyxCg43bzwOT4AAXaWZCCzOmjhBp2UH6svIIxKc@2R03e1NgOUqsoN4dwVqmJdKGSg7E2VhHP6aSvqWYUEh5GSt1kBqMVmMzWjDJbh7eFKFDeFb2@IzB68YAbDetyh@B4XmSGWrqy3oTPDtW04jd55PaWBJgSOUpnsdaTDBP1A4mOFzBwpVPiVVLYbnt0Wh6@y2OfulsIM50FIegkGl3t8oxQb9qAUHguAgZxHoMw60hw2IRxxKdTaRtqVCpHoO2ixj5sXIA6AExPpxrs43QjNC5HYsHLfDvpQI5ieaQmExPtuWpCmGN8d5e8iCPliziMKhbLJeOBnTqFH0TuAVIMY5E6qqEzlXgMKZ/pAFbRdNIZRFVlb1AhLDZbkca0uPyo@vkvyfX4kqbft0sV2HciqdchHZTxPgimU/EBoAaoDIrAsX82PrgAdWaiEdRw/YK5j4tf7QN9z8NR3K8/63QsxgPHC13FAz1upBPtZ17jOo8rdyXXdFdyzG84qx/vnxjn7drR@HkoAmhjO5rZguuisRCseodPwN05K9P6xJDBAxpsbV4bjm0@7GQUwt5EoOTmIqs42OEDsvdmHjd4hXIsCn@/lRdLg4RsjlUkUXoHFLLzceqBBms1t/RctjS6bhK7nESuJH5Ral6qVBq2dS/bFfSlRjEPesLqJyAJxq2Z5yDeR8w1ulagqnIQCrE5v1E6sX2DCudEaL6bC@S7E4mXGBBG0m/9/Zzi9hNPmMwIlBFSE/HPP8tGt/SE//lnQudaWc9p6BOVeObbOeUY51GkM69z5Ou5CVPmlJ30Nje1vvXQpRrwSQbCalwSj1JUA50jH0gTtXkS1cgAvFxmvFyPvFz64BR/UHr9lNtuJQUa0NXY4OxyNNSjIx8OlD2PfVkZnRIMAzXTHiz5BSTzg/NB93z/wJDSZFTlXk/FRHZ1cFHMPeWmUIcfx/2xPlSOfE4NKEgXIq6knUWAuzco2Pe0@KXZ0ke2LJbYrcwzEDY1zDXiU3LvlHsT5c0KF1LXLoPYBUXoVe636M7tlPsTbnrwCYqkGrTPDssuYptHoQoqA8VElriHRbIWJ@oiB14BgPfEWrnWkQysfwIxuV7yLW0ntkjbaEeKVE7b44G5CsrJbkQ1Rvf5DaEL6VcmviAsm4hB6UXmOIr6KUQfELYX3kju/BEui3y8TqtxQj3wgK64VhcebStsfy@SU500FNMoh9HKNDb2NWM00PRDFCVN2lX6Xk47V17F@EOV4Cgyhs2n4O4UDFtldWTUcqWot0tQ6uZUqSDWns0WEasgb4hcsL3a2LoERgGYQnQLuxEETYUVIvckofY0Fo2Xxo9@qcGNVkvnLjZaGt7Z1LSoh//xt@1Slfzjb0h0eZrnD2kZKS0DnWHPYLTcDwWrfWh02qO@viTN0FQF3BeeAJ/MqxhsYg8fLd8ZuIdaaUARoUoyL5CckHmqGR/KBPn5oGdC@kaoUPjPRIrvRZRB6QNXuYErXB2MCNzSs8IwnykBfB6ZIJbmppJ3KfhjY2jRfkaCBvps3DsGcwg/uybURyVxlvoTEd0WXEInh47jOY@NH6FI/s4npTqgWwybPKJz@FgFjZa2PI0WodfCTtgQJdlj9d6wu2riDqYJMPVy79YBLV3DztOS90jKLEhJgKKvbJv7jVA/NGig0Tnvct8zB4ZicG4n3NzTKApqzx2pU8/KoRz2uVucDxZutGcNFWw0sqWoU3WuWFVhK4r4zsERliYGUpQXPb84KTou8mCtr4o3ODk6OsoLw@qNF2X@KcwZ8og7yjZPAngOgiy5Ag/pqOJ0A1JpTXInme4UXcqoQYtcO9R2Sq4Rdv@UYCbt8ZGZBH4X0s2Zxih9PhSRZ5IVHiUrCHtR9JKX6zY45p5muhesJNuukG0Db0ph3xlnxcbnE0NXicCkD1xicgCVyAyGGz880mtyQ6LJYjAAmoh01xDsbjVVFVKedihNjB5KGkAaGxdKVMbD/uB8zOphTAXjJ4WxabwYSggRTVtE8wDtN1RGA4fEakNZmUNOtpDCSePKRNC@hEWENiziFTxIsIuocoYqlklUDbejHE00o8ZkzRAqvdhFCBVz/ZzQ7PHmS78TaFXrmBMwTi0lx4eR8NJK7one7ADoV/INEcXbAIaRYVuoEajwKrjelVyZyyV6W1Y2ja76FT/8Nm9JyvCmKBcPISijABUkelSef/gIq8W9UItKo3sGC4A4JwlNLJ7mx5XGruaslJzKYXp351W04x1tajbX6jUjBsGLQa0vwywnCqpP1UJKYwwr1yZhRgvPwH@RDhvhQy5NneVinkWGOaFMUKFDoOCaEvS6bhzS9ZzQLXNhLVOrd6mkL4E2cm1r2vvAVUNDQ6FXeI/i@H7rdXavdZgNs2rvlW83781ls4lPLCLRAJ4SPDZR3Gaz@snDCW/em/BmZUA0DmzzwYh1isfRnlfYClXa27dvS9fhLVTfaQb6jAz0LuVO4WhjMfrSyxN6f@bQqSCN9ju4E@dQBJ5hnHDjw6WUEgUTHSRf6pBISEMUQ1/A1A0DzEmFX7T3y0bplaXAUf79hEd@9YGSeMFDaa4@oYKY@MaREdrXnB1xF74hnMeGQaGM2AHeqOYDUXHT6PxN@sZOo1je6CGgTnBxK3EhzA032KUZtV2ImbnYjChlH5X5cwhXhh5o70RLQxx69BUYtNQzt9myGCiRAUa/O03tMe40TUMx8/HlhU5@iiT/cLEAvS1mshIkL1DxXhQZntZXUZElucBgLjFDz4mHLn79e@7N06u7vyNyfm6cfkr8X6hQq5SoQCpZdiwjBpptdlaMlZdNco@S2BdFSoX6oZcfF2kABv4gsF0eJH71jjahc6/Yk4jSSBdpMjPvYhM8iRF3tM9BF20NAuep4ZiYwrxR5k/w/cTvucymm4UR@BDcPMSgyKbriruKXiMfFs1696jfPTk4e6DyArpePYQISSZlU30WS/PekqLFw1QatT1LkZtjYLWt5oY5/q1mgdJ@joQphX8oeDFZqBGEfhBomLSApOz5SMTmRjEm@zEyghmTYI7E4o/7Rq6Kp3qbp7Sl@M7jvm2CmJlm4QY8NM/EUCNQarprEv02kVUeIEEZoNeP9C3ja6KAwCIUOo3j0kSb/eaged4clWiM2zWSjnmh4tALlZH0wL2/Lu/XKDi4JtwH00lrNfkd/KAPuLTNTYuklw05@cKQLnIQRBlTR77xBHza6/7IZCNlzIk4lgbBPtfW1nQCa40235s2fHDlpxnK7u9yvw1kHTAFgcMjB981108HScWIebgxsW@eL8T0xGQUgJI1B08vSkdn@MQETqtblEwnW/SJuvW5TsPf0sCUHKqfKgfVl14vVE1jh@6jnMo7PmUaR0Eah7JiwZAlRviSxNwy0kD49Mw8DxHOvaeyp/3h6DkbDfunpidf5pw4F3EoIG5gqHzKa9nBgwjYzVVBqIyNiEOa5ju8BtAWFLX1CP9CIjKRd0qJhvzyvMsTvalzciwJz2f@gp7K2HQ19rRys/J0L6eLIu0MJ/mDLwAXWoISSs2MEhHY0pwmXaqN4MRNlj@mq6g4iQrdkETc3P9z9DxH6SSeS32UExL71Bf0cq/shZIMoxSCnDyPVcm3RD4v2/JrAf0XCPMVaoimlZeCMaUmRrdG8m9zZXArp1qibukaG5SxXgYUq@q5cHy0bsYextw@N/fzihA/lIrVp3g/R9cllffaaYUARBdvdyAMNwTSzwniyuN9msQY9FmHz8yZJzwffiHNiS2Q4ca2obGRWxLbZHMTSsyNBWiNduHsUgXEI4agJIgxZQ@8csQjf5rqy3F/Sn8/UHlPl7jkTI1dcMO5yUPSw4@xa24wXbrBBCRJDYQKYSxNqieha5OxDLrm8AO6KwEvI@v0NJdMC8irhJoZXTmPzZuKhKRh3B8ZgBativcR45RumcpU8@9ei@cvbOkgLtpno@5FfzjWTlb@0Hv8Rad1HU1DElXfSxvChw@iW@SclY1EKlElFD5Yq1KX5kEPlHPSWcXbmM1yDGMuPBBujAQ5d@Mo9cP7722SiDgxjRLv17842s36C4LZQ8sJAC461fk80jn0SPgyAH4B7ao5IKXHdZfBHz4nD6rbY@i@tD1BdXvwz0zMQ1@sEOjdy/qm9JTk0qT70kARgE@Uyr@eynHkkcsoLjwr2luyh@9Z/aZiN29IIgHsnarEuLJTQisf39BN6ft2EV0Uj@c6PAa9Qa8AHrwFIBnKnwK8F9EEUw7FrYGpmkwZVHLCWETm3Qw97vrCSPpdQTGI/2Wy9x2Tr7yZEE0SZ2bhSbEbGKI3pTK0tNKRvrS8Qea4EhNjDK/4VcTDsLjtpvux2@IPkK4wpT/lnsfAYhttJhgSXLkyMvk2EmOAwHhGcfH6ncwQlO@1bFRaNvIWUGfVl@IuLeZKOnlcT954jghwWerHyg2e5EEsisETain/EOBKARtWniDeUqbsCsItjVCcehvr65Nb2hEQulSHDbcob1fND802@IdHzQPwE8@auhHZYHEgdEpnQX8lsgDzELoGw/340O60B9qFmxDXfeATOtYybp5QTjmrvDXMCOmwejax9ZlMkKeyVN/8ZTjFj/oS4A4D0I87req90B1K4kcRuplWPnc404/SJHFQG9/Ntem4Q7fmo5IO/hGQBlEqP8b6MO5gev8H "JavaScript (Node.js) – Try It Online") (all languages)
### How?
There are only \$10\$ distinct TIO uniqueness values, ranging from \$0\$ to \$13\$. Besides, more than 50% of the languages have a TIO uniqueness of \$3\$.
```
uniq. | count | ratio
-------+-------+--------
0 | 97 | 14.24%
1 | 12 | 1.76%
2 | 140 | 20.56%
**3** | **357** | **52.42%**
4 | 56 | 8.22%
5 | 11 | 1.62%
6 | 2 | 0.29%
10 | 4 | 0.59%
11 | 1 | 0.15%
13 | 1 | 0.15%
```
We need:
* a function \$H\_0\$ that turns the language name \$s\$ into an integer \$H\_0(s)\$
* a function \$H\_1\$ and a corresponding lookup table \$T\$ so that the TIO uniqueness of the language is \$T[H\_1(H\_0(s))]\$
It seems unlikely to find some simple functions \$H\_0\$ and \$H\_1\$ that would directly lead to a small lookup table. But if we use \$3\$ (the most common uniqueness) as the padding value for unused slots, the table is going to contain a lot of \$3\$'s.
So our strategy is to use:
* the first 14 printable ASCII characters (32 to 45, i.e. to `-`) to encode the actual uniqueness values other than \$3\$
* all other printable characters (46 to 126, i.e. `.` to `~`) to encode runs of 2 to 82 consecutive \$3\$'s
Conveniently, the single quote `'` (ASCII code 39) will never appear in the table because no language has a uniqueness of 7. So we can use it as our string delimiter and safely use `"` and ``` in the table without having to escape them.
We now need to find \$H\_0\$ and \$H\_1\$ so that the distribution of actual uniqueness values among the \$3\$'s leads to the smallest table with this simple compression scheme.
After some brute-forcing, it turns out that the following functions work reasonably well:
* `Buffer(s).reduce((p, c) => p * 79 ^ c) >>> 0` (actually implemented with a `.map()`)
* `% 12635`
[Answer]
# [Haskell](https://www.haskell.org/), 750 bytes
```
(("K%J#3#=#5##2'#5#3#L%5#5'2';#J#[%O'%_%8#d#B'70_'%t%7#e%]%7%D%Zq'G#Z3#5#4#e#8%2#<%6#7%9%R%k%9%5)4%>%ZX%u(D'<'@#Zj'3#U%W%2(~'4#]'M'6%R#2#5%<#D%Z%c'U#D#9%I':#a'J$=%ZY%`%2#3%R%3%C-Z_%3%;($I#A%Q%N#G'æ%3'v#d'¨%G#U#E#B'[%>#B%5%7$f%Z3#`'8#ZX'5%6#d%E-Y%r%B#@#;%¶#2#Zl%Ò%f%<%G%q-;'8#Q'k$_%l%[%Z#3'6$7'y#9%¢%N%f#^'>#S#C'2'k%5%o%Z_%F'P#c%;']#Zu'?#6%Zs#a'>#I%I%Į'B#B%B'9%;%2%O%Q#9%]%F%x#?#g#T%N'ª%V%B%j%I#3%M%u%Z3'7#T%%ZW#Ze#5%U%7#V#P#N%D%8#V%9%`(W%W';#g$|%a(5#K#6$3%~##A._#7%M%3#2#5#a%9'C%c%Z%V%V$;#?%#U'2%@$7%<%?%3%ě%G'c'4%J#Y%L#?%8#4%q%B'%K'=%B%L%E#A#9%6(@'D%2(Z[#8-D%V'L'?%i%A'¨%['m(3(@#>$U%M)I(e#5(;%w%J'o%2'T%H%E$[#9$8%8'5%2#=%y%>'k#P%4#?%#>#E%4#ZV'C%4#Q">>=(\i->[i-35|i<49]++([1..i-49]>>[3])).e)!!).foldr(\y a->mod(1323*a+(e y))9960)0
e=fromEnum
```
[Try it online!](https://tio.run/##hVlbd9tIcn7vXwEP1AtybNI2qevals2rRIk3E5Q4psfraQJNsk0ADeMiET5z5kfkLSdvecjZk4e85GR/gGfztzL5CqQuHs0mPmJVdQFodFfX5St4KeKV9Lzf5q9@/K1Q@O6cn5lV85W5Z5oVC7RqdvmeuWdVrBfmmfmeDyz@kR@arlm3Dp59tHjCD0zJP/AD3uTTz9aJOa3iqV1Tmoe8Yr7k@@YBP@IjvgLdK@7yYz79gaeFpvXSemNOP1lV84JPeKXwi7VrfrB61j4fmRVzj780MR93rAuzaR7xjvVnU1hnO6/49B3/CRNXMWWVN0rTj2AvCjsds8bf8r55Yv36b7xqXZmu9fWv/MS8MFtY6Xt@bNb5Hj/YmXOs7yfr0Jz@YO1hcS5vld7xiNfNN@YL/vVvePfU47/@E5/zl/yEfy69wL1vrdXOR@7x93xqVq39nQMrw5q@/ivv87n5F@vYtM0GDLTCGzTHitrW0HT4C@uDOU2t1@Y@n8ZY/bHZ4R3@9/@w6lhL3TriL3iFD/hbTPWBt/nafG0uzDHvW1//nV/yOv/EO9hmj6dYsnWAK3w6MacStrmAzS/NodmHzQ/NS1j2p8KET3BCi52fuSjsmefm/k6V/2KatfJHHECPV8mopuBHVoM7MOwlv9x5Yb7m5oVV4W92DrDb17Dk3/@Fn1iOtQsneMe7uH5o7vLPWC0/t15hTV3eMmtY8H7hjdXEqU3fm4elJr@0utZrrniNjP7e8gvVwhvzeOeC94qdAlZceMGv@ZmlecUa81Pe2nlvHu0c8kMcQcV8xTN@bK3MId@lBR2bLQjTSyx013z73fHxq8KPqnT8XpWqez@rl7tHHx4/Lrx/Xi6rEuTj4/fVD8ViWRYfPSqW59pzo8KPmSFKx752C8@rler34nFBGlmxeHS0/6z4jMlX80j7rSD1f/OFCl6pIJGRcJKdNPBUIOOyL0JjUc5l43opI8kM/FsYsfHKcHTgiOR9/MT4zigdG989MeKlvjZ2jLkRf/jt2V6t/rxlFDy5EE5WZM@7HwWR2qDDKs126qxYpcsqsZh5klWrrHolIrbLDtjREROlRSR8VjOGUkTGOJKS1eoN@pVEHEsfj0Ss5jiPHoHKRIMmqfC8jNVcYRRO@rVxkcQwAXUfP2a15tmFPWa1hStAdIAbl1K4RFNlFGSsEx1KPOM5S@mrGM91TwZdY/8Qs8lA5ZeUIzfU@JNR17Ot3OtCCJeiLhOxkWYySZQRh2KxJClX0nZrXuqrgI2X0qj5MKgSjtGG@Y2eCmJchu2ZCLK5WrPasGsUmpnw9MK4CJSjXVrBPWXDgyGU862ytU5k4Ep3q3W/COWLp5C3imARPBWhh1EYejKWEgYY1bstVouc5bXIbniFhOzX/0zBA3gRLB87SjV1ErOaPZQj9QM0@TlkRkHAAdb7u0@MrgrSdfHelbmI/X90beE4/@jS2eT/eC54eG1sY8FJInB0rJbOZLSAu7La5JyJtWZ14ayWInAhxEs2c1hdJdcqlkYjc3CAxlgsjHqaGBORGRMdxfL/vcGolJ@xuoSDggQ5sZeoGiQlgVqBy/harMHnabCQpaPqPdEotOv1TvEbTW/c/p1mmLVJvqfcf3DbwQPN4YPJD@9PpRL64e8s9UM2U4mz3FCjAFZaFm9G8VLNkyx/ogHbLRBtJMIet9ZhdQ@GxYOeWNGNgYgyoyv8GQKwITwn9dKY1bWmnzcn959p2L@uE6MV5AdUR6JZZuS3V8/vBrnki4S48rz8NhWU2njNRpzlx5hLmHmja3v5hkjMX5UrF3jvvaeNQi6fYtXFjdrTV9vp7VA4uUivVSJAgDeWm4m042hPsXo6Q9JZpDjzNELsfE5xf/rlS1t9@XLrMJTUZJSxhlFwPJitSBIcPedJzgUWDeM1xEoicTgwlFEYj8/pSnAlYrDIhS09ErSHdTTFFd0eRToBix3h0jBZYlHIvxBTT809fY0jaiA9YwYJM@LCEvsiGvmgcs42B4lMviAxlF5@0dH0rqXEXnMqXaNBkusiGzeWKmSNDjJHTwfagHCbfbFgFQTC14FxAqM4ao1pzhASSExEKDAa3c7QZg3t011dFWMuT39KUUMagzqSK/L0BebRODdQ7CbFFvV8LqXtRCpMjOffDivsyZMn@XwySESio40cOYr2oANX0fPBlVyDaRckkph5MGGNx4/vjoTkzaEM3zHnbYrJYLVIZGS1KAsTeBV4nNCsplEo91tjg@Yq5sNLFaPUGBDx9lBtbPGNvrMtoupK/u6e3IwQnD/U5kkEKrvLGulMOXlBIwn7gdNl80jRMaURIq0wrJ037OLNyPZ0gvBt4H4EqUZ0NVmzwppijlLXFFECgrBxHdZE2ZurePkLJAflwQP3fvZ/xh0SyQ1MRQmeQVVNI@YuWHNQb3VrW4aiomc4qSJralfHrAkLu3C7OSRst9QJjIkKXH3NmptDA0diXjEpsB0mG@zRG3OH/@VP3xeKHx8z6YSh8di4iZKb4e0JNbMrhadc1oLnspYn6eRZq9s2CuvD/af3q0DLU2sV4dplr9QZsZYvnHjjdK2Nv@B5X39SG5rjC59iIR9SfTWelffuRhupASli0teJyvNKi6RA@3noFQpFvBY4CUZrReRcBCTyXWMrMWvZg@FF/5y1xjXWSsOlRmYxqnfiLpO0u9Y69PIXbou3Ub9JY8Y4C6XRoSuRaLA55ag2/AqO36517RYGQaJ9sCiIr3WULFkbAb4Gjfq1flOzduuCtTs9AKDjl8eMjp21FXADVr/lCKq2p0LkfXAt4LjEZ8jmrK0Rye1Bo9Yt7R9hhOl0tJAJMeQJYgAsRFExFnPixXwYIYEWTrYSqdJI0byjWmM8qvVZ@9ugam9DAFIqkVZRrRyV0BIhJFq5JKyyDaX1ZkHmsROhBIhOsLmT2pCdSB9jqdmJl8HAW0aljBaG@l9kiyCFqRN2gqvaI4uAzbd@eoK1pig34HEMqnyStb7K2Anwxck1Ge0Uzh53cdKQ8kbxhhvPyxXsWc8ppm90VHxP00VcZF1FGSGRxs1jy5rdw31rCUKZBr51Krx5CfVmJQMU0MhQgXEqxVUG@Cvmc@WwU3hDVGpiYQGdHHLNraewU7kWOaw91bMZfO8U0RmB@jIOI3JzusHdBLyRRySUxjCWqatLt@CKdpaKBRaVokJjuylg6WnGOkyJBeuQ03fcSMWsgxNyKRRVsGKd/rg1gpewjmZn7KzW6rJPn9nZmp2V0lnGzgiFn4kr4PKzJgrdRhyEMsDQONwothm@UAd49ox@Dnfv60lT/hR/q7RDLCKC66xk9u2VS5pWUvrMae74ZxojFEuBQN/dSs8B5G50e7fS/q10wM6NwjlsXSSB4PMqlzT2sRJXqDHncsHOFcFpFJic4wZPovSe65n8739WpQaklQBJUHvZKopCtsJyvGo1YV0xy3A8CNwuFcyuwoq7yGAGMhhpjB6Rei4BHxFq6vYv7CHramcV@4oe1ItNwuoOuo1BswUF8lF3MGlhilTQzyiAnHXQEuUDMv1IxoTvuhnrsd4u205O6Q7yiog3097iTkAXEi/hNh4CvweUJ0Ajpbu1/gkkwJIopKrTAzKhoGITEKTYW5dCiOMSYjRBXSvm9yknZr3auIvBlcxLW0@s4aBg2Ux281zUQ@5FfaMA76kNuoTgIQ8AjUMKZDtS8zlJ5NqlSpMhqytAK2hWmpIyJIAnTIVgoMlzd8GbtQ42yZrEaImgghAFiAvkHqMBKOWQh/d0GsvSwdFWqDx7VtmKh1X29b/2We@iB5TToxznsd47/JXqNbvTYEBHEkgxNrybsOojDWWsT3Clr1apC@qzvsxJmsARNOsv9TJYymXE@hhoCZuRmLxNkULGeQPeH7fPEBGgjSLrpz4anmva50DECM3BLD/FAbQ6KD07gPRJOokxpEPy0B8M8dRGRwX7Dqp@o8urL6Cv8EuhYoOG8D02cBLCogPgUzZY@vQzripsAGPrAQAMOd8AWY4S5WB0DhmOuPkKwAb2KRve4vihiISrHeIw8RKdcIxch7R4o4CTkKyengzZNwsf1sanLMyBPhvKyEMRzdnelmE3SJIAUflwf8tgLSWdL/C74VKjm18T1zJjw1PMv8zQSAs2RBjleGGoUOOGClEw7HQHY6MQxrlQvBmPhgplBEP4ylDD8kNFT62VdFNsOcQ@KBUPdawSHAIJSTenN/lpHWKACQi2b1rHOzGvimwYSS91c@5T8QQPIzIZugJ0TIWGEiiYNyN70skHVDU3LO9RhyYbEtwmsi1zEJGjwOIlVogGJg@RYUa7pb4hBgvyDy5DwsPDDEGsXMOmzyKki8g2Wf5b5gSven4jVG4FLDCXivc0Hdhi@EB79kAzzIbZ7bh6K5RRTcNIlmAYKWJ5d8eDd1V/PwcMlOS5K0YFef36NXtrsrepcEc5jR7006S1iQLgwIlRfjGgT2O/v3HERpgXJhnVmhCB5kYIce3fq8wjESr0NyP5Z1dFFGCw6ggbINZCF7Sh2OdIOmkUqyu618UPxzKSI7lAN0NtHTL2EC0fsiJExEfqAaKRFFChOixXtgPMN74Y9TFar@GqEoUcfj8iDBBhNVQ3Enry178hlY4GgyF0YQZCsHIE51n0twzHOaICPkoD5aBpd4CiEj/vlkbk56M0oQ8DtnA3UW2LVYqd2pk/o@b0ng1sBLCgrvLLjSM1TjuN81b/ZniCzK6S7QjZJ1ZFdpKiQ2IxAPFuuYLtQWK2zEn48CRsVBBkZdRPW8ZoTGwcii3XD@6L51gOtb/beLCXgQhZDhIbGNAXgRfmY0hIxyG9rNwpd8uDss1sgI05qIfM@invC2zlI5byN7AORAXYulWuieOICBT4WF3HBj6yVazY06dPsTBAPV@7ap4RDLtnqATuIyLX6FHP3U3IqWMf/agdwLmwqz41zrvw@K2EqQN97QM72IQLCEi75BnFm3E9B/Xu7dgO0jiEdW3qnFn@3cO993Wth479iWEPO70imWkF@CiRkw1yiG3HdIcS7RA1lNlvCd0y@3OKOosSmIcaECzcJBcx//eEtTFAq0oMxkGr4yi6F6AhZnECY6JZuGZ2OosBTcHR1yvaVop8voEalKjy4QbAPsIgynsi@xpHaF@reULOF9954Cb@2Vg4AxC03OgH5tRU5PC5eKvDkRE8R@3LdTF9pIWL1AV1nWOAEjZ2PJY4gG1jieOtJRsOy8ZI14Dj1AO7QPeRP0/xyJLCbbxEGhUuOJoakCRlY4X6P1ZBAztDsGb1ds48KjtjdK/jjs3GGq9LCbTfYL7ffZ6kHspujDrDMRs/zF13qvuf/sZkzEWeM@5EhT4fowVFMThhWFqzwO6i1A@3EYK1JN6vf8U@stuoSTcI5wL9agQHcyE9WMid6v5C6GM2XnAReBswdwHMcxHQV4T8/wEuophSxaVRuKK4AW/3dIIEdpmrayO2/cxSB9hxjLyLvN9LXspoRmU3u5MIo2AQyyj5o4c3necfXLisN0ifxFm@HKqTZUW32l02kbO7mJmISSTCkDo/@rQ/IeA6FyjkiEX4z2SpopwilKKYvnXeyRWS4UT558eJclFTJ6j2LsoiYKCFajWhT60TDVNSNzMBPGLXMeA1zieN2aT8rlxDfjott5Cn@mW2bkmHreHM4ZK9q9Vr3S57J2a0K5bRB6C6UchmgHZZGrJplU0Pn@VofSrDZRaxqVqwLyuPTdF002d0No2X/@PMPbGIfys5Yfi/ "Haskell – Try It Online")
After Arnauld added an explanation for [his answer](https://codegolf.stackexchange.com/a/222636/82619), it looks like my answer was just a Haskell port of his. Here are the relevant differences:
* lenghts from \$0\$ to \$13\$ are encoded with character points \$35\$ to \$48\$, in order to avoid double quotes `"`;
* runs of consecutives \$3\$'s are encoded with character points \$49\$ to \$\infty\$;
* I used \$1323\$ in \$H\_0\$ and \$9960\$ in \$H\_1\$ (which should result in a slightly smaller lookup table).
] |
[Question]
[
Input
```
_ _ _ _ _ _ _ _
| _| _||_||_ |_ ||_||_|| |
||_ _| | _||_| ||_| _||_|
```
output
```
1234567890
```
**Rules**
Code golf - shortest code wins.
Input will be given as a 3-line string with each line separated by a newline, or as 3 separate strings. Each line is guaranteed to be a multiple of 3 characters long with no additional whitespace, and all lines will be the same length.
Each digit is represented as a 3x3 block of characters as above. Note that the `1` digit has two leading spaces in order to fill the 3x3 block.
[Answer]
# JavaScript (ES6), ~~105~~ 104 bytes
Takes input as an array of 3 strings. Returns an array of digit characters.
```
a=>a.map(s=>s.match(/.../g).map(([a,b,c],n)=>'3789465021'[(o[n]=~~o[n]+[++a|7*++b^44*++c])%13]),o=[])[2]
```
[Try it online!](https://tio.run/##ZY5NCsIwEIX3OUUoSBMTU23r3yK9SIgSY1sVTcSKq9Cr1yYtIjo8mDfDx5u5qJdq9ON8f86MPZZdxTvFC8Vu6o4aXjS9eeoTShhjSY3DGglFD1RLajAv4my92ear5TxdxAJZYSRvW9@IIES59ZSQwy7P@6YlniwyianlQmKRyk5b09hrya62RhUSIIJ97YM@5ksR9YSDey/nBZ1HB@8cdCPhtz0ER24gBh8BiQG72LNBcYwxAP8/fD0Q8kLykOHncHUM/0nr3g "JavaScript (Node.js) – Try It Online")
## How?
### Finding a concise way to process the input
A common trick to turn an input string into an identifier is to use `parseInt()`. But it only works with alphanumeric strings and is therefore pointless here. Other than that, JS is not very good at processing ASCII codes in few bytes, so we'd better find another trick.
We can notice that each digit in this font can still be uniquely identified if we replace each character with a binary value: \$1\$ for *space*, \$0\$ for *not space*:
```
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
-----+-----+-----+-----+-----+-----+-----+-----+-----+-----
_ | | _ | _ | | _ | _ | _ | _ | _
| | | | | _| | _| | |_| | |_ | |_ | | | |_| | |_|
|_| | | | |_ | _| | | | _| | |_| | | | |_| | _|
-----+-----+-----+-----+-----+-----+-----+-----+-----+-----
101 | 111 | 101 | 101 | 111 | 101 | 101 | 101 | 101 | 101
010 | 110 | 100 | 100 | 000 | 001 | 001 | 110 | 000 | 000
000 | 110 | 001 | 100 | 110 | 100 | 000 | 110 | 000 | 100
```
That looks like a good golfing start: it means that we can abuse the fact that a space is coerced to \$0\$ and can be turned into a \$1\$ by applying the pre-increment operator to it, while it will result in `NaN` for the other characters.
Hence the idea to implement something along these lines:
```
s.match(/.../g) // split each line into groups of 3 characters
.map(([a, b, c], n) => // for each group (a, b, c) of characters at position n:
??? // do some bitwise magic with ++a, ++b and ++c
// and use it to update an identifier for the n-th digit
) // end of map()
```
### Bitwise magic
After some experiments and brute-forcing, it turned out that a pretty short and efficient formula is:
```
o[n] = ~~o[n] + [++a | 7 * ++b ^ 44 * ++c]
```
*Step-by-step example:*
* The 1st line of a `"0"` is `" _ "`. Therefore, we have `++a -> 1`, `++b -> NaN` and `++c -> 1`.
So, `++a | 7 * ++b ^ 44 * ++c` evaluates to `1 | 7 * NaN ^ 44 * 1`, which is \$45\$.
Because `o[n]` is initially undefined, `~~o[n]` evaluates to \$0\$. And because \$45\$ is coerced to a string, `o[n]` is updated to `"045"`.
* The 2nd line of a `"0"` is `"| |"`. This time, we have `++a -> NaN`, `++b -> 1` and `++c -> NaN`. The bitwise expression evaluates to \$7\$ and `o[n]` is updated to `"457"`. (Note that the leading `0` is thrown away by `~~o[n]`.)
* The 3rd line of a `"0"` is `"|_|"`, leading to `++a -> NaN`, `++b -> NaN` and `++c -> NaN`. The bitwise expression evaluates to \$0\$ and the final value of `o[n]` is `"4570"`.
### Minimal perfect hash function
Of course, the parameters of the bitwise formula were not chosen at random (well ... at least no completely): by coercing the final identifier of a digit back to an integer and applying a modulo \$13\$, we get a unique value in \$[0..9]\$.
The following table summarizes the results for all digits:
```
digit | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
--------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------
ID | 4570 | 4377 | 45144 | 4511 | 4307 | 45441 | 45440 | 4577 | 4500 | 4501
--------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------
mod 13 | 7 | 9 | 8 | 0 | 4 | 6 | 5 | 1 | 2 | 3
```
Hence the 10-byte lookup table: `'3789465021'`.
[Answer]
# [J](http://jsoftware.com/), 55 bytes
```
(0 3,:3 3)(6 7 8 11 4 2 13 14 5 9 i.15|[:#.@,' '&=);.3]
```
[Try it online!](https://tio.run/##TYzLCsIwEEX3@YqDgmmghqZpfaQUBMGVK7dSsrAWdeMP5N9j04o4nIE73MO84kLLgdYhySlw4641x8v5FLMCmzuLVdmGLTuMoaLEWExFzZ6nNnW4uqU@5BK5alWjbReV6FtN1jXalyr9LATj@Ilf@GOsAz4REoTkzTkEgpgOksFXmus5CyXE/fZ4M9DHDw "J – Try It Online")
J has a primitive `;.3` called [Subarrays](https://code.jsoftware.com/wiki/Vocabulary/semidot3#dyadic) that let's you process a multi-dimensional "sliding window". Here we have a 3x3 window moving 3 steps to the right each time, which grabs exactly 1 digit.
We convert each 3x3 matrix to a boolean mask `' '&=`, flatten it `,`, and convert that binary number to decimal `#.`. After a little experimenting, I found that modding it by 15 `15|` returned a unique list of small numbers, and we just find the index within that.
More brute forcing could likely find an even more efficient encoding.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
€S3δôøðQε˜JC15%•#/ι®ˆ¼•sè
```
Input as a list of lines, output as a list of digits. If we could take the input as a 2D list of characters, the first 2 bytes can be removed.
[Try it online.](https://tio.run/##yy9OTMpM/f8/@NC2QwuNz205vOXwjsMbAs9tPT3Hy9nQVPVRwyJl/XM7D6073XZoD5BTfHjF//9KSkoKQBAPRnAGEuJSUKhRiAehGhBSqAGpg7BrahRquMAcBZAKBagiiDSEDTQeAA)
**Explanation:**
```
€S # Convert each line in the (implicit) input-list of strings to
# an inner list of characters
δ # Convert each inner list of characters to:
3 ô # Split it into blocks of size 3
ø # Zip/transpose; swapping rows/columns
ðQ # Check which characters are spaces (1 if truthy; 0 if falsey)
ε # Map each 3x3 block to:
˜ # Flatten it to a single list
J # Join it together to a single string
C # Convert it from binary to an integer
15% # Take modulo-15
•#/ι®ˆ¼• # Push compressed integer 105048012903067
s # Swap to take the earlier integer
è # And (0-based) index it into this to get the resulting digit
# (after the map, the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•#/ι®ˆ¼•` is `105048012903067` (NOTE: the leading `1` and all the `0`s except for the 3rd (7th digit) are fillers.
[Answer]
# [Python 3](https://docs.python.org/3/), 105 bytes
```
f=lambda p,q,r:p and'5498136207'[int(''.join(map(str,p[:2]+q[:3]+r[:2])))%49%11]+f(p[3:],q[3:],r[3:])or''
```
[Try it online!](https://tio.run/##XYzNCoMwEITvfYq9lE0wlGrsj0KfJASJiNRSY0y9FPLuqatSSodh@GBn1r2n@2BljO3tafq6MeDEKHzpwNgGT3lxTeU5O15QdXZiiIfH0FnWG8dekxdOlZlORlVKnXhizvk@L/ZpqpOWOSVLLcYlPSUfPGJ0nl61rEaYVS3@wo9R7GATVQNU5ECGQJuVQ4DwX6Xz3IZtsFZXRs7jBw "Python 3 – Try It Online")
Takes input as three bytestrings. It considers the following sections in a digit, which gives a unique combination:
```
_ 12
|_ => 345
_| 67
```
In this order, the base-10 ascii values for each character are converted into a string, concatenated, and converted back into an integer. In the example above this would be `'32'+'95'+'124'+'95'+'32'+'32'+'95' => 329512495323295`. This integer is reduced with a double modulo `%49%11`. This results in a unique value from `0` to `9` for each digit, hence the string map `'5498136207'`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes
```
E³SF÷L賫J⊕׳ι¹⊞υ÷⌕”{“→✂⌕Q¤αA?=¹⧴Zb⁻e⁵ηπ⪫Q¡”⁺KK⪫KMω⁹»⎚⪫υω
```
[Try it online!](https://tio.run/##TVDBisMgED3Xrxh6GiF7KD0tPe6y0LKFwPYuIXEbaaKp0e5h3W93HROhosPz@ebxxrZvbGuaIcbaKu3w3Ey4r@CoJ@@@XKKuyDk/sG9jAY/avauH6iR@Sn11Pd55BXvO4ZdtTn6cLiZJWitHqZ3s8KJGOZOb4km3Sy6b2s89evIvTh9Kd7gFEBCCCAHSylUQAyIsIAhilqdADNUCiBRPXcSUrrCtoB78jLWUN0wxTkbpfDkbYyUxP5zivdKUf@xtkI3FBJfvyGqfNYcYc4Qc5BmUzQJQupx5zRCWzPnK0oF1klVXGMLx5TH8Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
E³S
```
Copy the three lines of input to the canvas.
```
F÷L賫
```
Loop over the digits...
```
J⊕׳ι¹
```
... jump to the middle of the digit...
```
⊞υ÷⌕”{“→✂⌕Q¤αA?=¹⧴Zb⁻e⁵ηπ⪫Q¡”⁺KK⪫KMω⁹
```
... and concatenate the nine characters of the digit and look it up in a compressed string, dividing the index by 9.
```
»⎚⪫υω
```
Clear the canvas and output the detected digits.
[Answer]
# [PHP](https://php.net/), ~~104~~ 102 bytes
-2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
```
for(;!$i||$d&&print'6930274581'[crc32($d)%63%10];$i++)for($d=0;$a=$argv[++$$i];$d.=substr($a,$i*3,3));
```
[Try it online!](https://tio.run/##VYvdDoIwDIVfpSblZ44YYIqaSXwQYhZkUXejy0Cv@u5zU7mw@dqc9pzam/WHow3z8nC5XKAhQp2m1pn7lDV7Udbb9WZXZd3gBlHnqFnSiKQqTxIN5yx@oW5LiX2Lvbu@Os4RTXD1qh2f53EKfl@gWYpCMCa996AgloI/MeMJCAIqQhGgmPtq8qE/C4D65eZL1G8 "PHP – Try It Online")
Takes input as 3 separate strings.
### How?
I create a single line string for each digit with a leading "0" (10 in total for each digit), this is basically 3 lines of 3 characters for each digit concatenated to each other without new lines and a "0" at start of them. For string of each digit I get the cyclic redundancy checksum polynomial of 32-bit lengths ([crc32](https://www.php.net/manual/en/function.crc32.php)) and then do a mod 63 and mod 10 on it to get unique values for each digit. Then using the unique values and a mapping I simply output the actual digit. Look at the table below for a visual demonstration:
```
| Digit | Single line string | CRC32 | %63 | %10 |
|-------|--------------------|------------|-----|-----|
| 0 | "0 _ | ||_|" | 4018184249 | 23 | 3 |
| 1 | "0 | |" | 750606692 | 59 | 9 |
| 2 | "0 _ _||_ " | 2375221876 | 34 | 4 |
| 3 | "0 _ _| _|" | 2330511487 | 52 | 2 |
| 4 | "0 |_| |" | 745793270 | 26 | 6 |
| 5 | "0 _ |_ _|" | 1887416553 | 57 | 7 |
| 6 | "0 _ |_ |_|" | 366569277 | 60 | 0 |
| 7 | "0 _ | |" | 1506663000 | 45 | 5 |
| 8 | "0 _ |_||_|" | 2483214119 | 8 | 8 |
| 9 | "0 _ |_| _|" | 4054057203 | 21 | 1 |
```
### Commented
```
for(; // outer loop, iterates on digits
!$i|| // this allows the first iteration of loop to happen
$d&& // $d is the single line string of each digit
// continue the loop as long as $d is not empty
print // and if $d is not empty, print
'6930274581' // a character from mapping string
[crc32($d)%63%10]; // at index of CRC32 of the digit's single line string % 63 % 10
$i++ // increment $i by one, $i indicates which digit we are reading now
)
for( // inner loop to get single line string of each digit
// this loop iterates 3 times as we have 3 separate inputs
$d=0; // set $d to "0" on start of each loop
$a=$argv[++$$i]; // set $a to appropriate input (input 1 or 2 or 3)
$d.=substr($a,$i*3,3) // concatenate a sub string of current digit from $a to $d
);
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
s€3=⁶ZF€Ḅ%15“pŻḣṾ:’b⁴¤iⱮ’Ḍ
```
[Try it online!](https://tio.run/##y0rNyan8/7/4UdMaY9tHjdui3ICshztaVA1NHzXMKTi6@@GOxQ937rN61DAz6VHjlkNLMh9tXAfkPNzR8////2glBSCIByM4Awkp6XABVdQoxINQDQgp1ICUQtg1NQo1UBUgUaAiBag6iAoIWykWAA "Jelly – Try It Online")
A monadic link taking a list of three Jelly strings and returning an integer. Converts each input into a binary list where 1 is space and 0 anything else, converts back from binary, takes mod 15 (lowest divisor that yields unique output for each digit) and then looks these up in a list of 10 values to extract the relevant digit. Finally converts from a list of decimal digits to an integer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
20 if a list of digits is acceptable -- remove trailing `Ḍ`
...or if we may print with any leading zeros -- remove trailing `Ḍ` and replace the `D` with a `Ṿ`
```
ZOḅ3/ḅ⁹%129ị“ȯṂṾ;’D¤Ḍ
```
A monadic Link accepting a list of the three lines which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8/z/K/@GOVmN9IPGocaeqoZHlw93djxrmnFj/cGfTw537rB81zHQ5tOThjp7///9HqyvEK0ARBMTjQApYRNS5dNRrQJwaEKkAJGsgJAgp1ChASJg4kKsAkYpXAKMakH64qIICDMXDjAArQjJXAaEYLKIeCwA "Jelly – Try It Online")**
### How?
*Magic...*
```
ZOḅ3/ḅ⁹%129ị“ȯṂṾ;’D¤Ḍ - Link: list of lists of characters
Z - transpose
O - to ordinals
3/ - three-wise reduce using:
ḅ - (left list) from base (right) (vectorises)
⁹ - literal 256
ḅ - (left list) from base (256)
129 - literal 129
% - (left) modulo (129) (vectorises)
¤ - nilad followed by link(s) as a nilad:
“ȯṂṾ;’ - base 250 integer = 3792546810
D - to digits = [3,7,9,2,5,4,6,8,1,0]
ị - (left) index into (right) 1-indexed & modular (vectorises)
```
***Huh?...***
After `ZO` we have a list of columns of `32`s, `95`s, and `124`s where there were spaces, underscores, and pipes, respectively. For example:
```
_ _
_||_ -> [[32,32,32],[95,95,95],[32,124,124],[32,124,124],[95,95,95],[32,32,124]]
_||_|
```
The three-wise reduce using base conversion with vectorisation effectively takes each group of three lists (i.e. an input-digit), first converting the left-most to each base defined by the middle list and then converts that resulting list to each base defined by the right-most list:
```
[32,32,32]ḅ95 = 32×95²+32×95+32 = 291872
->
[32,32,32]ḅ[95,95,95] = [291872,291872,291872]
[291872,291872,291872]ḅ32 = 291872×32²+291872×32+291872 = 308508704
and
[291872,291872,291872]ḅ124 = 291872×124²+291872×124+291872 = 4524307872
->
[291872,291872,291872]ḅ[32,124,124] = [308508704,4524307872,4524307872]
similarly
([32,124,124]ḅ[95,95,95])ḅ[32,32,124] = [317844128,317844128,4661212704]
so applying ZOḅ3/ we have:
_ _
_||_ -> [[308508704,4524307872,4524307872],[317844128,317844128,4661212704]]
_||_|
```
This gives a unique triples for each input-digit which we convert to unique integers by conversion from base 256 (`ḅ⁹`) and modulo by 129 (`%129`) to find unique integers which remain unique if modulo-ed by ten.
```
ZOḅ3/ ḅ⁹ %129 (implicit %10 of ị)
0 [309401120,4628496048,4628496048] 21466435284656 110 0
1 [ 35751968, 524305824, 524305824] 2477787571616 119 9
2 [308605948,4525733964, 308605948] 21383695908860 104 4
3 [308508704,4524307872,4524307872] 21381173548448 41 1
4 [ 47306784, 602657424, 602657424] 3255180354192 6 6
5 [317746884, 317746884,4659786612] 20909862778740 15 5
6 [317844128, 317844128,4661212704] 20916262082080 97 7
7 [299993120,4492051872,4492051872] 20814806443424 92 2
8 [317844128,4661212704,4661212704] 22028164437536 8 8
9 [317746884,4659786612,4659786612] 22021424949108 93 3
```
(256 was chosen because it is a short literal in Jelly, `ḅ14%67` is the same length and also works but the lookup integer, `5987203416`, takes an extra base 250 digit - `“¡⁴,>ʠ’`.)
```
_ _ ZOḅ3/ḅ⁹ %129 (implicit %10 of ị)
_||_ -> [21381173548448,20916262082080] -> [41,97] -> [1,7]
_||_|
and the 1st and seventh elements of “ȯṂṾ;’D = [3,7,9,2,5,4,6,8,1,0]
...are three and six -> [3,6]
```
] |
[Question]
[
Imagine we have some [polyomino](https://en.wikipedia.org/wiki/Polyomino) and would like to uniquely identify them, however the polyominos can be rotated, so blindly hashing them won't give us the same fingerprint for a piece and a rotation thereof (in general).
For example if we have the L-tetromino
```
x
x
xx
```
we would like it to have the same fingerprint as any of these:
```
xx
x x xxx
xxx , x or x
```
**Note:** We only allow rotations on the plane (ie. they are one-sided polyominos) and therefore the following polyomino would be a different one:
```
x
x
xx
```
## Challenge
The task for this challenge is to implement a fingerprinting-function/program which takes an \$m\times n\$ Boolean/\$0,1\$-valued matrix/list of lists/string/.. encoding a polyomino and returns a string - the fingerprint of a polyomino. The fingerprint must be equal for all of the possible rotations (in general 4).
## Input / Output
* \$m \geq 1\$ and \$n \geq 1\$ (ie. no empty polyomino)
* you're guaranteed that \$m,n\$ are as small as possible (ie. all \$0\$ are trimmed to fit \$m\$ and \$n\$
* you're guaranteed that the input is
+ simply connected
+ has no holes
* output must be a string which is the same for each possible rotation of a polyomino
## Examples
**Here are some equivalence classes, for each class the fingerprint must be the same & for any two polyominos from two distinct classes they must differ.**
The rotations of the L-tetromino from the example:
```
[[1,0],[1,0],[1,1]]
[[0,0,1],[1,1,1]]
[[1,1],[0,1],[0,1]]
[[1,1,1],[1,0,0]]
```
The J-tetromino:
```
[[0,1],[0,1],[1,1]]
[[1,1,1],[0,0,1]]
[[1,1],[1,0],[1,0]]
[[1,0,0],[1,1,1]]
```
The unit polyomino:
```
[[1]]
```
A \$5\times 1\$ bar:
```
[[1,1,1,1,1]]
[[1],[1],[1],[1],[1]]
```
A \$2\times 2\$ corner:
```
[[1,1],[1,0]]
[[1,0],[1,1]]
[[0,1],[1,1]]
[[1,1],[0,1]]
```
W-pentomino:
```
[[1,0,0],[1,1,0],[0,1,1]]
[[0,0,1],[0,1,1],[1,1,0]]
[[1,1,0],[0,1,1],[0,0,1]]
[[0,1,1],[1,1,0],[1,0,0]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
f=lambda l,z=5:z and max(l,f(zip(*l)[::-1],z-1))
```
[Try it online!](https://tio.run/##fY9BCsMgEEX3nmKWWiYQC90IOYm4sKTSBGMkpGC9vDWpSdouOpuv3z@@Gf@c76M7p2Qaq4drq8FibC4ignYtDDpQi4bGztOTZVKIiiuMFWcsmXGCAJ0DKSXHGmuFWfmqdVauFBKZj/myW1tkffpOY4mWrs80FoBSgkAuP3VupoYO2tP54e0NA2OMkGWkvoy0U9@/HMQf0sYplM089uF/sP2CTS8 "Python 2 – Try It Online")
Takes the largest of the four rotations in terms of list comparison. Based on [FlipTack's solution](https://codegolf.stackexchange.com/a/177665/20260).
The code uses Python 2's ability to compare objects of different types. The base case value of `0` is harmless for `max` because it's smaller than any list. Also, `zip` produces a list of tuples while the input is a list of lists, but tuples are bigger than lists so the input list-of-lists is never a contender. This is why we rotate 5 times rather than 4, so that we get back to a tuplified version of the initial list. (Taking a list of tuples would also work, if that's an allowed form of input.)
[Answer]
# [Python 3](https://docs.python.org/3/), 63 bytes
```
def f(m):M=[];exec("m=[*zip(*m[::-1])];M+=m,;"*4);return min(M)
```
[Try it online!](https://tio.run/##ZY9NDsIgEIX3nIK4gopJia4gPUJPMJmVQqQJtCE1qV4esdLWHzaPGd68bxju47UPx5QuxlLLPFdtA6jNZM5s5xuoHm5glQelDhI56nbfeKF31YnraMZbDNS7wFqebB/pRF2gACBFLWoUWeWsdVaJKAjkay7W1mKZn77doljL1KdbFACiIjSfIbowMssmzgl57dGVPVbUe3TD/MQv4SV6aW6fkH@sLrPSEw "Python 3 – Try It Online")
Finds the rotation with the lexographical minimum, and prints that.
A lambda form comes in at the same byte count:
```
lambda m,M=[]:exec("m=[*zip(*m[::-1])];M+=m,;"*4)or min(M[-4:])
```
[Try it online!](https://tio.run/##ZY9NDoMgEIX3nIJ0BXZMJHWF4QiegM7CtppiChrjwvbylFrU/rB5zPDmfUN/H6@dO/hGHf2tsqdLRS2USqOsp/rMdlbp5GF6llgtZSqQY1HulYVil@S8G6g1jpU6zSVy34R6osZRrbWADDKEoGLWLKhABKLDNRRra7HMT99uiNY49emGCECUhIbTD8aNrGET54S89mjjHivqPbphfuKX8Bi9NLdPiD9WG1j@CQ "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ZU$ƬṂ
```
[Try it online!](https://tio.run/##y0rNyan8/z8qVOXYmoc7m/7//x8dbaBjqGMYqxMNJHUMwLQBkI4FAA "Jelly – Try It Online")
Full program.
Simply generates all possible rotations and picks the lexicographical minimum.
Note that singleton lists aren't wrapped in `[]` in the output. That doesn't matter, since the only case where singleton lists would exist in the input would be a vertical line (including the unit polyomino), which is the same as a horizontal line with the same size (where the ones aren't wrapped). The only case where the outer `[]` will not exist either is the unit polyomino.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 136 bytes
```
import StdEnv,Data.List
r=reverse;t=transpose;f=flatten
$l=[if((a==b)==(c==d))'x''X'\\a<-f l&b<-f(r(map r l))&c<-f(r(t l))&d<-f(t(r l))]
```
[Try it online!](https://tio.run/##bVLPb4MgFD7rX8GhWSFxi543bt1hyQ5LdlnijKEWWxoEA892/efnEK3VuhiE73u8H997FJIz1VZ610iOKiZUK6paG0CfsHtVp2jDgD29CwuhoYafuLH8GSgYpmyt3bmkpWQAXIUrSVNRYswo3RJKcUHpjpD1z3r9tf7@Zi@PJZIPW7dhgytWI4MkIQ9FT4AHuw4A9pas/QTm6qBIcggD4BasA6nMgYPRlVA6QscpaJSAvNbyMuBSnHi@veRauY2ZCMFZd7jbCm0Ud9Q5r7kC72CzMDDcNtLn6SrEqtki7Y8rgnwFoVAIMykRxpSSxFklV3s4EDS4RkhpQPjA7KZxEYbmXK2EkPB84IaHwURHJysMgjRNojiLxn@SZZGn4yh2wFM3MvFUPP5v9HDXeWVOUuDW8Z9c8cQ/Wfr3OWe5btWNdHwttbvb55pP4Sbtar@bykT78I3Ru8izNURYjHEaY1HhfSuXeq8N7KNPX8R0MKPSuL@/HE88tn5WwdTjrq9zj9nQ2t/CvZ29bR/f3tvNRbFKFD34cE@q1Kb6Aw "Clean – Try It Online")
Includes test verifier.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 16 bytes
```
{a@*<a:3{+|x}\x}
```
[Try it online!](https://tio.run/##ZVHRToMwFH3nK26iyYoyKTO@gCY@G999UBM7dgtkXUtKl7DM@etYKDDYGkqa03PPPfd0u5SZbBoeH9nr3TOLH4/3v/Xpqz41LCaEREATtyMfhhW@Lw0arXaFVF4LEAoUopZkaQ6xp4S6fUY6juX6HURIT7hQf7tUd5Vdj4l6b21EqLNpOR0UBEEE1yvcy8JAqcRhbEBcA5i5sMynOoI1004/iJLJNwzQ@/DnLVb1ClKlJerRW3JOZhh4ltNZcBiDtrBzFH4sS5TmKm/aJzpNYSyc5TVhDi/gex5fBCHzvDBlQgAHrjS0J6zZrhRYBZBptS9hfQCTI2is9sJUwOQGMjQgUGYmB8UBWZo7rtXKMd1CwduSA@yYsVdYl5ga3PR6rrDybj/JTbxg/p/9P7x0ZpIftU1@OCvEd/MP "K (ngn/k) – Try It Online")
min of rotations
`{` `}` function with argument `x`
`{+|x}` rotate, i.e. reverse (`|`) and transpose (`+`)
`3{` `}\` apply 3 times preserving intermediate results; this returns a list of the 4 rotations
`a:` assign to `a`
`<` ascend (compute the sort-ascending permutation)
`*` first
`a@` index `a` with that
[Answer]
# Japt `-g`, 6 bytes
```
4Æ=zÃñ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=NMY9esPx&input=W1swLDEsMV0sWzEsMSwwXSxbMSwwLDBdXQotZ1E=)
```
:Implicit input of 2d-array U
4Æ :Map the range [0,4)
z : Rotate U 90 degrees
= : Reassign to U
à :End map
ñ :Sort
:Implicit output of first element
```
[Answer]
# [J](http://jsoftware.com/), 16 bytes
-2 bytes thanks to Shaggy
```
[:/:~|.@|:^:(<4)
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/aSt@qrkbPocYqzkrDxkTzvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagrGCkYKKgiFQJwQbKij4Oekp@OiWpJYU5edm5uUrQJSqq8O0GAE1qQAVQ5TDtSTmFOcj60PXBrEJYY8hugJMARjEdAHE0SBogGmPMdRHEHug9H8A "J – Try It Online")
# [J](http://jsoftware.com/), 18 bytes
```
0{[:/:~|.@|:^:(<4)
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N@gOtpK36quRs@hxirOSsPGRPO/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCsYKRgoqCIVAvBBsqKPg56Sn46JaklhTl52bm5StAlKqrw7QYATWpABVDlMO1JOYU5yPrQ9cGsQlhjyG6AkwBGMR0AcTRIGiAaY8x1EcQe6D0fwA "J – Try It Online")
Returns the first item in the list of the lexicograpically sorted rotations of the polyomino.
## Explanation:
```
^:(<4) - do the verb on the left 4 times, storing all the steps
|.@|: - tranpose and reverse
/:~ - sort up the 4 matrices
[: - cap the fork
0{ - take the first matrix
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
3FÂø})Σ˜
```
-2 bytes thanks to *@Shaggy*.
[Try it online](https://tio.run/##yy9OTMpM/f/f2O1w0@EdtZrnFp@e8/9/dLShjkGsDpw0jI0FAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmR6feWib/eHVlS72SgqP2iYpKNn/N3Y73HR4R63mucWn5/yv1fkfHR1tqGMQqwMnDWNjdRSiow10DIBMsABMyBAsYAAnYYJQdUAdICElJYh2hFpDdLUQs5HMRLgAKmgAcwxEHcRMZKYOFEI1gBSjYGSVaEaj@hLdgQi/wfQj3GIAkUQPIgN4ECBZg6waxceoquEBFwsA).
**Explanation:**
```
3F } # Loop 3 times
 # Bifurcate (short for Duplicate & Reverse) the top of the stack
# (which is the input-matrix implicitly the first iteration)
ø # Transpose: swap rows/columns
) # After the loop, wrap everything on the stack in a list
Σ˜ # Sort this list of matrices by their flattened array (and output implicitly)
```
NOTE: Taking the minimum with `ß` or `W` will implicitly flatten, so will output `0`. And sorting with `{` doesn't seem to work for a list of matrices, which is why I use `Σ˜` instead.
] |
[Question]
[
There are some iron particles on a board. We pass a current carrying wire through that board and the particles form circles. Show these circles if input given is the position of the wire.
Consider the board to be a grid of size 7x7 (fixed)
No extra white spaces are allowed.
Input can be 0-indexed or 1-indexed. (0-indexed in examples)
### Examples
```
input:3,3 # 'X' is wire here but can be shown by anything other than '\/|-'
output:
/-----\
|/---\|
||/-\||
|||X|||
||\-/||
|\---/|
\-----/
input:1,2
output:
|/-\|||
||X||||
|\-/|||
\---/||
-----/|
------/
-------
input:0,0
output:
X||||||
-/|||||
--/||||
---/|||
----/||
-----/|
------/
input:0,3
output:
|||X|||
||\-/||
|\---/|
\-----/
-------
-------
-------
input:3,0
output:
---\|||
--\||||
-\|||||
X||||||
-/|||||
--/||||
---/|||
```
This is **code-golf** so shortest code wins.
[Answer]
# [J](http://jsoftware.com/), 40 bytes
```
7 7{.6 6&-|.0":<^:6@8[9!:7@'/_\___\_/|-'
```
[Try it online!](https://tio.run/##y/r/P81WT8Fcwbxaz0zBTE23Rs9AycomzsrMwSLaUtHK3EFdPz4mPh6I9Wt01f@nJmfkK6Q52CkYKBhYKwB1WCsYKhhZA7nG1grGCgb/AQ "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~136~~ ~~119~~ 116 bytes
```
function(i,j,m=diag(7),R=row(m)-i,a=j-col(m)){m[]='-'
m[R==a]='\\'
m[R==-a]='/'
m[R<a&R>-a|R>a&-R>a]='|'
m[i,j]=0
m}
```
[Try it online!](https://tio.run/##NU/NjsIgEL7zFJNsIpAM2a2aNTHibV@gemt7IJUqpoBpMTZZffYuxe6F72/gG7rxAwxeQXUaMmHcSQ/6RBo5NndXB@MdiylaeTLqzDYcc9n5B7NcGFTyKmrfRsF/bVFJKiixRS6lirwsZyEm9ZnETi3yvVDPfK8WIh4xeE5BbKjkF7GvMeg@9LAT0Jo@MFKzNa45RlziKmGG2Yxv/xuXCVe44YQTUqvA6OHiH6Ac6EHZW6vBNxAuETpzNk614O/hdg9gVejMAI3voEkFsC0d5eQtCCExYQ6Mg2zbancOF5b2i98lABOdNk1WUbiqimaqL93x53AEig4pMIrTRJFVSHHmy8h5rMJe3ySNjQB2mN5q2P/sPDdFj84EzQKzA8cMN9inKy8y/gE "R – Try It Online")
* -3 bytes saved thanks to @Giuseppe
Function that takes (row,col) coordinates of the wire (1-indexed) and returns a 7x7 matrix with the characters.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~27~~ ~~23~~ ~~22~~ 21 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
-7×[\+]↶ω⟳n↔┼⁷⁸╵77@↕↔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=LSV1RkYxNyVENyV1RkYzQiU1QyV1RkYwQiV1RkYzRCV1MjFCNiV1MDNDOSV1MjdGMyV1RkY0RSV1MjE5NCV1MjUzQyV1MjA3NyV1MjA3OCV1MjU3NSV1RkYxNyV1RkYxNyV1RkYyMCV1MjE5NSV1MjE5NA__,i=NCUwQTI_,v=8)
[Answer]
# JavaScript (ES7), ~~105~~ 103 bytes
Takes input as `(y)(x)`, 0-indexed.
```
Y=>X=>(g=x=>y<7?`/\\-|X
`[h=(X-x)**2,v=(Y-y)**2,x<7?h<v?2:h>v?3:h?x<X^y<Y:4:5]+g(x<7?x+1:!++y):'')(y=0)
```
[Try it online!](https://tio.run/##bYvfCoIwHEbvfYuu3M@18k8RjG2@xiQLw9QV4iJjbNC7L/MuDM7Fx@F894u5jPXz9niRQV8b33JfcCG5QB23XDh2yKttWZK3DKqj4kgSC1GUrg1HBXHztFOjmMlTqoTJM6pyy@TZsYLu6P6EO/QNLE7oCmMHNAwBOR6Dr/Uw6r7Z9LpDLcpgAoJfmQBKFzKGiT9yec/m0n8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 90 bytes
```
{<| v - \ X />[1+([-]($_>>.abs).sign||3+[*]($_).sign)for ^7-$^a X ^7-$^b].rotor(7)>>.join}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2qZGoUxBVyFGIUJB3y7aUFsjWjdWQyXezk4vMalYU684Mz2vpsZYO1oLJArha6blFynEmeuqxCUCdYEZSbF6Rfkl@UUa5ppAnVn5mXm1/9M0jHWMQdzixEprrjQNQx0jJJ6BjgEKD1mlMZLcfwA "Perl 6 – Try It Online")
Anonymous code block that takes two numbers and returns a list of lines.
[Answer]
# [Python 2](https://docs.python.org/2/), 105 bytes
```
lambda x,y:[''.join(['/-|'[cmp(abs(i-x),abs(j-y))],'\X'[i==x]][i-x==y-j]for j in R)for i in R]
R=range(7)
```
[Try it online!](https://tio.run/##JY2xDoMgFEV3vuJtQALW6tDEhNUPcGqCDFilhSga6yBJ/52KTue8e2/ylrB9Zl9EI9o46qnrNewsVBLjzM3WE4lv/Ifla1qI7r7E8p2yJI4HShXD7RNLK8SulDw6IQJ3yswrOLAeGprUnqpQI1bt3wN50NgPBmpyPKIVgrQZ08ZcybJav8GI4BRUk5KV9MCdFQk5yy@cYZmu@Ac "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
GL⁷-↙⁶X‖B↘¬‖J±N±NT⁷¦⁷
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9Pw8pHR8FcR0FJV0nTmiugKDOvRMPKJb88zyc1rURHwQwuqBQBUhCUmpaTmlziVFpSklqUllMJURuUmZ4BVGx1aA1CiQaQ6VWaWxCSr@GXmp5YkqrhmVdQWuJXmpuUWqShqamjgFUYqCukKDNXA@gkc03r//8NuUz@65blAAA "Charcoal – Try It Online") Takes 0-indexed column and row as input. Explanation:
```
GL⁷-
```
Draw a triangle of `-`s.
```
↙⁶
```
Draw a line along the hypotenuse. (This is the wrong way around but we'll fix that later.)
```
X
```
Draw the `X` that shows the position of the wire. (Any other ASCII character could be used here of course.) This completes one eighth of the drawing.
```
‖B↘¬
```
Reflect three times (`¬` = left + down) while transforming characters to almost complete the diagram.
```
‖
```
Reflect without transforming to switch the `/`s with the `\`s so they now point around the `X` instead of towards it.
```
J±N±N
```
Jump to the top left of the desired output.
```
T⁷¦⁷
```
Trim the result to the desired size.
] |
[Question]
[
How can I shorten:
```
p=gets.to_i
a=gets
b=gets.to_i
```
If my input is an integer, followed by a string, followed by an integer?
[Answer]
## Use ARGV ($\*) and mass assignment
*(disclaimer: I don't know Ruby, but this works [on TIO](https://tio.run/##KypNqvz/v0AnUSfJVkWLq8C2QK8kPz6TK8k2CcIoKC0pVkiEUEnaBf///zf8X5JaXPLfGAA "Ruby – Try It Online"))*
```
p,a,b=$*
p=p.to_i
b=b.to_i
```
~~28~~ 26 bytes instead of 30 (thanks to Snack for pointing out the $\* trick)
[Answer]
# Use a lambda
Answers are typically allowed as lambda functions with your input/output being the parameters/return value of the lambda, so you can do this:
`->p,a,b{...}`
If you assigned this to a variable `f` then it would be called as
`f[p,a,b]`
It's generally fine to assume the types of the inputs as well, but to be safe you can mention it in your answer.
[Relevant meta post about acceptable input/output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
[Answer]
If you need a full program with stdin/stdout io for some reason, the shortest you can do is use the `-n` flag to shorten one call to `gets.to_i` to `eval$_`:
```
p=eval$_
a=gets
b=gets.to_i
```
The `-n` flag surrounds your code with `while gets ... end`, so the program will loop if more input is supplied than your program consumes.
] |
[Question]
[
>
> Inspired by [this chat message](https://chat.stackexchange.com/transcript/message/40172973#40172973)
>
>
>
Your task will be to take a word and find the average position of its letters on the keyboard as a letter.
## Keyboard Layout
Since layouts vary from keyboard to keyboard, we will be using a standard based of of my own keyboard in this question.
The keyboard has 3 rows, the top row from left to right contains the keys
```
QWERTYUIOP
```
The second row contains the letters
```
ASDFGHJKL
```
The final row contains
```
ZXCVBNM
```
Each letter is 1 unit horizontal from its neighbor to the left. This means that `W` is 1 away from `Q` and `E` is 1 away from `W` and so on.
The keys at the beginning of each row have the positions:
```
Q : 0,0
A : 1/3,1
Z : 2/3,2
```
This means that the rows are separated one unit vertically and the bottom two rows are shifted by a third from the row above them.
---
You should take a word as input and output the letter that is closest to the average position of the letters in its word. The average of a set of vectors is
```
(average x value, average y value)
```
When two keys are equidistant from the average you may output either as the "closest" key.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
## Example solution
Let's calculate the average of `APL`.
We convert each letter to a vector
```
A -> (1/3,1)
P -> (9,0)
L -> (8 1/3,1)
```
We add these up the three vectors to get `(17 2/3, 2)`. We then divide each coordinate by 3 (The number of letters in the word) to get `(5 8/9, 2/3)`.
The closest letter to `(5 8/9, 2/3)` is `J` at `(6 1/3,1)` so our result is `J`.
## Test Cases
```
APL -> J
TEXT -> R
PPCG -> J
QQQQ -> Q
ZZZZ -> Z
PPPP -> P
MMMM -> M
QQSS -> A or W
```
[Answer]
# [Python 3](https://docs.python.org/3/), 130 bytes
```
lambda w,d={'QAZWSXEDCRFVTGBYHNUJMIKOOLPP'[i]:i%3*1j+i/3for i in range(28)}:min(d,key=lambda c:abs(d[c]-sum(map(d.get,w))/len(w)))
```
[Try it online!](https://tio.run/##TdBNb4JAEAbgu79ikqbZ3Yo1lktDQhO0fktdhFaLelhd0FVZCWKMafrb6R6qy3uZw5OZyUx6zbdHaRaxvSgOLFlxBheD2z/Ic8KpP2u/tyadr6Db/O59fA7c/nA8HlGK5mJpiUfzqbGriroZHzMQICRkTG4i/PJKfq1ESMyNfXS1/6euLbY6YT5fL2unc4ITlmL@vIly40JI/RBJrCop0kzIHMcYOXSECBCAB6i9waByh6A9CxC5wUQDpa2uhlKHp6LB0xCqaAjLo9SNd6AaXBUNbnmH72twQH1kWin@AA "Python 3 – Try It Online")
`d={'QAZWSXEDCRFVTGBYHNUJMIKOOLPP'[i]:i%3*1j+i/3for i in range(28)}` constructs the mapping from letters to points (represented as complex numbers, `(x+y*1j)`).
As for the lambda body, `sum(map(d.get,w))/len(w)` computes the average position of word `w`, and putting that in `min(d,key=lambda c:abs(d[c]-…))` finds the closest letter to that position. (For complex numbers, `abs(A-B)` corresponds to the Euclidean distance between `(A.real, A.imag)` and `(B.real, B.imag)`.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes
```
ØQi€µT÷3Ḣ+Ṁ;T
Ç€ZÆmðạ²SðЀØAÇ€¤iṂ$ịØA
```
[Try it online!](https://tio.run/##y0rNyan8///wjMDMR01rDm0NObzd@OGORdoPdzZYh3AdbgcKRh1uyz284eGuhYc2BR/ecHgCUOjwDEew1KElmQ93Nqk83N0NFPn/H6Lm0N7/So4BPkoA "Jelly – Try It Online")
lol way too long
# Explanation
```
ØQi€µT÷3Ḣ+Ṁ;T Helper Link; compute the position of a key
€ For each row of
ØQ ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"] (hooray for builtins)
i Find the first occurrence of the argument
µ Start a new monadic chain
T List of indices of truthy values; singleton list with the row of the key
÷ Divide the index by
3 3
Ḣ Take the first element
+ Add it to the original list
Ṁ Take the maximum (the adjusted horizontal position of the key)
; Append
T The index of the truthy value (the row)
Ç€ZÆmðạ²SðЀØAÇ€¤iṂ$ịØA Main Link
€ For each character in the input
Ç Compute its position using the helper link
Z Zip (all of the horizontal positions are in the first list; all of the vertical positions are in the second list)
Æm Take the arithmetic mean (of each sublist)
ðạ²Sð Dyadic chain to compute the distance (squared) between two coordinates
ạ Take the absolute difference between each coordinate value (auto-vectorization)
² Square each value
S Take the sum (returns the distance squared but for comparison that's fine)
Ѐ Take the distance between the mean position and each element in
ØAÇ€¤ [Nilad:] the positions of each character in the uppercase alphabet
€ For each character in
ØA "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Ç Compute its position
iṂ$ Find the index of the minimum (closest)
i First occurrence of in the list of distances
Ṃ the minimum
ị Index back into
ØA The alphabet
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 250 + 13 bytes
+13 bytes for `using System;`
```
n=>{var a=new[]{"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};float x=0,y=0;int i=0,j=0,l=n.Length;foreach(char c in n){for(i=0,j=0;i<2;){if(a[i][j]==c)break;if(++j>=a[i].Length){i++;j=0;}}x+=j;y+=i;}return a[(int)Math.Round(y/3)][(int)Math.Round(x/l+y/l/3)];}
```
[Try it online!](https://tio.run/##ZVHLbsIwEDzDV6xyihUaUHs0RqIU6APa8GihjXJwjQOmwZFsQ4mifHvqiIhLLVle7eyMd2eZvmGp4uVRC7mFRaYNP@AmS6jWEKh0q@gB8mZDG2oEg1MqNjClQrraKEsII6Bqq1FV0riQ/dFRsu4FbgHbUdWDGEgpSS8/UQWUSP4bRrkzWw3ny8/3p7fAaTn9xcNo/Pj8MrHx13rwcf86dQocJyk1cCadVkY6WEgDwsZ7exMi/QmXW7PDsW2fsp1bfQUMhASJcpt061osurcY5SJ2aSiicB8RwtC35fxgm/O8fY9UQC1nCz0PV7SiOHtkjzOPCFwobo5KAg1d2wWaUrPz5@lRbtysfYeif9lzO/GydlJhuChxo2HtuTpmuDaMaq6BgPUCrkAOTj@wDoCzHK6X1RsEg3H1zuxxoMBWph4X6g2Aria@SqJ6hf4glTpNuL9SwvCJkNyNXY2QVSiaRfkH "C# (.NET Core) – Try It Online")
Little sidenote: This outputs `F` for `TEXT`, since that was the original desired output.
Outputting `R` instead of `F` was changed after this answer was posted.
[Answer]
## JavaScript (ES6), 166 bytes
```
f=
s=>[...s].map(c=>(h+=c=s.search(c),v+=c%3,l++),h=v=l=0,s='QAZWSXEDCRFVTGBYHNUJMIKKOLLP')&&[...s].map((c,i)=>(i=(i-h/l)*(i-h/l)+(i=i%3-v/l)*i*9,i)<m&&(m=i,r=c),m=9)&&r
```
```
<input oninput=o.textContent=/^[A-Z]+$/.test(this.value)?f(this.value):``><pre id=o>
```
6 bytes could be saved by switching to ES7. Previous 131-byte solution used a simplistic distance check which is no longer acceptable.
```
f=
s=>([...s].map(c=>(h+=c=s.search(c),v+=c%3,l++),h=v=l=0,s='QAZWSXEDCRFVTGBYHNUJMIKKOLLP'),v=(v/l+.5|0),h=((h/l-v)/3+.5|0),s[h*3+v])
```
```
<input oninput=o.textContent=/^[A-Z]+$/.test(this.value)?f(this.value):``><pre id=o>
```
[Answer]
# Java, ~~257 243 242~~ 237 bytes
```
char h(String s){int l=s.length(),i=l+28;s="QAZWSXEDCRFVTGBYHNUJMIK<OL>P"+s;float d=9,x=0,y=0,e;for(;i>28;y+=(e=s.indexOf(s.charAt(--i)))%3/l,x+=e/3/l);for(;i-->0;)if((e=(x-i/3f)*(x-i/3f)+(y-i%3)*(y-i%3))<d){d=e;l=i;}return s.charAt(l);}
```
Saved 14 bytes - the distance away from the best key will be less than 3 units
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~452~~ ~~431~~ ~~424~~ ~~400~~ ~~389~~ ~~324~~ ~~322~~ ~~296~~ ~~285~~ ~~281~~ ~~276~~ ~~274~~ ~~260~~ ~~258~~ 257 bytes
Something to start golfing from
```
s->{String c="QWERTYUIOPASDFGHJKL;ZXCVBNM";int i=0,r=0,l=0;double x=0,y=0,D=99,t,f=s.length();for(;i<f;x+=l%10+l/10/3d,y+=l/10)l=c.indexOf(s.charAt(i++));for(;r<27;r++)if(D>(t=Math.pow(x/f-r/10/3d-r%10,2)+Math.pow(y/f-r/10,2))){D=t;l=r;}return c.charAt(l);}
```
[Try it online!](https://tio.run/##TVBbT8IwFH7nVzQkJp3bysUHQ0pJkIlXRJx340PdBYqlXbozZCH8diwyjSc5Sb9LT3u@OV9yX2eJmsefW7HItAE0txwBsUjIIa395woQkqSFikBotRNrkeR5jvpoXUO2cuAgIjSsHN0QjFBTbzDjhkeQmJ5m29zvrfc8ilh98nR6d//ycDG@7YfB8Oz88uqavj4PHk9uRnUqFCDBmp6xLVmTxrr4kAlaWVjaDlin44GXspzIRE1hhh2aaoOp6KZ05TJ50Gq6stFqNo5ir7TYHh3JIiJUnKzGKc5JZH/WByxc16numm77mBqLRYqDHgY24jAjmf7Cq0bqm/0039jRXttx/8SyEi3pOOuAAZXM0I1JoDAKRb8PSYdutja2XViZXcaGVWW21CJGCy4U3ofz9o64meZOleyuwjKHZEF0ASSzFpAKa8KzTJa4PpmEYd3u8GPe1Dbbbw "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 79 bytes
```
≔⪪”$±=K≕⦃Vj@η⟲.w\`o:7➙1”¶ηFθF³F⌕A§ηκι⊞υ⟦λκ⟧IE²∕ΣEυ§λιLθ§§η⁺·⁵∕ΣEυ⊟ιLθ⁺·⁵∕ΣEυ⊟ιLθ
```
[Try it online!](https://tio.run/##nY07b8IwFIX3/grL07VkGIqYmMyrpITWkLa8whAlKbZwnTR2EP/eWFEjIcHUuxzp6LvfSUVSpUWinGPGyKOGqFTSAl6uJ6uP7WfwzmPNovH0ZfY6D2O924y@hm8LTBGONSYUCTJ4@i4qBL8ENdn7y6nUGVMKmA10ll9AUHTyvCQE8doIqCnaK98dvIBXUlsYJcbCIinhmaKxPMssh6j@aRoPtx7VOLwpzPXRCr/rr1W00M0oV7WBbv@Rkhcl3Lv@8UIGzu0x4yE@uI46XwE "Charcoal – Try It Online")
Neil's golf using string functions.
# [Charcoal](https://github.com/somebody1234/Charcoal), 107 bytes
```
P”$±=K≕⦃Vj@η⟲.w\`o:7➙1”≔⟦⟧α≔⟦⟧βFχ«F³«JικFθ«¿⁼λKK«⊞α⎇›ⅉ⁰⁺∕¹¦³ⅈⅈ⊞βⅉ»»»»J⌊∕⁺Σα·⁵Lθ⌈∕⁺Σβ·⁵Lθ≔KKχ⎚χ¶I∕ΣαLθ¶I∕ΣβLθ
```
[Try it online!](https://tio.run/##jVDbTsJAEH1mv4L0aSYZTQnxA7BcpIJWqVfKw7audMOylW1LQgjfXttaDIYXk93knMmcc2YmirmJEq6KYpqrTHpG6gysh5fBo//2NL73At2b9YejG/d2Euj3V@f5@m5qIeulqVxqmC@In5IQ2TAx0LFxz1oV6lag5ebrLz8BSSssWVXf1PWW/ITBJucqBUWeECtAxPbey9MYOPnCaG52MDKCZ8KASzaSp/IU@nIrPwR0qIs0rh62K7daF5KLh5KV/8AOrIkeqqRMbXS1xyxfA0eyL6@QJkIvs7gcCpEcIdVZY3je@Lt2NTdFyBwluGE/Byxpc8lAW0fs8DQ7OjfpJ37/EIR/BEUxt3rexFoUF2r7DQ "Charcoal – Try It Online")
Draws the keyboard on the canvas and finds the average that way.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žVIšεεžVsδkDZkDŠ3/+à‚]ćøÅA`UòDžVsèŠè€θDX.xkè
```
Not too happy with it, but it works.. :/ Can definitely be golfed some more using a different approach.
I/O in lowercase.
[Try it online](https://tio.run/##yy9OTMpM/f//6L4wz6MLz209txXIKj63JdslKtvl6AJjfe3DCx41zIo90n54x@FWx4TQw5tcQCoOrzi64PCKR01rzu1widCryD684v//xIIcAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSvdL/o/vCKo8uPLf13FYgq/jclmyXqGyXowuM9bUPL3jUMCv2SPvhHYdbHRNCD29yAak4vOLogsMrHjWtObfDJUKvIvvwiv9KemE6/6OVEgtylHSUSlKLS4BUQUFyOpAqBAIgVQUEYMGCAiCVCwRgueJipVgA).
**Explanation:**
Step 1: create a list with all the coordinate-values, and convert the input in a similar matter as well:
```
žV # Push builtin ["qwertyuiop","asdfghjkl","zxcvbnm"]
Iš # Prepend the input-string to this list
ε # Map over each string:
ε # Inner map over each individual character:
žV # Push ["qwertyuiop","asdfghjkl","zxcvbnm"] again
s # Swap so the current character is at the top of the stack
δk # Get the index of this character in each of the three strings
# (or -1 if it's not found)
D # Duplicate this list of indices
Z # Get the largest index (without popping)
k # Get the index of this largest index in the triplet
D # Duplicate this index
Š # Triple swap the three values on the stack (a,b,c→c,a,b)
3/ # Divide it by 3
+ # Add it to each index in the list we duplicated
à # Pop and push the maximum again
‚ # And pair it with the duplicated & triple-swapped index
] # Close the nested maps
```
[Try just this first step.](https://tio.run/##yy9OTMpM/f//6L4wz6MLz209txXIKj63JdslKtvl6AJjfe3DCx41zIr9/z@xIAcA)
Step 2: get the average coordinate of the input:
```
ć # Extract head; pop and push remainder-list and first item separated
ø # Zip/transpose; swapping rows/columns
ÅA # Get the arithmetic mean of both inner triplets
```
[Try just the first two steps.](https://tio.run/##yy9OTMpM/f//6L4wz6MLz209txXIKj63JdslKtvl6AJjfe3DCx41zIo90n54x@FWx///EwtyAA)
Step 3: get the coordinate closest to this average coordinate, and convert it back to a character to output:
```
` # Pop and push both separated to the stack
U # Pop and store the second one in variable `X`
ò # Round the first value to the nearest integer
D # Duplicate this integer
žV # Push ["qwertyuiop","asdfghjkl","zxcvbnm"] yet again
s # Swap so the integer is at the top of the stack
è # Index it into the list of strings
Š # Triple-swap the values on the stack (a,b,c→c,a,b)
è # Index the duplicated integer into the remainder-list
€θ # Leave the last value of each inner pair
D # Duplicate the list
X.x # Pop the copy and leave the value closest to value `X`
k # Get the index of this value in the duplicated list
è # And index it into the string we triple-swapped
# (after which this character is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 31 bytes
```
Æịµ÷3Ċ+
ØQœiⱮÇÆmØQŒṪ¤Çạ¥ÐṂœịØQX
```
[Try it online!](https://tio.run/##y0rNyan8//9w28Pd3Ye2Ht5ufKRLm@vwjMCjkzMfbVx3uP1wWy6IN@nhzlWHlhxuf7hr4aGlhyc83Nl0dDJQB1Aq4v/DHZsOtz9qWhP5/79jgI9CiGtEiEJAgLO7QiAQKEQBAZAbEKDgCwRAseBgAA "Jelly – Try It Online")
Uses some features that were presumably not implemented when HyperNeutrino wrote his solution, so considering this only beats it by ~~4~~ 6 bytes, I wouldn't be surprised if a modernized version of his would come out shorter--but I started writing this before I even noticed his existed.
```
Æịµ÷3Ḟ+ Helper link (monadic):
Æị convert list to complex,
µ + add the complex number to
Ċ the imaginary part of
÷3 its quotient by 3.
ØQœiⱮÇÆmØQŒṪ¤Çạ¥ÐṂœịØQX Main link:
ØQœiⱮ multidimensional indices of input in QWERTY layout,
Ç apply helper link,
Æm average;
ØQŒṪ¤ for all multidimensional indices in the layout
ÐṂ keep those with the smallest
ạ¥ absolute difference between the average and
Ç their result from the helper link;
œịØQ index back into QWERTY
X and choose one key at random.
```
[Answer]
# Mathematica, 234 bytes
```
(r=(K=Round)@Mean[If[(w=First[q=#&@@Position[(s=X/@{"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"}),#]])==1,q=q-1,If[w==2,q=q+{-1,-2/3},q=q+{-1,-1/3}]]&/@(X=Characters)@#];z=If[(h=#&@@r)==0,r=r+1,If[h==1,r=r+{1,2/3},r=r+{1,1/3}]];s[[##]]&@@K@z)&
```
] |
[Question]
[
# Task
You will be given a positive integer and you must output a "[self-complementary graph](https://en.wikipedia.org/wiki/Self-complementary_graph)" with that many nodes. If you don't know what a self-complementary graph is the wikipedia article wont help you much so below are two explanations, a technical and a non-technical one.
## Non-Technical
A graph is a set of nodes that are connected by lines. Each pair of points can be connected by one line or none. The "complement" of a graph is the result of taking a graph and connecting all the nodes that are not connected and disconnecting all the nodes that are.
A self-complementary graph is a graph whose complement can be rearranged into the shape of the original. Below is an example of a self-complementary graph and a demonstration of how.
Here is a graph with 5 nodes:
[](https://i.stack.imgur.com/kJkcT.png)
We will highlight the all the places where connections could go with red dotted lines:
[](https://i.stack.imgur.com/AvCIW.png)
Now we will find the complement of the graph by swapping the red and black edges:
[](https://i.stack.imgur.com/M5E1K.png)
This does not look like the original graph but if we move the nodes around like so (each step swaps two nodes):
[](https://i.stack.imgur.com/Ys5Jm.png)
We get the original graph! The graph and its complement are the same graph
## Technical
A self-complementary graph is a graph that is isomorphic to its complement.
# Specifications
You will receive an positive integer via whatever method suits you best. And you will output a graph in whatever method you deem appropriate, this includes but is not limited to [Adjacency Matrix Form](https://en.wikipedia.org/wiki/Adjacency_matrix), [Adjacency List Form](https://en.wikipedia.org/wiki/Adjacency_list), and of course pictures! The outputted graph must be its own complement and have as many nodes as the integer input. If no such graph exists you must output a falsy value.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and you should aim to minimize your byte count.
# Test Cases
Below are pictures of possible outputs for several n
## 4

## 5

## 9

[Answer]
# [Haskell](https://www.haskell.org/), 72 bytes
```
f n=[(a,b)|b<-[1..n],a<-[1..b-1],mod n 4<2,mod(a+b+sum[b|odd n,a<2])4<2]
```
[Try it online!](https://tio.run/##JY0xDoMwEAS/cgWFLWwUrJTmCXmBdcWdSAQKPlCAzn83h9KNdlezE@3f97LU@gEZkiHHtnD0qe86QUd/Yt@jy@sIAs8YbjLUcrufOXFZR811GdBqiTXTLDBApu0F22@WAxpIRpwe2KKG6OF2hgdivQA "Haskell – Try It Online")
A belated improvement inspired by ideas [from kops](https://codegolf.stackexchange.com/a/223427/20260). Takes vertex `1` to the the special vertex in the \$n=1 \bmod 4\$ case, rather than vertex `n`.
---
# [Haskell](https://www.haskell.org/), 77 bytes
```
f n=[(a,b)|b<-[1..n],a<-[1..b-1],mod n 4<2,mod(a+(last$b:[a|odd n,n==b]))4<2]
```
[Try it online!](https://tio.run/nexus/haskell#JY0xCsMwEAS/soULiZwMDm4SpCfkBeKKO4zBEJ1N4lJ/V2TSDcwy21ZYyk5IfdUY8jSOxiR/0jAxlX2BYY73i5zc3Fu@56DPLHVfuiJLSdn7vuBWZDMkFDleOD6bnRiQnVF/8bVnYsAVfjC3Hw "Haskell – TIO Nexus")
This uses an easy-to-compute explicit criterion to decide whether an edge `(a,b)` belongs in the graph. Instantiates [this algorithm](https://math.stackexchange.com/a/412930/24654), with the permutation cycling among the values modulo 4
```
4*m -> 4*m+1 -> 4*m+2 -> 4*m+3 -> 4*m
```
We include edges whose two endpoint vertices add to 0 or 1 modulo 4. Note that cycling vertices as per this permutation adds 2 modulo 4 to the vertex sum on each each, and so swaps edges and non-edges. This gives a permutation of vertices that complements the edges.
If the graph has an extra node beyond a multiple of 4, it is put in a cycle alone. We include edges with it when then other vertex is even. Permuting the vertices flips the parity, and so the graph remains self-complementary.
If the number of vertices isn't 0 or 1 modulo 4, no self-complementary graph is possible because there's an odd number of edges in the complete graph
Overall, here are the conditions:
* If the input n isn't 0 or 1 modulo 4, output an empty list
* Otherwise if n is even, include all edges `(a,b)` with `a<b` and `a+b` equal to 0 or 1 modulo 4.
* Otherwise if n is odd, do the same, but instead include edges of the form `(a,n)` when a is even.
The code combines the second and third cases by replacing the condition `mod(a+b)4<2` with `mod(a+a)4<2` when both `odd n` and `b==n`.
[Answer]
# [Brachylog 2](https://github.com/JCumin/Brachylog), 24 bytes
```
{⟦₁⊇Ċ}ᶠpḍ.(\\ᵐcdl?∨?<2)∧
```
[Try it online!](https://tio.run/nexus/brachylog2#AS8A0P//e@KfpuKCgeKKh8SKfeG2oHDhuI0uKFxc4bWQY2RsP@KIqD88MiniiKf//zX/Wg "Brachylog – TIO Nexus")
This is a *function* that returns a pair consisting of two adjacency lists: one for the graph, one for the complement graph. (In the Brachylog interpreter on TIO, you can ask it to evaluate a function, rather than a full program, via giving `Z` as a command line argument.) For example, the output for input `5` is:
```
[[[1,2],[1,3],[1,5],[3,5],[4,5]],[[2,5],[2,3],[2,4],[3,4],[1,4]]]
```
Here's what that looks like as an image (showing the two graphs):
[](https://i.stack.imgur.com/purlZ.png)
As is common in Prolog-based languages, the function supports more than one call pattern. Notably, if you try to use it as a generator, it will output all possible self-complementary graphs with the given number of vertices (although I didn't take any effort to make this case usable, and notably it'll output each of the graphs many times each).
## Explanation
This is basically just a description of the problem, leaving the Prolog implementation to find the best method of solving it. (However, I doubt it will use an algorithm any better than brute force in this particular case, so it's likely fairly inefficient, and testing seems to confirm this, showing the performance getting much worse the larger the graph is.)
```
{⟦₁⊇Ċ}ᶠpḍ.(\\ᵐcdl?∨?<2)∧
⟦₁ The range [1, 2, …, ?], where ? is the input
⊇ A subset of that range…
Ċ …which has exactly two elements
{ }ᶠ A list of everything that fits the above description
{⟦₁⊇Ċ}ᶠ All edges that could exist in a ?-element graph
p Find a permutation of these…
ḍ …so that splitting it into two equal parts…
( ∨ ) …either:
dl? produces ? distinct elements
\ after transposing it
\ᵐ and transposing its elements
c and flattening one level;
or:
?<2 ? was less than 2
. ∧ Once you've found it, . specifies what to output
```
Incidentally, I ended up having to spend a whole 6 bytes (¼ of the program, the characters `(∨?<2)`) dealing with the special cases of 0 and 1. Frustrating, but that's the nature of special cases.
The `\\ᵐcdl?` section is a little hard to understand, so here's a worked example. Its purpose is to check whether something is a graph and its complement, with corresponding edges in the graph and complement being in the same order within the lists. The graph/complement pair becomes the eventual output of the program. Here's an example case:
```
[[[1,2],[1,3],[1,5],[3,5],[4,5]],[[2,5],[2,3],[2,4],[3,4],[1,4]]]
```
Transposing this gives us a list of pairs of corresponding edges between the graph and the complement:
```
[[[1,2],[2,5]],[[1,3],[2,3]],[[1,5],[2,4]],[[3,5],[3,4]],[[4,5],[1,4]]
```
Next, we transpose inside the list elements and flatten one level; that gives us a list of pairs of corresponding elements between the graph and the complement:
```
[[1,2],[2,5],[1,2],[3,3],[1,2],[5,4],[3,3],[5,4],[4,1],[5,4]]
```
Clearly, what we want here is for there to be no more than 1 pair starting from each element (thus proving that the elements of the graph and the complement are in 1-to-1 correspondence). We can almost verify that just by stating that the list has at exactly `?` distinct elements (i.e. a number of distinct elements equal to the number of vertices). In this case, the test succeeds; the distinct elements are:
```
[[1,2],[2,5],[3,3],[5,4],[4,1]]
```
However, this leaves room for a potential problem; if a vertex is entirely disconnected in the original graph, its correspondence won't be mentioned, leaving room for a duplicate correspondence from some other vertex. If this is the case, the complement graph must have an edge between that vertex (without loss of generality, let's say it's `1`), and every other vertex, and so the list of correspondences will contain `[1,2]`, `[1,3]`, …, `[1, ?]`. When `?` is large, this will lead to more correspondences total than we'd have otherwise, so there's no problem. The only issue happens when `?` is 3 or lower, in which case we only end up adding one extra correspondence (whilst removing one from `1` not appearing in the input); however, this is not a problem in practice, because there are 3 possible edges on a 3-element graph, which is an odd number (likewise, 1 possible edge on a 2-element graph is also an odd number), and thus the test will fail at the `\` step (you can't transpose a ragged list, i.e. ones whose elements have different lengths).
[Answer]
# BBC BASIC, 161 bytes
Tokenised filesize 140 bytes
Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
```
I.m:IF2ANDm ORm<4P.0:END
r=400n=-2A.m:t=2*PI/n:F.i=1TOn*n:a=i DIVn:b=i MODn:c=b:IFa+b A.2a*=t:b*=t:L.r+r*SINa,r+r*COSa,r+r*SINb,r+r*COSb:IF 1A.m A.c DRAWr*3,0
N.
```
**Ungolfed code**
```
INPUTm :REM get input
IF2ANDm ORm<4PRINT0:END :REM if m=4x+2 or 4x+3 or less than 4, print 0 and exit
r=400 :REM radius of diagram
n=-2ANDm :REM n = m truncated to an even number
t=2*PI/n :REM t = 1/n turns
FORi=1TOn*n :REM for each combination of vertices
a=i DIVn :REM extract a and b
b=i MODn :REM make a copy of c
c=b :REM if a+b MOD 4 = 2 or 3, convert a and b to angles and draw edge.
IFa+b AND2 a*=t:b*=t:LINEr+r*SINa,r+r*COSa,r+r*SINb,r+r*COSb:IF 1ANDm ANDc DRAWr*3,0
NEXT :REM if m is odd and c is odd, draw a line to the additional vertex for m=4x+1 input.
```
**Explanation**
This uses the same algorithm as Xnor, but produces a diagrammatic output.
Where `n` is of the form `4x+2` or `4x+3` there is no solution as the number of edges is odd.
Where `n` is of the form 4x we arrange all the vertices in a circle and draw those edges where `(a+b) mod 4`is 2 or 3 (not 0 or 1 as in Xnor's case, for golfing reasons. This is therefore the complement of the solution given by Xnor.)
To see this in a more pictoral sense, we take every second vertex and draw the edges to the vertices 1 and 2 places away in anticlockwise direction. This defines `n` parallel directions, half of the total. Then we add in all the other edges parallel to these.
The complement can be found by adding 1 to both a and b in each edge specification, or pictorally by rotating the diagram by a `1/n` turn.
Where `n` is of the form 4x+1 we add another vertex, which is linked to every second vertex of the 4x graph. If it was placed at the centre the symmetry of the diagram would be preserved, but I chose to place it outside the main circle of points for clarity.
**Output**
The following are the first few cases for 4x+1. the 4x cases can be seen by deleting the vertex at bottom right and its associated edges.
[](https://i.stack.imgur.com/d6OHe.png)
[Answer]
# [Haskell](https://www.haskell.org/), 75 bytes
```
f n=[(a,b)|b<-[1..n],a<-[1..b-1],n#0,a#sum(b:[a|n#3,n==b])]
x#y=mod(x+y)4<2
```
[Try it online!](https://tio.run/##Jc1BCsIwEEDRvacYiIsEJ8Wqm0rmCJ4gzGKCisVmLFahhdw9Ku7@6v2bTPfLMNR6BaVoBZMrKfjYNo0yyr@SbxnVbFHM9M42HaMUNXtUosSOV7NZKD/Odt4s7hB2NUuvQJBlPMH47PUFa4hW8ftwBRSChx/bMdcP "Haskell – Try It Online")
This is a direct golf of [@xnor's solution](https://codegolf.stackexchange.com/a/107949/101474) posted as a separate answer [for the bounty](https://codegolf.meta.stackexchange.com/a/18334/101474)
There are two 1 byte saves here, one by replacing `last` with `sum` since in the case where we are checking whether `a` is even via `2*a mod 4 < 2`, `b` happens to be known to be `1 mod 4` so adding it as well (producing `2*a+b`) is harmless.
The second is by creating the hammer of `x#y=mod(x+y)4<2` and aggressively finding a bunch of nails to hit with it, which just barely comes out to 1 byte shorter.
[Answer]
# JavaScript (ES6), 191 bytes
```
f=(n,a=[],v=n*~-n/4)=>v%1?0:eval(n>5?f(n-=4,a)&&'for(i=0;i<n;)a.push([i,n+1],[i++,n+2]);a.push([n,++n],[n,++n],[n,++n])-v':'for(l=x=0;x<n;x++)for(y=x;y<n;y++)l<v&y>>x&1?l=a.push([x,y]):a')||a
```
This function returns an adjacency list. It uses two algorithms, and differentiates between empty complementary graphs and non-outputs by returning `0` instead of `[]` when none exists. The first algorithm is based on [Rado Graphs constructed using the BIT predicate](https://en.wikipedia.org/wiki/Rado_graph#Binary_numbers), and creates valid 0-, 1-, 4- and 5-order complementary graphs. The other algorithm, found by [our friends at mathematics](https://math.stackexchange.com/a/40752/305226), constructs a valid V+4 vertex complementary graph by applying a [4-path addition](http://math.nie.edu.sg/fmdong/In-service/self-com.pdf) to a valid V vertex complementary graph.
It begins by validating the input to confirm the existence of a valid complementary graph (using `n*~-n/4%1`), and if that fails, returns `0`. It then checks if `n>5` and recurses to the `n-4` case to construct a valid lower order solution, then applies the 4-addition to the returned adjacency list on the way back up the recursion chain. Lastly, if `n>5` is not true, it iterates from `0` to `n-1` for `x` and `y`, and checks if the `(y>>x)&1` is true. If so, then those nodes are paired.
Here is a more readable format of the function, with ternary operators expanded to if-else statements and `eval()`s inlined:
```
// precalculate amount of required vertices in v
f = (n, a = [], v = n*~-n / 4) => {
// if amount is non-integer
if (v % 1) {
// no valid complementary graph
return 0;
} else {
if (n > 5) {
// generate valid (n-4)-order complementary graph
f(n -= 4, a);
// apply 4-path addition
for (i = 0; i < n;)
a.push([i, n+1],[i++, n+2]);
a.push([n, ++n], [n, ++n], [n, ++n]);
} else {
// construct Rado graph using BIT predicate
for(l = x = 0; x < n; x++)
for(y = x; y < n; y++)
// if amount of pairs is less than required and xth bit of y is high
if (l < v && (y>>x & 1))
// vertices x and y should be paired
a.push([x,y]);
}
return a;
}
};
```
### Demo
```
f=(n,a=[],v=n*~-n/4)=>v%1?0:eval(n>5?f(n-=4,a)&&'for(i=0;i<n;)a.push([i,n+1],[i++,n+2]);a.push([n,++n],[n,++n],[n,++n])-v':'for(l=x=0;x<n;x++)for(y=x;y<n;y++)l<v&y>>x&1?l=a.push([x,y]):a')||a
```
```
<input type="number" onchange="o.textContent=JSON.stringify(f(this.value))"><pre id="o"></pre>
```
] |
[Question]
[
Now, we all know most languages have very simple ways to "self-modify" code.
However, what if you were to actually modify the code and edit parts of it...on disk?
Your goal is to make code that prints a number, then edits its own file to replace the number with the next one in the Fibonacci sequence like so:
```
$ ./program
1
$ ./program
1
$ ./program
2
$ ./program
3
$ ./program
5
[etc...]
```
# Rules
1. You may not store the number(s) "outside" of the code. No comments, no telling the script to exit, no EOF, etc.
2. If your code works with any filename, subtract 2 from your byte amount and write `$BYTESNOW ($ORIGINALBYTES - 2)` in your title. (Filenames are assumed to be within the range of any alphanumeric file path.)
3. Your code must write the output to the file on it's own, without any external piping assistance.
4. Your code can start from one or zero. It doesn't matter.
[Answer]
# Bash, ~~52~~ 47 (49-2) bytes
EDITS:
* Saved 5 bytes, by starting with 1 instead of 0. Thanks @Leo !
**Golfed**
```
A=$[1+0]
echo $A
sed -ri "s/\w+\+(\w+)/\1+$A/" $0
```
**Test**
```
>for i in `seq 10`
> do
> ./fibo
> done
1
1
2
3
5
8
13
21
34
55
```
[Answer]
## Batch, 81 bytes
```
@call:c
@set/az=x+y
@echo %x%
@echo>>%0 @set/ax=%z%,y=%x%
:c
@set/ax=0,y=1
```
Note: the trailing newline is significant. Requires the script to be invoked using its full name including extension. Output starts at 0.
Since Batch can't realistically edit a file, I just add extra lines to the end of the file, so eventually it will know which the next number to print is. The `>>%0` placement saves a byte because I can't precede it with a digit.
[Answer]
## Python 2, ~~118~~ 111 bytes ( 113 - 2 )
```
a,b=0,1;print a
f=open(__file__,'r+')
s=f.read()
s=s.replace(s[4:s.find(';')],`b`+','+`a+b`)
f.seek(0)
f.write(s)
```
It works with any valid filename. There is not much to explain here, the code itself is very verbose.
Thanks to [FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack) for reminding me, `close()` is not mandatory.
[Answer]
## Python 3.6, ~~96~~ 91 (93-2) bytes
```
a,b=0,1
f=open(__file__,"r+");next(f);f.write(f"a,b={b,a+b}\n{next(f)}{f.seek(0)}");print(b)
```
hardcoding the filename would save 5 bytes (88 bytes):
```
a,b=0,1
f=open("f","r+");next(f);f.write(f"a,b={b,a+b}\n{next(f)}{f.seek(0)}");print(b)
```
*Saved some bytes thanks to @Artyer*
[Answer]
# C, 142 bytes (144 - 2)
```
void main(int x,char**a){FILE*f=fopen(*a,"r+");fseek(f,27,0);char n=fgetc(f),m=fgetc(f);fseek(f,27,0);printf("%d\n",fputc(fputc(m,f)?n+m:1,f));}
```
It's pretty straight forward. First it reads then saves the two chars at position 0x1A in the header. I probably could've looked deeper to find a safer spot to save the data but it works for me on my machine running OSX, compiled with GCC 4.2ish and I doubt it's very portable. Also, since it's based off chars it overflows after the 13th iteration.
It gives the output:
```
1
1
2
3
5
8
13
21
34
55
```
[Answer]
# Node.js, ~~152~~ 137 bytes (139 - 2)
Separated with newlines for clarity, not part of byte count.
```
f=_=>require('fs').writeFileSync(__filename,
`f=${f};f()`.replace(/(\d[^,]*),(\d[^\)]*)/,
(m,a,b)=>`${b=+b},${+a+b}`),console.log((0,1)));
f()
```
Explanation:
```
f=_=> // define `f` as function with a single unused argument `_`
require('fs').writeFileSync( // import the standard filesystem module and overwrite file
__filename, // string var containing path of file for current module
`f=${f};f()`.replace( // template string containing source of entire script
/(\d[^,]*),(\d[^\)]*)/, // regexp to match and group the numbers in this script
(m,a,b)=> // replace function with arguments match, group a, group b
`${b=+b},${+a+b}` // template string incrementing fibonacci numbers in place
), // end replace()
console.log( // prints to stdout, `undefined` passed to argument
(0,1) // comma separated group returns value of last expression
) // end console.log()
) // end fs.writeFileSync()
; // end statement defining `f` as arrow function
f() // run function to modify script and print fibonacci number
```
Usage:
```
// assuming above script is stored in program.js
$ node program
1
$ node program
1
$ node program
2
$ node program
3
$ node program
5
...
```
[Answer]
# bash + Unix utilities, 43 bytes (45-2)
```
dc -e9k5v1+2/z^5v/.5+0k1/p;sed -i s/z/z1+/ $0
```
The first time this is run, it uses dc to compute the 1st Fibonacci number via the Binet formula. Each call to sed modifies the program by changing the string passed to dc; this change tells dc to add an additional 1 to the exponent in the formula, which causes it to compute the next number in the Fibonacci sequence each time.
**Test**
```
> for k in {1..10}
> do
> ./fib
> done
1
1
2
3
5
8
13
21
34
55
```
To illustrate how it works, at this point, after the 55 is printed, the program has been modified to read:
```
dc -e9k5v1+2/z1+1+1+1+1+1+1+1+1+1+^5v/.5+0k1/p;sed -i s/z/z1+/ $0
```
so running it again yields
```
> ./fib
89
```
and the program now reads:
```
dc -e9k5v1+2/z1+1+1+1+1+1+1+1+1+1+1+^5v/.5+0k1/p;sed -i s/z/z1+/ $0
```
[Answer]
# SmileBASIC 3, 99 bytes (101 -2)
-2 byte bonus because it works with any filename.
```
A=0B=1F$="TXT:"+PRGNAME$()S$=LOAD(F$)SAVE F$,SUBST$(S$,0,INSTR(S$,"F"),FORMAT$("A=%DB=%D",B,A+B))?A+B
```
This one does work, and it somehow ended up being the same size as my broken one!
[Answer]
# Batch, 66 - 2 = 64 bytes
Uses \r line terminators (not traditional \r\n)
```
@call:a
@set/az=x+y
@(set/p=,x=%z%,y=%x%)<%0>>%0
:a
@goto&set/ax=1
```
Any filenames are allowed, except for `0-9` (which isn't a `.bat` anyways)
---
Credits to:
[Original answer](https://codegolf.stackexchange.com/a/107668/94029) by **@Neil**
**@dbenham** mentioning the weird [behavior](https://stackoverflow.com/a/20333575/12861751) of `GOTO :invalid_or_empty label` (originally discovered by some [Russians](http://forum.script-coding.com/viewtopic.php?id=9050)):
>
> In summary, `(GOTO) 2>NUL` behaves like `EXIT /B`, except it **allows execution of concatenated commands** in the context of the caller!
>
>
>
**Warning**: will overflow if the number exceeds `2^31-1` (47), because batch integers are 32-bits.
[Answer]
# R, 145 bytes (147 - 2)
```
a=c(1,1)
cat(a[1])
R=readLines(f<-sub("^.+=","",grep("^--f",commandArgs(F),v=T)))
cat(c(sprintf("a=c(%i,%i)",a[2],sum(a)),R[-1]),file=f,sep="\n")
```
(Has a trailing newline). It works with any valid filename.
[Answer]
# [Perl 6](http://perl6.org/), ~~67~~ 62 bytes (64 - 2)
```
say (1,1,*+*...*)[1];$*PROGRAM.&{.spurt: .slurp.&{S/\[<(\d+/{$/+1}/}}
```
```
say 0+1;$*PROGRAM.&{.spurt: .slurp.&{S/(\d+).(\d+)/$1+{$0+$1}/}}
```
[Answer]
# Stacked, noncompeting, 65 (67 - 2) bytes
Some issues regarding file IO were fixed in the most recent series of commits. Thus, noncompeting.
```
2:>
:sum\tail...\stack:0#out repr LF+program LF split last+d0\write
```
[Here's a link to the github.](https://github.com/ConorOBrien-Foxx/stacked)
## Example execution
(I omitted the actual path for clarity.)
```
C:\
λ type permanently-self-modifying-code.stk
2:>
:sum\last\stack:0#out repr LF+program LF split last+d0\write
C:\
λ stacked permanently-self-modifying-code.stk
1
C:\
λ stacked permanently-self-modifying-code.stk
1
C:\
λ stacked permanently-self-modifying-code.stk
2
C:\
λ stacked permanently-self-modifying-code.stk
3
C:\
λ stacked permanently-self-modifying-code.stk
5
C:\
λ stacked permanently-self-modifying-code.stk
8
```
## Explanation
How this works is by taking a pair of numbers to begin the sequence (`2:>` in this case is the integer range `[0, 2)`, which is `(0 1)`), then performing the Fibonacci transformation on them, like so:
```
:sum\last\ top of stack: (x y)
: duplicate. stack: ((x y) (x y))
sum sum of TOs. stack: ((x y) x+y)
\ swap order. stack: (x+y (x y))
last obtain last element. stack: (x+y y)
\ swap order. stack: (y x+y)
```
On each run, this transformation is executed on the top of stack. Then, the stack is pushed to the stack, duplicated, and its first member obtained (`stack:0#`). This item is then outputted, and is the desired Fibonacci number. `repr` then takes the representation of the stack and appends a newline. Then, the program is pushed to the stack, and split on newlines. Then, we take the last member (the last line), and append this to the aforementioned string. Finally, we push `d0` (the file itself; think `d`ollar sign `0` == `$0`.) and write to it.
[Answer]
# Ruby, 68 bytes (70-2)
```
p$a=1+0
f=open$0,'r+'
s=f.read.sub /\d+.(\d+)/,"\\1+#$a"
f.seek 0
f<<s
```
[Answer]
# Clojure, ~~209~~ ~~204~~ 195 bytes
```
0 1(let[u #(apply str %)a"./src/s.clj"p #(Long/parseLong(u %))l(fn[v](split-with #(Character/isDigit %)v))c(slurp a)[n[_ & r]](l c)[m r](l r)b(+(p n)(p m))](println b)(spit a(str(p m)" "b(u r))))
```
-5 bytes by switching to parse the numbers as a long instead of an integer, and removing a couple missed spaces.
-9 bytes by removing the space between the second number and `(let...)` (most expensive space ever!).
See the pregolfed code comments for a description.
Tested again, and it no longer throws unmatched bracket errors. It works up to 7540113804746346429, at which point it throws an integer overflow exception.
Also note, this assumes the source code is located at "./src/s.clj".
```
0 1 ; Starting numbers
(let [; The first 4 entires are shortcuts to functions and data that are used more than once
u #(apply str %) ; Turns a list into a string
a "./src/s.clj" ; Current location
p #(Integer/parseInt (u %)) ; Integer parsing shortcut
; Used to split a string on digits to parse them out
l (fn [v] (split-with #(Character/isDigit %) v))
src (slurp a) ; Get the source
[n [_ & r]] (l src) ; Use deconstructuring to grab the first number
[m r] (l r) ; Same as above, grabbing the second number
n' (+ (p n) (p m)) ; Parse the 2 numbers, and add them
; Put everything back together, only this time with the new numbers
k (str (p m) " " n' (u r))]
(println n') ; Print the new number
(spit a k)) ; Overwrite the old source
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 73 bytes
```
b=c=1;exec(a:="print(b);open(*'aw').write(f'b,c={c,b+c};exec(a:=%r)'%a)")
```
filename should be `a`
## Explanation
```
b=c=1;exec(a:="print(b);open(*'aw').write(f'b,c={c,b+c};exec(a:=%r)'%a)")
b=c=1 # Set b and c to 1
a:="print(b);open(*'aw').write(f'b,c={c,b+c};exec(a:=%r)'%a)" # Set a to the string and return it
exec( ) # Execute `a` as python code
print(b) # Prints b
open(*'aw') # Opens a files named `a` in write mode
f'b,c={c,b+c};exec(a:=%r)'%a # String Formatting: 'b,c=(<c>,<b+c>);exec(a:="<a>")'
.write( ) # Write the string to the file
```
[Try it online!](https://tio.run/##PYyxDsIgFAB3vuKFpAG0khIXY4ubrn7DA2nKAgRJqmn67cjkjZfcGXwv1WKBGyBM0wno/fmg1Wir1eg@znK8apqyD4UbMcbkAj8wXJmQa/bF8ZmZ3urN9uZo93/RZcE6FFTUtiNkjhk8@ACbklINw05ekUAjfcsSw1leAJsKrv4A "Bash – Try It Online")
] |
[Question]
[
This challenge is simple. Given a number, output a ascii-art representation of the number, using the Mayan Base-20 numeral system.
### What is the Mayan system?
The Mayans used base 20 to store numbers, so the first position was the `1`s place, the next the `20`s place, then the `400`s, etc.
So Mayan number `1` is `1` in base 10, but `10` is actually `20` in base 10, `207` is `807` in base 10, etc..
And they represented their numbers as pictographs, with a special symbol for `0`.
```
-------------------
| | | | |
| | | | |
|-------------------|
| |
| |
-------------------
```
That was their zero. (at least the half picascii half my artisticness ascii art version)

That is a ~~real~~ picture of the mayan zero symbol.1
This was their five:
```
--------------------------------
| |
--------------------------------
```
And a 4:
```
---- ---- ---- ----
| | | | | | | |
| | | | | | | |
---- ---- ---- ----
```
Finally, to put it together:
```
---- ---- ----
| | | | | |
| | | | | |
---- ---- ----
--------------------------------
| |
--------------------------------
--------------------------------
| |
--------------------------------
```
So they have `x//5` bars, and `x%5` dots on top of the bars. And if `x=0`, they use the shell/loaf instead of a blank space.
For more images, try [the Wikimedia Commons page of Maya number images](https://commons.wikimedia.org/wiki/Maya_numbers).
But this is only for numbers up to `19`. We aren't allowed to have more than `4` bars and `4` dots *in a single 'story'*... So we go up!
The output for 20 is:
```
----
| |
| |
----
-------------------
| | | | |
| | | | |
|-------------------|
| |
| |
-------------------
```
Note this would normally be invalid, because is has a `1` and a `0` at the same time. But the `3` (note that, your answer needs at least 3) newlines before the `0` mean a new place value.
The bottom story has dots, meaning `1`, and bars meaning `5`. But it actually has dots meaning `20^0` and bars meaning `20^0 * 5`.
Each story goes up a power. The second story dots mean `20` (`20^1`) and `100` (`20^1 * 5`).
So the number `506` can be represented as:
```
----
| |
| |
----
--------------------------------
| |
--------------------------------
----
| |
| |
----
--------------------------------
| |
--------------------------------
```
This is `(20^0) * 1 + (20^0 * 5) * 1 + (20^1 * 5) * 1 + (20^2) * 1 = 1 + 5 + 100 + 400 = 506`.
Your mission, should you choose not or choose to (it doesn't matter), is to output a ascii art representation of the base-10 number.
### Other Rules:
* Leading/trailing space is okay, as long as the dots, bars, and shells are intact.
* The bars, dots, and shells must be *exactly* what the test cases have. No resizing.
* Leading '0's are okay. (leading shells on the output)
* You don't have to have exactly 3 newlines between each place value or story, just at least 3.
### Test Cases:
```
15
--------------------------------
| |
--------------------------------
--------------------------------
| |
--------------------------------
--------------------------------
| |
--------------------------------
12
---- ----
| | | |
| | | |
---- ----
--------------------------------
| |
--------------------------------
--------------------------------
| |
--------------------------------
4
---- ---- ---- ----
| | | | | | | |
| | | | | | | |
---- ---- ---- ----
0
-------------------
| | | | |
| | | | |
|-------------------|
| |
| |
-------------------
24
----
| |
| |
----
---- ---- ---- ----
| | | | | | | |
| | | | | | | |
---- ---- ---- ----
33
----
| |
| |
----
---- ---- ----
| | | | | |
| | | | | |
---- ---- ----
--------------------------------
| |
--------------------------------
--------------------------------
| |
--------------------------------
20
----
| |
| |
----
-------------------
| | | | |
| | | | |
|-------------------|
| |
| |
-------------------
```
1: They also used the heads of gods for the symbols, but for this challenge the shell/bread/[zelda chest](https://www.youtube.com/watch?v=69AyYUJUBTg) will be used.
[Answer]
# Python 3.5, 404 400 392 312 311 308 290 281 285 281 bytes:
(*Thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) for a tip on saving 9 bytes(`290->281`) and [Neil](https://codegolf.stackexchange.com/users/17602/neil) for a tip on saving 4 bytes(`285->281`)!*)
```
def u(z):
p=[];P=print;S,N,M,X=' -|\n'
while not p or z:p+=[z%20];z=z//20
E=lambda i:(S+N*4+S)*i+X+((M+S*4+M)*i+X)*2+(S+N*4+S)*i+X;F=N*32+X+M+S*30+M+X+N*32+X;[P(S+N*19+S+X+M+((S*4+M)*4+X+M)*2+N*19+M+X+(M+S*19+M+X)*2+S+N*19+S+X*3)if y<1else P(E(y%5)+F*(y//5)+X*3)for y in p[::-1]]
```
[Try it online! (Ideone)](http://ideone.com/WIuD5V)
# Analysis
For the purposes of this analysis, we will use the character set `0123456789ABCDEFGHIJ` to represent each digit in base 20.
So, I could have gone and converted base 10 into base 20 using one of two algorithms I have. The first algorithm I thought of using is what I call the **powers algorithm**. This is not the one that I used in the code though as it would have made it way longer than it should have been, so I'm not going to talk about this one. However, I did create a python script that converts any integer in base 10 into any other base provided using this method, which you can use [here](https://repl.it/CL6R/1) on repl.it. The one I used instead for this challenge is what I call the **division algorithm**, which I think is explained pretty good [here](http://www.purplemath.com/modules/numbbase.htm). But basically what happens is that it takes the base 10 number provided and divides it by the base it needs to convert the number to, which in this case is 20, until the remainder is either 0 or 1. It then takes the quotiant and remainder, in that order, from the *last* division operation, and then all the other remainders from the other division operations in the order from last to first. All these digits are then joined together, and that joined sequence *reversed* is your base 10 number in base 20! To illustrate this, assume you want to convert the base 10 number `431` to base 20. So, what we would do is this:
```
[]=list we will put all remainders and the last quotient in
R = Remainder
1. 431/20 = 21 R11 [B (B=11 in base 20)]
2. 21/20 = 1 R1 [Add the remainder and quotient: B11]
```
Then, finally we would take the list we have, which in this case contains `B11`, and *reverse* it so that we now have `11B`. In doing this, we have finally got our final answer! 431 in base 10 converted to base 20 is `11B`, which can be confirmed using my Python script that uses the powers algorithm which I already shared a link to above, but I will do it again [here](https://repl.it/CL6R/1). [Here](https://repl.it/CL67/0) is one that also uses the division algorithm described in this answer and returns the same answer as the powers one.
This entire process is essentially what happens in my script in this `while` loop: `while not p or z:p+=[z%20];z=z//20`. The only difference is that numbers `>9` are *not* represented as letters but instead as themselves.
Moving on, after the base 10 number has been converted to base 20, for each digit in the base 20 integer, which we will call `g`, `g mod 5` dots are printed out and then `g//5` bars are printed out. Then the program prints 3 blank lines and moves on to the next digit. However, if the digit is `0`, then a single "loaf" is printed out followed by 3 new lines, and then the program moves onto the next digit. So, taking the base 20 number `11B`, we go to the first digit. The first digit is `1`, and therefore it would print 0 bars since `1//5=0`, and 1 dot since `1%5=1`. So, we would first get this:
```
----
| |
| |
----
```
and then 3 new lines. Moving onto the the second digit, we also see that it is 1, so it would output the same thing:
```
----
| |
| |
----
```
and also 3 new lines. Finally, moving onto the last digit, we see that it's a `B`. Since `B=11` in base 20, the program would output 1 dot since `11%5=1` and 2 bars since `11//5=2`. So now, we get this:
```
----
| |
| |
----
--------------------------------
| |
--------------------------------
--------------------------------
| |
--------------------------------
```
Finally, putting all this together, we get this:
```
----
| |
| |
----
----
| |
| |
----
----
| |
| |
----
--------------------------------
| |
--------------------------------
--------------------------------
| |
--------------------------------
```
And, that's the mayan numeral for 431! You finally have your base 10 number represented in base 20 Mayan numerals.
**Note:** You may or may not have noticed that `lambda` function in my code. Regardless, this function is used for the creation of the dots since multiple dots must be output next to each other.
[Answer]
# Ruby, ~~223~~ ~~180~~ ~~177~~ 179 bytes
Anonymous function, returns a multiline string.
Forgot to add some extra spacing that was needed, and also the recursion. Also golfed a bit more by shifting things around.
```
f=->n{s=?|;e=' ';n<20?(n<1?[t=e+d=?-*19,a=s+(e*4+s)*4,a,s+d+s,b=s+e*19+s,b,t]:((r=n%5)>0?[t=" ---- "*r,m="| | "*r,m,t]:[])+[a=?-*32,s+e*30+s,a]*(n/5))*$/:f[n/20]+$/*5+f[n%20]}
```
[Answer]
# Python 3, 243 bytes
```
s,v,h,x=' |-\n';P=print
t=s+h*19+s+x
def m(n):
n//20and m(n//20);r=n%20
if r:
for a,b,f in[(r%5*' ---- ',r%5*'| | ',1),('-'*32,'|'+' '*30+'|',r//5)]:P(*((a,b,b,a)*f),sep=x)
else:P(t+2*(v+(4*s+v)*4+x)+v+h*19+v+x+2*(v+s*19+v+x)+t)
P(x)
```
# Discussion
`n//20and m(n//20)` calls `m()` recursively if there are higher powers of 20 to be handled. The recursion is done before printing the current place value, so that higher powers get printed first.
If the current place value is non-zero (r!=0), the `for a,b,f`-loop prints the units and then the fives. `a` is the first/forth row and `b` is the second/third row. The trick is in the `print(*((a,b,b,a)*f),sep=x)`. For the units, f = 1 resulting in `print(*(a,b,b,a),sep=x)`, which prints the 4 rows that make up the units symbols (x is a '\n'). For the fives, f = the number of fives to print (r//5), so the tuple (a,b,b,a) gets multiplied (i.e., repeated) by the number of fives to print. If f = 2, we get `print(*(a,b,b,a,a,b,b,a),sep=x)`, which prints two symbols for five.
If the current place value is 0, then the zero symbol is printed.
[Answer]
# Python, 411 bytes
```
w,m=input(),[]
for i in[20**i for i in range(int(w**0.25))][::-1]:m.append(w/i);w=w%i
for i in m or[0]:print(lambda x,y='\n',w=' ---- ',z='| | ':w*(x%5)+y+z*(x%5)+y+z*(x%5)+y+w*(x%5)+y+('-'*32+'\n|'+' '*30+'|\n'+'-'*32+y)*(x/5)if x else''' -------------------
| | | | |
| | | | |
|-------------------|
| |
| |
------------------- ''')(i),'\n\n\n'
```
I created this to generate test cases, you can use it as a benchmark. Sorta golfed.
[Answer]
## JavaScript (ES6), 254 bytes
```
f=(n,r=(s,n=19)=>s.repeat(n))=>(n>19?f(n/5>>2)+`
`:``)+(n%5?`${r(s=` ---- `,n%5)}
${t=r(`| | `,n%5)}
${t}
${s}
`:``)+r(`${s=r(`-`,32)}
|${r(` `,30)}|
${s}
`,n/5&3)+(n%20?``:` ${s=r(`-`)}
${t=r(`| `,4)}|
${t}|
|${s}|
|${t=r(` `)}|
|${t}|
${s}
`)
```
[Answer]
# Python 3, 213 bytes
Came up with an even shorter version using a different approach:
```
s,v,h,x=' |-\n'
t=s+h*19+s
k=4*s+v
w=v+4*k
y=v+s*19+v
a=' ---- '
b=v+k+s
c=h*32
d=v+s*30+v
m=lambda n:m(n//20)+([n%5*a,n%5*b,n%5*b,n%5*a][:n%5*4]+n%20//5*[c,d,d,c]if n%20else[t,w,w,v+h*19+v,y,y,t])+[x,x]if n else[]
```
# explanation
The first 9 lines or so, build up strings that are used to make the symbols
```
s,v,h,x = ' |-\n'
k = ' |'
# parts for a unit
a = ' ---- '
b = '| | '
# parts for a five
c = '--------------------------------'
d = '| |'
# parts for a zero
t = ' ------------------- '
w = '| | | | |'
y = '| |'
```
The core of the solution is the recursive function `m`, which builds a list of strings, one string for each line in the output. Schematically, `m` looks like:
```
m(n//20) + (ones + fives if n%20 else zero) + [x,x] if n else []
```
`m` can be rewritten like:
```
def m(n):
if n:
ans = m(n//20) # process high digits first
if n%20: # if there is a base-20 digit
ans += [n%5*a,n%5*b,n%5*b,n%5*a][:n%5*4] # add strings for the 'ones' if any
ans += n%20//5 * [c, d, d, c] # add strings for the 'fives' if any
else:
ans += [t,w,w,v+h*19+v,y,y,t] # otherwise, add strings for a `zero`
ans += [x,x] # blank lines between digit groups
else:
ans = [] # base case
return ans
```
The recursive call `m(n//20)` comes first so that the most significant digits are done first.
`[n%5*a,n%5*b,n%5*b,n%5*a]` are the string for ones symbols. `a` is the top row for a single symbol. `n%5` is the number of one symbols for this digit. So, `n%5*a` is a string for the top (and bottom) row of `n%5` ones. Similarly, 'n%5\*b` is a string for the 2nd (and 3rd) row.
The expression `[:n%5*4]` acts like an `if` to avoid extra blank lines in the output if there aren't any 'ones' to output. It's not needed, but makes the output look better.
`n%20//5` is the number of symbols for five that are needed. `[c,d,d,c]` are the strings to make one symbol for five.
`[t,w,w,v+h*19+v,y,y,t]` are the strings to make the zero symbol
`[x,x]` puts at least three blank lines between groups of Mayan digits
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 89 bytes
```
20τƛ¶3*,¬[ð19-…\|4꘍4*\|+…,\|19-\|+,\|19꘍\|+…,,]5ḋ£ð4-ðd+`| `mð+"mƛ¥*t,;n5ḭ(32\|15꘍-m3/⁋,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=20%CF%84%C6%9B%C2%B63*%2C%C2%AC%5B%C3%B019-%E2%80%A6%5C%7C4%EA%98%8D4*%5C%7C%2B%E2%80%A6%2C%5C%7C19-%5C%7C%2B%2C%5C%7C19%EA%98%8D%5C%7C%2B%E2%80%A6%2C%2C%5D5%E1%B8%8B%C2%A3%C3%B04-%C3%B0d%2B%60%7C%20%20%60m%C3%B0%2B%22m%C6%9B%C2%A5*t%2C%3Bn5%E1%B8%AD%2832%5C%7C15%EA%98%8D-m3%2F%E2%81%8B%2C&inputs=20&header=&footer=)
Outputs a *lot* of extra newlines.
] |
[Question]
[
This [Stack Snippet](http://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) draws an [aliased](http://en.wikipedia.org/wiki/Aliasing) white rectangle on a black background given parameters for its dimensions, position, angle, and the grid dimensions:
```
<style>html *{font-family:Consolas,monospace}input{width:24pt;text-align:right;padding:1px}canvas{border:1px solid gray}</style><p>grid w:<input id='gw' type='text' value='60'> grid h:<input id='gh' type='text' value='34'> w:<input id='w' type='text' value='40'> h:<input id='h' type='text' value='24'> x:<input id='x' type='text' value='0'> y:<input id='y' type='text' value='0'> θ:<input id='t' type='text' value='12'>° <button type='button' onclick='go()'>Go</button></p>Image<br><canvas id='c'>Canvas not supported</canvas><br>Text<br><textarea id='o' rows='36' cols='128'></textarea><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>function toCart(t,a,n,r){return{x:t-n/2,y:r/2-a}}function vtx(t,a,n){return{x:n.x+t*Math.cos(a),y:n.y+t*Math.sin(a)}}function sub(t,a){return{x:t.x-a.x,y:t.y-a.y}}function dot(t,a){return t.x*a.x+t.y*a.y}function inRect(t,a,n,r){var e=sub(a,t),o=sub(a,n),l=sub(a,r),i=dot(e,o),v=dot(e,l);return i>0&&i<dot(o,o)&&v>0&&v<dot(l,l)}function go(){var t=parseInt($("#gw").val()),a=parseInt($("#gh").val()),n=parseFloat($("#w").val()),r=parseFloat($("#h").val()),e={x:parseFloat($("#x").val()),y:parseFloat($("#y").val())},o=Math.PI*parseFloat($("#t").val())/180,l=Math.sqrt(n*n+r*r)/2,i=Math.atan2(r,n),v=vtx(l,o+i,e),h=vtx(l,o+Math.PI-i,e),u=vtx(l,o-i,e),x=$("#c");x.width(t).height(a).prop({width:t,height:a}),x=x[0].getContext("2d");for(var s="",c=0;a>c;c++){for(var f=0;t>f;f++)inRect(toCart(f+.5,c+.5,t,a),v,h,u)?(s+="..",x.fillStyle="white",x.fillRect(f,c,1,1)):(s+="XX",x.fillStyle="black",x.fillRect(f,c,1,1));a-1>c&&(s+="\n")}$("#o").val(s)}$(go)</script>
```
([JSFiddle Version](https://jsfiddle.net/CalvinsHobbies/uznprwpr/embedded/result/))
The text representation has `XX` wherever there is a black pixel in the image and `..` wherever there is a white pixel. (It looks squished if they are `X` and `.`.)
Write a program that takes the text representation of a rectangle produced by the Snippet and outputs the approximate width and height of the rectangle, **both to within ± 7% of the actual width and height**.
Your program should work for effectively all possible rectangles that can be drawn by the snippet, with the constraints that:
* The rectangle width and height are 24 at minimum.
* The grid width and height are 26 at minimum.
* The rectangle never touches nor goes out of the grid bounds.
So the input rectangle may have any rotation, position, and dimensions, and the grid may have any dimensions, as long as the three constraints above are met. Note that except for the grid dimensions, the Snippet parameters can be floats.
### Details
* Take the raw text rectangle as input or take the filename of a file that contains the raw text rectangle (via stdin or command line). You may assume the text rectangle has a trailing newline.
* You may assume the text rectangle is made from any two distinct [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters other than `X` and `.` if desired. (Newlines must stay newlines.)
* Output the measured width and height as integers or floats to stdout in any order (since there's no way to determine which one actually went with which parameter). Any format that clearly shows the two dimensions is fine, e.g. `D1 D2`, `D1,D2`, `D1\nD2`, `(D1, D2)`, etc.
* Instead of a program, you may write a function that takes the text rectangle as a string or the filename to it and prints the result normally or returns it as a string or list/tuple with two elements.
* Remember that `XX` or `..` is one 'pixel' of the rectangle, not two.
# Examples
### Ex. 1
Parameters: `grid w:60 grid h:34 w:40 h:24 x:0 y:0 θ:12` (Snippet defaults)
**Input**
```
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX....XXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX........................XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..................................XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX............................................XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX....................................................XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..............................................................XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX..........................................................................XXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX................................................................................XXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX................................................................................XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX..................................................................................XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX..........................................................................XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX..............................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX....................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX............................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX..................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX........................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXX....XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
```
**Example Outputs**
* `40 24`
* `24 40`
* `[40.0, 24.0]`
* `42.8, 25.68` (+7%)
* `37.2, 22.32` (-7%)
### Ex. 2
Parameters: `grid w:55 grid h:40 w:24.5 h:24 x:-10.1 y:2 θ:38.5`
**Input**
```
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX......XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX............XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXX..................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXX......................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX............................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX..............................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX..................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX......................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXX............................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXX..................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXX......................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX............................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX..............................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX................................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXX..............................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXX..............................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXX............................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX......................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX....................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXX................................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXX............................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX......................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX..................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX..........................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX......................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX..................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXX..........XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXX......XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
```
**Example Outputs**
* `24.0 24.5`
* `25.68 26.215` (+7%)
* `22.32 22.785` (-7%)
# Scoring
The shortest code in bytes wins. Tiebreaker is highest voted post.
[Answer]
# Matlab, 226 bytes
The idea is simple: First I try to find out how much the rectangle was turned, then turn the image accordingly such that the rectangle is upright. Then I just 'sum' up all the pixels in the row columns sperately and try count how many of the sums are above than average (simple thresholding) for determining the width and height. This simple method works surprisingly reliably.
*How can I detect the angle?*
I just try each step (one degree each) and sum along the columns and get a vector of sums. When the rectangle is upright, I should ideally get only two sudden changes in this vector of sums. If the square is on the tip, the changes are very gradual. So I just use the first derivative, and try to minimize the number of 'jumps'. Here you can see a plot of the criterion we are trying to minimize. Notice that you can see the four minima which corresponds to the fours possible upright orientations.

Further thoughts: I am not sure how much it could be golfed as the exhausive angle search takes a lot of characters and I doubt you could achieve that so well with built in optimization methods, because as you can see there are a lot of local minima that we are not looking for. You can easily improve the accuracy (for big pictures) by choosing a smaller step size for the angle and only search 90° instead of 360° so you could replace `0:360` with `0:.1:90` or somehting like that. But anyways, for me the challenge was more finding a robust algorithm rather than golfing and I am sure the entries of the golfing languages will leave my submission far behind=)
PS: Someone should really derive a golfing language from Matlab/Octave.
### Outputs
Example 1:
```
25 39
```
Example 2:
```
25 24
```
### Code
Golfed:
```
s=input('');r=sum(s=='n');S=reshape(s',nnz(s)/r,r)';S=S(:,1:2:end-2)=='.';m=Inf;a=0;for d=0:360;v=sum(1-~diff(sum(imrotate(S,d))));if v<m;m=v;a=d;end;end;S=imrotate(S,a);x=sum(S);y=sum(S');disp([sum(x>mean(x)),sum(y>mean(y))])
```
Ungolfed:
```
s=input('');
r=sum(s=='n');
S=reshape(s',nnz(s)/r,r)';
S=S(:,1:2:end-2)=='.';
m=Inf;a=0;
for d=0:360;
v=sum(1-~diff(sum(imrotate(S,d))));
if v<m;
m=v;a=d;
end;
end;
S=imrotate(S,a);
x=sum(S);y=sum(S');
disp([sum(x>mean(x)),sum(y>mean(y))])
```
[Answer]
# CJam, ~~68 65~~ 64 bytes
This *can* be golfed a little more..
```
qN/2f%{{:QN*'.#Qz,)mdQ2$>2<".X"f#_~>@@0=?Qz}2*;@@-@@-mhSQWf%}2*;
```
**How it works**
The logic is pretty simple, if you think about it.
All we need from the input `X.` combinations is 3 coordinates of two adjacent sides. Here is how we get them:
### `First`
In any orientation of the rectangle, the first `.` in the whole of the input is going to be one of the corners. For example..
```
XXXXXXXXXXXXXX
XXXXXXX...XXXX
XXXX.......XXX
X............X
XX.........XXX
XXXX...XXXXXXX
XXXXXXXXXXXXXX
```
Here, the first `.` is in the 2nd line, 8th column.
But that's not it, we have to do some adjustment and add the width of the `.` run on that line to the coordinates to get the coordinate of the right end.
### `Second`
If we transpose the above rectangle (pivoted on newlines), then the bottom left corner takes the above step's place. But here, we do not compensate for the `.` run length as we would have wished to get the bottom left coordinate of the edge anyways (which in transposed form will still be the first encountered `.`)
### `Rest two`
For rest two coordinates, we simply flip horizontally, the rectangle and perform the above two steps. One of the corners here will be common from the first two.
After getting all 4, we simply do some simple math to get the distances.
Now this is not the most accurate method, but it works well within the error margin and well for all possible orientations of the rectangle.
**Code expansion** (bit outdated)
```
qN/2f%{{:QN*'.#Q0=,)md}:A~1$Q='.e=+QzA@@-@@-mhSQWf%}2*;
qN/2f% e# Read the input, split on newlines and squish it
{ ... }2* e# Run the code block two times, one for each side
{:QN*'.#Q0=,)md}:A~ e# Store the code block in variable A and execute it
:QN* e# Store the rows in Q variable and join by newlines
'.# e# Get the location of the first '.'
Q0=,) e# Get length + 1 of the first row
md e# Take in X and Y and leave out X/Y and X%Y on stack
1$Q= e# Get the row in which the first '.' appeared
'.e=+ e# Get number of '.' in that row and add it to X%Y
QzA e# Transpose the rows and apply function A to get
e# the second coordinate
@@-@@- e# Subtract resp. x and y coordinates of the two corners
mh e# Calculate (diff_x**2 + diff_y**2)**0.5 to get 1 side
SQWF% e# Put a space on stack and put the horizontally flipped
e# version of the rows/rectangle all ready for next two
e# coordinates and thus, the second side
```
[Try it online here](http://cjam.aditsu.net/#code=qN%2F2f%25%7B%7B%3AQN*'.%23Qz%2C)mdQ2%24%3E2%3C%22.X%22f%23_~%3E%40%400%3D%3FQz%7D2*%3B%40%40-%40%40-mhSQWf%25%7D2*%3B&input=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX%0AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX%0AXXXXXX............................................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXXXX..........................................................................................XXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXX..........................................................................................XXXXXX%0AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX............................................XXXXXX%0AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX%0AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
[Answer]
# Python 3, ~~347~~ 337 bytes
This turned out harder than I expected. Work in progress...
```
def f(s):
l=s.split('\n');r=range;v=sorted;w=len(l[0]);h=len(l);p=[[x,y]for x in r(w)for y in r(h)if'X'>l[y][x]];x,y=[sum(k)/w/h for k in zip(*p)];g=[[x/2,y]];d=lambda a:((a[0]/2-a[2]/2)**2+(a[1]-a[3])**2)**.5
for i in r(3):g+=v(p,key=lambda c:~-(c in g)*sum(d(j+c)for j in g))[:1]
print(v(map(d,[g[1]+g[2],g[2]+g[3],g[1]+g[3]]))[:2])
```
[Try it online!](https://tio.run/##lVZLb@M2EL77V8waKELZsmzJyRawqkV72FMPC@QUwCsEtERLSvQqRdtSDfevpzOkZHs3KZIebA6H3zcznAftulNpVS5fXmKxhS1rrNUI8qBxmjrPFLv5Xt5YvgwkLxPh74OmkkrE/iHIRcny9SK0/NTIll8H63Vrd@G2ktBCVoJkB4s2ndmkVra9ebj5kq@7cN2GoY/gYN3sCvZszQ/zFAj7TNi/s5pNaiv0EzI599Bo6MdBzotNzIGvGOPoeu7N@NrDxZpMvCmq3BAVy5C2@HHuRtpiZrwvrVUyDfastp9FN5iKVv/MWESAxJpQJDF7mkY66CejtdYrNxyBFGonS9izgtcsttcJOpsm6N2mL5SWJLlGConlhS9RzpsG9iLyMKdA@X18zMpMPT6yRuRbG1obOmsFtHFaCKD1jdyh3J0pPI7PjArhQyxol/XUKVQOGuvJtOusM7/Zbd7jz37gz675caVec3vahGjorufRlsL@vVFcZVEhsLPi3kxd5VwyaQNHK1lRYx9BwVXq/xCORBukdaKqYdyy4axoshIVl0tJUcv@VpewtmNt5WjCO9lgpO5kjUcj4mWlFJFiddVgIDZsbIiQXWO6Od4a1T5A0@82PqhejM5RLuA3qB2dEwvFZhB5GV@dKTpTvagdqyriUjEquA3JAT/pT5WgIiQHmINHh7SiAqug6YkoheRKMEO1AZfU9I/OKKblKqe44xi5zpvkccZLSiZqCzmom78wmgMm94DlS3FNLXKJmOhM5YqXHiNnxI1c1JtIqWuRRhvH1LWgwqIq0m4i7wNQ7aLOKLuGtHyXdIbe/g/7Q1A4igLzU1YKWIHNFLnU8Uij76X@vnVaLFwAM1MHpLqAL0HB2/9Efwn6omFwBmxMdxrcaXCnwV1vOn3D9JtoMj30gUs36Ltl/L0cO08V@hkPq@OMITt399Br6MS5wwT1a991aN4ld@TMApE3AsYPD2O4vNr01GOjWRZcHm@jS3EAR32joSquilGziyLR0MwsRlwpUdTKbBSXiaABcheL0SHNcgEDFmdDH1LbnjlTROIesxmArHZlzLzPGLlx44i2rvZcZjQD7ty90y8BpufDWG3WnO/KDC9WMO/W1gXoE4Np9giZfhjJXyMXNiw/L3S19Bi1jCZ1mK32NeHSa9K@tJIkC91b6PQKnV6jlexW@u16561AqGgjUSv4Q09EVpVfpazkCqKqVFm5E4gYKtUXBR@QYeIm5h8Ao38KOrFRJeXPh2tyGepjoU/JwExDUbXhMarGX@/vv91/0o3LNw1DoB4oWDiLX/FBIjD@uGAHDqfdz6dd377f/vw0Rru1zErFtuNEZvEKjsnh1B6T9ASbqsXtYeW4W9SkesW@g2OrRfvY9aoywSY9crOTotnlCokYu9P2ZJJ7tDBJO@q45ybaCfa6Pv3F6Duj7671ePvTmDKD99aZuKRi1V@hsUbnu/TFjDGOflJOQBfEH7BqCzhXUYq/cqZcJ9jzPIvR@su/) Comes with a test harness that tries 100 random valid rectangles. **Note:** The test harness seems to produce some errors and prints the corresponding grids. It seems like these cases all have rather round corners - an issue which seems to be caused by the grid generation code, which I translated from the original snippet.
Defines a function `f` taking the string as an argument and printing the result to STDOUT.
# Pyth, ~~87~~ ~~84~~ ~~82~~ ~~81~~ ~~75~~ ~~72~~ ~~71~~ bytes (broken)
```
Km%2d.zJf<@@KeThTG*UhKUKPSm.adfqlT2ytu+G]ho*t}NGsm.a,kNGJ3]mccsklhKlKCJ
```
This seems to have been broken in 2015. Since then, something in Pyth has changed so that the old versions now crash and the new ones return `[0, 0]`. Right now I have neither the slightest idea what this monstrosity does nor the time to figure it out. I'm leaving it here as crossed-out for historical reasons.
~~~~Way~~ Still too long. Basically a port of the previous. Loving Pyth's `.a` Euclidean distance. Takes input via STDIN and gives output via STDOUT. Expects the non-rectangle character to be lower-case `x` (well, anything with ASCII value 98 or more).~~
## Algorithm
Both of these use the same algorithm. I basically start with an array containing the center of mass of the rectangle area. I then add three points to the array of all points in the rectangle, always choosing the one with maximum *sum of distances* to the points already in the array. The result is always three points in different corners of the rectangle. I then just calculate all the three distances between those three points and take the two shortest ones.
[Answer]
# Python 2, 342 bytes
```
import sys
r=[]
h=.0
for l in sys.stdin:w=len(l);r+=[[x*.5,h]for x in range(0,w,2)if l[x:x+2]=='..'];h+=1
x,y=.0,.0
for p in r:x+=p[0];y+=p[1]
n=len(r)
x/=n
y/=n
m=.0
for p in r:
p[0]-=x;p[1]-=y;d=p[0]**2+p[1]**2
if d>m:m=d;u,v=p
m=.0
for p in r:
d=p[0]*v-p[1]*u
if d>m:m=d;s,t=p
print ((u-s)**2+(v-t)**2)**.5+1,((u+s)**2+(v+t)**2)**.5+1
```
This took inspiration from @Pietu1998's algorithm. It takes the idea of determining one corner as the point farthest from the center, but differs from there:
* I determine the second corner as the point with the largest cross product with the vector from center to first corner. This gives the point with the largest distance from the line from center to first corner.
* There's no need to search for a third corner, since it's just the mirror image of the second corner relative to the center.
So the code follows this sequence:
* First loop is over the lines in the input, and builds a list `r` of rectangle points.
* Second loop calculates the average of all rectangle points, giving the center of the rectangle.
* Third loop finds the point farthest from the center. This is the first corner. At the same time, it subtracts the center from the points in the list, so that the point coordinates are relative to the center for the remaining calculation.
* Fourth loop finds the point with the largest cross product with the vector to the first corner. This is the second corner.
* Prints out the distance between first corner and second corner, and distance between first corner and mirror image of second corner.
* `1.0` is added to the distances because the original distance calculations use pixel indices. For example, if you have 5 pixels, the difference between the index of the last and first pixel was only 4, which needs compensation in the final result.
Precision is quite good. For the two examples:
```
$ cat rect1.txt | python Golf.py
24.5372045919 39.8329756779
$ cat rect2.txt | python Golf.py
23.803508502 24.5095563412
```
[Answer]
# Python 2, 272 bytes
Posting this as a separate answer since it's an entirely different algorithm than my previous one:
```
import sys,math
y,a,r=0,0,0
l,t=[1<<99]*2
for s in sys.stdin:
c=s.count('..')
if c:a+=c;x=s.find('.')/2;l=min(l,x);r=max(r,x+c);t=min(t,y);b=y+1
y+=1
r-=l
b-=t
p=.0
w,h=r,b
while w*h>a:c=math.cos(p);s=math.sin(p);d=c*c-s*s;w=(r*c-b*s)/d;h=(b*c-r*s)/d;p+=.001
print w,h
```
This approach does not identify corners at all. It is based on the observation that the size (width and height) of the bounding box and the area of the rotated rectangle are sufficient to determine the width and height of the rectangle.
If you look at a sketch, it is fairly easy to calculate the width (`wb`) and height (`hb`) of the bounding box with `w`/`h` the size of the rectangle, and `p` the rotation angle:
```
wb = w * cos(p) + h * sin(p)
hb = w * sin(p) + h * cos(p)
```
`wb` and `hb` can be extracted directly from the image. We can also quickly extract the total area `a` of the rectangle by counting the number of `..` pixels. Since we're dealing with a rectangle, this gives us the additional equation:
```
a = w * h
```
So we have 3 equations with 3 unknowns (`w`, `h` and `p`), which is enough to determine the unknowns. The only bummer is that the equations contain trigonometric functions, and at least with my patience and math skills the system cannot easily be solved analytically.
What I implemented is a brute force search for the angle `p`. Once `p` is given, the first two equations above become a system of two linear equations, which can be resolved for `w` and `h`:
```
w = (wb * cos(p) - hb * sin(p)) / (cos(p) * cos(p) - sin(p) * sin(p))
h = (hb * cos(p) - wb * sin(p)) / (cos(p) * cos(p) - sin(p) * sin(p))
```
With these values, we can then compare `w * h` with the measured area of the rectangle. The two values would ideally be equal at some point. This is of course not going to happen in floating point math.
The value of `w * h` decreases as the angle increases. So we start at angle 0.0, and then increment the angle by small steps until the first time `w * h` is less than the measured area.
The code only has two main steps:
1. Extract size of bounding box and rectangle area from input.
2. Loop over candidate angles until termination criterion is reached.
The precision of the output is good for rectangles where the width and height are significantly different. It gets somewhat iffy with rectangles that are almost square and rotated close to 45 degrees, just barely clearing the 7% error hurdle for test example 2.
The bitmap for example 2 actually looks slightly odd. The left corner looks suspiciously dull. If I add one more pixel at the left corner, it both looks better (to me), and gives a lot better precision for this algorithm.
] |
[Question]
[
Write a named function or program that accepts a single integer N and prints (to STDOUT) or returns (as a string) the first N bars of the spiral below, beginning with the vertical bar in the center and spiraling clockwise outward.
```
_______________
/ _____________ \
/ / ___________ \ \
/ / / _________ \ \ \
/ / / / _______ \ \ \ \
/ / / / / _____ \ \ \ \ \
/ / / / / / ___ \ \ \ \ \ \
/ / / / / / / _ \ \ \ \ \ \ \
/ / / / / / / / \ \ \ \ \ \ \ \
| | | | | | | | | | | | | | | |
\ \ \ \ \ \ \___/ / / / / / / /
\ \ \ \ \ \_____/ / / / / / /
\ \ \ \ \_______/ / / / / /
\ \ \ \_________/ / / / /
\ \ \___________/ / / /
\ \_____________/ / /
\_______________/ /
```
You may assume that 0 < N <= 278. Your output cannot contain any whitespace in front of the leftmost character of the spiral. You may optionally print a single trailing newline.
For an input of 10, the correct output is
```
_
/ \
| |
\___/
```
For an input of 2, the correct output is
```
/
|
```
For an input of 20, the correct output is
```
___
/ _ \
/ / \ \
| | | |
\___/ /
```
An output that would be incorrect because the leftmost character is preceded by whitespace is
```
___
/ _ \
/ / \ \
| | | |
\___/ /
```
The winner is the shortest submission, in bytes.
[Answer]
# Python 2, ~~290~~ 289
It's probably really bad, but I tried :D
The output contains trailing spaces, but that is not forbidden in the spec.
**Update:** saved 1 byte with changing `\n` to `;`.
```
m=x=y=c=0
l,f=1,[31*[' ']for t in[0]*31]
for i in[0]*input():
k=m%4;f[14+y+(2<m<6)][14+x-(m>3)],x,y,c='|/_\\'[k],x+(k>0)*(2*(4>m)-1),y+(k!=2)*(2*(2<m<6)-1),c+1
if(c==l)*(m%2)+(k==0)+(k==2)*(c==2*l-1+m//3):m,c,l=(m+1)%8,0,l+m//7
print'\n'.join(''.join(e[16-l*2:])for e in f if[' ']*31!=e)
```
[Answer]
# CJam - 156 / 147
```
L{[W1]{:I0'|{IIW*:J'/}X*[0J'_]X2*I+*[J0_]I1={\}*{J_'\}X*0I0}%L*3/{~_{[UV@]a3$+}{;@}?V@+:V;U@+:U;}/}A,1>fX]ri=_z::e<2<f{[\\]z::-}$_W=0=)S50*a*\{~3$3$=\tt}/N*
```
[Try it online](http://cjam.aditsu.net/#code=L%7B%5BW1%5D%7B%3AI0'%7C%7BIIW*%3AJ'%2F%7DX*%5B0J'_%5DX2*I%2B*%5BJ0_%5DI1%3D%7B%5C%7D*%7BJ_'%5C%7DX*0I0%7D%25L*3%2F%7B~_%7B%5BUV%40%5Da3%24%2B%7D%7B%3B%40%7D%3FV%40%2B%3AV%3BU%40%2B%3AU%3B%7D%2F%7DA%2C1%3EfX%5Dri%3D_z%3A%3Ae%3C2%3Cf%7B%5B%5C%5C%5Dz%3A%3A-%7D%24_W%3D0%3D)S50*a*%5C%7B~3%243%24%3D%5Ctt%7D%2FN*&input=20)
It works with inputs from 1 to 378 inclusive (100 more than required)
Using the latest committed (publicly available in hg) but unreleased CJam code at the time this challenge was posted, the solution can be shortened to 147 characters:
```
L{[W1]{:I0'|{IIW*:J'/}X*[0J'_]X2*I+*[J0_]I1={\}*{J_'\}X*0I0}%L*3/{~_{[UV@]a3$+}{;@}?V@+:V;U@+:U;}/}A,1>fX]ri=_:.e<2<f.-$_W=0=)S50*a*\{~3$3$=\tt}/N*
```
**Explanation:**
The program iteratively constructs all the spirals as arrays of [x y character] starting with `[0 0 '|]`, gets the requested spiral, adjusts the coordinates so that the minimum x and y are 0, creates a matrix of spaces (with the correct number of rows and 50 columns) then sets the characters from the spiral and joins the rows with newlines.
```
L start with an empty array (spiral no. 0)
{…}A,1>fX for X in 1..9 (A=10)
each X represents a full 360° tour with groups of X /'es and \'es
[W1]{…}% transform the array [-1 1] (W=-1) applying the block to each item
the block generates a series of triplets dx, dy, character
note: dx is down, dy is right; -1 handles ↑↗→↘, 1 handles ↓↙←↖
:I store the current item in I
0'| add 0 and |, which will form a triplet with the previous I
{…}X* repeat X times
IIW* add I and -I
:J'/ also store -I in J, and add /
[0J'_] make an array [0 J _]
X2*I+* repeat the array X*2+I times
[J0_] make an array [J 0 0]
(a 0 instead of a character means only changing the position)
I1={\}* if I=1, swap the two arrays (the position adjustment is different
for the upper and lower horizontal sections)
{…}X* repeat X times
J_'\ add J, J and \
0I0 add 0, I and 0 (another position adjustment)
L* flatten the array (since we added a few inner arrays)
3/ split into [dx dy char] triplets
{…}/ for each triplet
~_ dump the 3 items on the stack and duplicate the character
{…} if the character is not 0
[UV@] make an array [U V char] (U and V are initially 0)
U represents "x" and V represents "y"
a3$+ add it as an element to a copy of the previous spiral
{…} else
;@ pop the character and bring the previous spiral to the top
? end if
V@+:V; V+=dy
U@+:U; U+=dx
] put all the spirals in an array
ri= read token, convert to integer and get that spiral
_z::e< copy the spiral and get a triplet with the minimum values
2< keep only the first 2 items (xmin and ymin)
f{…} for each triplet and the array [xmin ymin]
[\\]z::- subtract xmin and ymin from x and y in the triplet
(in the latest CJam code this is simply ".-")
$ sort the spiral (putting the triplets in order by x then y)
_W=0=) get the maximum (updated) x and increment it
S50* make a string of 50 spaces
a* put it in an array and repeat it xmax+1 times
this is the initial matrix of spaces
\ swap with the spiral
{…}/ for each triplet in the spiral
~ dump the 3 items (x y char) on the stack
3$3$= copy the matrix and x, and get the x'th row
\t swap with the character and put that character in the y'th position
t put the modified row in the x'th position in the matrix
N* join the matrix rows with newlines
```
[Answer]
# JavaScript (ES6) 257 ~~288 321~~
**Edit** Steps merged.
**Edit** Golfed code fiddling to cut some more char
Build the output iteratively into the r array, keeping track of current x and y position and current direction. When the x or y position is < 0 the whole r array is readjusted.
Main variables:
* r result array or rows
* x,y current position.
* s current direction (0..7) (or current state)
* d current symbol to draw (0..3) -> '|\\_/'
* l runnig position on the current sequence (down to 0)
* w current spiral radius (more or less)
```
F=n=>
(w=>{
for(r=b=[],s=y=x=d=0;n--;
d&&--l||((s=s+1&7,d=s&3)?l=d-2?w:s/2-2+w+w:w+=!s))
s>0&s<4?++x:s>4?x?--x:r=r.map(v=>' '+v):b+=' ',
q=r[s>2&s<6?++y:y]||b,
r[y]=(q+b).slice(0,x)+'|/_\\'[d]+q.slice(x+1),
s<2|s>6?y?--y:r=[,...r]:x+=!d*2,x-=!d
})(1)||r.join('\n')
```
**Ungolfed**
```
F=n=>{
var r=[], s,x,y,d,w,l, q
for(l=w=1, s=x=y=d=0; n--;)
{
if (s>2 && s<6) ++y; // right side, inc y before drawing
if (x < 0) // too left, adjust
{
r = r.map(v=>' '+v) // shift all to right
++x; // move current position to right
}
if (y < 0) // too up
{
r = [q='',...r] // shift all to bottom
++y; // move current position to bottom
}
q = r[y] || ''; // current row, if undefined convert to empty string
r[y] = (q+' '.repeat(x)).slice(0,x) + '|/_\\'[d] + q.slice(x+1); // add current symbol in the x column
if (s<2 || s>6) --y; // left side, dec y after drawing
if (s>0 && s<4) // always change x after drawing
++x;
else if (s > 4)
--x;
--l; // decrement current run
if (l == 0) // if 0, need to change direction
{
s = (s+1) % 8; // change direction
d = s % 4; // change symbol
if (d == 0)
{
// vertical direction, adjust x and if at 0 increase radius
l = 1 // always 1 vertical step
if (s == 0)
++x, ++w
else
--x
}
else
{
if (d != 2)
{
l = w; // diaagonal length is always w
}
else if (s == 2)
{
l = w+w-1 // top is radius * 2 -1
}
else
{
l = w+w+1 // bottom is radius * 2 +1
}
}
}
}
return r.join('\n')
}
```
**Test** In Firefox/FireBug console (or [JSFiddle](http://jsfiddle.net/0drqymzn/8/) thx @Rainbolt)
```
;[1, 2, 10, 20, 155, 278].forEach(x=>console.log(F(x)))
```
*Output*
```
|
/
|
_
/ \
| |
\___/
___
/ _ \
/ / \ \
| | | |
\___/ /
___________
/ _________ \
/ / _______ \ \
/ / / _____ \ \ \
/ / / / ___ \ \ \ \
/ / / / / _ \ \ \ \ \
/ / / / / / \ \ \ \ \ \
| | | | | | | | | | | |
\ \ \ \ \___/ / / / /
\ \ \ \_____/ / / /
\ \ \_______/ / /
\ \_________/ /
\___________/
_______________
/ _____________ \
/ / ___________ \ \
/ / / _________ \ \ \
/ / / / _______ \ \ \ \
/ / / / / _____ \ \ \ \ \
/ / / / / / ___ \ \ \ \ \ \
/ / / / / / / _ \ \ \ \ \ \ \
/ / / / / / / / \ \ \ \ \ \ \ \
| | | | | | | | | | | | | | | |
\ \ \ \ \ \ \___/ / / / / / / /
\ \ \ \ \ \_____/ / / / / / /
\ \ \ \ \_______/ / / / / /
\ \ \ \_________/ / / / /
\ \ \___________/ / / /
\ \_____________/ / /
\_______________/ /
```
[Answer]
# Pyth, ~~166~~ 165
I just translated [my Python answer](https://codegolf.stackexchange.com/a/47605/30164) to Pyth, with my not-great Pyth skills. The resulting vomit is below.
```
Jm*31]d*31dK0=G0=H0=Y1VQ X@J++14H&<2K<K6+14-G<3K@"|/_\\"%K4~G*<0%K4-*2>4K1~H*n2%K4-*2&<2K>6K1~Z1I||&qZY%K2!%K4&q2%K4qZ+-*2Y1/K3~Y/K7=K%+1K8=Z0;jbmj>d-16*2Ykfn*31]dTJ
```
] |
[Question]
[
You are given a list of (*a,b*), and a list of *x*. Compute the maximum *ax+b* for each *x*. You can assume *a*, *b* and *x* are non-negative integers.
Your program or function must run in expected (to the randomness if your code involves that, not the input) **O(*n*log*n*) time** where *n* is the total input length (sum or maximum of the lengths of both lists).
This is code-golf. Shortest code wins.
### Example
```
[[2 8] [4 0] [2 1] [1 10] [3 3] [0 4]] [1 2 3 4 5]
```
Output:
```
[11 12 14 16 20]
```
Explanation:
```
11 = 1*1 + 10
12 = 1*2 + 10 = 2*2 + 8
14 = 2*3 + 8
16 = 2*4 + 8 = 4*4 + 0
20 = 4*5 + 0
```
### Note about the complexity:
If you used a builtin having a good average-case complexity, and it can be randomized to get the expected complexity easily in theory, you can assume your language did that.
That means, if your program can be tested to be in O(*n*log*n*), possibly with edge case exceptions because of the implementation of your language, but cannot be seen logically in your own code, we'll say it is O(*n*log*n*).
[Answer]
## Python, 214 bytes
```
S=sorted
def M(L,X):
H=[-1,0];R={}
for a,b in S(L):
while H[2:]and a*H[-3]+b>H[-2]*H[-3]+H[-1]:H=H[:-3]
H+=[1.*(H[-1]-b)/(a-H[-2]),a,b]
for x in S(X):
while H[2:]and x>H[2]:H=H[3:]
R[x]=H[0]*x+H[1]
return R
```
Computes the convex hull by iterating through the input `a,b` in increasing `a` order. The convex hull is recorded in `H` using the format `-1,0,x1,a1,b1,x2,a2,b2,x2,...,xn,an,bn` where `xi` is the x coordinate of the intersection of `a{i-1},b{i-1}` and `ai,bi`.
Then I iterate though the input `x`s in sorted order, truncating the convex hull to keep up as I go.
Everything is linear except for the sorts which are O(n lgn).
Run it like:
```
>>> print M([[2,8],[4,0],[2,1],[1,10],[3,3],[0,4]], [1,2,3,4,5])
{1: 11, 2: 12, 3: 14, 4: 16, 5: 20}
```
[Answer]
# Haskell, 204 271 bytes
*Edit*: golfed much further by updating the convex hull as a list (but with the same complexity as the ungolfed version), using "split (x+1)" instead of "splitLookup x", and removing all qualified function calls like Predule.foldl.
This creates a function *f* which expects the list of (a,b) pairs and a list of x values.
I guess it will be blown away length-wise by anything in the APL family using the same ideas, but here it goes:
```
import Data.Map
r=fromListWith max
[]%v=[(0,v)]
i@((p,u):j)%v|p>v#u=j%v|0<1=(v#u,v):i
(a,b)#(c,d)=1+div(b-d)(c-a)
o i x=(\(a,b)->a*x+b)$snd$findMax$fst$split(x+1)$r$foldl'(%)[]$r$zip(fmap fst i)i
f=fmap.o
```
Sample usage:
```
[1 of 1] Compiling Main ( linear-min.hs, interpreted )
Ok, modules loaded: Main.
λ> f [(2,8), (4,0), (2,1), (1,10), (3,3), (0,4)] [1..5]
[11,12,14,16,20]
λ> f [(1,20), (2,12), (3,11), (4,8)] [1..5]
[21,22,23,24,28]
```
It works in O(n log n) time; see below for analysis.
*Edit:* Here's an ungolfed version with the big-O analysis and a description of how it all works:
```
import Prelude hiding (null, empty)
import Data.Map hiding (map, foldl)
-- Just for clarity:
type X = Int
type Y = Int
type Line = (Int,Int)
type Hull = Data.Map.Map X Line
slope (a,b) = a
{-- Take a list of pairs (a,b) representing lines a*x + b and sort by
ascending slope, dropping any lines which are parallel to but below
another line.
This composition is O(n log n); n for traversing the input and
the output, log n per item for dictionary inserts during construction.
The input and output are both lists of length <= n.
--}
sort :: [Line] -> [Line]
sort = toList . fromListWith max
{-- For lines ax+b, a'x+b' with a < a', find the first value of x
at which a'x + b' exceeds ax + b. --}
breakEven :: Line -> Line -> X
breakEven p@(a,b) q@(a',b') = if slope p < slope q
then 1 + ((b - b') `div` (a' - a))
else error "unexpected ordering"
{-- Update the convex hull with a line whose slope is greater
than any other lines in the hull. Drop line segments
from the hull until the new line intersects the final segment.
split is used to find the portion of the convex hull
to the right of some x value; it has complexity O(log n).
insert is also O(log n), so one invocation of this
function has an O(log n) cost.
updateHull is recursive, but see analysis for hull to
account for all updateHull calls during one execution.
--}
updateHull :: Line -> Hull -> Hull
updateHull line hull
| null hull = singleton 0 line
| slope line <= slope lastLine = error "Hull must be updated with lines of increasing slope"
| hull == hull' = insert x line hull
| otherwise = updateHull line hull''
where (lastBkpt, lastLine) = findMax hull
x = breakEven lastLine line
hull' = fst $ x `split` hull
hull'' = fst $ lastBkpt `split` hull
{-- Build the convex hull by adding lines one at a time,
ordered by increasing slope.
Each call to updateHull has an immediate cost of O(log n),
and either adds or removes a segment from the hull. No
segment is added more than once, so the total cost is
O(n log n).
--}
hull :: [Line] -> Hull
hull = foldl (flip updateHull) empty . sort
{-- Find the highest line for the given x value by looking up the nearest
(breakpoint, line) pair with breakpoint <= x. This uses the neat
function splitLookup which looks up a key k in a dictionary and returns
a triple of:
- The subdictionary with keys < k.
- Just v if (k -> v) is in the dictionary, or Nothing otherwise
- The subdictionary with keys > k.
O(log n) for dictionary lookup.
--}
valueOn :: Hull -> X -> Y
valueOn boundary x = a*x + b
where (a,b) = case splitLookup x boundary of
(_ , Just ab, _) -> ab
(lhs, _, _) -> snd $ findMax lhs
{-- Solve the problem!
O(n log n) since it maps an O(log n) function over a list of size O(n).
Computation of the function to map is also O(n log n) due to the use
of hull.
--}
solve :: [Line] -> [X] -> [Y]
solve lines = map (valueOn $ hull lines)
-- Test case from the original problem
test = [(2,8), (4,0), (2,1), (1,10), (3,3), (0,4)] :: [Line]
verify = solve test [1..5] == [11,12,14,16,20]
-- Test case from comment
test' = [(1,20),(2,12),(3,11),(4,8)] :: [Line]
verify' = solve test' [1..5] == [21,22,23,24,28]
```
[Answer]
## Common Lisp - 648 ~~692~~
With an actual binary search.
```
(use-package :optima)(defun z(l e)(labels((i(n m)(/(-(cadr m)(cadr n))(-(car n)(car m))))(m(l)(match l((list* a b c r)(if(<(i a b)(i b c))(list* a(m(list* b c r)))(m(list* a c r))))(_ l)))(f(x &aux(x(cdr x)))`(+(*,(car x)x),(cadr x)))(g(s e)(let*((q(- e s))(h(+ s(floor q 2)))d)(if(> q 1)(let((v(g s h))(d(pop l)))`(if(< x,(car d)),v,(g(1+ h)e)))(cond((not(car (setq d (pop l))))(f d))((> q 0)`(if(< x,(car d)),(f d),(f(pop l))))(t(f d)))))))(setq l(loop for(a b)on(m(remove-duplicates(#3=stable-sort(#3# l'< :key'cadr)'< :key'car):key 'car)) by #'cdr collect`(,(when b(i a b)),(car a),(cadr a))))`(mapcar(eval(lambda(x),(g 0(1-(length l)))))',e)))
(z '((2 8) (4 0) (2 1) (1 10) (3 3) (0 4)) '(1 2 3 4 5))
=> (11 12 14 16 20)
```
# Explanation
Let *n* be the length of (a,b) and *k* the length of points.
* sort (a,b) by a, then b - *O(n.ln(n))*
* remove entries for duplicate `a` (parallel lines), retaining only the parallel line with the maximum `b`, which is always greater than the other (we prevent divisions by zero when computing intersections) - *O(n)*
* compress the result - *O(n)* : when we have consecutives elements (a0,b0) (a1,b1) (a2,b2) in the sorted list, such that the intersection point of (a0,b0) and (a1,b1) is *greater* than the one of (a1,b1) and (a2,b2), then (a1,b1) can safely be ignored.
* build a list of (x a b) elements, where *x* is the value up-to-which line *ax+b* is maximal for *x* (this list is sorted by *x* thanks to previous steps) - *O(n)*
* given that list, build a lambda that perform an interval check for its input and computes the maximum value - the binary tree is built in *O(n)* (see <https://stackoverflow.com/a/4309901/124319>). The binary search that will be applied has *O(ln(n))* complexity. With the example input, we build the following function (that function is then compiled):
```
(LAMBDA (X)
(IF (< X 4)
(IF (< X 2)
(IF (< X -6)
(+ (* 0 X) 4)
(+ (* 1 X) 10))
(+ (* 2 X) 8))
(+ (* 4 X) 0)))
```
* apply that function for all elements - *O(k.ln(n))*
Resulting complexity: **O((n+k)(ln n)))** in a worst-case scenario.
We can't provide a complexity estimate for the total number of inputs (n+k), because *k* and *n* are independant.
For example, if *n* is asymptotically negligeable w.r.t. *k*, then the total complexity would be *O(k)*.
But **if** we suppose that *k=O(n)*, then the resulting complexity is **O(n.ln(n))**.
## Other examples
```
(z '((1 10) (1 8) (1 7)) '(1 2 3 4 5))
=> (11 12 13 14 15)
```
And if we move backquotes to see what is being computed, we can see that we don't even need to make any comparison (once the first list is preprocessed):
```
(MAPCAR (LAMBDA (X) (+ (* 1 X) 10)) '(1 2 3 4 5))
```
Here is another example (taken from a comment):
```
(z '((1 20) (2 12) (3 11) (4 8)) '(1 2 3 4 5))
=> (21 22 23 24 28)
```
The effective function:
```
(MAPCAR
(LAMBDA (X)
(IF (< X 4)
(+ (* 1 X) 20)
(+ (* 4 X) 8)))
'(1 2 3 4 5))
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth) - 99 98 bytes
This is pretty much a direct translation of @KeithRandall's Python answer. It can definitely be golfed a lot more. I will be posting an explanation soon.
```
K[_1Z;FNShQAkdNW&>K2>+*k@K_3d+*@K_2@K_3eK=K<K_3)~K[c-eKd-k@K_2kd;FNSeQW&>K2>N@K2=K>K3)aY+*hKN@K1;Y
```
Takes two comma delimited lists, separated by commas through stdin.
[Try it here](http://pyth.herokuapp.com/?code=K%5B_1Z%3BFNShQAkdNW%26%3EK2%3E%2B*k%40K_3d%2B*%40K_2%40K_3eK%3DK%3CK_3)~K%5Bc-eKd-k%40K_2kd%3BFNSeQW%26%3EK2%3EN%40K2%3DK%3EK3)aY%2B*hKN%40K1%3BY&input=%5B%5B2%2C8%5D%2C%5B4%2C0%5D%2C%5B2%2C1%5D%2C%5B1%2C10%5D%2C%5B3%2C3%5D%2C%5B0%2C4%5D%5D%2C%20%5B1%2C2%2C3%2C4%2C5%5D)
```
K K=
[ ) A List containing
_1 Negative 1
Z Zero
FN For N in
ShQ Sorted first input
Akd Double assign k and d
N To N
W While
& Logical And
>K2 K>2
> Greater Than
+*k@K_3d K[-3]*k+d
+ Plus
*@K_2@K_3 K[-2]*K[-3]
eK K[-1]
=K K=
<K_3 K[:-3]
) Close while loop
~K K+=
[ ) List constructor
c Float division
- Minus
eK K[-1]
d d
- Minus
k k
@K_2 K[-2]
k k
d d
; End list and for loop
FN For N in
SeQ Sorted second input
W While loop
& Logical and
>K2 K[2:]
> Greater than
N N
@K2 K[2]
=K K=
>K3 K[3:]
) Close while loop
aY Y.append - Y is empty list
+ Plus
*hKN (K+1)*N
@K1 K[1]
; Close out everything
Y Print Y
```
] |
[Question]
[
[Graham's number](http://en.wikipedia.org/wiki/Graham%27s_number) ends in a 7. It is a massive number, in theory requiring more information to store than the size of the universe itself. However it is possible to calculate the last few digits of Graham's number.
The last few digits are:
```
02425950695064738395657479136519351798334535362521
43003540126026771622672160419810652263169355188780
38814483140652526168785095552646051071172000997092
91249544378887496062882911725063001303622934916080
25459461494578871427832350829242102091825896753560
43086993801689249889268099510169055919951195027887
17830837018340236474548882222161573228010132974509
27344594504343300901096928025352751833289884461508
94042482650181938515625357963996189939679054966380
03222348723967018485186439059104575627262464195387
```
Your program may not contain these (or similar numbers), but must calculate them. It must calculate 200 digits or more.
Output to stdout. Running time of a maximum of 2 minutes on decent hardware. Shortest program wins.
[Answer]
## dc - 21 chars
```
[3z202>xO200^|]dsxxrp
```
This takes about a minute on my computer, and would take lots longer for values larger than 200. It doesn't output leading zeroes.
Here's a slightly longer but faster version (26 chars):
```
[3rAz^|dz205>x]dsxxAz6-^%p
3[3rAz^|dz202>x]dsxxAz3-^%p # or an extra character for a few less iterations
```
[Answer]
## Haskell, 99
Performance not stellar, but it manages to compute 500 digits in a minute on my decade-old hardware.
```
f a b|b==0=1|odd b=mod(a*f a(b-1))m|0<1=f(mod(a^2)m)$div b 2
main=print$iterate(f 3)3!!500
m=10^500
```
(btw, I'd love to hear about its performance on more modern hardware)
[Answer]
# Python - 41 chars
499 digits
```
x=3;exec'x=pow(3,x,10**500);'*500;print x
```
500 digits
```
x=3;exec'x=pow(3,x,10**500);'*500;print'0'+`x`
```
[Answer]
# Python - 62 59 55 chars
```
x=3
for i in range(500):x=pow(3,x,10**500)
print"0%d"%x
```
Takes around 12 seconds on my PC.
```
sh-3.1$ time python cg_graham.py
02425950695064738395657479136519351798334535362521430035401260267716226721604198
10652263169355188780388144831406525261687850955526460510711720009970929124954437
88874960628829117250630013036229349160802545946149457887142783235082924210209182
58967535604308699380168924988926809951016905591995119502788717830837018340236474
54888222216157322801013297450927344594504343300901096928025352751833289884461508
94042482650181938515625357963996189939679054966380032223487239670184851864390591
04575627262464195387
real 0m11.807s
user 0m0.000s
sys 0m0.015s
sh-3.1$
```
[Answer]
# Axiom, 63 bytes
```
f()==(r:=3;d:=10^203;for i in 1..203 repeat r:=powmod(3,r,d);r)
```
ungolf and result
```
--This find the Graham's number follow the algo found in wiki
--http://en.wikipedia.org/wiki/Graham%27s_number
ff()==
r:=3; d:=10^203
for i in 1..203 repeat r:=powmod(3,r,d)
r
(3) -> a:=f()::String
(3)
"8871783083701834023647454888222216157322801013297450927344594504343300901096
92802535275183328988446150894042482650181938515625357963996189939679054966380
03222348723967018485186439059104575627262464195387"
Type: String
(4) -> #a
(4) 203
Type: PositiveInteger
```
#a=203 means the number len is >200 it menas too that it not has some 0 first...
[Answer]
## Headsecks, 602 bytes
```
(h@HP0&Y+h8h (hx0RWc@4vYcx#@#PJ"B?[#CPx (h Lx$2(pl2YL;KD:T{9$2j<
LSSh,ZT l2I<Pp,@4SX`,:xtc@T",($)<cKT\lbBAy44,dQl[yL"l+i,;9<*j0P
|)lD[+`\RBi!< LaD(LHPLyt{{@\iADRQdHTZQIT3[X`DB*`X$Cxh$*(T0$| ,[;
4:bit0DqAqi!lCYQ)<Ad(|1<$R4l+#tZrLPDatC[d*@0pDclJbh0|#S9<JRy!TP0
D+!|qiTXp<r$##Atj,B1ts;HLJ"Xp44I4cK4@|Q,4JI$|hp$Zyd+yl:y<s#\pD:9
4RDK,A!<X \cqLZ" h,kHp|qLRQIDh,+StZbL+{(|jqqL;9L"(xd"<s$8\:x,CY\
z0T[,(XdcxlbaD*D;+tDj\JIi4k[)LPDLBzP@DSc$jL $s4BjQ19|;!)|9t;TaQA
dLzit[0@l2!)I$,0P@$y<L4pLPLStQT"!a| $+8(DZ`00t ,RtX4C@$yQ11|KI\"
`|2<k3|R(Dyi<)LshTrzQ$sp D+DRbH|Q$CqT0D;AA\jdXd"ppdK3LzZl#\Bl`@t
k$*,11qTK+Xp|rqDZXp4{C!<Y4
```
Prints the last 200 digits.
Please remove the newlines before running.
] |
[Question]
[
### Background
The look-and-say sequence begins with \$1\$, each following term is generated by looking at the previous and reading each group of the same digit (eg. \$111\$ is three ones, so \$111 \rightarrow 31\$). The first few terms are
$$ 1, 11, 21, 1211, 111221, 312211, \dots $$
Conway's cosmological theorem says that from any starting point, the sequence eventually becomes a sequence of "atomic elements", which are finite subsequences that never again interact with their neighbors. There are 92 such elements.
See also: [Wikipedia](https://en.wikipedia.org/wiki/Look-and-say_sequence), [OEIS](https://oeis.org/A005150)
### The Challenge
In this challenge you will take no input and you must output all 92 of Conway's atomic elements. The output may be in any order, and of any reasonable form for a list of numbers.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
Sample Output:
```
22
13112221133211322112211213322112
312211322212221121123222112
111312211312113221133211322112211213322112
1321132122211322212221121123222112
3113112211322112211213322112
111312212221121123222112
132112211213322112
31121123222112
111213322112
123222112
3113322112
1113222112
1322112
311311222112
1113122112
132112
3112
1112
12
3113112221133112
11131221131112
13211312
31132
111311222112
13122112
32112
11133112
131112
312
13221133122211332
31131122211311122113222
11131221131211322113322112
13211321222113222112
3113112211322112
11131221222112
1321122112
3112112
1112133
12322211331222113112211
1113122113322113111221131221
13211322211312113211
311322113212221
132211331222113112211
311311222113111221131221
111312211312113211
132113212221
3113112211
11131221
13211
3112221
1322113312211
311311222113111221
11131221131211
13211321
311311
11131
1321133112
31131112
111312
132
311332
1113222
13221133112
3113112221131112
111312211312
1321132
311311222
11131221133112
1321131112
311312
11132
13112221133211322112211213322113
312211322212221121123222113
111312211312113221133211322112211213322113
1321132122211322212221121123222113
3113112211322112211213322113
111312212221121123222113
132112211213322113
31121123222113
111213322113
123222113
3113322113
1113222113
1322113
311311222113
1113122113
132113
3113
1113
13
3
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 174 bytes
```
F⪪⪪”}∧I*₂φ,.i\`β↷Ht≧'θvυQ=^ι←ºρ²≡O✂⟦F!n^φ⁰γ↨ΣP@g,C[¦⟦“↥⁼>∕νDIwO4(fO↓;⧴�i⁷·P↨]]WWUB⎚Rcρw∕✳Iⅉ}⟲⊘&:'▶≕…7»↗→➙…⁶⪪✳‖↨FM&⦄Js/″⁷mβ⊗⊞4W⟲L.”0²«≔⊟ιθFI⊟ι«⟦θ⟧≔⟦⟧ηFθ⊞⊞Oη⊕∧⁼↨η⁰Iλ∧⊟η⊟ηIλ≔⪫ηωθ
```
[Try it online!](https://tio.run/##dVFNT4QwED3Dr2g4lQSTTkdXE0@r8aAXSTxu9kBYFBIsn6sHs78dZ9rCkmyWwPB4fW9ep@Rl1udNVk/TZ9ML@dHW1ehrBEprpRWC1gCoqfIDfKND6kGdMSoWMdoQq27JSATR6JepkQIvQnTNEJljJXgCYMmjRujy2McIkZGPXHo4h03w3d1WL9O8csM8gEu@VNLKHech0BQ8g7ZfvKOVbh7ZTrmagT3gXNePDldHh8vRobpXGCUiUlGcCB3H4i8MtsNQfRmZNq2siO3ixzCwP@s5G0ZPO2WQ9pUZ5a7bs2Y27vaJKC1hXV0s0uNQSi7vbdFnY9PLMhGvJu@L78KMxUFuzUG@dMesHuRTNhS8rCjaBtYxIRZwcknYvfk6K1bxb01luMHvvPdTeJqm6ean/gc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⪪⪪”...”0²«
```
Split and loop over a compressed string of elements that aren't the result of a look-and-say of another element and the number of elements in that element's group of look-and-say derivatives.
```
≔⊟ιθ
```
Get the element.
```
FI⊟ι«
```
Loop over it and each derivative.
```
⟦θ⟧
```
Output the element.
```
≔⟦⟧η
```
Collect the look-and-say results in an array.
```
Fθ
```
Loop over the digits of this element.
```
⊞⊞Oη⊕∧⁼↨η⁰Iλ∧⊟η⊟ηIλ
```
If this digit equals the last digit so far then the previous digit is removed and incremented otherwise `0` is incremented and that and the current digit is then pushed (back).
```
≔⪫ηωθ
```
Join the array to create the next element. (Note that the "last" element is never output.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 47 bytes
```
ŒrF
J‘œṖ€⁸Ç9¡€F⁼ɗƇÇ9¡Ḣ)Ẏḟ®
3WWḷ;ɼÑWÇÐLƊ€ẎƲÐLḊɼU
```
[Try it online!](https://tio.run/##y0rNyan8///opCI3Lq9HDTOOTn64c9qjpjWPGnccbrc8tBDIdHvUuOfk9GPtYP7DHYs0H@7qe7hj/qF1XMbh4Q93bLc@uefwxPDD7Ycn@BzrAqoHSh/bBOQ83NF1ck/o//8A "Jelly – Try It Online")
A full program that runs with no input and outputs the 92 Conway elements. Broadly, this works by starting with `[3]`, iteratively generating the next look say sequence member and then attempting to iteratively split this into irreducible elements. Each irreducible element thus found is then passed onto the next iteration after filtering out any previously seen ones. Testing for irreducibility is done by splitting a sequence into every possible pairwise split and finding the first where nine generations of look say algorithm produces the same result as running 9 generations on the unsplit sequence. (Nine was found empirically.) Full explanation to follow.
Note the order is determined by the first time a sequence is seen with this approach, so is not the same as the order in Conway’s paper.
## Explanation
```
ŒrF # ‎⁡Helper link 1: takes a sequence of integers and returns the look say encoding (reversed)
Œr # ‎⁢Run-length encode
F # ‎⁣Flatten
J‘œṖ€⁸Ç9¡€F⁼ɗƇÇ9¡Ḣ)Ẏḟ® # ‎⁤Helper link 2: Takes a list of sequences and returns a list of sequences where each of the original ones have been split, if possible, into two
) # ‎⁢⁡For each sequence in list:
J # ‎⁢⁢- Range from 1 to length of sequence
‘ # ‎⁢⁣- Increment by 1
œṖ€⁸ # ‎⁢⁤- Split each of the original sequence just before the index of each of these integers
ɗƇ # ‎⁣⁡- Keep only those where:
Ç9¡€F # ‎⁣⁢ - The result of running helper link 1 on each half of the split and then flattening
⁼ # ‎⁣⁣ - Is equal to:
Ç9¡ # ‎⁣⁤ - The result of running helper link 1 on the unsplit sequence
Ḣ # ‎⁤⁡- Take the first valid split (which will be the original sequence and an empty list if there is no split possible)
Ẏ # ‎⁤⁢Join outer lists together
ḟ® # ‎⁤⁣Filter out any sequences already held in the register
3WWḷ;ɼÑWÇÐLƊ€ẎƲÐLḊɼU # ‎⁤⁤Main link: takes no arguments and returns a list of all 92 elements
3WW # ‎⁢⁡⁡Start with 3 wrapped in a list and wrapped again (i.e. [[3]])
ƲÐL # ‎⁢⁡⁢Repeat the following until no change between iterations:
;ɼÑ # ‎⁢⁡⁣- Concatenate the current list of elements to the register
ḷ # ‎⁢⁡⁤- But then revert to the current list of elements
Ɗ€ # ‎⁢⁢⁡- For each element in the list:
Ñ # ‎⁢⁢⁢ - Use helper link 1 to generate the next look say sequence from this
W # ‎⁢⁢⁣ - Wrap this in a list
ÇÐL # ‎⁢⁢⁤ - Then use helper link 2 to iteratively split the sequence into irreducible elements
Ẏ # ‎⁢⁣⁡- Join outer lists
Ḋɼ # ‎⁢⁣⁢Remove the first member of the list in the register (will be a 0 that started off there originally)
U # ‎⁢⁣⁣Finally, reverse each element (since helper link 1 generates them reversed)
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
## Alternative without use of the register, 49 bytes
```
ŒrF
J‘œṖ€⁸Ç9¡€F⁼ɗƇÇ9¡Ḣ
3WW,‚Å∏√ëW√á‚Ǩ·∫é·∏ü…ó∆¨·π™ ã‚Ǩ·∫é,…ó;¬•/√êL·π™U
```
[Try it online!](https://tio.run/##y0rNyan8///opCI3Lq9HDTOOTn64c9qjpjWPGnccbrc8tBDIdHvUuOfk9GPtYP7DHYu4jMPDdUDyE8MPtwPlH@7qe7hjPlDFmoc7V53qhojonJxufWip/uEJPkDB0P//AQ "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~104~~ 103 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
3 90FDÅγs.ιJ•KтË:äþÒ¶Æ₁Ž“cì¥%ât5)§65g-Aér)тθñ.µBηâε;Ü∍ï¨ZÀи}â*5ü”7₃Lƒ-ñh5!•43вNè•"[¯₁Šä•₂в.¥Nåi£ë.£]22)
```
Outputs Conway's atomic elements in reversed order as list.
[Try it online.](https://tio.run/##AbIATf9vc2FiaWX//zMgOTBGRMOFzrNzLs65SuKAokvRgsOLOsOkw77DksK2w4bigoHFveKAnGPDrMKlJcOidDUpwqc2NWctQcOpcinRgs64w7EuwrVCzrfDos61O8Oc4oiNw6/CqFrDgNC4fcOiKjXDvOKAnTfigoNMxpItw7FoNSHigKI0M9CyTsOo4oCiIlvCr@KCgcWgw6TigKLigoLQsi7CpU7DpWnCo8OrLsKjXTIyKf//)
**Explanation:**
If we look at the [*Element name* and *Decays into* of the Wikipedia table](https://en.wikipedia.org/wiki/Look-and-say_sequence#cite_ref-Martin2006_5-3), we can see that a lot of the *Decays into* are just a single element. The others are either at the start or end, with the exceptions of `Ho.Pa.H.Ca.Co` to `Ca` (Atomic Number 21) and `Hf.Pa.H.Ca.Li` to `H` (Atomic Number 2), although those still work fine if we take a portion of another element at the start/end instead.
I basically generate all Conway's atomic elements in reversed order, starting at `3`, taking either the leading or trailing portion of the correct output-length. I'll take the leading portion if the (0-based) index is one of `[19,23,24,28,30,34,52,53,59,67]`, and the trailing portion (or full† look-and-say number) otherwise. And because this would end with `12`, I drop that value (by looping one iteration less) and add a hard-coded `22` instead.
```
3 # Start with a 3
90F # Loop `N` in the range [0,90):
D # Duplicate the current value
Åγs.ιJ # Convert it to its look-and-say number:
Åγ # Run-length encode the number into two separated lists of values and lengths
s # Swap so the list of values is at the top of the stack
.ι # Interleave the lists of lengths and values together
J # Join this list together to a single string
•KтË:äþÒ¶Æ₁Ž“cì¥%ât5)§65g-Aér)тθñ.µBηâε;Ü∍ï¨ZÀи}â*5ü”7₃Lƒ-ñh5!•
# Push compressed integer 50110820926426684400408736251820828634922551372994851769669719792848756768639391390052494466780374103702329447321431509239639153836796651173069320
43–≤ # Convert it to base-43 as list: [2,4,4,6,10,12,7,10,10,9,12,14,18,24,28,34,42,27,32,5,6,10,14,9,7,12,16,11,7,6,3,6,8,10,5,6,8,14,18,13,7,5,8,10,12,18,24,21,15,20,28,23,7,7,10,14,16,20,26,23,17,3,6,8,5,8,12,5,8,14,16,2,4,4,6,10,12,7,10,10,9,12,14,18,24,28,34,42,27,32]
Nè # Index the current loop-index `N` into this list
# (let's call this value, which are the lengths of the outputs, `L`)
•"[¯₁Šä• "# Push compressed integer 104005171539992
‚ÇÇ–≤ # Convert it to base-26 as list: [19,4,1,4,2,4,18,1,6,8]
.¥ # Undelta it with leading 0: [0,19,23,24,28,30,34,52,53,59,67]
Nåi # If the current loop-index `N` is in this list:
£ # Keep the first `L` amount of digits from the current string
ë # Else:
.£ # Keep the last `L` amount of digits from the current string
] # Close both the if-statement and loop
22 # Push the final edge-case value 22
) # Wrap everything on the stack into a list
# (which is output implicitly as result)
```
[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 compressed integers(-lists) work.
*†*: For the full numbers it doesn't matter if we take the leading or trailing portion. So the additional `0` in the undelta-list `[0,19,23,24,28,30,34,52,53,59,67]` loopup list, won't make any difference in the output for this first (length 2) value `13`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 396 bytes
```
221¶3122113222122211211232221122¶1232221128¶13221123¶126¶311324¶321123¶3123¶132211331222113321¶311311222113111221132221¶31121126¶11121331¶123222113312221131122111¶3113221132122213¶1322113312221131122111¶132116¶31122211¶13221133122111¶111315¶1324¶11132222¶132211331121¶13211323¶3113112221¶111324¶3122113222122211211232221132¶1232221138¶13221133¶37
%`.$
$*#
{%`#$
#+
$&¶$%`
(?=(\d).*#)(\1)+
$#2$1
```
[Try it online!](https://tio.run/##fVA7DsIwDN19jaSoLVIl5xXogrhIhyLBwMKA2LhXD9CLBTtOWxASUj7O@znJ4/q83c8xUgg8jWDZGEFWnawDVoVpXOpOaqQKiu7VKEArewZhVBIBFgZYCwZngHntlxh1S5rialtbLhnmyDlmTsxvt0WpErY7JuZLaQqV7xLe2kmE4UPHYc6BvW5@Q1a3/74OH1@Hbk0Vz4GKofHka0evYnCeyG3Jb6bRFwOVp2PZX6qmdlXZcyWEC55jfAM "Retina 0.8.2 – Try It Online") Explanation: Port of my Charcoal answer.
```
221¶3122113222122211211232221122¶1232221128¶13221123¶126¶311324¶321123¶3123¶132211331222113321¶311311222113111221132221¶31121126¶11121331¶123222113312221131122111¶3113221132122213¶1322113312221131122111¶132116¶31122211¶13221133122111¶111315¶1324¶11132222¶132211331121¶13211323¶3113112221¶111324¶3122113222122211211232221132¶1232221138¶13221133¶37
```
Insert the base elements each with the count of derived elements appended to them.
```
%`.$
$*#
```
Convert the element counts to unary.
```
{`
```
Repeat until all elements have been derived.
```
%`#$
```
Decrement the remaining count by 1 for each element.
```
#+
$&¶$%`
```
Duplicate each unfinished element, but without the count.
```
(?=(\d).*#)(\1)+
$#2$1
```
Perform the look-and-say to derive the next element.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~256~~ 201 bytes
```
z=?3;"7773398pr20540910737b10720340557d19713567l19f39r10710760n17h1h33353054b26773398pr272100".scan(/.../){|x|a,b,c=x.chars.map{|r|r.to_i 36};a.times{z=p(z).gsub(/(.)\1*/){|a|"#{a.size}#$1"}};z=z[b,c]}
```
[Try it online!](https://tio.run/##PczRisIwEAXQX5G6D63INNMxHUMp@yEqklR3W1C3JApumnx7jS/C5b5c7rEP8z/Pvv2mJmNmIrUdbSXkRigUTGxSV4I2Qko@oWIkWfMF1Q8pm6aUWtyQe@yJSFI6mqr@OFyhEBm4Tt/yEgDKYgrPoNdm3bVP6HptHVz1OAUbLNz/jsOC6thouA/Xs5t8O@a@gF/3MHmZQ7HH1RvQIVtOGtzgz3H5hVmMjW/9LpmHOM8v "Ruby – Try It Online")
Use the sequence from the linked [page](http://www.se16.info/js/lands2.htm) starting with '3'.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 211 bytes
Uses the construction described on [this page](http://www.se16.info/js/lands2.htm) (linked from OEIS and pointed out by [Level River St](https://codegolf.stackexchange.com/users/15599/level-river-st)).
```
B=Buffer;for(i in[...q=B(s="(3(d 3 38(499 !4M( =3(d2")])for(v=q[i]*96+B(".:oyKhZXY;LhXMH:xX]x(ZJKU:oyp")[i]-3104,k=0;k<=v%8;console.log(k++?s:s=s.substr(v>>8,v/8&31)))s=s.replace(/(.)\1*/g,s=>s.length+s[0])
```
[Try it online!](https://tio.run/##FYxLT4NAFIX/ykiiuVPoAEIMDy8mrIxtlyZYZIF0eAhhKJeS@usRFmfzne@c33zOqRibYdr36iKXJcb4VpZyDEs1QsOaPhVCXDEGQg0cuDDGnC0euL7P2IN7AoYrf9Z4xrfNjNe0yXb@ix6DJgL1d6jPyVd4rJPTe3BPsjucPw6fKx80vop7x7Zco0UrbF9xfvTCQvWkOik6VUGr628UEJKg2w9N63kUecZsek@OzTnfilEOXV5IMEHwb3tnVgZhRKKTfTXVOqVWxpflHw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 222 bytes
A full program printing output in reverse order to the question. Longer than I had hoped for with this approach, but will be golfed when I have time.
```
w="\2[IGBeECQwggWOUEGMecgKgie[IG"
s=?3
j=0
q=0xa02411270730708b3140480
92.times{|k|p s
c=0
(s+t=b=?X).chars{|i|i!=b ? t+=c.to_s+b*c=1:c+=1;b=i}
s=t[3,99]
(0<1&q/=2)&&(v=w[j-=1].ord;s=s[(v/32-3)*v%=32,v])}
```
[Try it online!](https://tio.run/##XY1Ra8IwFEbf8ysywdJarTdJoVa9FDZEZAzxQRRqGSYrNY7hbLJWWf3tXZ/3PZ5z4Ct/5L1ta@wdeLpaPueLl01dFLv1drF8y1XxWui84z1iMBHkjECuCLcj8JAxHkEkIIKJFCyEcAIk5oHVX7n5bT6bb2qI6nrX@BYlJnsvUKdj2Tnd6CeUNKHWRxXYy7vx5UAhmyof2UyiftDuzqZiGMcZ/T/iwpw51zFyz3HcCuv0PEKWBZfyY2bQpG41FnwkvEHVR8GHVeY92vYP "Ruby – Try It Online")
Starting with `3` we work through the look and say sequence as shown on <http://www.se16.info/js/lands2.htm> . At the branch points it is only necessary to carry on with exactly one branch. These are binary encoded in magic number `q`.
The sequence on the linked page actually uses a branch at the beginning or the end of the current string (even in the case `21Sc -> 20Ca` although it is not explained that way.) The only exception is `1H` where the required substring `22` is found at position `-6` (six from the right) in the output of the previous step (amongst other positions.)
The magic string encodes (from right to left) in each character the number of characters in the branch, as well as the number `3` or `2` for the index (in the format `index code * 32 + length`). When 3 is subtracted from the code, we get `(3-3)*l=0` for substrings that appear at the beginning, and `(2-3)*l=-l` for substrings that appear at the end. Ruby interprets `-l` as `l` characters from the righthand end of the string and extracts the correct characters.
For `2H` an escape sequence gives ASCII 2 which gives `l=2` and `(0-3)*2=-6` giving the correct characters for `2H`.
] |
[Question]
[
The challenge is to write a program which will find the shortest (least number of characters) command which will navigate to a target directory, given a starting directory, assuming a standard linux file system.
Take the following file system as an example, starting from `~`:
```
.
├── target
└── test
└── starting
```
If the user is in `~/test/starting` and wants to navigate to `~/target`, the shortest command is `cd ~/target`.
However, if the user is in `~/test/starting` and wants to navigate to `~/test`, the shortest command is `cd ..`
If the user wants to navigate to `~`, the shortest command is `cd ~`.
If the user wants to navigate to `/etc`, the shortest command is `cd /etc`.
**INPUT**
The input is two strings; the starting directory and the target directory. For example:
`/etc/kernel` and `/opt`.
The method and order these are input is up to you. (eg: array, list, arguments, input, etc)
**OUTPUT**
Print or return the shortest command which navigates to the target directory.
**SCORING**
Standard code golf rules.
**Some example test cases**
Input format is `starting` `target`
>
> Input: `~/a/b/c` `~/a/z`
>
>
> Output: `cd ~/a/z`
>
>
>
>
> Input: `~/apple/banana/carrot` `~/apple/banana/z`
>
>
> Output: `cd ../z`
>
>
>
>
> Input: `~/apple/banana/carrot` `/test`
>
>
> Output: `cd /test`
>
>
>
>
> Input: `/a/b` `/a/b/c`
>
>
> Output: `cd c`
>
>
>
>
> Input: `/a/b` `/a/b`
>
>
> Output: `cd .`
>
>
>
**CLARIFICATIONS**
* `~` is equivalent to `/home/golfer`
* Assume that inputs are already minimal. For example, you would not get `/home/golfer/a` as an input, and would instead get `~/a`
* The only aliases you need to worry about are `/` and `~`
* Shortest path from `~` to `/home` is `..`
* @loopywalt has pointed out that `cd` with no argument will navigate to `~`. This behaviour will be ignored, so please assume that an argument must always be specified.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~60~~ 56 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ëi'.ë'~’/€¨/’:'/©δ¡ζ.γË}¦˜2ôøðδK`®ýsg…../×ì®Ü}Iθ)éн…cd ì
```
-4 bytes thanks to *@JonathanAllan*
Inputs as a pair.
[Try it online](https://tio.run/##yy9OTMpM/f//cHemut7h1ep1jxpm6j9qWnNohT6QZaWuf2jluS2HFp7bpndu8@Hu2kPLTs8xOrzl8I7DG85t8U44tO7w3uL0Rw3L9PT0D08/vAbIn1PreW6H5uGVF/YChZNTFA6v@f8/WqlOP7GgICdVPykxDwj1kxOLivJLlHTQxauUYgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8Pdmep6h1er16k/alpzaIW6/qGVeod3WB1ad27LoYXntumd23y4u/bQstNzjA5vObzj8IZzW7wTDq07vLc4/VHDMj09/cPTD68B8ufUVp7boXl45YW9QOHkFIXDa/7r/I@OVqrTL0ktLtEvLkksKsnMS1fSAYkkFqWnlijF6ijgkAeKIMuCBNH4@qklyTChRP0k/WSwxkT9KrhgQUFOqn5SYh4Q6icnFhXll0CUIIsTUI3kEJAlIBGIXehCUGNAvIz83FQ0rn5osGuQoZExVFtZakZmMtA2oDX6xQX5RSXFIFZKfn6Rfk5@cjZIF7KSkqLS5GwkaTSz0/Nz0pRiYwE).
**Explanation:**
```
Ëi # If both paths in the (implicit) input-pair are the same:
'. '# Push "."
ë # Else:
'~ : '# In the strings of the (implicit) input-pair, replace all "~"
’/€¨/’ # with dictionary string "/home/"
'/© '# Push "/", and save it in variable `®` (without popping)
δ # Map over the pair, with "/" as argument:
¡ # Split the paths in the strings by this "/"
ζ.γË}¦˜2ôøðδK # Remove the matching path-prefixes:
ζ # Zip/transpose; swapping rows/columns,
# using a " " as filler-character if the paths are of unequal length
.γ } # Then group the pairs by:
Ë # Check if the two values in the pair are the same
}¦ # After the group-by: remove the first group
˜ # Flatten it to a single list
2ô # Split it back into pairs
ø # Zip/transpose these pairs back
δ # Map over each inner list:
ð K # Remove all spaces
` # Pop and push both lists separated to the stack
®ý # Join the second list with "/" delimiter
s # Swap so the first list is at the top of the stack
g # Pop and push its length
…../× # Pop this length, and repeat string "../" that many times
ì # Prepend it in front of the other string
®Ü # And trim a potentially trailing "/"
} # Close the if-else statement
Iθ # Push the second string of the input-pair
) # Wrap all values on the stack into a list
é # Sort it by length
н # Pop and leave just the first/shortest one
…cd ì # Prepend "cd " in front of it
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’/€¨/’` is `"/home/"`.
[Answer]
# [Python 3](https://docs.python.org/3/), 81 bytes
```
lambda p:'cd '+min(relpath(*map(expanduser,p)),p[0],key=len)
from os.path import*
```
[Try it online!](https://tio.run/##jY3LCsIwEEX3/YrsktRgBHdCv6TtYtpOaTGPIY1gXfjr0VYEFQWZxQz3nOHSHAfv9qkvqmTANh0wOvC2Y3xjRycCGoI4iNwCCTwTuO40YVAkpaJyV6sjzoVBJ7M@eMv8tF10NlryIeaJwuii6EXJrxr0hat1N7rltZTZGyUyqBtw93mKr1ELIfj48aYjTvFf99Gr1uML@0EGb3FpWPJ0Aw "Python 3 – Try It Online")
This utilizes the `os.path.relpath` function to get a relative path. The shortest path command is either the relative path or the absolute path, whichever is shorter, so the code just checks which using `min`. `expanduser` is used to expand the `~` directory to the user's home directory, which doesn't have to be `home/golfer` to meet the requirements. This is necessary to handle cases with `~` in the path name.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 101 bytes
Expects `[ current_dir, target_dir ]`.
```
a=>'cd '+((s=require('path').relative(...a.map(s=>(q=s).replace(/~/,'/home/@')))||".")[q.length]?q:s)
```
[Try it online!](https://tio.run/##ldHNbgIhEAfwe5@C7AVIdebeZG3fw3gYcXTXsAsL1IMxvvp2vzRNtNsWLiQz/OAPRzpRNKH0aVm7Hbf7vKV8Jc1OyFelYh64@SwDK@kpFVJDYEupPLECAIKKfNezUk0e@5K3ZFjhFRcSC1cxfkit9eWSQabXDViuD6nYvDdvUbfG1dFZBusOaq/WIrsi4RZNthiX50xstBY/DkTRXXLofHlmeW8Zt1R3Ew2F4NIkfy9Mh4wWwL8oTBzTwyVHaqg9Wn3CYeuYdD7gzTLzzq/KzYEn2Qak/6k/KHdnFsKjY0yVnwXv7z01t18 "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 66 bytes
Expects `(current_dir)(target_dir)`.
Assumes a \*nix system where `~` redirects to `/home/some_user`. On TIO, `~` is `/home/runner/~`. So this may fail because of that.
```
a=>b=>'cd '+((s=require('path').relative(a,b)||".")[b.length]?b:s)
```
[Try it online!](https://tio.run/##lc9LDsIgEAbgvado2ABRYW/SehDjYqDThyGlAnZhGq9eax@JqbFG2JDM8M38F2jAa1fWYV/ZFLss7iBOVJxQnUZ0y5iPHV5vpUNGawgF5cKhgVA2yGCneNsSQfhJCYNVHorzUR0877StvDUojM1ZxshDglRSEz4@74Tz6OuRMupHD32bT6euDUoFVX@lBudsmNT3wjBgdIT4g5EBfVgsNzJDZem8Ug3fpnQroWZHrxk/hNkQ3RM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 99 bytes
```
$
¶$%`
¶
/¶
m`^~(?=/.*¶)
/home/golfer
^(.*/)(.*¶)\1
$2
\G.*?/
../
1`¶
/¶
¶
O#$`
$.&
1G`
^$
.
^
cd
```
[Try it online!](https://tio.run/##dYw9CsMwDIX3dwpDneJksEj3kjFjh67B2EndH8gfrqcOOVYOkIu5TjoUCkXSk9CTPmf9ozchEWfNAscy80RHBcXqtJpEcSSZLXMKug@dpdvQXq2DEjKjVGxOlYMfUJUyKwhSEnIdnzdCzNOOa3C5R15qKA4JhebCQpjIUE0NW/sLUcextVSbPgY1xrnBs5/tvzPy9umx8tgH@p3f "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on space for convenience. Explanation:
```
$
¶$%`
```
Duplicate the last (to) line.
```
¶
/¶
```
Append `/` to the first two (original from and to) lines.
```
m`^~(?=/.*¶)
/home/golfer
```
Expand any leading `~` on the first two lines.
```
^(.*/)(.*¶)\1
$2
```
Remove any common prefix (ending in `/`) on the first two lines.
```
\G.*?/
../
```
Change any remaining "from" directories to `..`.
```
1`¶
```
Join those `..`s with the remaining "to" directories.
```
/¶
¶
```
Remove the trailing `/`.
```
O#$`
$.&
```
Sort numerically by length.
```
1G`
```
Take the first i.e. shortest string.
```
^$
.
```
If it's the empty string then replace it with `.`.
```
^
cd
```
Prefix `cd` to the string.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 66 bytes
```
(a,b,c)=>"cd "+((c=Path.GetRelativePath(a,b)).Length<b.Length?c:b)
```
[Try it online!](https://tio.run/##nZAxb8IwEIV3fsXJky3SeA8ENrpkqFi6sNjHAZYiE9lHhRj46ykxCGVAuKo8@J38/L7Tw/iB0fWrk8d55OD8voDX9wJ2UEMvTWELVPVC4BbEVEqsvwwfyk/iNbWG3Q8N82BTqmzI7/kwtw@xxMqqfjaZfAfH1DhPUgAEiqeWKxAwhZ0UV2201SgKSPIyCKHUbPyJzh0h07aC2xbJtfF3Xz6861rS1vjb0WhCOPIDNX7IU8syQf8N1EyRs5Tk2njIcobSUuyzvLe5@IfVx5H5OlJg/ws "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Python](https://www.python.org), 87 bytes
```
lambda t,s:"cd "+[t,r:=relpath(t:=expanduser(t),s)][len(r)<len(t)];from os.path import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XYxNCsIwFIT3niJklWg0W6n2Al7ARe0ibRNayB8vr6AuvIibguidvI0tFRcyi4GP-eb-ihdsgx8eJj89ezTr7ftolasaRVCkjNYNoasCBWQ5aBsVtgyzXJ-j8k2fNDDkIvGysNoz4PupkJc7A8GRkDaTQDoXA-Dye3-I0HlkhtGbVDFaLSvlx8grFf-oVgABKeeLnyTb4PS0HOn8OAxzfwA)
Expects `target, start`.
] |
[Question]
[
Your challenge, should you choose to accept it, is to take as input:
1. A program in DirectionLang (as an ASCII string consisting of DirectionLang instructions)
2. A list of pairs of integers, henceforth known as the pretty places. This list may be taken in any reasonable format.
You should then output a truthy value if the program halted at a pretty place, and a falsey value otherwise.
## DirectionLang
A DirectionLang instruction is hereby defined to be either
1. `<`: Decrement the x coordinate by 1.
2. `>`: Increment the x coordinate by 1.
3. `^`: Increment the y coordinate by 1.
4. `V`: Decrement the y coordinate by 1.
5. `S`: Skip the next instruction if the program is currently at a pretty place.
A DirectionLang program is executed by performing each instruction, in order. A DirectionLang program starts at the origin (coordinates `(0, 0)`). A DirectionLang program halts when every instruction has been executed.
If a DirectionLang program ends with an `S`, then its behavior is undefined.
If a DirectionLang program has no instructions, then its behavior is undefined.
DirectionLang is quite obviously not Turing complete, as there is not a way of looping.
## Test cases
```
"<>^^" [(0, 2), (0, 0)] -> True
"<>^^" [(0, 1)] -> False
"S^>>" [(0, 0), (2, 0)] -> True
"<SS^" [(-1, 0), (-1, 1)] -> True
"<SS^" [(-1, 0), (-1, -1)] -> False
"S^>>" [(2, 0)] -> False
"S^>>V" [(2, 0)] -> True
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 101 bytes
Expects `(program_string)(pretty_places)`. Returns \$0\$ or \$1\$.
```
s=>a=>Buffer(s+0).map(n=>(p=a.some(a=>x+[,y]==a),+s)?s=0:(n%=5)-3?y-=~-"121"[x+=n%3-1,n]:s=p,x=y=0)|p
```
[Try it online!](https://tio.run/##lY/BasMwDIbvewpjKNjETp2UXcrkwg57gYxdggOmdcZGaptoHQmMvXoWr1svg5LpIoH08f16te8W9/1LfJM@HNzUwoSgLej7U9u6nmGmeH60kXnQLILNMRwdm/dDVovRAFguMuQ7BLVlfgW3XG52o4RPSYuyoPWQgV9tZCG82SJEMcAIin/EaR88hs7lXXhmLaN3umko4ayulSClESR1ZQwhhHOyXpPH/uRurkHF9/FvnaEH2@Efqmq0vlAqqcoFqqr6Uc2/nKk0JOm/ITlTi/Jdci386oleoVLA6Qs "JavaScript (Node.js) – Try It Online")
### How?
The ASCII codes of the DirectionLang instructions are unique modulo \$5\$. Furthermore, the value of \$dx\$ can be easily deduced from them with an additional modulo \$3\$. We use a short lookup string for \$dy\$.
```
char. | c | n = c mod 5 | dx = (n mod 3) - 1 | dy = -~-"121"[n]
-------+----+-------------+--------------------+------------------
"<" | 60 | 0 | -1 | 0
">" | 62 | 2 | 1 | 0
"^" | 94 | 4 | 0 | 1
"V" | 86 | 1 | 0 | -1
"S" | 83 | 3 | n/a | n/a
```
[Answer]
# [Python](https://www.python.org), 128 bytes
*-39 bytes thanks to `Wheat Wizard` and -12 bytes thanks to `ovs`.*
```
def f(p,l):
s=a=0
while p:h=p[0];s+=abs('< >'.find(h))-1;a+=abs('V ^'.find(h))-1;p=p[1+(h=='S'and(s,a)in l):]
return(s,a)in l
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVHBisIwFGSP9gv2-PCSBJMl9SRq8hMFLyWFiA0pSAxtZVlE2P_w4sX9p_VrTLdaVyzmkjAzmXm8Ofz4r9pu3PF42taGTX6_V7kBgz1dk2kEldCCR_Bpi3UOfmqFT7maVSOhlxVGc5DowxRuhS0hLJ7pK76A7AH34Vs8wlYIlCAd4IpqUjgIESqCMq-3peuwdo7z27vZlBDGgACm6XAus2xIIcWcwphQaG5OlKIR3M-jLH6mk0zKG80bl3G_S5K0Liy-6ppHj1-_kL1K7hIHg45Y_GdU2Dv4snA1Nmj318SeyV3byR6RdkG3wi4)
[Answer]
# JavaScript, ~~118~~ 111 bytes
-7 bytes thanks to Arnauld!
```
p=>g=([d,...r],x=0,y=0,i='S>V ^'.indexOf(d),P=p.some(a=>x+[,y]==a))=>d?g(r.slice(!i&P),i<2?x+i:x,i<2?y:y+i-3):P
```
[Try it online!](https://tio.run/##hVJNj5swEL3nV0yjqrYbY0jaqlKydk7toYduJKq9sI5igUNdEbDAWRHt7m9PbUiz3V56AN4w72PG8i/1oLq8NdZFdVPo856fLRclx1lBGWOtpD1P6Mk/hqNU3MEWMVMXur/d44LQDbesaw4aKy76WUZPknNFCBfFusQt6yqTa/zGvNsQam4W635mlv2ATsvTzEQfyHJzXk0mu8n0Rmy3U8hwQmFBKIRvQiREAn60R/2qPx//f1VV5xvpVohLIwnCxb/CNB2E0fxCCGD@X0b0KmXHXGsOmLDOVsZhdF8jwvZN@0XlP7HTnQMu4HECkDe1LzIKtm3KVh0C0M6dKOje6txJ4BD47KCcl8ZTnPnNHlL5nkwBsxkJmTjM9TQkk5isrramtkefBNnV/Ft6@51Z1XYajzms1bZS/tDjDBMZlxS6MJp/cQ4II1gDyhAsAUlEiHzxbo5uNN/jISabS3JBifxrBqs6b3alc4jDsDELS@Fxxyu7qTSrmhIPGh98f1x8Tj4N6QF@zBEFf8mGFAooEr4ejSn80QT27mKsC3j7OMJnsvMxz2R1/g0 "JavaScript (Node.js) – Try It Online")
A recursive function expecting input as `f(p)(d)`, where `p` is a 2D array of pretty places, and `d` is a string of instructions. Outputs `true` if in a pretty place, otherwise `false`.
#### Ungolfed and Explained
```
p => g = ( // p = pretty places (PP's), g = recursive func
[d, ...r], // split instruction string and look at first char
x = 0, y = 0, // set default x and y
i = 'S>V ^'.indexOf(d), // find index of command
P = p.some(a => x + [, y] == a) // check if we are at PP
) => d ? // check if we are at end of input
g( // if not, recurse
r.slice(!i & P), // if char is 'S' and at PP, skip one
i < 2 ? x + i : x, // if i < 2, change x by i
i < 2 ? y : y + i - 3 // if i >= 2, change y by i-3
) :
P // if at end, return P
```
## Previous Answer, ~~125~~ 121 bytes
-4 bytes thanks to Steffan!
```
p=>g=([d,...r],x=0,y=0,P=!p.every(([u,v])=>u-x||v-y))=>d?g(r.slice(P&d=='S'),x+~~{'<':-1,'>':1}[d],y+~~{V:-1,'^':1}[d]):P
```
[Try it online!](https://tio.run/##hVJNj5swEL3nV0yjqra7xkDUqlKyZk/toYc2ElUvXkdB4FAqEixjoqAk@9dTG7LZbi89YJ5n3seM4He2z9rcVNoGu6ZQlw2/aJ6UHIuCMsaMpAce0d49S/5GM7VXpsdYdHQvCU@64HA67YOeOFw8lNiwtq5yhZfvCs5Rigg93D09HdE9mgcxRQmax2dRSNr76s@htrrWyHx5WUwm68n0PlmtpiBwRGFGKPh3RCQECfwwnXrVj8f6l6xuXSNdJcm1EXnh7F9hmg5CFzsSPIj/ywhepayZNdUWE9bqurIYPe4QYZvGfM7yX9iq1gJP4DgByJuduwgK2jSlybYeKGt7CuqgVW4lcPB8ts2sk4ZTLNxm@1S@J1PA7I74TOznOg3JJCSLm221051LAnEz/5p@/8Z0ZlqFxxxmlK4z9zFCgYkMSwqtH80dnAPCCB4ACQRzQBIRIl@8m86O5hs8xIhYkiuK5F8z6Kx1Zjc6h9APGzK/FB53vLGbWrG6KfGgccGP3exT9HFI9/BDjii4321IoYCCxN1HYwrPGs9eX41VAW@PIzyTtYs5k8XlDw "JavaScript (Node.js) – Try It Online")
A recursive function expecting input as `f(p)(d)`, where `p` is a 2D array of pretty places, and `d` is a string of instructions. Outputs `true` if in a pretty place, otherwise `false`.
#### Ungolfed and Explained
```
p => g = ( // p = pretty places (PP's), g = recursive func
[d, ...r], // split instruction string and look at first char
x = 0, y = 0, // set default x and y
P = !p.every(([u, v]) => u - x || v - y) // check if we are at PP
) => d ? // check if we are at end of input
g( // if not, recurse
r.slice(P & d == 'S'), // if char is 'S' and at PP, skip one
x + ~~{'<': -1, '>': 1}[d], // increment x by lookup
y + ~~{V: -1, '^': 1}[d] // increment y by lookup
) :
P // if at end, return P
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
FA«J⊟ι⊟ι1»J⁰¦⁰FSF¬∧υΣ⊟υ≡ιS⊞υKKM✳⊗⌕^<VιT¹¦¹
```
[Try it online!](https://tio.run/##RY5Bi8IwEIXP9lcMOU0gQnutXhZEcEEppHgpFbpptGHbpqSJe1j87TGpgnOZ94bH90Z0jRG66b2/agN4GCdnkVL4T1bfbphKjYWeUFEGr003yaowarRIMhLMI3nHUgZp8B8KtyF2i6zldtIWv8YWHQPuhoXqaByY/5QVHQR4aBXNLIFwkkPh5i6mCyl/Mfa28tq43uZw1HeJO2WksEqPuNPup5ct7lXAk8v2TBioSI7flUYNmDHI6Mb7qqrWQac1g0VkdVBky/mF1H59758 "Charcoal – Try It Online") Link is to verbose version of code. Takes the pretty places as the first argument and outputs `1` if the directions end on a pretty place, nothing if not. Explanation:
```
FA«
```
Loop over the pretty places.
```
J⊟ι⊟ι
```
Jump to those coordinates. (Note that on canvas they are actually rotated 90° from the description but I rotate the movements to compensate.)
```
1
```
Mark each pretty place with a `1`.
```
»J⁰¦⁰
```
Jump back to the origin.
```
FS
```
Loop over the instructions.
```
F¬∧υΣ⊟υ
```
If the previous instruction was not an `S` or we were not at a pretty place, then...
```
≡ιS
```
... if the current instruction is an `S` then...
```
⊞υKK
```
... save the current cell for the check on the next loop, otherwise...
```
M✳⊗⌕^<Vι
```
... move in the appropriate direction.
```
T¹¦¹
```
Delete the canvas except for the current cell.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~112~~ ~~105~~ 102 bytes
*-7 bytes using the (c mod 5) formula from [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/248059/65425)*
```
s,p=input()
x=y=0
while s:k=(x,y)in p;exec'xyxky--+++'[ord(s[0])%5::5]+'=1';s=s[1+k/2:]
print(x,y)in p
```
[Try it online!](https://tio.run/##fY7BCoJAEIbvPsWghC670ip4UddjL2A3UYgSFEUXV2mX6NktSy1C@i8z8H98M1z1Rdu44ygIZ2XDh95CmmSKUe1alHUOwq@YJYlCZQM8yGV@NqWSlbJtjLGZtN3FEglN0c7zfS/FJnPMQDCROLjau36q8a5s@lUwGqCHUZbpBG4WJeAiAtOk6A7PGHDshlz7gZx3ucSAw6kWLyrOomih6KRyN1Qr9Ck3VGEcvw/azuyaltfpr682IXuiZtX4h3kA "Python 2 – Try It Online")
Accepts input from STDIN as `<DirectionLang string>, <pretty places>`
[Answer]
# [Ruby (2.7.0)], 143 bytes
```
x=0i
y=!p
_,d,v=t.split ?"
a={?<=>-1,?>=>1,?^=>1i,?V=>-1i,?S=>0}
(d+?S).chars.map{|c|x+=a[c]if y
y=y&&c==?S?!v.match("(#{x.rect*', '})"):!p}
!y
```
Decided to try using complex numbers. Probably would be easier to do x,y and separate increment statements. The "a" hash is what we add to x for each character, the "y" is "yes" for if we should do the next line. We add an 'S' on the end to force the final comparison and return !y. Converting the complex number to "(x, y)" was pretty costly. Just uses a string match to see if the place is nice.
I should point out that "t" is the variable containing the full test string (the "program" and the nice values), if you needed it to be stdin, you'd need to change that to a gets or such. The final statement is the return value (!y), you'd need a "p !y" or $> or such if you want it printed. Right now you can test/run it by wrapping it in a def like:
```
def directionLang(t)
<code golf above>
end
```
[edit]
Actually I just wrote it without complex numbers and was surprised that it grew. There'd probably be a better way to handle the addition, but here's the basic code:
```
x=y=0
m=!p
_,d,v=t.split ?"
(d+?S).chars.map{|c|x+=(c==?<)?-1:(c==?>)?1:0if m
y+=(c==?V)?-1:(c==?^)?1:0if m
m=m&&c==?S?!v.match("(#{x}, #{y})"):!p}
!m
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~39~~ ~~38~~ ~~35~~ 33 bytes
```
x0Ti"@2\?y1GmY~}J@k11\Q^/+T]]x1Gm
```
Inputs are: a vector of complex coordinates, then a string.
[Try it online!](https://tio.run/##y00syfn/v8IgJFPJwSjGvtLQPTeyrtbLIdvQMCYwTl87JDa2Aij2/3@0UZaOgkEsl7qNXVycOgA) Or [verify all test cases](https://tio.run/##y00syfmf8L/CICRTycEoxr7S0D03sq7WyyHb0DAmME5fOyQ2tgIo9t8lqiLkf7RRlo6CQSyXuo1dXJw6V7RhFoJtoKNgBOQFx9nZAXm6hjoKuobaEAXBwXFwIV1kISQNMGaYOgA).
### How it works
```
x % Input: numeric vector of complex coordinates. Delete
0 % Push 0. This is the complex coordinate where the program starts
T % Push true. This is the interpret state: if false, the next
% instruction should be skipped
i" % Input: string containing the instrunctions. For each instruction:
@2\ % Push current instruction (converted to ASCII code), modulo 2
? % If nonzero (this is true only for 'S')
y % Duplicate from below: push copy of current coordinate
1Gm % Is it in the first input, i.e. is it pretty? Gives true or false
Y~ % XOR with interpret state. This toggles the interpret state.
% So if the state was true, it is now set to false because the
% current instruction is 'S' and the current coordinate is pretty.
% If the state was false, that means that the current instruction
% should have been skipped. So we simply set the interpret state
% to true
} % Else (the current instruction is not 'S', but may need skipping)
J % Push j (imaginary unit)
@k % Push current instruction converted to lowercase
11\ % (Convert to ASCII code) modulo 11
Q % Add 1
^ % Power. This gives -1 for '<', 1 for '>', -j for '^', j for 'V'.
% Note that the values for '^' and 'V' are reversed
/ % Divide the current interpret state (true: 1, or false: 0) by
% the above value. Dividing, instead of multiplying, has the
% effect of reversing the values for '^' and 'V' (and not those
% for '<' and '>'), and gives 0 if the interpret state is false
* % Add the result to the current coordinate, to update it
T % Push interpret state (note that it has been consumed) as true
] % End
] % End
x % Delete interpret state
1Gm % Is the current coordinate a member of the first input? Gives true
% or false. Implicit display
```
[Answer]
# Java 10, 168 bytes
```
P->C->{var r=0>1;int x=0,y=0,f=9;for(var c:(P+0).getBytes()){r=0>1;for(var t:C)r|=x==t[0]&y==t[1];y+=f<1&r|c%7>3?0:c%6-3;x+=f<1&r|c%9<6?0:c%5-1;f=f<1?9:c%83;}return r;}
```
[Try it online.](https://tio.run/##lZJdT4MwFIbv9ytOSDQQPgIufmxAjZp4Z7IE483CksqKMrGQcpgjjN8@C2OZOjV6UVpOn/fl8LYLuqTmYv6yiVJaFHBHE14PAAqkmESwkLtWiUlqxSWPMMm4ddsvvABFwp@MX5mE4zSchgZcZ1nKKCcEYvA3E5PcmKReUgHCt4njSg5Wvm1UcsT@yI0zoba70Vid6LZmPTG8rpAVqqbVW8WOwPGNJtb@yvdxaofHVTs7oVvpfuw5x2IdHZ2T4aU9jo7OzKG72pdH3llXPjWlWVu9HMm3i6HbCIal4CDcZuMOZBZ5@ZjKLPpIllkyh1cZk7oNYBoC1drIAGSDqCrEm80Ug7M36P@@rm3jpDHk024azf2AeuQb1PkCBTNCDiBb@p0c@gXBVz/T6Vg5Of@BzT90cfj9Fnr4kWoG@4vVpdiJtilCTvHZ2Kkgl2eA1SSlESv6cIOqQPZqZSVauVRgytVWoytA@RwUfX8Nr4SgVWHNGcvvs629@slQV8ZSEFs0z9Oqc9F2649Y33SzeQc)
**Explanation:**
```
P->C->{ // Method with String + 2D int-array parameters & boolean return
var r=0>1; // PrettyPlace-flag, starting at false
int x=0,y=0, // x,y coordinates, starting at 0,0
f=9; // Skip-flag, starting at non-0
for(var c:(P+0)// Append a trailing dummy '0' to the path-String (to determine
// if we're at a PrettyPlace after the last input-character)
.getBytes()){
// Loop over the characters as codepoints:
r=0>1; // Reset the PrettyPlace-flag to false
for(var t:C) // Loop over the input-coordinates:
r|= // Check if any is truthy for the PrettyPlace-flag:
x==t[0]&y==t[1];
// Where an input-coordinate matches the current x,y
y+= // Modify the y-coordinate by increasing with:
f<1 // If the skip-flag is 0,
&r // and the PrettyPlace-flag is truthy
|c%7>3? // Or if the current character is 'S'/'^'/'V':
0 // Leave y the same by increasing with 0
: // Else (the current character is '<'/'>'):
c%6-3; // Add -1 if '<', or add 1 if '>'
x+= // Modify the x-coordinate by increasing with:
f<1 // If the skip-flag is 0,
&r // and the PrettyPlace-flag is truthy
|c%9<6? // Or if the current character is 'S'/'<'/'>':
0 // Leave x the same by increasing with 0
: // Else (the current character is '^'/'V'):
c%5-1; // Add -1 if 'V', or add 1 if '^'
f= // Change the skip-flag to:
f<1? // If the skip-flag was 0 this iteration:
9 // Reset it back to non-0
: // Else:
c%83;} // Set it to `c` modulo-83 (0 for 'S', non-0 otherwise)
return r;} // After the loop, return the last PrettyPlace-flag as result
```
How the magic numbering works for the characters:
| Character | `c` | `c%7>3` | `c%6-3` | `c%9<6` | `c%5-1` | `c%83` |
| --- | --- | --- | --- | --- | --- | --- |
| '<' | 60 | true | | false | -1 | 60 |
| '>' | 62 | true | | false | 1 | 62 |
| '^' | 94 | false | 1 | true | | 11 |
| 'V' | 86 | false | -1 | true | | 3 |
| 'S' | 83 | true | | true | | 0 |
] |
[Question]
[
Please help me automate my discrete mathematics homework. Given a valid propositional formula, check if it is an instance of one of Łukasiewicz's axioms. Here's how it works.
A *term* can be defined inductively as follows:
* Single lower-case letters of the Latin alphabet (`a`, `b`, `c`, etcetera) are terms.
* Given a term `ϕ`, `¬ϕ` is also a term.
* Given terms `ϕ` and `ψ`, `(ϕ→ψ)` is also a term.
A formula is itself a term, usually made up of smaller terms. An example of a formula is `(a→b)→¬(¬c→¬¬a)`.
Now, these are the three axioms. They are formula templates; some formulae are instances of an axiom. You make an instance by replacing all the variables (the Greek letters) with terms.
```
A: ϕ→(ψ→ϕ)
B: (ϕ→(ψ→χ))→((ϕ→ψ)→(ϕ→χ))
C: (¬ϕ→¬ψ)→(ψ→ϕ)
```
Same Greek letters have to be substituted with the same terms. Thus, one instance of the axiom A is `(b→¬c)→(c→(b→¬c))`. In this case `ϕ` has been substituted with `(b→¬c)`, and `ψ` with `c`. Key to solving problems or making proofs in propositional logic is recognising when formulae are instances of axioms.
Note that all these axioms have their outer parens stripped away, which is common to do on the highest level. The strict way to write these
is `(ϕ→(ψ→ϕ))` `((ϕ→(ψ→χ))→((ϕ→ψ)→(ϕ→χ)))` `((¬ϕ→¬ψ)→(ψ→ϕ))`, with surrounding parens, but people usually leave those out when the meaning is clear so I'll leave it free how you choose to parse them.
The goal of the program is to take as input a **valid** formula in string or character array format, and output A, B or C (upper or lower case is fine) if it is an instance of the respective axiom, and do something else (output zero, output nothing, basically do anything except throwing an error) if it is not. The question is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest code wins!
### Test cases
```
input; output
(a→(a→a))→((a→a)→(a→a)); B
(a→(b→¬¬¬¬¬c))→((a→b)→(a→¬¬¬¬¬c)); B
(¬¬¬x→¬z)→(z→¬¬x); C
(¬(a→(b→¬c))→¬(c→c))→((c→c)→(a→(b→¬c))); C
(b→¬c)→(c→(b→¬c)); A
a→(b→c); 0
```
Alternatively, with surrounding parentheses:
```
input; output
((a→(a→a))→((a→a)→(a→a))); B
((a→(b→¬¬¬¬¬c))→((a→b)→(a→¬¬¬¬¬c))); B
((¬¬¬x→¬z)→(z→¬¬x)); C
((¬(a→(b→¬c))→¬(c→c))→((c→c)→(a→(b→¬c)))); C
((b→¬c)→(c→(b→¬c))); A
(a→(b→c)); 0
```
If you want to stick with printable ascii characters, you can use > for → and ! for ¬:
```
input; output
(a>(a>a))>((a>a)>(a>a)); B
(a>(b>!!!!!c))>((a>b)>(a>!!!!!c)); B
(!!!x>!z)>(z>!!x); C
(!(a>(b>!c))>!(c>c))>((c>c)>(a>(b>!c))); C
(b>!c)>(c>(b>!c)); A
a>(b>c); 0
```
Alternatively, with surrounding parentheses:
```
input; output
((a>(a>a))>((a>a)>(a>a))); B
((a>(b>!!!!!c))>((a>b)>(a>!!!!!c))); B
((!!!x>!z)>(z>!!x)); C
((!(a>(b>!c))>!(c>c))>((c>c)>(a>(b>!c)))); C
((b>!c)>(c>(b>!c))); A
(a>(b>c)); 0
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 175 bytes
```
n s='!':s
s%t='(':s++'>':t++")"
p[a]|a>'`'=1
p(n s)=p s
p(s%t)=p s*p t
f(a++'>':b%a)|p a==p b="A"
f(a%(b%c)++'>':(a%b)%(a%c))|p a*p b==p c="B"
f(n a%n b++'>':b%a)|p a==p b="C"
```
[Try it online!](https://tio.run/##bY9BawMhEIXv/orZAVGzzaHXBQfangotPfQYQqvSlFAishpIQ/77dnQ35NJF1jfvfU8xHMfxd53cT8jTFCFb1akhiyyLVZpV3ytSQ@l7NCjSxm0vjtSnsvciacaNTZBZMt/kKkERO@3mmpfOXBI4y5G3@IA1ktrLYGaAJ28k/4Np4KpyDAeLjxWO4GQE/@9pTziVr1xgGOC9jPv4DWuC5zfQRjQ/g4V0LJyxJLpqrBjejJcIescPEeLg9pE7B5deP6AdsUHtqQuGdKBZGbwD1I54OcN@25fpGjFYv7DkvuVXq0EsT9SdOThzcFrMpVt7HV849@tOt6ShbQoGt9Mf "Curry (PAKCS) – Try It Online")
Takes input in ASCII characters. Returns nothing if it is not an axiom.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~99~~ 83 bytes
```
(AZ'^.("9>,9>\1
,9>,9>9 >,,\1>\2 >,\1>\3
,!9>!9 >,\2>\1"R9C+XX^n).` $`NaTRpk@?:1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSblGOUuzC6qWlJWm6FjeDNRyj1OP0NJQs7XQs7WIMuXTADEsFBTsdnRhDuxgjIANEGytw6Sha2ilagvhGQJVKQZbO2hERcXmaegkKKgl-iSFBBdkO9laGmhCjl9Yq-CqkQ9gLbvZqJNkpJmvaaSTbQViaXBqJdkCUqAkUBNNQHlgcqAQEkqGSSWBJmBCXBpCusFOsAopWAUUrNLnAWpJBMlDdIJ2KQMsgJoBoO4QM1IUA)
### Explanation
A lightly compressed regex solution.
First, we're going to modify the input a bit:
```
aTRpk
a Command-line argument
TR Transliterate
p from "()"
k to ", "
```
Using `,` in place of `()` saves bytes on backslashes in the regexes.
Next, we're going to construct a list containing the following three regexes for axioms A, B, and C respectively:
```
^(.+)>,.+>\1 $
^ $ The full string must match
(.+) Match any run of characters (capture group 1)
>, →(
.+ Match any run of characters
> →
\1 Match group 1 again
␠ )
^,(.+)>,(.+)>(.+) >,,\1>\2 >,\1>\3 $
^ $ The full string must match
, (
(.+) Match any run of characters (capture group 1)
>, →(
(.+) Match any run of characters (capture group 2)
> →
(.+) Match any run of characters (capture group 3)
␠␠>,, ))→((
\1 Match group 1 again
> →
\2 Match group 2 again
␠>, )→(
\1 Match group 1 again
> →
\3 Match group 3 again
␠␠ ))
^,!(.+)>!(.+) >,\2>\1 $
^ $ The full string must match
,! (¬
(.+) Match any run of characters (capture group 1)
>! →¬
(.+) Match any run of characters (capture group 2)
␠>, )→(
\2 Match group 2 again
> →
\1 Match group 1 again
␠ )
```
We start with this string:
```
"9>,9>\1
,9>,9>9 >,,\1>\2 >,\1>\3
,!9>!9 >,\2>\1"
```
Then:
```
'^.("..."R9C+XX^n).` $`
"..." The above string
R9 Replace each 9 with:
XX Regex `.`
+ Apply + quantifier: `.+`
C Wrap in capture group: `(.+)`
^n Split the resulting string on newlines
'^. Concatenate "^" to the front
.` $` Concatenate ` $` to the end, coercing the result to a regex
```
Now we use the `N` operator to count the number of matches of each of these regexes in the transliterated input. The result will be a list of 0's and 1's: `[1 0 0]` if the first regex matched, `[0 1 0]` if the second matched, `[0 0 1]` if the third matched, or `[0 0 0]` if none matched.
Finally:
```
(AZ...@?:1)
... That three-element list
@?: Find the index of the first occurrence of
1 1
(AZ ) Use that number to index into the uppercase alphabet
If 1 is not found, returns nil, which results in no output
```
[Answer]
# Python3, 450 bytes:
```
lambda t,y:next((b for a,b in t if all(c(a,p(y)[0],{}))),0)
T=type
def p(s,c=0):
q,n=[],0
while s and(c==0 or s[0]!=')'):
n+=(S:=s[0])=='!'
if S.isalpha():q+=[[n,S]];n=0
if S=='(':t,s=p(s[1:],1);q+=[(n,t)];n=0
s=s[1:]
return q,s
def c(a,b,d):
if T(a)!=T(b):return
for x,y in zip(a,b):
p,q=x;n,m=y
if(t:=T(x))==list:yield all([d.get(q,m)==m,not p or p%2==n%2]);d[q]=m
if t==tuple:yield all([T(y)==tuple,not p or p%2==n%2,*c(q,m,d)])
```
[Try it online!](https://tio.run/##bVJNi9swED2vfsU4sHjUFcG7vRSbMbSFPfaS3LymyB9pBLai2Fpqt/S3p5LstA1dg5E08@a9pxmZ2R5P@v0HM1ye6eXSyb5qJFgxp7qdLGIFh9MAUlSgNFhQB5BdhzVKYXDmRVKKn7845yLhbE92Ni1r2gMYHEVNCU8ZnIWmohQJg@9H1bUwgtQN1kQJOOLRMUQU89hDQT8Q7lLyQU4UR7GLOcXdVo2yM0eJPD0/UFFosSvLTFOy5h0W49SKkZxw8ZiW4pFnHolaWH5FjhRyDIbWvg7aORuDWX@ZSjTegSPbo@QR7bHi6YJjoQOTmH0Hfijj0cGtEWeaMi16moMPtKmrm7iz3qnRprNquya0q2i231qLZ9G7XC/0yYLxtzf3T0T6/qnkWVOcS@qX@1gi@2q69l@Gvev2Gv6/XryrPbm7Q8kvclKnfqTNZiNzrHLJM/jIMOxrznN028ot0p8y@MQwknnkIwv2sysEVsuxDRzMhaPaZet82f2hkw6@0Em@ngJdUIr8dyt3Db2lyVZ7GSQut1L48sjpLjR@zf9mVqdhgPKrbXuDfoJ362yLwqCfh9qOplMW4wxi7p9reLJgi8eyDHNVfqoH1dl2wC8n3QporiUv2pWUjL0NCx26gTr1ScAMBDeq7M4MSlt8xtXnMiAuYHL/zC@/AQ)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 102 bytes
```
T`()`{}
{((.+)>{.+>\2}|(.+)>{(.+)>(.+)}}>{{\3>\4}>{\3>\5}|!(.+)>!(.+)}>{\7>\6)}$|.+
$#2$*A$#4$*B$#6$*C
```
[Try it online!](https://tio.run/##RYy9DsIwDIT3vEVUIzmplKGUslkCBl6AMUN/xMDCgBiqpnn2YCcFoujO/i6X1/39eA5ph9c@3Xo0fYgqILraUHA1@SauZckqEiOF4PfkWx7ED3HVOc0q8Ei@MxFWVyuoGrAnqFqwZ6g6sJeUcCC@g@H/sm@bEj6SljNt4ZjDL1LIPpNemC5MZyFbSxoaJypNcfon/K5MxMmP5XgyHw "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs nothing unless the input is one of the axioms. Explanation: Another regex-based answer.
```
T`()`{}
```
Translate the `()`s to `{}`s to avoid 14 `\`s.
```
{((.+)>{.+>\2}|(.+)>{(.+)>(.+)}}>{{\3>\4}>{\3>\5}|!(.+)>!(.+)}>{\7>\6)}$|.+
```
Try to match one of the three axioms, but if there isn't an immediate match then just match everything.
```
$#2$*A$#4$*B$#6$*C
```
Output the corresponding letter if one of the capture groups in the relevant axiom exists. (Axiom `A` only has one capture group but for the others any representative capture group works.)
[Answer]
## PERL, ~~116~~114 bytes
```
#!/usr/bin/perl -p
y/()/XY/;s/^(.+)>X(.+)>\1Y$/A/;s/(X.+>)X(.+)>(.+YY)>X\1\2Y>\1\3$/B/;s/X!(.+)>!(.+)Y>X\2>\1Y/C/
```
This comes with a shebang line, so is suitable for a standalone executable script. If you are willing to execute it as `perl -p scriptfilename`, the shebang line can be dropped, or to execute as `perl scriptfilename`, the shebang line can be replaced with a final `;print`
The behaviour for the "not an axiom instance" case is to print the input with parentheses replaced by X and Y, respectively. This certainly counts as "do something else" because this output is guaranteed to be different from A, B, C (e.g., it is guaranteed to contain a lowercase letter)
] |
[Question]
[
Wholly surprised this hasn't been posted already, given the large number of chess puzzles on the site. While I thought of this myself, credit to Anush for [posting it to the sandbox back in March](https://codegolf.meta.stackexchange.com/a/17463/70388). But I figured it's been long enough that I could go ahead and do so myself.
A [checkmate](https://en.wikipedia.org/wiki/Checkmate) in chess is a position in which the king is attacked and there is no move that can defend it. If you aren't familiar with how chess pieces move, [you can familiarize yourself on Wikipedia](https://en.wikipedia.org/wiki/Chess#Movement).
# The challenge
For this challenge, your input will be the position of a chess board in whatever notation you like. To clarify, your input will describe the pieces on a chess board, with their colors and positions, along with the possible [en passant](https://en.wikipedia.org/wiki/En_passant) capture square, if any. (Ability to castle is irrelevant as you cannot castle out of check.) [You may find FEN notation useful](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation), but any convenient format is fine. For simplicity, **you can assume it's Black to play** - this means Black will always be the checkmated player. A position where White is in check, checkmate, or stalemate will be considered invalid for this challenge.
You must output a truthy value if the position is checkmate, and a falsey value if it is not. Note that **stalemate is not checkmate** - the king must be attacked!
# Truthy test cases
>
> [1k5R/6R1/8/8/8/8/8/6K1 b - -](https://lichess.org/analysis/standard/1k5R/6R1/8/8/8/8/8/6K1_b_-_-)
>
>
> [rn2r1k1/pp1p1pQp/3p4/1b1n4/1P2P3/2B5/P5PP/R3K2R b - -](https://lichess.org/analysis/standard/rn2r1k1/pp1p1pQp/3p4/1b1n4/1P2P3/2B5/P5PP/R3K2R_b_-_-)
>
>
> [kr5R/rB6/8/8/8/5Q2/6K1/R7 b - -](https://lichess.org/analysis/standard/kr5R/rB6/8/8/8/5Q2/6K1/R7_b_-_-)
>
>
> [2K5/1B6/8/8/8/7N/R7/R3r2k b - - 0 1](https://lichess.org/analysis/standard/2K5/1B6/8/8/8/7N/R7/R3r2k_b_-_-)
>
>
> [8/4Q1R1/R7/5k2/3pP3/5K2/8/8 b - -](https://lichess.org/analysis/standard/8/4Q1R1/R7/5k2/3pP3/5K2/8/8_b_-_-)
>
>
> [2K5/1B6/8/8/8/4b2N/R7/4r2k b - -](https://lichess.org/analysis/standard/2K5/1B6/8/8/8/4b2N/R7/4r2k_b_-_-_0_1)
>
>
>
# Falsey test cases
>
> [rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq -](https://lichess.org/analysis/standard/rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR_b_KQkq_-)
>
>
> [8/8/8/8/8/1KQ5/4N3/1k6 b - -](https://lichess.org/analysis/standard/8/8/8/8/8/1KQ5/4N3/1k6_b_-_-)
>
>
> [2K5/1B6/8/8/8/7N/R7/4r2k b - -](https://lichess.org/analysis/standard/2K5/1B6/8/8/8/7N/R7/4r2k_b_-_-)
>
>
> [8/8/2Q5/3k4/3Q5/8/8/7K b - -](https://lichess.org/analysis/standard/8/8/2Q5/3k4/3Q4/8/8/7K_b_-_-)
>
>
> [8/4Q1R1/R7/5k2/3pP3/5K2/8/8 b - e3](https://lichess.org/analysis/standard/8/4Q1R1/R7/5k2/3pP3/5K2/8/8_b_-_e3) (Watch that en passant!)
>
>
>
Code golf - shortest code in bytes wins. Good luck!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~499 ... 374~~ 370 bytes
Takes input as `(b)(X)`, where \$b\$ is an array of 64 integers describing the squares (from left to right and from top to bottom) and \$X\$ is the 0-based index of the en-passant target square, or \$-1\$ if there's none.
Below are the expected values for each square:
```
0: empty square
5: white pawn 6: black pawn
9: white king 10: black king
17: white bishop 18: black bishop
33: white rook 34: black rook
49: white queen 50: black queen
65: white knight 66: black knight
```
Returns \$64\$ for checkmate, or \$0\$ for not-checkmate.
```
b=>e=>(g=(c,k)=>b.map((v,p,h,s=p+(p&~7),M=t=>v&-~c?c?(B=[...b],K&=g(b[t?b[T]=b[p]:b[b[e-8]=0,e]=6,p]=0),b=B):k|=V&8:0,m=([a],[x,t,...d]=Buffer(a))=>d.map(c=>(h=n=>(V=(a+=c-66)&136?3:b[T=a+a%8>>1])&v&3||t>>!V&v>>x&n>31&&h(n-4/!V,M``))(t,a=s)))=>(v=b[p],m`##123ACQRS`,m`$?13QS`,m`%?2ACR`,m`&#!#04PTac`,c?(p-e+8.5&~1||M(),m`"!QS`,p<16?m`"&R`:m`""R`):m`"!13`))|k)(1,K=g())*K
```
[Try it online!](https://tio.run/##jVJdc5s4FH3Pr5CTFkuLQBZfZr0RntjTJyZeQ9O8UHYNWI6zJFjFrCed9eavZ6/sNtOknZ2iGekKjs4594i/il2xrdpb1VnNZimfVuKpFJEUEb4RuKI1EVFp3xcK4x1VdE23QplYGY9DQi9FJ6KdYT1W42qMJyKzbbvMaWyIG1xm3bjMrnJRZioflVmZSSvMxYDKXARUQUVoKSZkVO/FtRGOBvRe4KzIafZAOwpEy1xM/l6tZIsLAh6WBw8V2FqLBuZrgQtTVFYQEIO7wdgFjStRmMXbMIp4Toyd4e73XRT1ro1dFD0YTeRyw1jjxvJY75peLhaE4I4WYks0P94dnNL7xdkZd9yLaZK@X8DuzZi7yaF6O3YupqmujLPe2cCbXxXVgkLjypJmaPvGI9/vLzEBwGlPH1HnPBjDxkgXI1hO0wXRa4@7IL2vCeY0hqQI@SV@6uS2QwKtZINEhP45QSj7k6KSIpkfX0P7XbXG7A/88b1JkI1sE2HbJG8Y@Q3QUgFMIiFQ3@qjMbI4GiEcIgvJDNJA5@fIRXvYDHK7WhftFK76osMDAohfh0BQbop2CRwXbVt8xoFH7NXt3R0ANPvxYu3Vpn1XgIlKe6wOYkyLKWSgITIMhLULrLfweyAThQRcmNUBYgpdjY5CmTJN3VjmURRSxAOKXIciD@rAy7PTeTxJk9mpfdss5cPvK1zZ3eaDUrKdFlsJieXQi/UIRiLwUPQJRVpZmwW31abZbu6kfbe5wSt80CNYKgJf/z05@fZrf7qWVQ3Jyj450VeA@7z2UxaknIXPI4g5KiEn6xnUNk7La86U4jASxVzlMV7yBua5M3eZM/HZ3J/PWerGTvrqdN2CRDsJvtD7iaMlWDp8hXNin/Fn2HAGCOBrnfoVLmRewlNNwPzaAS9gwI8dfep/Gb3SOXB6P6LkSumeVA1zyJzEP5qIn4Evg/zYzDYdqr6Ls23KT3XZtBDV8Tkqg8OQzeHhcx3SbJLEk5nOKU7qTy98fB08BgvezGW8Dn4ipx/2dOzDrT3mJt7rfn4uS@l@A3WUz5IhSxxghPUl4dN/ "JavaScript (Node.js) – Try It Online")
## How?
### Board representation
We use the classic [0x88 board representation](https://www.chessprogramming.org/0x88), so that out-of-bounds target squares can be easily detected.
```
| a b c d e f g h
---+----------------------------------------
8 | 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07
7 | 0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17
6 | 0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27
5 | 0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37
4 | 0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47
3 | 0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57
2 | 0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67
1 | 0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77
```
### Move encoding
Each set of moves is encoded with 5 parameters:
* the type of piece
* the maximum number of squares that can be visited in each direction
* a flag telling if captures are allowed
* a flag telling if non-captures are allowed
* a list of directions
All these parameters are packed into a single string. For instance, knight moves are encoded as follows:
```
`&#!#04PTac`
||\______/
|| | +------> 0 + 1 = 1 square in each direction
|| | | +----> standard moves allowed
|| +---> 8 directions | |+---> captures allowed
|| / \||
|+--------> ASCII code = 35 = 0b0100011
|
+---------> 1 << (ASCII code MOD 32) = 1 << 6 = 64
```
To decode a direction, we subtract \$66\$ from its ASCII code:
```
char. | ASCII code | -66
-------+------------+-----
'!' | 33 | -33
'#' | 35 | -31
'0' | 48 | -18
'4' | 52 | -14
'P' | 80 | +14
'T' | 84 | +18
'a' | 97 | +31
'c' | 99 | +33
```
which gives:
```
[ - ] [-33] [ - ] [-31] [ - ]
[-18] [ - ] [ - ] [ - ] [-14]
[ - ] [ - ] [ N ] [ - ] [ - ]
[+14] [ - ] [ - ] [ - ] [+18]
[ - ] [+31] [ - ] [+33] [ - ]
```
All sets of moves are summarized in the following table, except en-passant captures which are processed separately.
```
string | description | N | S | C | directions
------------+-------------------------+---+---+---+----------------------------------------
&#!#04PTac | knight | 1 | Y | Y | -33, -31, -18, -14, +14, +18, +31, +33
##123ACQRS | king | 1 | Y | Y | -17, -16, -15, -1, +1, +15, +16, +17
"!13 | white pawn / captures | 1 | N | Y | -17, -15
"!QS | black pawn / captures | 1 | N | Y | +15, +17
"&R | black pawn / advance x2 | 2 | Y | N | +16
""R | black pawn / advance x1 | 1 | Y | N | +16
$?13QS | bishop or queen | 8 | Y | Y | -17, -15, +15, +17
%?2ACR | rook or queen | 8 | Y | Y | -16, -1, +1, +16
```
### Commented
```
b => e => (
// generate all moves for a given side
g = (c, k) =>
b.map((
v, p, h,
// s = square index in 0x88 format
s = p + (p & ~7),
// process a move
M = t =>
// make sure that the current piece is of the expected color
v & -~c ?
c ?
// Black's turn: play the move
( // board backup
B = [...b],
// generate all White moves ...
K &= g(
// ... after the board has been updated
b[
t ?
// standard move
b[T] = b[p]
:
// en-passant capture
b[b[e - 8] = 0, e] = 6,
p
] = 0
),
// restore the board
b = B
)
:
// White's turn: just update the king's capture flag
k |= V & 8
:
0,
// generate all moves of a given type for a given piece
m = ([a], [x, t, ...d] = Buffer(a)) =>
d.map(c =>
( h = n =>
( // advance to the next target square
V = (a += c - 66) & 136 ? 3 : b[T = a + a % 8 >> 1]
)
// abort if it's a border or a friendly piece
& v & 3 ||
// otherwise: if this kind of move is allowed
t >> !V &
// and the current piece is of the expected type
v >> x &
// and we haven't reached the maximum number of squares,
n > 31 &&
// process this move (if it's a capture, force n to
// -Infinity so that the recursion stops)
h(n - 4 / !V, M``)
)(t, a = s)
)
) =>
(
v = b[p],
// king
m`##123ACQRS`,
// bishop or queen
m`$?13QS`,
// rook or queen
m`%?2ACR`,
// knight
m`&#!#04PTac`,
c ?
// black pawn
( // en-passant capture
p - e + 8.5 & ~1 || M(),
// standard captures
m`"!QS`,
// standard moves
p < 16 ? m`"&R` : m`""R`
)
:
// white pawn (standard captures only)
m`"!13`
)
) | k
// is the black king in check if the Black don't move?
// is it still in check after each possible move?
)(1, K = g()) * K
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~1165~~ ~~1065~~ 1053 bytes
*Bytes saved thanks to [Leo Tenenbaum](https://codegolf.stackexchange.com/users/62859/leo-tenenbaum)*
```
n=Nothing
x?y=Just(x,y)
o(x,y)=x<0||y<0||x>7||y>7
m#k@(x,y)|o k=n|1>0=m!!x!!y
z(x,y)m p(a,b)|o(x+a,y+b)=1<0|Just g<-m#(x+a,y+b)=elem g[(p,0),(5,0)]|1>0=z(x+a,y+b)m p(a,b)
t(x,y)p(a,b)m|o(x+a,y+b)=[]|g<-(x+a,y+b)=(g%p)m++do[0|m#g==n];t g p(a,b)m
c m|(x,y):_<-[(a,b)|a<-u,b<-u,m#(a,b)==6?1],k<-z(x,y)m=or$[m#(x+a,y+b)==6?0|a<-0:s,b<-0:s]++do a<-s;[k 3(a,b)|b<-s]++(k 2<$>[(a,0),(0,a)])++[m#l==4?0|b<-[2,-2],l<-[(x+a,y+b),(x+b,y+a)]]++[m#(x-1,y+a)==p?0|p<-[0,1]]
c m=1>0
(k%p)m=[[[([p|a==k]++[m#a])!!0|a<-(,)b<$>u]|b<-u]|not$o k]
w(Just(_,1))=1<0
w x=1>0
m!u@(x,y)|g<-m#u,Just(q,1)<-g,v<-((u%n)m>>=),r<-v.t u g,k<-(do[0|n==m#(x+1,y)];(u%n)m>>=(x+1,y)%g)++(do a<-s;[0|n<m#(x+1,y+a)];v$(x+1,y+a)%g)++(do[0|(x,n,n)==(1,m#(x+1,y),m#(x+2,y))];v$(x+2,y)%g)++(do a<-s;[0|1?0==m#(x,y+a)];v((x,y+a)%n)>>=(x+1,y+a)%g)=[k,k,do a<-s;[(a,0),(0,a)]>>=r,do a<-s;b<-s;r(a,b),do a<-s;b<-[2,-2];l<-[(x+a,y+b),(x+b,y+a)];v$l%g,do a<-0:s;b<-[0|a/=0]++s;r(a,b),do a<-[x-1..x+1];b<-[y-1..y+1];[0|w$m#(a,b)];v$(a,b)%g]!!q
m!u=[]
u=[0..7]
s=[1,-1]
q m=all c$m:do a<-u;b<-u;m!(a,b)
```
[Try it online!](https://tio.run/##7VdLb@M2EL7zV4wQByBhypWcFxCbTtGeukUX2156EIiAcrSyIYlSbCmRt@5vT4eUrHW33jZpHpt2bcPycB7fDGfIITVTyyRK07vfXPKDLqoS3ueLTJXEAxfeqVtN/JYA@r3SEEYwVUVZLaIriDQUarlUumRkiFq/5HlCjpD4br6c5QU5RvJHPY9nJTlB8ucqijQ5Ncy5jgl5m5czJMB8XHibQzGPphF5Uy1LoJqDzwxUqqbJpxLPSH6dzcuolbi/32nR4pH6YiWMKq35ipHc/ol67K3XK/OoJ2dITc5IdpB8a4XrHBKh1/7EE5nj1I6zIh@sIIOCKh6iAq37iq/6IRM@YthA4rGbHXzkR2mUQRzQgnuM0xN8Sov4oVPZoJEmsmaQbWMHco2oH8c0PixY1u9f5YG3zg5iIbQcoecWKCNTyNYW7Pxy7AZNrGrsVjw0DwzPcIQ4vfAlT8ZuOyuRL3rBduyo4Bk773xpLPFPGqeArOUoSOCoQUaREdAEhuPexLgzU/W4YpL1@4iYCnGMSKgXDLk7lDw1UW3ccKRCpFBdWnVau74dC1GgWYHKHvelNNMSmDtCEzN/EQQBDYq1EiJpDJVkjmMjppyFGEsljVN86rzsYTUluaV2CVxyn9makVuoLWbmVG3VbQErbvWuUW/sxvwGIWl1qFk2mQjGF2P3ZlBCBbFJH7V10ELY3GHoTI465ZZzGGMqaJc7VB9vtM3ERze9brBRRSUMSHONeaA@78AbaojUxm64y4F/4TURbTzQlsTAurgadyJIeMI72@0Couaik5hCjxa26Nu8pqijzxUVY0wP49YA15A1wSp9Izws2yeAAdZ@MMDYpFVbmdHKjNDitteuXDttQxzG0nGuTe1wjxB8eIPBmSRLEfjc9SW5xgWj0hSmvey8wa8MbDXKHGt/dxWFVQxhrhZX4v08LaMFxaUymLKe5bVGDWwTd0MZYQNBMjXXIlPFT5e0WMx1ObhmEKCER/odD9N8mvBlqdKIR3UpCYmyolyBIAABfgHa7sSfkgT0A8D3@Hv814oP@FO7toFtu6emAe3TtMd/OL5dP8MnXj@PB22Xtc/@ug3CbhvsUuI7Juez@3o0MT9TGXbgW9bxk@R@vw2@CL6t4NGfK/ho/H9o6e02wOvS//xa9Nij7QHxW1e@dWVJ7z49457x@@x15f/vG93u1m25Jw8sxQtdi@w7w/OcCV@gFPszYX8m/Oszwb44g4AnOxY@cw17UFs9fum2sdWsdqVtv1a/irflqC6/hvvRycvdj06f79B8rfeL/yJ@1/OajXD3Bw "Haskell – Try It Online")
~~This is not exactly well golfed as of now, but it is a start.~~ With some help along the way I've now golfed this down pretty aggressively (and fixed an error along the way).
The one perhaps questionable thing this does is that it assumes that, other than by a king or a pawn en passant, you can never get out of check by capturing one of your own pieces. In chess you are not allowed to make this move but my program considers these moves to save bytes under the assumption that if you are in check this can never get you out of it.
This assumption is valid because such moves
1. Cannot capture the piece that is attacking the king, since the piece they capture is black.
2. Cannot block the path of the piece that is attacking the king, since the captured black piece would have already been doing that.
We also add the additional stipulation that if you have no king you are in check.
This program also makes the assumption that if there is a pawn that can be captured en passant, then the pawn was the last piece to move and that move was a legal move. This is because the program does not check if the square it moves the black pawn to is empty so if there is a piece there things can get a little screwy. However this cannot be obtained if the last move was a legal move and furthermore cannot be represented in [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation). So this assumption seems rather solid.
Here is my "ungolfed" version for reference:
```
import Control.Monad
out(x,y)=x<0||y<0||x>7||y>7
at b (x,y)
|out(x,y)=Nothing
|otherwise=(b!!x)!!y
inLine (x,y) ps m (a,b)
| out (x+a,y+b) = False
| elem (m `at` (x+a,y+b)) $ Just <$> ps = True
| m `at` (x+a,y+b) == Nothing = inLine (x+a,y+b) ps m (a,b)
| otherwise = False
goLine (x,y) p (a,b)m
| out (x+a,y+b) = []
| otherwise = case m `at` (x+a,y+b) of
-- Just (n,1) -> []
Just (n,_) -> set(x+a,y+b)p m
Nothing -> set(x+a,y+b)p m ++ goLine(x+a,y+b)p(a,b)m
checkBishop (x,y) m=or[inLine(x,y)[(3,0),(5,0)]m(a,b)|a<-[1,-1],b<-[1,-1]]
checkRook (x,y) m=or$do
a<-[1,-1]
inLine(x,y)[(2,0),(5,0)]m<$>[(a,0),(0,a)]
checkKnight (x,y) m=any((==Just(4,0)).(at m))$do
a<-[1,-1]
b<-[2,-2]
[(x+a,y+b),(x+b,y+a)]
checkPawn (x,y) m=or[at m a==Just(p,0)|a<-[(x-1,y+1),(x-1,y-1)],p<-[0,1]]
checkKing (x,y) m=or[at m(a,b)==Just(6,0)|a<-[x-1..x+1],b<-[y-1..y+1]]
check m
| u:_<-[(a,b)|a<-[0..7],b<-[0..7],(m!!a)!!b==Just(6,1)] =
checkBishop u m ||
checkRook u m ||
checkKnight u m ||
checkPawn u m ||
checkKing u m
| otherwise = True
set (x,y) p m=[[[head$[p|(a,b)==(y,x)]++[(m!!b)!!a]|a<-[0..7]]|b<-[0..7]]|not$out(x,y)]
white(Just(n,0))=True
white x=False
moves m (x,y)
|g<-m `at` (x,y)=case g of
Just(2,1) -> do
a<-[1,-1]
b<-[(a,0),(0,a)]
set(x,y)Nothing m>>=goLine (x,y) g b
Just(3,1) -> do
a<-[1,-1]
b<-[1,-1]
set(x,y)Nothing m>>=goLine (x,y) g(a,b)
Just(4,1) -> do
n<-set(x,y)Nothing m
a<-[1,-1]
b<-[2,-2]
l<-[(x+a,y+b),(x+b,y+a)]
-- guard$white$n `at` l
set l g n
Just(5,1) -> do
a<-[1,-1]
c<-[(a,0),(0,a),(a,1),(a,-1)]
set(x,y)Nothing m>>=goLine (x,y) g c
Just(6,1) -> do
a<-[x-1..y+1]
b<-[x-1..y+1]
guard$white(m `at`(a,b))||Nothing==m`at`(a,b)
set(x,y)Nothing m>>=set(a,b)g
Just(n,1) -> (do
guard$Nothing==m `at` (x+1,y)
set(x,y)Nothing m>>=set(x+1,y)g) ++ (do
a<-[1,-1]
guard$white$m`at`(x+1,y+a)
set(x,y)Nothing m>>=set(x+1,y+a)g) ++ (do
guard$(x,Nothing,Nothing)==(1,m`at`(x+1,y),m`at`(x+1,y))
set(x,y)Nothing m>>=set(x+2,y)g) ++ (do
a<-[1,-1]
guard$Just(1,0)==m`at`(x,y+a)
set(x,y)Nothing m>>=set(x,y+a)Nothing>>=set(x+1,y+a)g)
_ -> []
checkmate m=all check$m:do
a<-[0..7]
b<-[0..7]
moves m(a,b)
```
[Try it online!](https://tio.run/##7VdZb9tGEH7nrxgBeuBCS0H0CSSmHhqgQI8EaVGgDwThLKW1RJgXJKqhUPa3u7MnddBXYrtOIwumRrOz3xw7x3LOltc8TW/@9pyf8nJVwVWxyFjljMCDj@xz7viaAPcdyyHmMGFltVrwKfAcSrZcsrwizhFK/V4U184xEj8ky3lROidI/pIns3nlnCL524rz3DkTzCSfOc6HopojAeLPgw8FlAmfcOfn1bICN6fgEwGVssn17spIrPw5TyquV7x/bpKsLBYVvCvyalGkw/dFzqZOsarcmq5JUF@MmmYtHvX4HKnxucMqiEGuOgCNldRWSV4154vPyZIHbtzr1aTXWztJ/muSc7UPyiVk4DIaExDygCC4MmB0PUBWAD@ydMnlCk85SmbwiVWfWhECfZBOXfTHAiyAPxYrtWFXFIIATMACsFaY1T1LjOnWilmxabiSzTqtDqM9iAnDrz2TiivH88TpmYMRJzZW@1vmpWQueWU3lpBJiY0E2JeAwQCUzS1XGz2Z88m1yjHtTxYUi1AFRTJC95iOCHVP8RllclvDLrzQp54f0dhQkYISeYs2tFD9aYEG2g1Ib2EfbWDjyYWILxgjyohGVFlvEVm@dt0gEBFxT1CWDF3MvoyQfUXCtiPqHQk6tJ5TpGKkrAJVkK3vAg6YVlGiCumuW3s@7vLFfkF5PoloiQsjap0XtbiLJAOmwc4MGCIMh/VAx28tfiG0gQGVS6s3l0KvDfhoODxXGxTlZr0ew0KKLTqaBIFMh81jXaE7TdOy9RHtsnWcd9kyOh3SKtlW2tbNBJd1hxlo6yMLwjCcczbth2Wj4@GuaU2iwSAUXsToBYtaJ6Mmbsm8qPqmo0TOZ9GpXOlvLk4/kNokF@pAlWdW/MVlDauG1MwuPFtvoi3JCpyJklOVhUmoqk1m0HYOqSzaykrBlAWGWKbssvE42OoKM4gN@vF96O2v@2Fl@AzyyTZyfuHtAdyi0pQFQCpzu6M2ZCvxYLZii2lfBrifqyimxlZI0c/cWHN6l5@T7ShSpH35FHX00JBOjKqzfVW1KSLr4zZnww89O2QoSdNohUGQWe6tBgmeEJgZS0yjdrUpSk0Lafu8r4bj7bBKZEZEszZou1HccqOv7JX78MS0wJ3wKLarwEDiJr3FfIsq9emGErL1g1iA21UedXjU5VVrhgyqj3lijqPedO5ObVJQc/ecRoBLPVBl/8JrGRfTJE1VP@tnb@z8kI1Hzw9D654iD/9myuMVFniBBgdXSVrxhYtdaiiBSF/yEa3FemuR3iocKaLuDU7GkjzIWPn@0i0XSa5hhH0EQpSgPP9I47SYXNNlxVJOeV1FDs/Kai2bfYgfO//pU5IQOYhPD/gH/NeKD/jPusrA3rcOYTrgfwG@vhc@bf58Pai9/eyXQWzLoEuIdjjnk4dqFDY/0zF04Nt3u0OafqP4@r1nRJ4S/56WrssAb0v/82vR1462R9hvb@OaHD2kZzzQfp@8rvjf3ei6W7d@733cUbzQtUi@MjzPTPgPjuIwEw4z4YtngnxvhgCebCzccg17VFs9eem2sdGsusJ2yNXv4m2Z19X3cD86fbn70dnzDc3Xer/4FvFtz1OFcPMv "Haskell – Try It Online")
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), 729 bytes
```
F=lambda a,b:a<'^'<=b or a>'^'>=b
def m(b,P,A=0):
yield b
for(r,f),p in b.items():
if F(P,p):continue
*d,n,k={'R':[(0,1),8,4],'N':[(1,2),(2,1),2,4],'B':[(1,1),8,4],'Q':[(0,1),(1,1),8,4],'K':[(0,1),(1,1),2,4],'P':[(2,0),(1,0),(1,1),(1,-1),2,1],'p':[(-2,0),(-1,0),(-1,1),(-1,-1),2,1]}[p if p=='p'else p.upper()]
if p in'pP':d=d[d!=[2,7][p=='p']+A:]
for u,v in d:
for j in range(k):
for i in range(1,n):
U=r+u*i;V=f+v*i;t=b.get((U,V),'^')
if U<1or U>8or V<1 or V>8:break
if F(p,t):
B=dict(b);B[(U,V)]=B.pop((r,f))
if t in'eE':B.pop(([U+1,U-1][t=='e'],V))
yield B
if t not in'^eE':break
u,v=v,-u
M=lambda b:all(any('k'not in C.values()for C in m(B,'W',1))for B in m(b,'b'))
```
[Try it online!](https://tio.run/##jVbbbts4EH3XV0yTB1I1bVlynHjdKEBdNMDCaNbxNumDqgKSRSeqbUql6GwDw9@eHZKSL02BXRnQZXhmOJczQ5fP6rEQvXb5XD6/vFyHy2SVZgkkLB0ml@QbuQxTKCQkV/h@FaZOxuewoimbsPdh1x068JzzZQapA/NCUsnmLishF5B2csVXFXWH4ADkc7imE1a6w1khVC7WHIVvMybYItyQKRlGtMt8lw3YWczIjf72WeAyGmhpYKQjK92hbndah9LxL1KrO9HSgHWNtNus4b1tID5CSg1pW0zbbx6@fTSwbVTqWMowRDxfVhzKzrosuaRubMPUwZMS98vCLMrehFHALuLIKsSt90MNw0zBmj3pNGWYQSv4rj9lIh44XbhGasT5XuwzUS/AXShb67f5u/tw3nrCpwrTzgNXlN6xe5dhqVyLQ4fuLn00c3c1wPv9pa@LeX81GKaSJ4sd6JqWTDXGYRRm@UzR1H03iozFOBx1yqKkpr61aa2mdLD8IxnWy9Fdy2d3bT@OFAbMSYy6DdzyZOTsdUVh9L9pA3t3MDHhE2uvnU8NF5GJyyVNxDMlC2KV4EPnKVmuOfJLJ@mDFq3oiJEvBEtmZCMrSxlJieu@nILilZolFa8cR8m1enyGEAghZlN/0Z9651PfG@x@52MfUmhD2wCkCKS/8L2y9PF3W3q98szzU1/gfRJMel4w6nuT/mTiTXvjYHqguZBoWo7Oa7P920Cb9qYXB5hg3Pf8HeTiBlfRjgwWFgNd8A1u4J3d@lOt7PUXAfqAG/fHgdY6sKaDcuYJsvMwRCnSH4tUSAzBXmavM7Qw8CZ4@RPt/M3odjy60f6Pbxc/aoP7pPjj2753dtPz/MX5f/h/tnP/f7nOe0C/JGr2COoxUcAFlElVJUK9cfdBnTqn8PmRg8RSMvi@rhSiJJYUlbgpMJgKQyIykGth5CtUc@ayWCHgp/pHJtiiq7KQCjKecaHsWl400r@VzMXDn385jhl2ZgNasbRuD8nVWgqI6DIXvFMhuKRupyqXuaJuNDwb9mLEmt7VCM3Cyi7rTySsJr/VtTpx3SD2cnQUFdbN7muZyuCzXHMXWrXUFpfBtX66Rs34OueCNm3c1H2iNdDrJX/CbGoDaL7Alv94A5UJFV1UBeiW1/Iy5zPsEdOlIuM/OQ73Z6A4ghZsni@52zkyb3MSDuzACi1PrQ0MYrPdg3RGZjodKurGw13QmI1ZJ6@y/EEnY3iUjDm0Qu0dnbnHSWpe@FKrQ4g098ixroR2WLfN3tyvkgNDFT/WtzFEOPFiVJu99us3lvRYi/wY3qA/7QN/9MaFzKhexOBd5Lv@JAnRNd0bkmDDNTg/3gft/N4rPXsjGYa9@LUvNU/rchp6pEWCu6a7YwRrOMO5qzgEGSTVLM8RPkM1rolg0GCaQ3PjqOC6thEB0vle5ILWZ485/DFuS/754cH1h53Jci8bsK4@VeNDXyn5KkhLvEXDrrUcETw0KxdbsVgr3LPpTerigEMyZqZRqsq8dPfpOtXdD3hs7AZD5WgHBKM2IYz/LPlM8czVLnGxXnGJiaAGWqdnx2LdVvbDViRfofDTkagpv14KoTG@Z0DtpKGN85pwdTBHrCqlpoKdUXR@cnJyVGPcJrQTbyO2@uOX6xh8/NW4B2TTvG4Jgwc8WskmX21J57XOxpKnzh74F@72GIAOuuxYpMdFiIXD@tlg5icbm4itJtimSUod/rYe3lbcOUE1zKhdqytirJx8FV/FNYr17DIFG564B@u4oyak@YNA6/8fL/8C "Python 3 (PyPy) – Try It Online")
] |
[Question]
[
### Challenge
Given a non-negative integer, output whether it is possible for two dates (of the Gregorian calendar) differing by exactly that many years to share a day of the week. A year is assumed to be a leap year either if it is divisible by 4 but not by 100, or if it is divisible by 400.
Output may be:
* [falsey/truthy](https://codegolf.meta.stackexchange.com/a/2194/53748) (in either orientation)
* any two distinct values
* one distinct value and one being anything else
* by program return code
* by success/error
* by any other reasonable means - just ask if you suspect it may be controversial
But **not** by two non-distinct sets of values, except for falsey/truthy (as this would allow a no-op!)
### Detail
This is whether the input is a member of [OEIS sequence A230995](http://oeis.org/A230995).
Members:
```
0, 5, 6, 7, 11, 12, 17, 18, 22, 23, 28, 29, 33, 34, 35, 39, 40, 45, 46, 50, 51, 56, 57, 61, 62, 63, 67, 68, 73, 74, 78, 79, 84, 85, 89, 90, 91, 95, 96, 101, 102, 106, 107, 108, 112, 113, 114, 117, 118, 119, 123, 124, 125, 129, 130, 131, 134, 135, 136, 140, 141, 142, 145, 146, 147, 151, 152, 153, 157, 158, 159, 162, 163, 164, 168, 169, 170, 173, 174, 175, 179, 180, 181, 185, 186, 187, 190, 191, 192, 196, 197, 198, 202, 203, 204, 208, 209, 210, 213, 214, 215, 219, 220, 221, 225, 226, 227, 230, 231, 232, 236, 237, 238, 241, 242, 243, 247, 248, 249, 253, 254, 255, 258, 259, 260, 264, 265, 266, 269, 270, 271, 275, 276, 277, 281, 282, 283, 286, 287, 288, 292, 293, 294, 298, 299, 304, 305, 309, 310, 311, 315, 316, 321, 322, 326, 327, 332, 333, 337, 338, 339, 343, 344, 349, 350, 354, 355, 360, 361, 365, 366, 367, 371, 372, 377, 378, 382, 383, 388, 389, 393, 394, 395
plus
400, 405, 406, 407, 411, ...
```
Non-members:
```
1, 2, 3, 4, 8, 9, 10, 13, 14, 15, 16, 19, 20, 21, 24, 25, 26, 27, 30, 31, 32, 36, 37, 38, 41, 42, 43, 44, 47, 48, 49, 52, 53, 54, 55, 58, 59, 60, 64, 65, 66, 69, 70, 71, 72, 75, 76, 77, 80, 81, 82, 83, 86, 87, 88, 92, 93, 94, 97, 98, 99, 100, 103, 104, 105, 109, 110, 111, 115, 116, 120, 121, 122, 126, 127, 128, 132, 133, 137, 138, 139, 143, 144, 148, 149, 150, 154, 155, 156, 160, 161, 165, 166, 167, 171, 172, 176, 177, 178, 182, 183, 184, 188, 189, 193, 194, 195, 199, 200, 201, 205, 206, 207, 211, 212, 216, 217, 218, 222, 223, 224, 228, 229, 233, 234, 235, 239, 240, 244, 245, 246, 250, 251, 252, 256, 257, 261, 262, 263, 267, 268, 272, 273, 274, 278, 279, 280, 284, 285, 289, 290, 291, 295, 296, 297, 300, 301, 302, 303, 306, 307, 308, 312, 313, 314, 317, 318, 319, 320, 323, 324, 325, 328, 329, 330, 331, 334, 335, 336, 340, 341, 342, 345, 346, 347, 348, 351, 352, 353, 356, 357, 358, 359, 362, 363, 364, 368, 369, 370, 373, 374, 375, 376, 379, 380, 381, 384, 385, 386, 387, 390, 391, 392, 396, 397, 398, 399
plus
401, 402, 403, 404, 408, ...
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in each language wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
u=-abs(200-input()%400)-4
print u/100+5>(u-8)*5/4%7>u%4/-3
```
[Try it online!](https://tio.run/##fZhNrybHbUb39SsuFAiYcUZQdX2SCcZA9l55a2ShyKNYMHwljGaA5Ncr5/BmkVUWfPF2F7u6i4fdxYe//veXv/3yOn7/9F@ffvzmm29@//rxux/@47d3o/fvfn799euXd@@/Xb2//261Xz///Prl5ev3T@//vP/47ut38f4P@/v17f3j12/X99/N37n8Dw8XtvZPL//29csv//jhy6e/vvz4t08//r21v3766eWnd6/v/@X/3OD1f6f@18@fvnz9/Pr/zN3anz7@pX942R9ezoeX@@HlebCB@T8@vAz@j4n5Pz@8TP7PhXHF5Hhx8eL/4vLtRFy//c/1h/@H6w/XHI@Z4/L/cv31P9cH/4Prg//J9ck1yXEyx9N9mO7T9Dr0mXr4kJ57pj/Ln3rwGkgf34HhwNj@eG52f5zPp398/Gc6qQt4lgPLSV3Ls2rASV3Osx3YTrrrnDfaTuriHlf3HCd1fc9x4DqpS31c63Od1NU@4UA4qYt@whuFk7r2x8U/6aS1/KwBA28MRhdDX/7UOeYbT/fHAQMxnu2PA8OB8fjjuXH8ubJ0wECMWWgdmDXgpAZiGIixnNQYjFUDTmoMxvZG20kNxDAQ4zipMRjHgeOkBmIYiHGd1BiM68B1UmMwwhtFZZcDUQOVaA6kA@mkFYM0@1z@7Oaey58uf5qy05XPh1mmi56m7Rx1eE1aDyt1Zx2GP06wKp2d1AVOM3juSm/nc1nTLJ6nDp3PRJ6uaF4nvXXofC5mupgZdeh8LmG6hGlO81L6U/@OP1y7fPplPq@nDrl2@fTLLF6jDn3PfPpl7i5zd9W7Vy9fvX1m7Nr1LjrfrkPn8@mXebrM03XqnJOancvsXLcOnc@XcZmYy6df5uQyJ1c9fdYr7vttOu5eh9ef8L33nJm4zcTtYvZTA0y1Xcz2ldym43ZF20zcZuJ2WdtlbdNxu6xtJm4zcbvAXd8X03HXF8ZXcpuOe9c5b2Qmbpe6Xeo2HbdL3WbiNhO3i94uepuO20VvX8ltOm5Xvs3EbSZul79d/jYddy0/a4BJjzE4vpLHnDy9zqUfve6PAwbimJjHGBxfyTPqm@g5s/OYncdAHANxZn0tHZg14KQG4hiIY7IeY3BWDTipMThm7DFjj4E4BuKYu8cYHHP3mLvHQBwDcUzgYwyOr@S59XX2nFl8zOJjIE7UgJMag2M@H/P5VAx8Ja/Lvyb1dfnX5V@T@rry6yt5XfQ1qe@ow@s@4KFJfWcd1t7gBKt2CCd1gdekvi7wusDrsq5JfU8dOp9JfV3R9ZW8tw6dz8VcF3OjDp3PJVyXcE3q8JWMXv@OP1wbPn2Yz/HUIdeGTx9mcYw6dOvy6cPcDXM3Zm1nzmfGhhkbPn2YsbHr0Pl8@jBPwzyNU@ec1OwMszNuHTpf7Y@1Qfr0YU6GORn19OZk@kqm6Zi9Dq8/4VbqOTMxzcR0MfnUgJuti0lfyTQd0xWlmZhmYrqsdFlpOqbLSjMxzcR0gblqwEl3bdoOmI6565w3MhPTpaZLTdMxXWqaiWkmpotOF52mY7ro9JVM0zFdeZqJaSZmVQhVIpiOWcvPGnDr7W@lgi8lv6t@385nFRO9fmu0yoZuhvJbo6NGx1vFUedH1Ryjio4qH3rVD33WXap46PNttO5SRUSvKqKvukuVEH29jdZdqorou@6@6y5VTfQqJ/qpu1Qt0U@NnrpL1RS9iop@6y5VUfT7VhW9lUV1PuruUXep4qLH22jdpUqLnjWadZe3uPkeP09F7PFd4LfOVMSeKgmfitXj60z1VWdGFWHj7UxVYPOtLKu6bL6dqaJs1mzrrV6ru1Q0nl3zVzSeisZTEXhOzX/eztT8p2artT@37nLfztT8teqnVv3E25mav1b61Eqf3P/e2p9fPr785fXlp18@v7y@/Pz68vmH1//89M7a@v3Lz291NF4//Pbbp89fXv708eOff@/taaPNttpup90WLdvDyac9oz2zPas9uz2nPbc90Z5so7fBNaON2cZqY7dx2rhtRBvZZm/zaZMpZ5urzd3mafO2GW1mW72tp63RFndcbe22Tlu3rWgr2@5tP22PtmfbPNBu@7R92462s53eztPOaGe2s9rheU87t51oJ9vt7T7tjnZnu6vd3S7Lue1Gu9mit3hajBazxWqxW5wWrDZaZMve8mk5Ws6Wq@VueVrelgTDaBCOTjw6AelEpBOSTkw6QelEpROWjl@FDT8DZ@QMnbEzeEbP8BE/aGDGFz9iSCWP4UcYyTMMPyJJSY/hNwWBH@GkrsfwI6LkHoYfQaXAx/BbEsOPyFLlY/gRXPIRjPgRX8p9DL8tWvwIMoU/hh9xJkcx/Ag1xT@G3zEH8CPeyAAMP0JOxmL4EXWkAIbfNVnwI/SIArIGP6JPFmP4AQB1gOEXZhV@UEAiYPgBgszG8IMFWgHDL00/848EhAeiASMH4THgMeAx4IF6wPB7TFT84IGEwPCDx4DHgMeAxzCfTejKaPzMaZParDatzWsTGx4oCwy/aerjB48BDyQGhh88BjwGPNAZGH7LdwQ/eAx4IDgw/OAx4DHgMeCB8sB8mfCDx4AH8gPDDx4DHgMeAx7oEMy3Dj94DHggRngF8YPHgMeAx4AHqgTz9cQPHgMeAx7IEww/eAx4DHigUTDfY/zgMeAx4IFYwfCDx4DHgMeAB6oF843nlYfHhMeEBxoG472Hx4THhAdqhs@Cnwb84DHhMeGBrMHwg8eEx4THhAciB8MPHhMeEx7IHQw/eEy/NH5q/NbUxwY/Pzd@b/zg@MXxkwOPCY8JjwkP9BCGHzwmPCY8JjxQR3yq8IPHhMeEBzoJww8eEx4THhMeqCYMP3hMeEx4oJ8w/OAx4THhMeGBkMLwg8eEx4THvH4Q8YPHhMeEx4QHAgvDDx4THhMeM/xy4gePCY8JjwkPhBeGHzwmPCY8ZvqJ9RvLRxYeCx4LHgseiDKMTy08FjwWPNbjxxg/eCx4LHgseCx4oNUw/OCx4LGGX2384LHgseCx4LHggYbD8IPHgseaft7xgwdaDsMPHgseyz3ATcBdwG2g9gH83AncCtwL3AzggdzD8IPHgsfabhj4wQPth@EHjwUPZCCGHzwWPNZxZ8EPHshBDD94LHgseKAOMfzgsa5bEH7wQCayF@EHjwWPBQ9UI4YfPFa4V@EHD@Qjhh88FjwWPBCSGH7wWOmm5q7GtgYPVCXGzgaPDQ8EJsbuBo8Nj/24/eEHD4Qmhh88NjyQmxh@8Njw2MN9Ej94IDsx/OCx4bHhgQBlE8UPHnu6oeIHD0Qohh88Njw2PJCjGH7w2MudFz94IEkx/OCx3Z3dnt2f3aDdoWuLxs9N2l3abRoeGx4bHkhVDD947ONejh880KwYfvDY8NjwQLhi@MFjXzd9/OCBgmX3xw8eGx4bHhseSFkMv7A6wA8e6FkMP3hseGx4bHggbDH80jLCOoJCAh4oXIxaAh4HHgceBx5IXQy/x4IDP3igdzH84HHgceBx4IHwpSLBb1iZ4AePAw8UMIYfPA48DjyQwRh@0xIGP3gceKCHMfzgceBx4IEoxvBb1jr4wePAA3WM4QePA48DjwMPZDJmUYQfPA480MoYfhZOVk6WTtZOFk9VPeFn/WQBBQ@EM4YfPA48DjyQ0JhlFn7wOPA48EBLY/jB48DjwANBjVmP4QePA48DD5Q1hh88DjwOPA48kNiYlRulGzwuPC48ENwY9Rs8LjwuPJDelHeWePjB48LjwgMNjuEHjwuPC48LDxQ5hh88LjwuPNDmGH7wuPC48LjwQKlj@MHjwuPCA82O4QePC48LjwsPxDuGHzwuPC48LjyQ8pSc@MHjwuPCA1GP4QePC48LjwsPJD6GHzwuPC48EPsYfvC48LhWtJa01rQWtVa1lrXWtVXY4mdpC48LjwuPC48LjwuPC48LjxtWwPjB48LjwuPC48LjwuPC48LjwuOmpbK1MsUyPAIeAY@AR8Aj4BHwCHgEPOKxqMYPHgGPgEfAI@AR8Ah4BDwCHjGsvvGDR8Aj4BHwCHgEPAIeAY@AR0zLdPzgEfAIeAQ8Ah4Bj4BHwCPgEct6Hj94BDwCHgGPgEfAI@AR8Ah4xLbwxw8eAY@AR8Aj4BHwCHgEPAIecVQI@MEj4BHwCHgEPAIeAY@AR8AjrlICP3iEWkOxodpQbqg3FBwqDiVHaQ784BHwCHgEPAIeAY@AR8Aj4BGpOFGdIE/gkfBIeCQ8Eh4Jj4RHwiPhkY8yBj94JDwSHgmPhEfCI@GR8Eh45FDv4AePhEfCI@GR8Eh4JDwSHgmPnAoj/OCR8Eh4JDwSHgmPhEfCI@GRSwWFHzwSHgmPhEfCI@GR8Eh4JDxyK7Xwg0fCI@GR8Eh4JDwSHgmPhEceNRl@8Eh4JDwSHgmPhEfCI@GR8MireMMPHgmPhEfCI@GR8Eh4JDwSHhmqPPxUgcpAdaBCUCWoFFQLKgZVgyUHSw8qCEsRliQsTViisFRhycLShSUMVYb9KQnpFYrDrjrsysOuPuwKxK5C7ErErkbsisQ@SnV6hTqxKxS7SrErFbtasSsWu2qxKxe7erHPEqpeoWTsasauaOyqxq5s7OrGrnDsKseudOyrtK1XqB678rGrH7sCsqsguxKyqyG7IrKrIvsuOewVCsmukuxKya6W7IrJrprsysmunuwKyn5KQXuFmrIrKruqsisru7qyKyy7yrIrLbvast8S3V6hvOzqy67A7CrMrsTsasyuyOyqzK7M7FE63StUml2p2dWaXbHZVZtdudnVm13B2VWcPUval7ZX3Mu82gDVB6hGQHUCqhVQvYBqBrx1A97aAV5RDYHqCFRLoHoC1RSorkC1BWRejYHqDFRroHoD1Ryo7kC1B6o/UA2C6hBUi6B6BNUkqC5BtQmqT1CNguoUVKugegXVLKhuQbULql9QDYPqGFTLoHoG1TSorkG1DapvUI2D6hxU66B6B9U8qO5BtQ@qf1ANhOogVAuhegjVRKguQrURqo9QjYTqJFQroXoJ1UyobkK1E6qfUA2F6ihUS6F6CtVUqK5CtRWqr1CNheosVGuhegvVXKjuQrUXqr9QDYbqMFSLoXoM1WSoLkO1GZ7M/wE "Python 2 – Try It Online")
A direct formula.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 18 bytes
```
99R4ḍj`‘ṡ%4ȷ$S€P7ḍ
```
Outputs **1** for members, **0** for non-members.
[Try it online!](https://tio.run/##y0rNyan8/9/SMsjk4Y7erIRHDTMe7lyoanJiu0rwo6Y1AeZA0f///xsaAgA "Jelly – Try It Online")
### How it works
```
99R4ḍj`‘ṡ%4ȷ$S€P7ḍ Main link. Argument: n
99 Set the return value to 99.
R Range; yield [01, .., 99].
4ḍ Test each element in the range for divisibility by 4.
j` Join the resulting array, using itself as separator.
The result is an array of 9801 Booleans indicating whether the
years they represent have leap days.
‘ Increment the results, yielding 1 = 365 (mod 7) for non-leap
years, 2 = 366 (mod 7) for leap years.
%4ȷ$ Compute n % 4000.
ṡ Take all slices of length n % 4000 of the result to the left.
S€ Take the sum of each slice.
P Take the product of the sums.
7ḍ Test for divisibility by 7.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
`0Gv@+5:YcYO8XOda
```
The program halts if the input belongs to the sequence, or runs indefinitely (infinite loop) otherwise.
Let `n` be the input. The code executes a loop that tests years `1` and `1+n`; then `2` and `2+n`; ... until a matching day of the week is found. If no matching exists the loop runs indefinitely.
The membership function for `n` is periodic with period `400`. Therefore, at most `400` iterations are needed if `n` belongs to the sequence. This requires less than 20 seconds in Try It Online. As a proof of this upper bound, here's a [modified program](https://tio.run/##y00syfn/P8HAvcxB29QqMjnS3yLCPyXRwcTA0Ebr/38TAxMA) that limits the number of iterations to 400 (by adding `@401<*` at the end). Note also that this bound is loose, and a few seconds usually suffice.
[Try it online!](https://tio.run/##y00syfn/P8HAvcxB29QqMjnS3yLCPyXx/38TA1MA)
### Explanation
```
` % Do...while
0Gv % Push column vector [0; n], where n is the input number
@+ % Add k, element-wise. Gives [k; k+n]
5: % Push row vector [1, 2, 3, 4, 5]
Yc % Horizontal "string" concatenation: gives the 2×6 matrix
% [k, 1, 2, 3, 4, 5; k+n, 1, 2, 3, 4, 5]. The 6 columns
% represent year, month, day, hour, minute, second
YO % Convert each row to serial date number. Gives a column
% vector of length 2
8XO % Convert each date number to date string with format 8,
% which is weekday in three letters ('Mon', 'Tue', etc).
% This gives a 2×3 char matrix such as ['Wed';'Fri']
d % Difference (of codepoints) along each column. Gives a
% row vector of length 3
a % True if some element is nonzero, or false otherwise
% End (implicit). The loop proceeds with the next iteration
% if the top of the stack is true
```
---
## Old version, 24 bytes
```
400:"0G&v@+5:YcYO8XOdavA
```
Output is `0` if the input belongs to the sequence, or `1` otherwise.
[Try it online!](https://tio.run/##y00syfn/38TAwErJwF2tzEHb1CoyOdLfIsI/JbHMESRjCgA "MATL – Try It Online")
### Explanation
```
400 % Push row vector [1, 2, ..., 400]
" % For each k in that array
0G&v % Push column vector [0; n], where n is the input number
@+ % Add k, element-wise. Gives [k; k+n]
5: % Push row vector [1, 2, 3, 4, 5]
Yc % Horizontal "string" concatenation: gives the 2×6 matrix
% [k, 1, 2, 3, 4, 5; k+n, 1, 2, 3, 4, 5]. The 6 columns
% represent year, month, day, hour, minute, second
YO % Convert each row to serial date number. Gives a column
% vector of length 2
8XO % Convert each date number to date string with format 8,
% which is weekday in three letters ('Mon', 'Tue', etc).
% This gives a 2×3 char matrix such as ['Wed';'Fri']
d % Difference (of codepoints) along each column. Gives a
% row vector of length 3
a % True if some element is nonzero, or false otherwise
v % Concatenate vertically with previous results
A % True if all results so far are true
% End (implicit). Display (implicit)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 83 bytes
```
lambda i:all(c(y)-c(y-i)for y in range(401))
c=lambda n:(5*(n/4)+n%4-n/100+n/400)%7
```
[Try it online!](https://tio.run/##RcvBCsIwEATQe79iL6W7tqGJRIRA@yVeYjW6ELcl9JKvjxEKzmFgYN6W9/cq5xKmW4n@c394YOdjxAUzqVqKKawJMrBA8vJ6otWGqFmm4y4OLyeU0VIvrVUyGq37OrWm9lp@lv/WVOsaqNkSyw48QKfmboCATOUL "Python 2 – Try It Online")
Direct port of [my Haskell answer](https://codegolf.stackexchange.com/a/152188).
[Answer]
# [Haskell](https://www.haskell.org/), 76 bytes
*-35 bytes thanks to Jonathan Allan. -2 bytes thanks to Lynn.*
```
f i=or[c y==c$y+i|y<-[0..400]]
c n=(5*n#4+n%4-n#100+n#400)%7
(%)=mod
(#)=div
```
[Try it online!](https://tio.run/##JY27DoIwAEV3vuKGR9LalNQE42L9Ap0ckaEpIo1QGkCFxG@3QtzuPWc4tRoet6bxvoKRXZ9rzFLqeGbmMx94LtI0E6IoAg0ryW5jo4zZJOM22grBlicETfYBSahsuzIgEZWleflWGQuJVrkziHuOl7E/WaQg1wn8CDLU3RsTBWMIVxCu609jVIuhFGt7iRT@q6tG3QfPtXM/ "Haskell – Try It Online")
Using the OEIS PARI program's algorithm.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 32 bytes
```
iI7*FsM.:hMs.iKiIL4S99*98]K%Q400
```
**[Try it here!](https://pyth.herokuapp.com/?code=iI7%2aFsM.%3AhMs.iKiIL4S99%2a98%5DK%25Q400&input=10&test_suite=0&test_suite_input=0%0A5%0A6%0A7%0A11%0A1%0A2%0A3%0A4%0A10&debug=0)** (Click "Switch to Test Suite" to verify more test cases at once)
### How?
Uses a cool [trick](https://codegolf.stackexchange.com/questions/40039/tips-for-golfing-in-pyth/152205#152205) I just added to the "Tips for golfing in Pyth" thread.
```
iI7*FsM.:hMs.iKiIL4S99*98]K%Q400 | Full program. Reads from STDIN, outputs to STDOUT.
S99 | Generate the integers in 1 ... 99.
L | For each integer N in that list...
iI 4 | Check if 4 is invariant over applying GCD with N.
| This is equivalent to checking if 4 | N.
K | Store the result in a variable K.
.i *98]K | And interleave K with the elements of K wrapped
| into a list and repeated 98 times.
s | Flatten.
hM | Increment.
.: | And generate all the substrings...
%Q400 | Of length % 400.
sM | Sum each.
*F | And apply folded product.
iI7 | Check if 7 is invariant when applied GCD with the
| product (basically check whether 7 | product).
| Implicitly output the appropriate boolean value.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~110~~ 107 bytes
```
from datetime import*
lambda n,d=date:0in[d(i,1,1).weekday()-d(i+n%400,1,1).weekday()for i in range(1,999)]
```
[Try it online!](https://tio.run/##jYxLDoIwEIb3nGI2hlaLgegGEo6gFxAXJZ3qRDsltYnh9BV8bNzov/tf3zDGs@dNSjZ4B0ZHjOQQyA0@xGVm26t2vdHAyrRz25TEByNIVaqS6zvixehRyGKKVrzYluVXYX0AAmIImk8oKlXXtTymIRBHke/Q9RhuTS6zr@FEkk0Gs8gKK0h@7FOvPylk0@Yw3bM3seOO954L9yeZfYSf9PQA "Python 3 – Try It Online")
*-3 bytes thanks to Mr. Xcoder.*
] |
[Question]
[
Take three inputs, a string of text, `T`; a string of characters to replace, `F`; and a string of characters to replace them with, `R`. For each substring of `T` with the same (case insensitive) characters as `F`, replace them with the characters in `R`. However, keep the same case as the original text.
If there are more characters in `R` than `F`, the extra characters should be the same case as they are in `R`. If there are numbers or symbols in `F`, then the corresponding characters in `R` should keep the case they have in `R`. `F` will not necessarily appear in `T`.
You can assume all text will be in the printable ASCII range.
# Examples
```
"Text input", "text", "test" -> "Test input"
"tHiS Is a PiEcE oF tExT", "is", "abcde" -> "tHaBcde Abcde a PiEcE oF tExT"
"The birch canoe slid on the smooth planks", "o", " OH MY " -> "The birch can OH MY e slid OH MY n the sm OH MY OH MY th planks"
"The score was 10 to 5", "10", "tEn" -> "The score was tEn to 5"
"I wrote my code in Brain$#@!", "$#@!", "Friend" -> "I wrote my code in BrainFriend"
"This challenge was created by Andrew Piliser", "Andrew Piliser", "Martin Ender" -> "This challenge was created by Martin Ender"
// Has a match, but does not match case
"John does not know", "John Doe", "Jane Doe" -> "Jane does not know"
// No match
"Glue the sheet to the dark blue background", "Glue the sheet to the dark-blue background", "foo" -> "Glue the sheet to the dark blue background"
// Only take full matches
"aaa", "aa", "b" -> "ba"
// Apply matching once across the string as a whole, do not iterate on replaced text
"aaaa", "aa", "a" -> "aa"
"TeXT input", "text", "test" -> "TeST input"
```
[Sandbox link](https://codegolf.meta.stackexchange.com/a/13738/29974)
[Answer]
# [Retina](https://github.com/m-ender/retina), 116 bytes
```
i`(.+)(?=.*¶\1(¶.*)$)|.*¶.*$
¶¶$2¶$1¶¶
{T`l`L`¶¶.(?=.*¶[A-Z])
T`L`l`¶¶.(?=.*¶[a-z])
}`¶¶¶(.)(.*¶).
$1¶¶¶$2
¶¶¶¶.*|¶
```
[Try it online!](https://tio.run/##K0otycxL/P8/M0FDT1tTw95WT@vQthhDjUPb9LQ0VTRrQFw9LRWuQ9sObVMxAmJDEIurOiQhJ8EnAcTWg2qKdtSNitXkCgEK56BKJOpWASVqwYKHtmnoaWqAhDX1uCCGgQzmgjBAdtUAjf//PyS1okShJLW4hKvElSvXEwA "Retina – Try It Online") Explanation:
```
i`(.+)(?=.*¶\1(¶.*)$)|.*¶.*$
¶¶$2¶$1¶¶
```
This searches `T` and whenever there's a case-insensitive match against the lookahead to `F` the match is surrounded in a bunch of newlines and the lookahead to `R` is also inserted.
```
{T`l`L`¶¶.(?=.*¶[A-Z])
T`L`l`¶¶.(?=.*¶[a-z])
}`¶¶¶(.)(.*¶).
$1¶¶¶$2
```
Each letter of the copy of `R` is adjusted in case to match that of the match, following which it is moved out of the working area so that the next letter can be processed, until either the copy of `R` or the match runs out of letters.
```
¶¶¶¶.*|¶
```
If the copy of `R` runs out of letters, then the remainder of the match will be preceded by 4 newlines, so delete it. Otherwise, anything left will be left-over pieces of copies of `R` which need to be concatenated with the non-matching parts of the input to produce the result.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~75~~ ~~73~~ 72 bytes
Prompts for `T`, `R`, and `F` in that order. `R` must b given in Dyalog transformation format and `F` must be given in PCRE format.
```
⍞⎕R(⍞∘{(⊣⌿d)l¨⍨(1∘⌷≠(⊢⌿d∊⎕A,l⎕A)∧≠⌿)d≠(l←819⌶)d←↑⍺⍵.Match↑¨⍨≢⍺})⍠1⊢⍞
```
[Try it online!](https://tio.run/##hVLBbhMxEL37KwbBIZEoag5IcKNASlspApU9gMRl1h6yVlxPZDtKIsQ1pFW2KodKPVVVOdAfACQuSHyKfyTYKaeILD6M/ea9mWePjEOzpaZouL@M80/P0FMPg6y07R/S0KCkZawv4@n5YSvv84sPrXjyJS5@qbb5fRPrm1YnJePiRzy@Ssx1ZuL8JBXs3Dc5tuP8a@JSvq2yxsTZ2aPO47j4nvDsLM4@x/pnrL89WNkmuOoaj69T@mM71led3LW@zLdbwmr945KioEkAbYejIAL5HCZBbJaHPf0a9j0gvNJd2QXehdCdFAJLqUho31BaVASldrICiZYJvNEK2EJIeX/EHCpIQjtIPV7uQe8tCP5PNy/ZEYzRQ2cbAsNDEbpWdLYbyvZh7DgQHE1BsqL0cnjqUNt7d5/cEbtOk1Xi3Qo0WWsPskJjyPZv/aUjDKSgnMKOVY7GaTxGe3Kihy4kk65VCaxxmy0OuLKgmDxYDjCwPBYHaAme818uHzaXvzAjup1rRRTyaDJQ6AZQZqpEOeg7HqXHvmdukG@tyzd7IqIoU2yWoMBmTUFvivX/@Ac "APL (Dyalog Unicode) – Try It Online")
`⍞` prompt for `T`
`⊢` yield that (separates 1 and `T`)
`⍞⎕R(`…`)⍠1` prompt for `F` and **R**eplace matches with the result of the following function:
`⍞∘{…}` derive a monadic function by tying the prompted-for `R` as left argument to:
`≢⍺` count the number of letters in `R`
`⍺⍵.Match↑¨⍨` take that many letters from each of `R` and the match
`⍺` is the left argument, which we tied `R` as.
`⍵` is a namespace in which `Match` contains the currently found string.
`↑` mix those two into a two-row matrix
`d←` store as `d`
`(`…`)` apply the following tacit function to that:
`819⌶` lowercase (mnemonic: **819** looks like **Big**)
`l←` store that function as as `l`
`d≠` Boolean where `d` differs (i.e. gives 0/1 for each lowercase/uppercase letter)
`(`…`)` apply the following tacit function to that:
`≠⌿` vertical XOR
`(`…`)∧` Boolean AND with the following array:
`l⎕A` lowercased **A**lphabet
`⎕A,` prepend uppercase **A**lphabet
`d∊` Boolean for each letter in d whether a member of that (i.e. whether a letter)
`⊢⌿` last row i.e. for character of the match whether it is a letter
`1∘⌷≠` XOR with the first row, i.e. whether each character of `R` is uppercase
`(`…`)l¨⍨` use that to lowercase (if 0) or uppercase (if 1) each letter of:
`⊣⌿` the first row, i.e. `R`
---
\* Byte count for Dyalog Classic using `⎕OPT` instead of `⍠`.
[Answer]
## [Perl 5](https://www.perl.org/), 108 bytes
**107 bytes code + 1 for `-p`.**
```
chomp(($s,$r)=<>);s|\Q$s|$&=~s!.!$_=substr$r,"@-",1;$&=~/[a-z]/i?$&eq uc$&?uc:lc:$_!egr.substr$r,"@-"+1|gie
```
[Try it online!](https://tio.run/##K0gtyjH9/z85Iz@3QENDpVhHpUjT1sZO07q4JiZQpbhGRc22rlhRT1El3ra4NKm4pEilSEfJQVdJx9AaJKUfnahbFaufaa@illqoUJqsomZfmmyVk2ylEq@Yml6kh6JH27AmPTP1//@Q1IoShcy8gtISrhIgE0gUl/zLLyjJzM8r/q9bAAA "Perl 5 – Try It Online")
[Answer]
*Withdrawn. Dom's answer beats it by a long shot.*
~~# [Perl 5](https://www.perl.org/), 136 + 1 (-p) = 137 bytes~~
```
$f=<>;chomp$f;@R=($r=<>)=~/./g;for$i(/\Q$f/gi){$c=$n='';$"=$R[$c++],$n.=/[A-Z]/?uc$":/[a-z]/?lc$":$"for$i=~/./g;s/\Q$i/$n.substr$r,$c/e}
```
[Try it online!](https://tio.run/##LcyxDoIwFIXhnaeoeBM0CFcHF7GKDiYODjKKDlgKNsGWFIhRo49uBeP4n@R8JdfF1BjI6HwRsIu6lpAFYUQHoNtlSN/oYx5kSoMY4HEPGeZi@ARGQVLHCcCmEMXAXPc0AulTjFfe4YTLhoE9wzjxHm0UXYD9Q/5g1VkC20vVnKtagx4BQ/4yZktuWtWcXO@EqZQTIclaJ0JCP@yRIpF5k@Tc6sraaMFl@lFlLZSsjLeb@uPJ2HjlFw "Perl 5 – Try It Online")
*made a huge cut after @Dom Hastings mentioned `\Q`*
~~# [Perl 5](https://www.perl.org/), 176 + 1 (-p) = 177 bytes~~
```
sub h($){chomp@_;pop=~s/[^a-z0-9 ]/\\$&/gir}$f=h<>;@R=($r=<>)=~/./g;for$i(/$f/gi){$c=$n='';$"=$R[$c++],$n.=/[A-Z]/?uc$":/[a-z]/?lc$":$"for$i=~/./g;$i=h$i;s/$i/$n.substr$r,$c/e}
```
[Try it online!](https://tio.run/##VY6xTsMwFEX3foUVPdFEbfLC0AFSl3ZgrIQqJtKAUseJLQXHek5VQdV@OsYgFrZ7pHuPrpXUL7x3xwNTMSRnoYZ3u34r7GD51WH5WqefeXrHKtzv4QY7TRdouVquivWOx0B8uUr4FTPsinYg0DFCG1rJGQQHw6fTAiIOuxLEbFbNwWQcy036UuHDUUB0j2XwB@h/AKJfxZ8uBAW6cAgawy48dCMBzUGgvHj/rLRjQtV9L00n2akORLIeZcMOH2xjGpIn9qR77SRlk/882dY0asMeTSPpa7CjHozz6XaR5be5T@03 "Perl 5 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 190 bytes
```
param($T,$F,$R)[regex]::Replace($T,'(?i)'+[regex]::escape($F),{param($m)-join(0..$R.Length|%{(($y=$R[$_]),("$y"."To$((('Low','Upp')[($z="$m"[$_])-cmatch($C='[A-Z]')]))er"()))[$z-match$C]})})
```
[Try it online!](https://tio.run/##PctNS8NAEMbxrxLHkZ3BJHguBF8KAaGnUC@GIMt2aFaS3WUbiGntZ1@1FE/P4ff8g58lHnoZhpSCjnok3OZY59hwG2UvX91q1UgYtJE/UfRoWd3/kxyMDr9Sc3665iMXn946eihLbMqNuP3Uf9@diHCpsGnxo@OcABcoYeuRiNTGzypXbyEobgmPFeAIl19hRj2ZnnBdqfa5eO8Ud8wSgZi5xWNxYVx3Zz5zSgleszn6SbJxyYzfSWZd9hK1dXj7dAMJrlNHK24HPw "PowerShell – Try It Online")
Explanation:
```
[Regex]::Replace(
input text T,
Find text F with case insensitive and [regex]::escape() for symbols,
{scriptblock} for computing the replacement
)
```
The replacment scriptblock does:
```
$m is the matched text with case information
loop over each character in R as $y
$z is the same index character in $m ($null if R overruns)
$z-match'[A-Z]' checks if alphabetic, so we must to case-match
otherwise, non-alphabetic or null, no case-match, return $y unchanged.
if case-matching, check if z case-sensitive matches '[A-Z]' and
use dynamic method calling from a generated string, either
$y."ToLower"()
$y."ToUpper"()
to force the match
-join the loop output into a replacement string
```
Test cases:
```
function f {
param($T,$F,$R)[regex]::Replace($T,'(?i)'+[regex]::escape($F),{param($m)-join(0..$R.Length|%{(($y=$R[$_]),("$y"."To$((('Low','Upp')[($z="$m"[$_])-cmatch($C='[A-Z]')]))er"()))[$z-match$C]})})
}
Import-Module Pester
$Cases = @(
@{Text = "Text input"; Find = "text"; Replace = "test"; Result = "Test input" }
@{Text = "tHiS Is a PiEcE oF tExT"; Find = "is"; Replace = "abcde"; Result = "tHaBcde Abcde a PiEcE oF tExT" }
@{Text = "The birch canoe slid on the smooth planks"; Find = "o"; Replace = " OH MY "; Result = "The birch can OH MY e slid OH MY n the sm OH MY OH MY th planks" }
@{Text = "The score was 10 to 5"; Find = "10"; Replace = "tEn"; Result = "The score was tEn to 5" }
@{Text = "I wrote my code in Brain$#@!"; Find = "$#@!"; Replace = "Friend"; Result = "I wrote my code in BrainFriend" }
@{Text = "This challenge was created by Andrew Piliser"; Find = "Andrew Piliser"; Replace = "Martin Ender"; Result = "This challenge was created by Martin Ender" }
@{Text = "John does not know"; Find = "John Doe"; Replace = "Jane Doe" ; Result ="Jane does not know" }
@{Text = "Glue the sheet to the dark blue background"; Find = "Glue the sheet to the dark-blue background"; Replace = "foo"; Result ="Glue the sheet to the dark blue background" }
@{Text = "aaa" ; Find = "aa"; Replace = "b"; Result ="ba" }
@{Text = "aaaa"; Find = "aa"; Replace = "a"; Result ="aa" }
@{Text = "TeXT input"; Find = "text"; Replace = "test"; Result ="TeST input" }
)
Describe "Tests" {
It "works on /<Text>/<Find>/<Replace>/ == '<Result>'" -TestCases $Cases {
param($Text, $Find, $Replace, $Result)
f $Text $Find $Replace | Should -BeExactly $Result
}
}
```
[Answer]
## TXR Lisp, 285 bytes
```
(defun f(s f r)(let*((w(copy s))(x(regex-compile ^(compound,(upcase-str f))))(m(reverse(tok-where(upcase-str s)x))))(each((n m))(set[w n]r) (for((i(from n)))((< i (min(to n)(len w))))((inc i))(cond((chr-isupper[s i])(upd[w i]chr-toupper))((chr-islower[s i])(upd[w i]chr-tolower)))))w))
```
Conventionally formatted original:
```
(defun f (s f r)
(let* ((w (copy s))
(x (regex-compile ^(compound ,(upcase-str f))))
(m (reverse (tok-where (upcase-str s) x))))
(each ((n m))
(set [w n] r)
(for ((i (from n))) ((< i (min (to n) (len w)))) ((inc i))
(cond ((chr-isupper [s i]) (upd [w i] chr-toupper))
((chr-islower [s i]) (upd [w i] chr-tolower)))))
w))
```
[Answer]
# JavaScript, 177 bytes
```
(T,F,R)=>T.replace(eval(`/${F.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')}/gi`),F=>[...R].map((r,i)=>/[A-Z]/i.test(f=F[i]||'')?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r).join``)
```
```
F=
(T,F,R)=>T.replace(eval(`/${F.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')}/gi`),F=>[...R].map((r,i)=>/[A-Z]/i.test(f=F[i]||'')?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r).join``)
document.write([
["Text input", "text", "test"],
["tHiS Is a PiEcE oF tExT", "is", "abcde"],
["The birch canoe slid on the smooth planks", "o", " OH MY "],
["The score was 10 to 5", "10", "tEn"],
["I wrote my code in Brain$#@!", "$#@!", "Friend"],
["This challenge was created by Andrew Piliser", "Andrew Piliser", "Martin Ender"],
["John does not know", "John Doe", "Jane Doe"],
["Glue the sheet to the dark blue background", "Glue the sheet to the dark-blue background", "foo"],
["aaa", "aa", "b"],
["aaaa", "aa", "a"],
["TeXT input", "text", "test"],
].map(a=>F(...a)).join('<br>'))
/*
(T,F,R)=>T.replace(
eval(`/${F.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')}/gi`),
//F=>eval("for(i in R)r+=(f=F[i])&&/[A-Z]/i.test(f)?R[i][`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():R[i];r",r='')
//F=>[...R].map((r,i)=>(f=F[i])&&/[A-Z]/i.test(f)?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r).join``
//F=>[...R].reduce((s,r,i)=>s+(f=F[i])&&/[A-Z]/i.test(f)?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r,'')
F=>[...R].map((r,i)=>/[A-Z]/i.test(f=F[i]||'')?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r).join``
)*/
```
Less golfed:
```
(T,F,R) => T.replace(
eval(`/${F.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')}/gi`),
F=>[...R].map((r,i) =>
/[A-Z]/i.test(f = F[i] || '')
? r[`to${
f > '`' && f < '{'
? 'Low'
: 'Upp'
}erCase`]()
: r
).join``
)
```
47 bytes came from [this regex escape function](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript/3561711#3561711) since the program has to handle symbols. :(
[Answer]
# [Python 2](https://docs.python.org/2/), ~~193~~ 200 bytes
```
T,F,R=input()
w=str.lower
i=-len(T)
l=len(F)
T+=' '
while i:
s=T[i:i+l]
if w(s)==w(F):T=T[:i]+`[[y,[w(y),y.upper()][x<'a']][x.isalpha()]for x,y in zip(s,R)]`[2::5]+R[l:]+T[i+l:];i+=l-1
i+=1
print T
```
[Try it online!](https://tio.run/##FY1Bi8MgFITv/opHLlG0gRb24q7HhO2tpN5EaLa15IEkEi0m/fNZe5lvmBmYsKVxnk77rkUneoVTeCXKSFYxLY2fs1sIqoN3E9WMePUxHSOaqxpqkkf0DlASiEoblMi9JYBPyDQypXKZSl0aiZbfjNmEyXRjYmteIbiFMmvWn3qobWGDcfBhHEr4nBdYxQY4wRsDjaJn9mZOUn5Z3hsvLS9fvPAbufKHY3nk6kjCglMCve9V@sUrnCMMcMH23sLcQWpXHc/XSkCF8aPD3/3hqn8 "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 183 bytes
```
import re
j="".join
f=lambda T,F,R:j((p,j((y,(y.lower(),y.upper())[x<'a'])[x.isalpha()]for(x,y)in zip(p,R))+R[len(F):])[i%2>0]for i,p in enumerate(re.split('('+re.escape(F)+')',T,0,2)))
```
[Try it online!](https://tio.run/##lVNNbxMxEL3vr5gG0NrURGkRl4ggWpHQIipQmwOo6sG7O@m62diW7SgJqL89jJ1s01JaiT14Pt6bN7P@sKtQG/12vVYza1wAh9nNoNPp3hils8mgkbOikjAWI3Hev2HMClpWgq26jVmgY1ysunNro8cvl@9zmV@R7SovG1tLxq8mxrGlWHGl4ZeyVH/O@f75ZYOajXifyOrV4YdepIESFoiGej5DJwMyh11vGxVYzvJ9CtCX0iLV7ec8F2PRE4ec8zUu5cw26AeXGdDHWGeMy0BSdh46AjqBoo31ocMFob5FuWhLwom6gFMPEr6rYTkEM4IwXI5jnfJxlUVZYSwPJ/KYXDiKiUf8neK4RiiUK2sopTYIvlEVGA2B8n5mTKjBNlJPk7qJC3w7gbOfkGa8X7zNbyW2USu0DbdmJ/pwEF8ah7CQHg56EAy8i/0OemlbhrrtuGNRckPbyZzCwpmAMFtBaejP6aiOnVT65YuPe1GntSOnUFdR8qmKO8ZuQuWhrGVD1@J6M0DpkK5ABcUKjnTlcEH73CiPLrZ4nDmTLpD8UFcUp795TvEvdjvGF1NrqAx60CbAVJtFlE7ZTwaTLzUmn1ok/yF7J/W5mePmgGrEELcyBpV0UygiVMhyeu3MnLaBZJ9mv/kHe2JM7P8fLXZzSSnTZU5rEWUK@RC@h0ckuvcOCn@Mn3tYFy3Ks6ssy@KrZikhzDyQ4emBb99rP6lap3RgE/Y68XhLTJj0dLwB7sDBYIPGW3Z0@nVvj7QslnSq/fx37zYXIMswlw1FB7d5p0v9ZzKwtuhOh2frPw "Python 3 – Try It Online")
`re.split` + keep all even elements and replace all the odd elements by the correct transformation of the replacement string:
```
>>> re.split("(is)","tHiS Is a PiEcE oF tExT",0,2) # 2=re.IGNORE_CASE
['tH', 'iS', ' ', 'Is', ' a PiEcE oF tExT']
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~210~~ ~~211~~ ~~207~~ 189 bytes
Had to add one byte to fix a bug with the capitalization for the "BrainFriend" testcase
Wow was this tedious... Now to golf away some bytes
```
char*c,*p;d,l;f(t,f,r){for(d=isalpha(*(p=f)),p=c=t;c=strcasestr(c,f);p=c+=l>0?l:0){for(l=strlen(f);p<c;)putchar(*p++);for(p=r;*p;p++,c+=l-->0)putchar(d*l<1?*p:*c&32?*p|32:*p&~32);}puts(p);}
```
[Try it online!](https://tio.run/##lVRdb9owFH3nV9yxqUpCkPjQXkhD12p0tFK1SeVhe3Rsh1gY27KNaNV2f53ZfHQJCWjLA8nxPfec4/gS3J1jvNngAukIx5FKSMyTPLBxHuvwJZc6ICkziKsCBVGg0jwMY5Xi1CY4NVZjZKi7BTjOw8Std1I@7l3xUW/Xyz2HUxH46iVOQrWy3iqIVKcTJp6iUp04W4dj393tjnvvLBLxy/5VpEYRvhgO3MPrcDCK1MXv4SBM3hzLBMo9bJaIiSBsvbTAXUozYfOgPXPBgAnHgu4Y2s4tcGHISvnS077UDmM4rFq3WsXG4TCpqNopusGEwnXmfxH8YBM8AXkLdvI0qxnZKXuEO3PMK7swU0bIy9ZMZwWFjGlcAEYCvk/h4RdQMJwR2CMB1nHMcg/3N1uA4kgsTP0NlBXlXkseVKR87yyHk2Wwt2jMarDUFNbIuN06TQmfGwP8pfV7W1ZZv9@rnMVE1JzuYK2lpbB8BizdYTABN9pNwq1mVJCa4yn6p49fPpStjvFOrmGfzICbUu7Ge77bBdYUWUoge4YHpK0zmAhCdcPez7VeC6Lp2g0MZ4bqcpJa5VAou9WC3iNBgUhqQEgLCyHXtUD3shBVStl2W/0qaWXNi27Xjty@8RXdTVFBqfWn6gFBegGZL2UIL@ZarhoO6N9by0lOd3XPdOVS1qJnqBYJIVT5d1ZQVlNAjQpnJFB9rOjj7ORX6@fsP75ab63NHw "C (gcc) – Try It Online")
[Answer]
# [C# (Mono C# compiler)](http://www.mono-project.com/docs/about-mono/languages/csharp/), 241 bytes
```
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
r("Text input","text","Test");
}
static void r(string v,string i,string u)
{
System.Console.WriteLine(Regex.Replace(v,i,u,RegexOptions.IgnoreCase));
}
}
```
[Try it online!](https://tio.run/##VY7BasMwDIbvfgqRUwxuXiDH0sNgY6UN9FB2MJkwgsQOkhxSSp89c0t26Em/hPTp62U3ppjWNQvFAOebKI5Nh4s2Jwx58HxYJkYRSlFa0w9eBI6cAvsR7kbUK/UwJ/qFL0@xFuXCuf6A5yC2bHBdPWlAccpauUpLU0qHopVtzeMNwds9zG4L9B@yNXez6e2LSxqwuTApflLEurjiUoynwfdYz45cdq/Z96RP8@YjxMS494LWtlDePtb1Dw "C# (Mono C# compiler) – Try It Online")
] |
[Question]
[
>
> *If you are not familiar with Braid-Theory I recommend that you read [this](https://en.wikipedia.org/wiki/Braid_group#Basic_properties) first. This question assumes that you are at least familiar with the concepts at hand and assumes you are well familiar with group-theory*
>
>
>
Let us define \$\sigma\_n\$ to be the braid in which the \$n\$th strand (One indexed) from the top crosses over the \$n+1\$th strand, and \$\sigma\_n^-\$ to be the inverse of \$\sigma\_n\$ (That is the \$n+1\$th strand crosses the \$n\$th strand).
The braid group \$B\_n\$ is then generated by \$\langle\sigma\_1,\sigma\_2,\sigma\_3,\dots,\sigma\_{n-1}\rangle\$. Thus every braid on \$B\_n\$ can be written as the product of the \$\sigma\$-braids.1
---
Determining if two braids on a group are equal is not a simple task. It may be pretty obvious that \$\sigma\_1\sigma\_3 = \sigma\_3\sigma\_1\$, but it is a little less obvious that for example \$\sigma\_2\sigma\_1\sigma\_2 = \sigma\_1\sigma\_2\sigma\_1\$.2
So the question is "How can we determine if two braids are the same?". Well the two examples above each represent a bit of this. In general the following relations, called Artin's relations, are true:
* \$\sigma\_i\sigma\_j = \sigma\_j\sigma\_i; i - j > 1\$
* \$\sigma\_i\sigma\_{i+1}\sigma\_i = \sigma\_{i+1}\sigma\_i\sigma\_{i+1}\$
We can use these two relations in conjunction with the group axioms to prove that any equal braids are equal. Thus two braids are equal iff the repeated application of these relations and the group axioms can demonstrate so.
## Task
You will write a program or function to take two braids and determine whether or not they are equal. You may also optionally take a positive integer representing the order of the group.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with less bytes being better.
## Input and Output
You should represent a Braid as an ordered list of generators, (or any equivalent structure, e.g. vector). You may represent the generators in any reasonable form (e.g. an integer, a two tuple of a positive integer and a boolean).
On par with standard [descision-problem](/questions/tagged/descision-problem "show questions tagged 'descision-problem'") rules you should output one of two distinct values, an accept an reject.
## Test Cases
```
[], [] -> True
[1,-1], [] -> True
[1,2,1], [2,1,2] -> True
[1,3], [3,1] -> True
[1,3,2,1],[3,2,1,2] -> True
[1,4,-4,3,2,1], [3,2,1,2] -> True
[2,2,1], [2,1,2] -> False
[1,2,-1], [-1,2,1] -> False
[1,1,1,2],[1,1,2] -> False
```
---
1: Note that while \$B\_n\$ satisfies all the properties of a group the operation on our braid group is *not* commutative, and thus our group is not abelian.
2: If you would like to verify this for yourself I suggest applying \$\sigma\_1^-\$ to both sides, If you draw the two out on paper, or model them with actual strings it should become apparent why this is the case.
[Answer]
# [Haskell](https://www.haskell.org/), 190 bytes
```
i!j|j<0=reverse$map(0-)$i!(-j)|i==j=[i,i+1,-i]|i+1==j=[i]|i+j==0=[j+1]|i+j==1=[-j,-i,j]
_!j=[j]
j%(k:a)|j+k==0=a
j%a=j:a
i&a=foldr(%)[]$foldr((=<<).(!))[i]a
a?n=map(&a)[1..n]
(a#b)n=a?n==b?n
```
[Try it online!](https://tio.run/##hY/RioMwEEXf/YpIbUkwEaPuS3Hoh4SwTKnLZrRpscs@@e9uUn2qhYWQO5l7htz5xkffDcM8u5QmaksYu99ufHTZFe@8VCJzKVckJgdAYJx0uZbK2Sno0oklAZRgKNfrQ4NRFDBJNvlMAxWU9rw/opgo7yONoYFAR0zcAeHrNlxGvhfGZkvJoW1FwVMhwg@Y4MlDDHRAYXRReJtw3J2Fh2jA@eTnKzrPgF1uCWP30fkfljG@E8zYePRrNyyhn061dSoZrXDLyrJ669fBrSPTvPHW6afG@TdMI1WzBT9ewerfINWyhFojvyH0MmtWrec/ "Haskell – Try It Online")
### How it works
Let *F**n* be the [free group](https://en.wikipedia.org/wiki/Free_group) on *n* generators *x*1, …, *x**n*. One of the first results in braid theory (Emil Artin, [Theorie der Zöpfe](http://rdcu.be/ufmh), 1925) is that we have an injective [homomorphism](https://en.wikipedia.org/wiki/Group_homomorphism) *f* : *B**n* → [Aut(*F**n*)](https://en.wikipedia.org/wiki/Automorphism_group_of_a_free_group) where the [action](https://en.wikipedia.org/wiki/Group_action) *f*σ*i* of σ*i* is defined by
*f*σ*i*(*x**i*) = *x**i**x**i* + 1*x**i*−1,
*f*σ*i*(*x**i* + 1) = *x**i*,
*f*σ*i*(*x**j*) = *x**j* for *j* ∉ {*i*, *i* + 1}.
The inverse *f*σ*i*−1 is given by
*f*σ*i*−1(*x**i*) = *x**i* + 1,
*f*σ*i*−1(*x**i* + 1) = *x**i* + 1−1*x**i**x**i* + 1,
*f*σ*i*−1(*x**j*) = *x**j* for *j* ∉ {*i*, *i* + 1}
and of course composition is given by *f**ab* = *f**a* ∘ *f**b*.
To test whether *a* = *b* ∈ *B**n*, it suffices to test that *f**a*(*x**i*) = *f**b*(*x**i*) for all *i* = 1, …, *n*. This is a much simpler problem in *F**n*, where we only need to know how to cancel *x**i* with *x**i*−1.
In the code:
* `i!j` computes *f*σ*i*(*x**j*) (where either `i` or `j` may be negative, representing an inverse),
* `foldr(%)[]` performs reduction in the free group,
* `i&a` computes *f**a*(*x**i*),
* `a?n` computes [*f**a*(*x*1), …, *f**a*(*x**n*)],
* and `(a#b)n` is the equality test for *a* = *b* in *B**n*.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~270~~ ~~263~~ ~~260~~ ~~250~~ ~~249~~ 241 bytes
```
def g(b,i=0):
while i<len(b)-1:
R,s=b[i:i+2]
if R<0<s:b[i:i+2]=[[],[s,-R,-s,R],[s,R]][min(abs(R+s),2)];i=-1
i+=1
return b
def f(a,b):
b=g(a+[-v for v in b][::-1]);i=0
while i<len(b)and b[0]>0:b=b[1:]+[b[0]];i+=1
return g(b)==[]
```
[Try it online!](https://tio.run/##XU9BbsMgEDzXr9hbQF4km@RETY55AFfEwSh2gpSQyLip@np3cexG6YXdmR12Zu8/4/kW5TQdux5OzGPQFVcFfJ/DpYPQXLrIPBc1UWAwaW@DCqV0BEMPpqmapFZOW@vQJhQGRUIz98Y5ew2RtT4xUyaOkrvPoEWdF5SaytCNX0MEX@QEPWvRZ3@vT6wtrXhAfxvgAYEUziolasfpf/U/YRuP4G3l9pXyFLJWrrQZkxm5AMCfER3JtbZuvviw@H3chxBHIIAbvd/gM0dRHFg@yfHc1EjmLyAxI3pRrtSWiC3RK1w0c32pdih26wzeh3Jh4X2vnJ3BiqfrwtazBO2z8ukX "Python 2 – Try It Online")
Implementation of the 'subword reversing' method of solving the braid isotopy problem: a=b iff ab^-1 = the identity.
Algorithm taken from: [Efficient solutions to the braid isotopy problem, Patrick Dehornoy](http://www.sciencedirect.com/science/article/pii/S0166218X08000437?via%3Dihub); he describes several other algorithms which may be of interest...
This algorithm works by marching left to right in the list, searching for a negative number followed by a positive number; i.e., a sub-word of the form xi-1xj with i,j >0.
It uses the following equivalences:
xi-1xj = xjxixj-1xi-1 if i=j+1 or j=i+1
xi-1xj= identity (empty list) if i==j
xi-1xj = xjxi-1 otherwise.
By repeated application, we end up with a list of the form `w1 + w2`, where every element of `w1` is positive and every element of `w2` is negative. (This is the action of the function `g`).
We then apply `g` a second time to the list `w2 + w1`; the resulting list should be empty iff the original list was equivalent to the identity.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 110 bytes
```
!FreeQ[(r=Reverse)[Or@@#||Or@@-r@#2//.(s=i_||j_/;i<0<j:>Switch[i+j,0,1<0,1|-1,j||-i||-j||i,_,j||i])]//.s,1<0]&
```
[Try it online!](https://tio.run/##hU47a8MwEN7zK64ITEKl2rIztXbQ1DV9jEIYE2R8hnSQTTJI@u2OVGLsdmiH47vvcY9zM3b63Ix4aqYWqunh1Wj9Lrem@tAXbQa9k0cjBHEuAjOC5Gn6tB0qrJ3r6/QFy6zsnw@fVxxPncTHnmaUl6Ec47R3jmGogEjrSFHtVFgwxIxKpjeDX6O0hHhgB2glIUpBAkKIDVhrPQXrPd1AIJwC47@EnMK3FDGwlVNEuYj2SlsG7u3PmX24sP8nlv91NJ9fZPNvi8fv6eDOrffTDQ "Wolfram Language (Mathematica) – Try It Online")
A port of [Chas Brown's Python answer](https://codegolf.stackexchange.com/a/133106/9288).
] |
[Question]
[
Given a positive integer ***n ≤ 500***:
* Find the *smallest* positive integer ***k*** such that all digits in the decimal representation of ***n\*k*** are either ***0*** or ***d***, with ***1 ≤ d ≤ 9***.
* Print or return ***d*** in less than 30 seconds (read more about that in the *Clarifications and rules* section).
## Easy examples
Here are the first 30 values of ***d***.
```
+----+-------+---------+---+ +----+-------+---------+---+
| n | k | n * k | d | | n | k | n * k | d |
+----+-------+---------+---+ +----+-------+---------+---+
| 1 | 1 | 1 | 1 | | 16 | 5 | 80 | 8 |
| 2 | 1 | 2 | 2 | | 17 | 653 | 11101 | 1 |
| 3 | 1 | 3 | 3 | | 18 | 5 | 90 | 9 |
| 4 | 1 | 4 | 4 | | 19 | 579 | 11001 | 1 |
| 5 | 1 | 5 | 5 | | 20 | 1 | 20 | 2 |
| 6 | 1 | 6 | 6 | | 21 | 37 | 777 | 7 |
| 7 | 1 | 7 | 7 | | 22 | 1 | 22 | 2 |
| 8 | 1 | 8 | 8 | | 23 | 4787 | 110101 | 1 |
| 9 | 1 | 9 | 9 | | 24 | 25 | 600 | 6 |
| 10 | 1 | 10 | 1 | | 25 | 2 | 50 | 5 |
| 11 | 1 | 11 | 1 | | 26 | 77 | 2002 | 2 |
| 12 | 5 | 60 | 6 | | 27 | 37 | 999 | 9 |
| 13 | 77 | 1001 | 1 | | 28 | 25 | 700 | 7 |
| 14 | 5 | 70 | 7 | | 29 | 37969 | 1101101 | 1 |
| 15 | 2 | 30 | 3 | | 30 | 1 | 30 | 3 |
+----+-------+---------+---+ +----+-------+---------+---+
```
## Not-so-easy examples
One particularity of this challenge is that some values are much harder to find than others -- at least with a purely brute-force approach. Below are some examples of ***n*** that lead to a high value of ***k***.
```
+-----+------------+---------------+---+ +-----+------------+---------------+---+
| n | k | n * k | d | | n | k | n * k | d |
+-----+------------+---------------+---+ +-----+------------+---------------+---+
| 81 | 12345679 | 999999999 | 9 | | 324 | 13717421 | 4444444404 | 4 |
| 157 | 64338223 | 10101101011 | 1 | | 353 | 28615017 | 10101101001 | 1 |
| 162 | 13717421 | 2222222202 | 2 | | 391 | 281613811 | 110111000101 | 1 |
| 229 | 43668559 | 10000100011 | 1 | | 405 | 13717421 | 5555555505 | 5 |
| 243 | 13717421 | 3333333303 | 3 | | 439 | 22781549 | 10001100011 | 1 |
| 283 | 35371417 | 10010111011 | 1 | | 458 | 43668559 | 20000200022 | 2 |
| 299 | 33478599 | 10010101101 | 1 | | 471 | 64338223 | 30303303033 | 3 |
| 307 | 32576873 | 10001100011 | 1 | | 486 | 13717421 | 6666666606 | 6 |
| 314 | 64338223 | 20202202022 | 2 | | 491 | 203871711 | 100101010101 | 1 |
| 317 | 3154574483 | 1000000111111 | 1 | | 499 | 22244489 | 11100000011 | 1 |
+-----+------------+---------------+---+ +-----+------------+---------------+---+
```
## Clarifications and rules
* ***n\*k*** will always contain at least one digit ***d***, but it may contain no zero at all.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. However, your program or function must be able to return the result for any ***1 ≤ n ≤ 500*** in *less than 30 seconds* on middle-range hardware.
* Keep in mind that some values are harder to find than others. A program that would try to brute-force the value of ***k*** is unlikely to comply with the time-limit constraint (a good test case is ***n = 317***). There are significantly faster methods to find ***d***.
## Reference table
All values of ***d*** for ***1 ≤ n ≤ 500*** are listed below.
```
n | d
--------+--------------------------------------------------
001-025 | 1 2 3 4 5 6 7 8 9 1 1 6 1 7 3 8 1 9 1 2 7 2 1 6 5
026-050 | 2 9 7 1 3 1 8 3 2 7 9 1 2 3 4 1 6 1 4 9 2 1 6 7 5
051-075 | 3 4 1 9 5 7 1 2 1 6 1 2 9 8 5 6 1 4 3 7 1 9 1 2 3
076-100 | 4 7 6 1 8 9 2 1 4 5 2 3 8 1 9 1 4 3 2 5 6 1 7 9 1
101-125 | 1 6 1 8 7 2 1 9 1 1 1 7 1 2 5 4 9 2 7 6 1 2 3 4 5
126-150 | 6 1 8 3 1 1 6 7 2 9 8 1 6 1 7 1 2 1 9 5 2 7 4 1 3
151-175 | 1 8 9 7 5 4 1 2 1 8 7 2 1 4 3 2 1 8 1 1 3 4 1 6 7
176-200 | 8 3 2 1 9 1 2 1 8 5 6 1 4 9 1 1 6 1 2 3 7 1 9 1 2
201-225 | 3 2 7 4 5 2 9 8 1 7 1 4 1 2 5 9 7 2 3 2 1 2 1 7 9
226-250 | 2 1 4 1 1 3 8 1 6 5 4 3 7 1 6 1 2 3 4 7 6 1 8 3 5
251-275 | 1 6 1 2 3 8 1 6 7 2 9 2 1 6 5 7 3 4 1 9 1 8 3 2 5
276-300 | 6 1 2 9 7 1 2 1 4 5 2 7 9 1 1 3 4 1 7 5 8 9 2 1 3
301-325 | 7 2 3 8 5 6 1 4 3 1 1 8 1 2 9 4 1 2 1 8 1 7 1 4 5
326-350 | 2 1 8 7 3 1 4 3 2 5 8 1 2 3 2 1 6 1 8 3 2 1 4 1 7
351-375 | 9 8 1 6 5 4 7 2 1 9 1 2 3 4 5 2 1 8 9 1 7 6 1 2 3
376-400 | 8 1 9 1 2 3 2 1 6 7 2 9 4 1 3 1 7 1 2 5 9 1 2 7 4
401-425 | 1 6 1 4 5 2 1 8 1 1 3 4 7 9 5 8 1 2 1 6 1 2 3 8 5
426-450 | 2 7 4 3 1 1 9 1 7 3 4 1 6 1 4 3 2 1 4 5 2 3 7 1 9
451-475 | 1 4 3 2 5 8 1 2 9 2 1 6 1 8 3 2 1 6 7 1 3 8 1 6 5
476-500 | 7 3 2 1 6 1 2 3 4 5 6 1 8 3 7 1 6 1 2 9 8 7 6 1 5
```
[Answer]
## JavaScript (ES6), 83 bytes
```
n=>{for(p=1;;p=k)for(d=0;d++<9;)for(k=p;k<p+p;k++)if(k.toString(2)*d%n<1)return d;}
```
Now returns `6` for `n=252`! I tried a recursive approach but it's also 83 bytes and crashes out for me for the harder numbers:
```
f=(n,p=1,d=1,k=p)=>k<p+p?k.toString(2)*d%n<1?d:f(n,p,d,k+1):d>8?f(n,p+p):f(n,p,d+1)
```
[Answer]
# Mathematica, ~~103~~ ~~100~~ 97 bytes
```
#&@@IntegerDigits[Sort[Join@@Table[Cases[FromDigits/@{0,i}~Tuples~13/#,_Integer],{i,9}]][[10]]#]&
```
*finds 317 in 0.39 sec*
[Try it online](https://sandbox.open.wolframcloud.com/app/objects/)
copy/paste the code, add [317] at the end and press shift+enter to run
*-3 bytes from @JungHwan Min
-3 bytes from @Keyu Gan*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ ~~15~~ 14 bytes
```
²B€Ḍ9×þF%Þ¹ḢQS
```
Quadratic runtime (under 25 seconds on TIO).
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//wrJC4oKs4biMOcOXw75GJcOewrnhuKJRU////zMxNw "Jelly – Try It Online")
### Alternate version, 15 bytes
```
2ȷB€Ḍ9×þF%Þ¹ḢQS
```
Constant runtime (approx. 1 second on TIO).
[Try it online!](https://tio.run/##AScA2P9qZWxsef//Msi3QuKCrOG4jDnDl8O@RiXDnsK54biiUVP///8zMTc "Jelly – Try It Online")
### How it works
```
²B€Ḍ9×þF%Þ¹ḢQS Main link. Argument: n
² Take the square of n.
This bound is high enough for all integers up to 500.
In fact, The highest value we need is 1387 for input 471, so
2000 (2ȷ) is also enough (and a lot faster).
B€ Binary; convert 1, ..., 4159 to base 2.
Ḍ Undecimal; convert each digit array from base 10 to integer.
This generates the array A of all positive integers up to n²
whose decimal representations consist entirely of 1's and 0's.
9×þ 9 multiply table; for each x in A, yield [x, 2x, ..., 8x, 9x].
F Flatten; concatenate the resulting arrays, yielding the vector
V. Note that V contains all numbers that match the regex ^d[0d]*$
in base 10, in ascending order.
¹ Identity; yield n.
%Þ Sort the entries for V by their remainders modulo n. This places
multiples of n at the beginning. The sorting algorithm in stable,
so the first element of sorted V is the smallest multiple of n.
Ḣ Head; extract the first element.
Q Unique; deduplicate its digits in base 10. This yields [d, 0].
S Take the sum, yielding d.
```
[Answer]
# Python 2/3, ~~129~~ ~~128~~ 127 bytes
```
from itertools import*
lambda n:next(d for p in count()for d in range(1,10)for k in range(2**p,2*2**p)if d*int(bin(k)[2:])%n<1)
```
-1 byte: `count(0)`→`count()`
-1 byte: `==0`→`<1` since it can't be negative
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
9Rṭ€0ṗ€⁴ẎḌḍ@Ðf⁸ṢDFḟ0Ḣ
```
A monadic link returning the number OR a full program printing it.
A limited-range brute-forcer which takes less than 20 seconds for any **1 ≤ n ≤ 500** (less than 3 seconds for a 1 byte code cost - replace `⁴` with `13`).
**[Try it online!](https://tio.run/##ATsAxP9qZWxsef//OVLhua3igqww4bmX4oKs4oG04bqO4biM4biNQMOQZuKBuOG5okRG4bifMOG4ov///zMxNw "Jelly – Try It Online")**
### How?
```
9Rṭ€0ṗ€⁴ẎḌḍ@Ðf⁸ṢDFḟ0Ḣ - Link: number, n
9R - range of 9 = [1,2,3,4,5,6,7,8,9]
ṭ€0 - tack €ach to 0 -> [[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9]]
⁴ - literal 16
ṗ€ - Cartesian product for €ach
Ẏ - tighten (flatten by 1 level)
Ḍ - covert from decimal list to number (vectorises)
⁸ - chain's left argument (n)
Ðf - filter keep items for which this yields a truthy value:
ḍ@ - divisible? with swapped @rguments
Ṣ - sort
D - convert to decimal list (vectorises)
F - flatten into a single list
ḟ0 - filter out zeros
Ḣ - head (get the first value)
```
[Answer]
# [PHP](https://php.net/), 87 bytes
```
for(;++$i<5e3;)for($n=10;$d=--$n*decbin($i);)($y&&$d>$y)|$d%$argn?:$x=$n.!$y=$d;echo$x;
```
[Try it online!](https://tio.run/##HcyxDoIwFAXQnb@QXEkrwUiIMfFRGQyDiy7uRGiFLm3z4gCJ8ddrdDzLCVOIdROmkBhmzx2b4Pll3Sg@bXe93S/nVlKCB49OpVV5SCk@PQvKc9h6byqSP8KpckfQqijgNtoMvXUCVpIUWLIM@oRFvqHX/6g5YlZw2xUWBU1mmDxmivEL "PHP – Try It Online")
# [PHP](https://php.net/), 89 bytes
```
for(;++$i<5e3;)for($n=10;$d=--$n*decbin($i);)$d%$argn?:$r[$d]=$n;krsort($r);echo end($r);
```
[Try it online!](https://tio.run/##Hc2xCsIwEIDhvU8h5YTEUrCKDl5DB@ngooubSNHm2oTCJZzOvnrUjt/w80cXU91EFzMSCdIJxSBvz6P6tN35cj0dW40ZPGRkk1f7TY5pCKKwKMDXO9qi/hPYVGsEa8oSeGWpf3pW4DVqsMs5bg4gN7B3A4yTvH4PBaKRehcWxHZGSl8 "PHP – Try It Online")
] |
[Question]
[
Related: [Validate a stem-and-leaf plot](https://codegolf.stackexchange.com/questions/93153/validate-a-stem-and-leaf-plot)
# Input
A non-empty list of positive integers. If needed, they can be taken as strings. You cannot assume it is sorted.
# Output
A [stem-and-leaf plot](https://en.wikipedia.org/wiki/Stem-and-leaf_display) of the numbers. In ~~a~~ this stem-and-leaf plot, numbers are ordered into stems by tens, then all numbers that fit into that stem have their ones value placed into the stem, and then all are sorted. In this challenge, newlines separate the stems, and spaces separate the stems from the leaves.
You may either include or exclude all empty stems that are between non-empty stems.
# Test Cases
(lists can be taken in your language's list default, I used JSON for the below)
Including empty stems:
```
[1, 2, 3, 3, 3, 3, 3, 10, 15, 15, 18, 1, 100]
0 11233333
1 0558
2
3
4
5
6
7
8
9
10 0
[55, 59, 49, 43, 58, 59, 54, 44, 49, 51, 44, 40, 50, 59, 59, 59]
4 034499
5 0145899999
[10000, 10100]
1000 0
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010 0
```
Excluding empty stems:
```
[1, 2, 3, 3, 3, 3, 3, 10, 15, 15, 18, 1, 100]
0 11233333
1 0558
10 0
[55, 59, 49, 43, 58, 59, 54, 44, 49, 51, 44, 40, 50, 59, 59, 59]
4 034499
5 0145899999
[10000, 10100]
1000 0
1010 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Ṣµ:©⁵Ġṁ@%⁵®Q¤żK€Y
```
[Try it online!](https://tio.run/##y0rNyan8///hzkWHtlodWvmoceuRBQ93NjqoAlmH1gUeWnJ0j/ejpjWR////jzbUUTDSUTBGRYYGQGwKxRZADBIyiAUA "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~78~~ ~~75~~ 79 bytes
```
s=-1
for i in sorted(input()):
if i/10^s:s=i/10;print'\n%d-'%s,
print`i`[-1],
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hW15ArLb9IIVMhM0@hOL@oJDVFIzOvoLREQ1PTikshM00hU9/QIK7YqtgWxLAuKMrMK1GPyVNN0VVXLdbhUgALJGQmROsaxur8/x9tqKNgpKNgjIoMDYDYFIotgBgkZBALAA "Python 2 – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~38~~ 30 bytes
*Thanks to Neil for saving 2 bytes, and to Leo for saving another 6.*
Byte count assumes ISO 8859-1 encoding.
```
O#`
.\b
$&
\B
0
D$`¶?.+
$*
```
Input is a linefeed-separated list of integers. Output omits empty prefixes.
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg899fOYFLLyaJS0FFjSvGSYHLQIHLRSXh0DZ7PW0FLhWt/8EJKv8NdYx0jOHQ0EDH0BSMLHQMgTwDLlNTHVNLHRMgMtYxtQCxTU10TExAIqaGYIaBjqkBWByEuIB6DICGGABpAA "Retina – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 12 bytes
```
stem(scan())
```
[Try it online!](https://tio.run/##K/r/v7gkNVejODkxT0NT878RlxGXMRCagKHpfwA "R – Try It Online")
Explanation:
```
s # imports RAND's "Million Random Digits"
e ) # cooks a pound of spaghetti and places it on the stack
t # transposes the output 42 times
can # goes for a pee
m( # grows moustache, turns head to side and frowns
s ( # implicitly ignores all criticism
) # makes a stemplot of the input
```
[Answer]
## JavaScript (ES6), 89 bytes
```
a=>a.sort((a,b)=>a-b).map(e=>r[d=e/10|0]=(r[d]||d+` `)+e%10,r=[])&&r.filter(e=>e).join`
`
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~146~~ ~~140~~ ~~133~~ ~~124~~ ~~120~~ ~~118~~ ~~109~~ ~~107~~ ~~90~~ ~~86~~ ~~84~~ ~~91~~ ~~82~~ ~~81~~ ~~70~~ 63 bytes
*-6 bytes thanks to Rod. -9 bytes thanks to ovs.*
```
lambda l:{i/10:[j%10for j in sorted(l)if j/10==i/10]for i in l}
```
[Try it online!](https://tio.run/##VU7RCoMwDHzvV@RloFBY6yw4oV/iZLhpWaVTsX0ZY9/eJeo2FnLQ3F2umR7hNg5ZNPoUXXO/tA248mn3UpRVv5PCjDP0YAfw4xy6NnGpNdCjrDWZatIt6e4VQ@fD@dr4zoOGigFWJTlkHA7/LQVCbSgQRImarysKWXXkkBPQrYp1VjnO@corub0xSYlNX/BJwUBB3whKZjVj30t/Z5aLdZrtEMAkNo1v "Python 2 – Try It Online")
Okay, something is slightly wonky. As all Python programmers should know, dicts are unordered, meaning the original order of the key-value pairs is not preserved. However, in my current code, I do not sort the resulting dict at all. Yet, I have tested multiple times, checking for equality and order every single time, and the dict always comes out right. If anybody either disproves that it always comes out right or knows why this works, I'd love to know.
Input as a python list and output as a dict. Example:
Input:
```
[1, 2, 3, 3, 3, 3, 3, 10, 15, 15, 18, 1, 100]
```
Output:
```
{0: [1, 1, 2, 3, 3, 3, 3, 3], 1: [0, 5, 5, 8], 10: [0]}
```
[Answer]
# Mathematica, 103 bytes
Code taken from @user202729's deleted answer
```
Grid[Table[{Keys[#][[i]],""<>ToString/@#[[i]]},{i,Length@#}]]&@(GroupBy[Sort@#,⌊#/10⌋&]~Mod~10&@#)&
```
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 84 bytes
```
1&0\n~a7+3.
:}<$?)@:$@:v!?
r~&^?-l&:+1&/&:,a-%a::
&=?v~&1+:&ao>n" "o:?!;::a%:@-a,&:
```
[Try it online](https://tio.run/##dctNCsIwEAbQfU6RlnZA0mjGIsrnz@QgIsxGKkgLCtmZq0fqQty4ebt3vT2HUpjCecy6df3SWLwOjSwimohUiXlkuoi/ExzTitCpbxUwdJSUiR1Ip9NY23qCVHtAW0SvHaGU4pPlmfVM/w8OHzc/7r6VQ3gD "><> – Try It Online"), or at the [fish playground](https://fishlanguage.com/playground)!
Assumes the input numbers are [already on the stack](https://codegolf.meta.stackexchange.com/a/8493/66104).
Explanation: First, we sort the stack using a [bubble sort](https://en.wikipedia.org/wiki/Bubble_sort), with this bit of code:
```
1&0\
:}<$?)@:$@:v!?
^?-l&:+1&/
```
Next, we compute the integer-quotient of the first thing in the stack by 10 using `::a%-a,`, put that in the register, and go through the stack printing the last digits of the numbers until their first digits aren't the same as the register, then incrementing the register and continuing. When we reach the end of the list, marked with a `0`, we stop.
[Answer]
# PostgreSQL, 53 bytes
```
SELECT n/10,json_agg(n%10ORDER BY n)FROM t GROUP BY 1
```
The list of integers must reside in an `integer` column `n` of an existing table `t`. The result is a two-column table: each row consists of a "stem" column and a "leaves" column. The "leaves" column is in JSON array format. (As noted in the comments, it is not necessary to adhere exactly to the format shown under "Test Cases".)
Though the order of stems is not guaranteed (to save 10 bytes, `ORDER BY 1` is omitted from the end of the query), in my testing, the stems did seem to end up in the correct order.
[View result on SQL Fiddle](http://sqlfiddle.com/#!17/30c1d/1)
] |
[Question]
[
# Task
Given two positive integers:
1. Draw the rectangle with dimensions specified by the two integers.
2. Repeat Step 3 until there is no more space.
3. Draw and fill the largest square touching three sides of the (remaining) rectangle.
4. Output the resulting rectangle.
# Example
For example, our input is `6` and `10`.
We draw the hollow rectangle of size 6 x 10:
```
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
```
After repeatedly filling squares, this is what we would obtain:
```
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaaccdd
aaaaaaccdd
```
There are 4 squares here (`a`, `b`, `c`, `d`), each with side length `6`, `4`, `2`, `2` respectively.
# Rules and freedom
1. You must use a different letter for each square.
2. You can choose which letters to support, as long as the letters supported are all printable characters and there are at least `10` characters supported.
3. In each iteration of Step 3 above, you have two choices (except in the last iteration, where you only have one choice). Both choices are valid.
4. The number of squares required will not exceed the number of letters you support.
5. You can fill in the squares with the letters you support in **any order**.
# Testcases
Input: `6, 10`
Output:
```
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaaccdd
aaaaaaccdd
```
or
```
aaaaaaccdd
aaaaaaccdd
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
```
or
```
bbbbaaaaaa
bbbbaaaaaa
bbbbaaaaaa
bbbbaaaaaa
ccddaaaaaa
ccddaaaaaa
```
or
```
ccddaaaaaa
ccddaaaaaa
bbbbaaaaaa
bbbbaaaaaa
bbbbaaaaaa
bbbbaaaaaa
```
or
```
ddddddaaaa
ddddddaaaa
ddddddaaaa
ddddddaaaa
ddddddbbcc
ddddddbbcc
```
Input: `1,1`
Output:
```
a
```
Input: `1,10`
Output:
```
abcdefghij
```
Input: `10,1`
Output:
```
a
b
c
d
e
f
g
h
i
j
```
Note that there are more possibilities than I can include for the testcases above.
# Scoring
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]
# [Haskell](https://www.haskell.org/), 90 bytes
```
(['a'..]!)
a?x=a<$[1..x]
((a:b)!y)x|x*y<1=""?y|x>y=map(a?y++)$b!y$x-y|z<-y-x=a?x?x++(b!z)x
```
[Try it online!](https://tio.run/##DctBC4IwFADgu79ik4FbYyMvHcK1Q9cCoUtgEs/IilQkDd4Tf3vL@/c9YXjfmybU7hJkkUBibclVBB4dZKJIrcUykhK2leKkcMYVZamLY08z7si10EvwpLUSFSeBhuYpM2SW7dGj1rLik8LQwqtjji38eGX9dzyNn0PHBKvZhqXr8LvVDTyGYM77PP8D "Haskell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
NδNγFβ¿×γδ«UOγδι¿‹γδA⁻δγδA⁻γδγ
```
[Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzW0DE5vd7lp3bdGj/4ennNp/bcmj1@z1b3@9ZD2Kf23lo/6OGnSDm@z0LHzXuBgoh2CAFm///N@MyNAAA "Charcoal – TIO Nexus") Explanation:
```
Nδ Input d
Nγ Input g
Fβ For i In ['a' ... 'z']
¿×γδ« If g * d
UOγδι Oblong g, d, i
¿‹γδ If g < d
A⁻δγδ d = d - g
A⁻γδγ Else g = g - d
```
Annoyingly Charcoal's Oblong command won't take `0` for a dimension, which costs me 4 bytes. The other approach would be to loop while `g * d`, but then I couldn't work out how to iterate over `b` (which is predefined to the lowercase letters).
[Answer]
# [Uiua](https://www.uiua.org/), ~~31 bytes~~ 32 bytes
Edit: The `recur ↬` glyph has been removed from the language
```
|2+@`;⍥(⎋=0⧻.⊙⬚0+.↘⇌×⍖.△.)∞.↯∶1⊂
```
[Try it online!](https://www.uiua.org/pad?src=RXVjbGlkaWFuIOKGkCB8MiArQGA74o2lKOKOiz0w4qe7LuKKmeKsmjArLuKGmOKHjMOX4o2WLuKWsy4p4oieLuKGr-KItjHiioIKCkV1Y2xpZGlhbiA2IDEwCkV1Y2xpZGlhbiAxIDEKRXVjbGlkaWFuIDEwIDEKRXVjbGlkaWFuIDEgMTAK)
**Explanation:**
```
⊂ # Put the dimensions into an array
↯∶1 # Make a matrix of 1s with the dimensions
. # Copy the result
⍥( )∞ # Repeat forever
△. # Get the shape of the latest matrix
⍖. # Get the descending indices
× # Multiply these with the shape
# (zeros out the larger dimension)
⇌ # Reverse the array
↘ # Remove the largest square from the latest matrix
⊙⬚0+. # Add the new matrix to the original
# (using 0s where the shape doesn't match)
⎋=0⧻. # Break if the length of the new matrix is 0
+@`; # Add char ` to the result to get 1=a, b=2, etc.
|2 # Signature of function
```
**Example:**
```
Input: 4 2 Stack (top on left):
# 4 2
⊂ # [4 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
# ╯ ╯
⍥( )∞
△. # [4 2] ╭─ ╭─
# ╷ 1 1 ╷ 1 1
# 1 1 1 1
# 1 1 1 1
# 1 1 1 1
# ╯ ╯
⍖. # [0 1] [4 2] ╭─ ╭─
# ╷ 1 1 ╷ 1 1
# 1 1 1 1
# 1 1 1 1
# 1 1 1 1
# ╯ ╯
× # [0 2] ╭─ ╭─
# ╷ 1 1 ╷ 1 1
# 1 1 1 1
# 1 1 1 1
# 1 1 1 1
# ╯ ╯
⇌ # [2 0] ╭─ ╭─
# ╷ 1 1 ╷ 1 1
# 1 1 1 1
# 1 1 1 1
# 1 1 1 1
# ╯ ╯
↘ # ╭─ ╭─
# ╷ 1 1 ╷ 1 1
# 1 1 1 1
# ╯ 1 1
# 1 1
# ╯
⊙⬚0+. # ╭─ ╭─
# ╷ 1 1 ╷ 2 2
# 1 1 2 2
# ╯ 1 1
# 1 1
# ╯
⧻. # 2 ╭─ ╭─
# ╷ 1 1 ╷ 2 2
# 1 1 2 2
# ╯ 1 1
# 1 1
# ╯
⎋=0 # No break
△. # [2 2] ╭─ ╭─
# ╷ 1 1 ╷ 2 2
# 1 1 2 2
# ╯ 1 1
# 1 1
# ╯
⍖. # [0 1] [2 2] ╭─ ╭─
# ╷ 1 1 ╷ 2 2
# 1 1 2 2
# ╯ 1 1
# 1 1
# ╯
× # [0 2] ╭─ ╭─
# ╷ 1 1 ╷ 2 2
# 1 1 2 2
# ╯ 1 1
# 1 1
# ╯
⇌ # [2 0] ╭─ ╭─
# ╷ 1 1 ╷ 2 2
# 1 1 2 2
# ╯ 1 1
# 1 1
# ╯
↘ # [] ╭─
# ╷ 2 2
# 2 2
# 1 1
# 1 1
# ╯
⊙⬚0+. # [] ╭─
# ╷ 2 2
# 2 2
# 1 1
# 1 1
# ╯
⧻. # 0 [] ╭─
# ╷ 2 2
# 2 2
# 1 1
# 1 1
# ╯
⎋=0 # Break
+@`; # ╭─
# ╷ "bb"
# "bb"
# "aa"
# "aa"
# ╯
```
~~Previous solution:~~
```
+@`!(|1 ⬚0+↬>0/+△.↘⇌×⍖.△..)↯∶1⊂
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 34 bytes
```
M?*GH?<HGCgHG+*G]jk*G]~hZgG-HGYjgF
```
[Try it online!](https://pyth.herokuapp.com/?code=M%3F%2aGH%3F%3CHGCgHG%2B%2aG%5Djk%2aG%5D~hZgG-HGYjgF&input=6%2C10&debug=0)
[Answer]
# [Haskell](https://haskell.org), 181 bytes
```
import Data.List
(['!'..'~']&)
a#[]=a
a#b=zipWith(++)a$transpose b
(s&a)b|b<1=[]|b>a=transpose$s&b$a|n<-div a b,(t,u)<-splitAt n s=foldl1(#)((<$[1..b]).(<$[1..b])<$>t)#(u&b$mod a b)
```
[Try it online!](https://tio.run/##RYxRS8MwFEbf@ytuaVkTtgaLIgjJYEzZy5SBiA9dkRvaumCblOZOh1b/eq0I@nQOnI/vgP6laprxI41gu7rbPKw2N7De7SBKPwPTdq4nuEZCsTWeglrtR5YnYSJE8pUUMx5glBcKJ2j1brpHQwc2n3OMqUfrO@cr0AHzM@R60DJTeTHoJaq/GvuZjnGwMi3NKyDoBaPFkcvUd42hFYEFr2rXlE3GIs6YjPNMCF1w8a8yXhKP2HF6al35c8LHoEVjQUGL3e0TdEe6p35rQQDbnzykS6iBnXwYnvFfZpxPcVpDX2E56ZvrSw9KSniuaO0sVZb8eHkB51ff "Haskell – Try It Online")
For `10` bytes more you get a nice spiral instead :)
```
!!!!!!!!!!!!!$$$#####
!!!!!!!!!!!!!$$$#####
!!!!!!!!!!!!!$$$#####
!!!!!!!!!!!!!%%'#####
!!!!!!!!!!!!!%%&#####
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
```
[Try it online!](https://tio.run/##RY1RS8MwFIXf@yvuaFkTtgaLIgjJYEzZy5TBEB@6Ijc0c8E2LcndHDr967Xiw56@A@fwnT2Gd1PX/VcWw2r@tHyeLx9gsV5DnH1HtulaT3CPhGJlA0U7te1ZkY5SIdKftBzzCOOiVDhAq0/bvVjas8mEY0IeXejaYBJvjsYHI5OZjlgYI9dnLXNVlGc9Q3XZhbFO8OxkVtkjIOgpo@mByyx0taU5gYOgdm1d1TmLOWMyKXIhdMnFJQ4fxGN2GExNW/1JeB81aB0oaLB7fIXuQBvyKwcC2PYUIJvBDtgpjEZX/J8550M5rMEbrIb40foqgJIS3gwtWkfGUehvb@D67hc "Haskell – Try It Online")
### Ungolfed
The `(#)` operator puts two matrices next to each other, but transposes the right one, eg:
```
!!! !!!"
!!! # "#$ -> !!!#
!!! !!!$
a # [] = a
a # b = zipWith (++) a $ transpose b
```
This is basically the recursive version of Euclid's algorithm, but instead of forgetting the divisors&remainders and returning the `gcd`, it builds squares from it and accumulates these with `(#)`. The `s` variable are the remaining characters that we can use:
```
(s & a) b
| b == 0 = [] -- Base case
| b > a = transpose $ (s & b) a -- In this case we can just flip the arguments and rotate the result by 90 degrees
| n <- div a b -- set n to the number of squares we need
, (t,u) <- splitAt n s = -- take n characters, ..
((<$[1..b]).(<$[1..b]) <$> t) -- .. build squares from them and ..
foldl1 (#) -- put them next to each other
(u & b $ mod a b) -- recursively build the smaller squares with the remaining characters..
# -- .. flip them and put them next to the previous one(s)
```
The actual function just calls the function from above with a string of all printable characters:
```
(['!'..'~']&)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes
```
Ṁ,ạ/y
³,⁴ÇÐĿp/€Fs2
pµ¢ṣLµ€+95ỌsY
```
[Try it online!](https://tio.run/nexus/jelly#AT0Awv//wrMs4oG0wrXhuYAs4bqhL3nCtcOQxL9wL@KCrEZzMgrCouG5o0wKcMOH4oKsKzk14buMc1n///82/zEw "Jelly – TIO Nexus")
`Ṁ,ạ/y` you want an explanation? Here it is.
```
Ṁ,ạ/y - perform one step of the Euclidean Algorithm, input 2-element list
, - pair of the following two:
Ṁ - maximum of the the input list
ạ/ - absolute difference of the two elements
y - use this as a mapping on the input.
³,⁴ÇÐĿp/€Fs2 - apply Euclidean Algorithm
³,⁴ - start with the pair [input 1, input 2]
Ç - apply a step of the Euclidean Algorithm
ÐĿ - repetitively until the results repeat
p/€ - take the Cartesian product of each step
Fs2 - flatten and split into all coordinate pairs of letters
pµ¢ṣLµ€+95ỌsY
p - Cartesian product of inputs: provides all possible coordinate pairs.
µ µ€ - for each coordinate
ṣL - find the number of times it is included in
¢ - the above list of covered coordinates.
+95Ọ - convert number of times to letters
s - split into rows
Y - join by newlines.
```
I can likely golf a little more by using implicit arguments instead of `³,⁴`.
[Answer]
# [J](https://www.jsoftware.com), 78 bytes
```
>/|:[:u:97+1(0&g@{:]F.:(((g=.$~,~)~1+0{,),(~:#)|:])}:)@}.0}:@{0|:(<.,|@-)/^:a:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=tdHNTgIxEAfweOUp_sjKttky22KCMnxkogknw8ErLoYYQI3RxMBpu_siXvDAQ-HTWFnCiauHppPp5DeT6df362Z30a2zyzp17sZx7ZziBQaMGAYWHE6LcHt_N9quV4vW9W48TD1PeM3dq8Qp21xKztmIWCm1HFBUmlKXLrG50UaV3NCeM12wloJswZJbz6pPxktLp1OecaX-nGW6Nr4hOChl90hgsXehTCkTRHAJXE5GMh1GO9qo8EcXGhz08Hz09-rsbTX_fJ-t5oxhCs-YMFRPCv6DchKTeJaIxZNEesrBTkMgvTCDFvVC0kDSpCGMhmqjHfUp1ej36BIPXEa2avI_8vzp-QMLdOBsFYcvOuTcqZyFO1FXbXmzqe5f)
Surprisingly tough to golf in J. Tried a few approaches, this was the best of them, but still feels like there's room for improvement.
Basic approach:
* Generate successive differences until a repeat, eg: `10 6` gives `6 4 2 2`.
* "Roll it up" starting from the smaller squares (ie, stack a 2x2 on a 2x2, then transpose it and put a 4x4 on that, then transpose that and put a 6x6x on top of it). We do transposes as needed to make the side lengths line up. We always stack our new larger square atop the result up to that point. The whole computation is expressed as a fold.
* The first square starts as a square of zeroes, and as we add each additional square its number increments by one. At the end we have our result but with numbers instead of letters.
* Convert the numbers to ascii letters.
* Finally, transpose the entire result if needed, so that the result dimensions match the order of the arguments.
[Answer]
# [J](https://www.jsoftware.com), 30 bytes
```
[:u:97+0]F.:({.>:)(-/:*|.)^:a:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9XQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxL9qq1MrSXNsg1k3PSqNaz85KU0NX30qrRk8zzirRCqJooSaEXnDTJl3B0EDBhEtXV5crXcEEyIEyzRBMQwVDBAsuaKBgCDEEAA)
Saw `... F.: ... ^:a:` in Jonah's answer and thought it might work better, and it actually did. Remove the leading `[:u:97+` to get a numeric matrix.
```
[:u:97+0]F.:({.>:)(-/:*|.)^:a: input: a vector of dimensions
( )^:a: repeat until convergence and collect iterations:
-/:*|. subtract smaller from larger
(it stops when one side becomes zero)
[10,4] becomes [[10,4],[6,4],[2,4],[2,2],[2,0]]
0]F.:({.>:) construct the numeric matrix:
0]F.:( ) fold from the right, starting with single 0,
{.>: increment the input matrix and pad with zeros
to the size of the next larger dimensions
[:u:97+ map 0, 1, ... to a, b, ...
```
---
# [J](https://www.jsoftware.com), 37 bytes
```
[:u:97+f=:$&0`({.1+[:f]-/:*|.)@.(~:/)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9XQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmtxUzXaqtTK0lw7zdZKRc0gQaNaz1A72iotVlffSqtGT9NBT6POSl8TonghlF5w0yZdwdBAwYRLV1eXK13BBMiBMs0QTEMFQwQLLmigYAgxBAA)
Recursive function seems to be the way here. Takes a vector of two positive integers and returns a character matrix. If a numeric matrix is acceptable, [28 bytes](https://ato.pxeger.com/run?1=m70wa8FOJT0F9XQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxR0XNIEGjWs9QO9pKxSpWV99Kq0ZP00FPo85KXxOiZCGUXnDTJl3B0EDBhEtXV5crXcEEyIEyzRBMQwVDBAsuaKBgCDEEAA): `$&0`({.1+[:$:]-/:*|.)@.(~:/)`.
```
[:u:97+f=:$&0`({.1+[:f]-/:*|.)@.(~:/)
f=:$&0`({.1+[:f]-/:*|.)@.(~:/) inner recursive function
` @.(~:/) if two parts are equal,
$&0 create a zero matrix of that dimensions
( ) otherwise,
]-/:*|. subtract the smaller part from the larger part
[:f recurse
{.1+ add 1 to each element and pad to the requested size
with zeros
[:u:97+ map 0, 1, ... to a, b, ...
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 111 bytes
```
x=>h=(y,i=x,j=y)=>j?(g=(x,y,k)=>(x>y?x-=y:y-=x,i)?x<i|y<j?k:g(x,y,k+1):`
`)(x,y,0)+(i?h(y,i-1,j):h(y,x,j-1)):''
```
[Try it online!](https://tio.run/##XYzLCoMwEEX3/ogzmJSm0AfBSX5FkaqJYkotkoH@exrbXXf3HA7Xt1u7dk/3eMntlnpKkcxIwMJRFJ4YyXgLA0EULKZMEA3bKIk1y5w4tLF2b669nfTwqyqFuika/NIRK3B23B@lEh71PvO1VIi6LFMXljXM98McBuhBnRDOiMWfvSJcsk0f "JavaScript (V8) – Try It Online")
] |
[Question]
[
>
> *This question is the second of several Brain-flak Birthday challenges designed to celebrate Brain-Flak's first Birthday! You can find more information about Brain-Flak's Birthday [here](https://hackmd.io/KwRgnARiAcCGAsBaaEBMAGR8DG8Cmis0AZsVhPLOtsWAOzQAmIQA?view)*
>
>
>
# Challenge
For this challenge you'll be generating all fully matched strings from a list of brackets. To borrow [DJMcMayhem's](https://codegolf.meta.stackexchange.com/users/31716/djmcmayhem) definition of a fully matched string:
* For the purpose of this challenge, a "bracket" is any of these characters: `()[]{}<>`.
* A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
```
()
[]{}
```
Or if every subelement inside of it is also matched.
```
[()()()()]
{<[]>}
(()())
```
Subelements can also be nested several layers deep.
```
[(){<><>[()]}<>()]
<[{((()))}]>
```
* A string is considered "Fully matched" if and only if each pair of brackets has the correct opening and closing bracket in the right order.
---
# Input
Your program or function will take a list of four non-negative numbers in any convenient, consistent format. This includes (but is not limited to) a list of integers, a non-digit delimited string, or separate arguments. These four numbers represent the number of matched pairs of each type of bracket. For example, `[1,2,3,4]` would represent:
* 1 pair of `()`
* 2 pairs of `{}`
* 3 pairs of `[]` and
* 4 pairs of `<>`
You may choose which pair of brackets each input corresponds to as long as it is consistent.
# Output
You should output all fully matched string that can be formed from this list of brackets without duplicates. Output can be in any reasonable format which includes printing a non-bracket delimited string to STDOUT, or a list of strings as a return value from a function.
Your algorithm must work for any arbitrary input, but you don't need to worry about memory, time or integer size limits (e.g. if your answer is in C you won't get 233 as an input).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
# Example Input and Output
For these example I will use the same input order as above.
For each example, the first line will be input and the following lines will be the output
```
Example 0:
[0,0,0,0]
Example 1:
[1,0,0,0]
()
Example 2:
[0,2,0,0]
{}{}
{{}}
Example 3:
[0,0,1,1]
[]<>
[<>]
<[]>
<>[]
Example 4:
[0,1,2,0]
{}[][] {}[[]] {[]}[] {[][]} {[[]]}
[{}][] [{}[]] [{[]}] []{}[] []{[]}
[][{}] [][]{} [[{}]] [[]{}] [[]]{}
Example 5:
[1,0,0,3]
()<><><> ()<><<>> ()<<>><> ()<<><>> ()<<<>>> (<>)<><> (<>)<<>>
(<><>)<> (<><><>) (<><<>>) (<<>>)<> (<<>><>) (<<><>>) (<<<>>>)
<()><><> <()><<>> <()<>><> <()<><>> <()<<>>> <(<>)><> <(<>)<>>
<(<><>)> <(<<>>)> <>()<><> <>()<<>> <>(<>)<> <>(<><>) <>(<<>>)
<><()><> <><()<>> <><(<>)> <><>()<> <><>(<>) <><><()> <><><>()
<><<()>> <><<>()> <><<>>() <<()>><> <<()><>> <<()<>>> <<(<>)>>
<<>()><> <<>()<>> <<>(<>)> <<>>()<> <<>>(<>) <<>><()> <<>><>()
<<><()>> <<><>()> <<><>>() <<<()>>> <<<>()>> <<<>>()> <<<>>>()
Example 6:
[1,1,1,1]
(){}[]<> (){}[<>] (){}<[]> (){}<>[] (){[]}<> (){[]<>} (){[<>]}
(){<[]>} (){<>}[] (){<>[]} ()[{}]<> ()[{}<>] ()[{<>}] ()[]{}<>
()[]{<>} ()[]<{}> ()[]<>{} ()[<{}>] ()[<>{}] ()[<>]{} ()<{}[]>
()<{}>[] ()<{[]}> ()<[{}]> ()<[]{}> ()<[]>{} ()<>{}[] ()<>{[]}
()<>[{}] ()<>[]{} ({})[]<> ({})[<>] ({})<[]> ({})<>[] ({}[])<>
({}[]<>) ({}[<>]) ({}<[]>) ({}<>)[] ({}<>[]) ({[]})<> ({[]}<>)
({[]<>}) ({[<>]}) ({<[]>}) ({<>})[] ({<>}[]) ({<>[]}) ([{}])<>
([{}]<>) ([{}<>]) ([{<>}]) ([]){}<> ([]){<>} ([])<{}> ([])<>{}
([]{})<> ([]{}<>) ([]{<>}) ([]<{}>) ([]<>){} ([]<>{}) ([<{}>])
([<>{}]) ([<>]){} ([<>]{}) (<{}[]>) (<{}>)[] (<{}>[]) (<{[]}>)
(<[{}]>) (<[]{}>) (<[]>){} (<[]>{}) (<>){}[] (<>){[]} (<>)[{}]
(<>)[]{} (<>{})[] (<>{}[]) (<>{[]}) (<>[{}]) (<>[]){} (<>[]{})
{()}[]<> {()}[<>] {()}<[]> {()}<>[] {()[]}<> {()[]<>} {()[<>]}
{()<[]>} {()<>}[] {()<>[]} {([])}<> {([])<>} {([]<>)} {([<>])}
{(<[]>)} {(<>)}[] {(<>)[]} {(<>[])} {}()[]<> {}()[<>] {}()<[]>
{}()<>[] {}([])<> {}([]<>) {}([<>]) {}(<[]>) {}(<>)[] {}(<>[])
{}[()]<> {}[()<>] {}[(<>)] {}[]()<> {}[](<>) {}[]<()> {}[]<>()
{}[<()>] {}[<>()] {}[<>]() {}<()[]> {}<()>[] {}<([])> {}<[()]>
{}<[]()> {}<[]>() {}<>()[] {}<>([]) {}<>[()] {}<>[]() {[()]}<>
{[()]<>} {[()<>]} {[(<>)]} {[]()}<> {[]()<>} {[](<>)} {[]}()<>
{[]}(<>) {[]}<()> {[]}<>() {[]<()>} {[]<>()} {[]<>}() {[<()>]}
{[<>()]} {[<>]()} {[<>]}() {<()[]>} {<()>}[] {<()>[]} {<([])>}
{<[()]>} {<[]()>} {<[]>()} {<[]>}() {<>()}[] {<>()[]} {<>([])}
{<>}()[] {<>}([]) {<>}[()] {<>}[]() {<>[()]} {<>[]()} {<>[]}()
[(){}]<> [(){}<>] [(){<>}] [()]{}<> [()]{<>} [()]<{}> [()]<>{}
[()<{}>] [()<>{}] [()<>]{} [({})]<> [({})<>] [({}<>)] [({<>})]
[(<{}>)] [(<>){}] [(<>)]{} [(<>{})] [{()}]<> [{()}<>] [{()<>}]
[{(<>)}] [{}()]<> [{}()<>] [{}(<>)] [{}]()<> [{}](<>) [{}]<()>
[{}]<>() [{}<()>] [{}<>()] [{}<>]() [{<()>}] [{<>()}] [{<>}()]
[{<>}]() [](){}<> [](){<>} []()<{}> []()<>{} []({})<> []({}<>)
[]({<>}) [](<{}>) [](<>){} [](<>{}) []{()}<> []{()<>} []{(<>)}
[]{}()<> []{}(<>) []{}<()> []{}<>() []{<()>} []{<>()} []{<>}()
[]<(){}> []<()>{} []<({})> []<{()}> []<{}()> []<{}>() []<>(){}
[]<>({}) []<>{()} []<>{}() [<(){}>] [<()>{}] [<()>]{} [<({})>]
[<{()}>] [<{}()>] [<{}>()] [<{}>]() [<>(){}] [<>()]{} [<>({})]
[<>{()}] [<>{}()] [<>{}]() [<>](){} [<>]({}) [<>]{()} [<>]{}()
<(){}[]> <(){}>[] <(){[]}> <()[{}]> <()[]{}> <()[]>{} <()>{}[]
<()>{[]} <()>[{}] <()>[]{} <({})[]> <({})>[] <({}[])> <({[]})>
<([{}])> <([]){}> <([])>{} <([]{})> <{()}[]> <{()}>[] <{()[]}>
<{([])}> <{}()[]> <{}()>[] <{}([])> <{}[()]> <{}[]()> <{}[]>()
<{}>()[] <{}>([]) <{}>[()] <{}>[]() <{[()]}> <{[]()}> <{[]}()>
<{[]}>() <[(){}]> <[()]{}> <[()]>{} <[({})]> <[{()}]> <[{}()]>
<[{}]()> <[{}]>() <[](){}> <[]()>{} <[]({})> <[]{()}> <[]{}()>
<[]{}>() <[]>(){} <[]>({}) <[]>{()} <[]>{}() <>(){}[] <>(){[]}
<>()[{}] <>()[]{} <>({})[] <>({}[]) <>({[]}) <>([{}]) <>([]){}
<>([]{}) <>{()}[] <>{()[]} <>{([])} <>{}()[] <>{}([]) <>{}[()]
<>{}[]() <>{[()]} <>{[]()} <>{[]}() <>[(){}] <>[()]{} <>[({})]
<>[{()}] <>[{}()] <>[{}]() <>[](){} <>[]({}) <>[]{()} <>[]{}()
```
[Answer]
# [Haskell](https://www.haskell.org/), 128 bytes
`f` is the main function, it takes a list of `Int`s and returns a list of `String`s.
```
f=g.($zip"({[<"")}]>").zipWith replicate
g=max[""].(#g)
l#c=[b:s|x@(b,e):r<-l,s<-(r:filter(/=x:r)l)?(map(e:).c)]
l?c=c l++l#(?c)
```
[Try it online!](https://tio.run/nexus/haskell#PY69boQwEAZ7ngIZil1hHJzrLHzkLVJwFD7HEEuLhQyRUH6enXBEQduM5ttiRuOD9mFx0dgl/wjkg5vFaCa4UXmlomDqFlhRwP/U59GZt5QQxSG2Xg8C8k8/Mfhqa8bwp7syFLt49ct7Gt1E3prFJYMezdoy1gnIBkwos7q9q/l7fYE7d6hiXRKf6xKi6j3tRfCkVxWRsIFHkFMoLHYJNVbbdE@jDBqL29ZW/LguaeVJFX8@qeKSy4Pkw55/l4Pk3/oL "Haskell – TIO Nexus")
# How it works
* `f` transforms its input list into a list of lists of tuples, each tuple containing a bracket pair, with each type of bracket in its own sublist. E.g. `[1,2,0,0]` becomes `[[('{','}')],[('[',']'),('[',']')]]`. Then it calls `g` with the transformed list.
* The remaining functions use a partially continuation-passing style intermingled with list manipulation. Each continuation function `c` takes a list `l` of remaining bracket tuple lists and returns a list of possible strings to be suffixed to what's already been generated.
* `g l` generates the list of fully matched strings formable by using all the brackets in `l`.
+ It does this by calling `l#g` to generate strings beginning with some bracket. The recursive `g` parameter is itself used as a continuation by `#`, to generate what comes after the first bracketed subelement.
+ In the case where there are no such strings (because `l` has no brackets left inside) `g` instead returns `[""]`, the list containing just the empty string. Since `[""]` compares smaller to all nonempty lists produceable by `#`, we can do this by applying `max`.
* `l#c` generates strings from `l` beginning with at least one bracketed subelement, leaving to the continuation `c` to determine what follows the element.
+ `b` and `e` are a selected pair of brackets in the tuple `x`, and `r` is the list of remaining tuples of the same bracket type.
+ `r:filter(/=x:r)l` is `l` with the tuple `x` removed, slightly rearranged.
+ `?` is called to generate the possible subelements between `b` and `e`. It gets its own continuation `map(e:).c`, which prefixes `e` to each of the suffix strings generated by `c`.
+ `#` itself prepends the initial `b` to all the strings generated by `?` and `c`.
* `l?c` generates the fully matched strings formable by using zero or more bracket pairs from `l`, and then leaves to its continuation `c` to handle what's left over. The `c l` part goes directly to `c` without adding any subelements, while `l#(?c)` uses `#` to generate one subelement and then call `(?c)` recursively for possible further ones.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~50 40~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-6 bytes thanks to Leaky Nun (getting reduce to work where I couldn't)
```
“()“{}“[]“<>”©ẋ"FŒ!QµW;®œṣF¥/µÐLÐḟ
```
Plain and inefficient.
**[Try it online!](https://tio.run/nexus/jelly#@/@oYY6GJpCorgUS0bFAwsbuUcPcQysf7upWcjs6STHw0NZw60Prjk5@uHOx26Gl@oe2Hp7gc3jCwx3z/x9uj/z/P9pQxwAIjWMB)** (times out at TIO for [1,1,1,1] - yes, inefficient.)
### How?
Recursively removes pairs of matching brackets that reside right next to each other until no more may be removed for every possible string one may form, keeping such strings which reduce to nothing (hence have all matching content).
```
“()“{}“[]“<>”©ẋ"FŒ!QµW;®œṣF¥/µÐLÐḟ - Main link: list: [n(), n{}, n[], n<>]
“()“{}“[]“<>” - literal ["()", "{}", "[]", "<>"]
© - copy to register
" - zip with:
ẋ - repeat list
F - flatten
Œ! - all permutations (yeah, it's inefficient!)
Q - de-duplicate
µ - monadic chain separation
Ðḟ - filter discard if (non empty is truthy):
µÐL - loop until no change:
® - recall value from register
W - wrap loop variable in a list
; - concatenate
¥/ - reduce with last two links as a dyad:
œṣ - split left on occurrences of sublist on the right
F - flatten the result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ ~~32~~ ~~30~~ ~~27~~ 25 bytes
Saved 7 bytes thanks to *Riley*.
Input order is `[(),<>,[],{}]`
```
žu4äשJœJÙD[D®õ:DŠQ#]€g_Ï
```
[Try it online!](https://tio.run/nexus/05ab1e#@390X6nJ4SWHpx9a6XV0stfhmS7RLofWHd5q5XJ0QaBy7KOmNenxh/v//4821AHDWAA "05AB1E – TIO Nexus")
**Explanation**
```
žu # push the string "()<>[]{}"
4ä # split in 4 parts
© # store a copy in register
× # repeat each bracket a number of times decided by input
JœJÙ # get the unique permutations of the string of brackets
D # duplicate
[ # start infinite loop
D # duplicate current list of permutations
®õ: # replace any instance of (), [], <>, {}
# with an empty string
DŠ # duplicate and move down 2 places on stack
Q# # if the operation didn't alter the list, exit loop
] # end loop
€g # get the length of each subtring
_Ï # keep only the strings in the original
# list of unique permutations
# that have a length of 0 in the resulting list
```
[Answer]
# Pyth - ~~83~~ ~~74~~ ~~71~~ 63 bytes
```
K("\[]""{}""\(\)""<>")Fd{.psm*:@Kd*\\2k@QdU4JdVldFHK=:JHk))I!Jd
```
[Try It](http://pyth.herokuapp.com/?code=Kc%22%5C%5B%5D%20%5C%7B%7D%20%5C%28%5C%29%20%3C%3E%22%29Fd%7B.ps%2AV-R%5C%5CKQJdVldFHK%3D%3AJHk%29%29I%21Jd&input=1%2C0%2C2%2C0&debug=0)
[1](http://pyth.herokuapp.com/?code=Kc%22%5C%5B%5D%20%5C%7B%7D%20%5C%28%5C%29%20%3C%3E%22%29Fd%7B.ps%2AV-R%5C%5CKQJdVldFHK%3D%3AJHk%29%29I%21Jd&input=1%2C0%2C2%2C0&debug=0): Kc"[] {} () <>")Fd{.ps\*V-R\KQJdVldFHK=:JHk))I!Jd
Also, this 53-byte version thanks to Leaky Nun
```
Kc"\[] \{} \(\) <>")Fd{.ps*V-R\\KQJdVldFHK=:JHk))I!Jd
```
[Here](http://pyth.herokuapp.com/?code=Kc%22%5C%5B%5D%20%5C%7B%7D%20%5C%28%5C%29%20%3C%3E%22%29Fd%7B.ps%2AV-R%5C%5CKQJdVldFHK%3D%3AJHk%29%29I%21Jd&input=1%2C0%2C2%2C0&debug=0)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 123 bytes
```
->a{"<>{}[]()".gsub(/../){$&*a.pop}.chars.permutation.map(&:join).uniq.grep /^((\(\g<1>\)|\[\g<1>\]|\{\g<1>\}|<\g<1>>)*)$/}
```
[Try it online!](https://tio.run/nexus/ruby#JcbdCoIwFADgVxEROZM6S7oL3Ys4g5PMZfiz3NbN3LNbJN/N19dyPwsKaSVCbFpgKWrrH8AROQtZXhCaxUTsnrRaNGqdvCM3LDNOZCC/vZZhZujn4Y16VSbhdwAJUlelkGyTzbF2k@FY3Kp/BCtYxuNuvLNJjx2NY6I@NIJWzrK9KU@Xn2v7BQ "Ruby – TIO Nexus") It's inefficient, though, so even inputs like `[1,2,1,1]` will time out online. All the listed examples will work, at least!
### Explanation
```
->a{ # Procedure with input a
"<>{}[]()".gsub(/../){ # For all pairs of brackets
$&*a.pop # Pop last item in input, then repeat
# the bracket pair by that number
}.chars # Get characters
.permutation # All permutations of characters
.map(&:join) # For each permutation, join the chars
.uniq # Get unique permutations only
.grep /^((\(\g<1>\)|\[\g<1>\]|\{\g<1>\}|<\g<1>>)*)$/}
# Only return permutations that match
# this bracket-matching regex
```
] |
[Question]
[
## Definitions
You can skip this part if you already know the definitions of **groups**, **finite groups**, and **subgroups**.
### Groups
In abstract algebra, a *[group](https://en.wikipedia.org/wiki/Group_(mathematics))* is a tuple **(G, ∗)**, where **G** is a set and **∗** is a function **G × G → G** such that the following holds:
* Closure: for all **x, y** in **G**, **x ∗ y** is also in **G** (implied by the fact that **∗** is a function **G × G → G**).
* Associativity: for all **x, y, z** in **G**, **(x ∗ y) ∗ z = x ∗ (y ∗ z)**.
* Identity: there exists an element **e** in **G** such that for all **x** in **G**, **x ∗ e = x = e ∗ x**.
* Inverse: for each **x** in **G**, there exists an element **y** in **G** such that **x ∗ y = e = y ∗ x**, where **e** is the identity element mentioned in the previous bullet point.
### Finite groups
A *[finite group](https://en.wikipedia.org/wiki/Finite_group)* is a group **(G, ∗)** where **G** is finite, i.e. has finitely many elements.
### Subgroups
A *[subgroup](https://en.wikipedia.org/wiki/Subgroup)* **(H, ∗)** of a group **(G, ∗)** is such that **H** is a subset of **G** (not necessarily proper subset) and **(H, ∗)** is also a group (i.e. satisfies the 4 criteria above).
### Examples
Consider the *[dihedral group **D3**](http://mathworld.wolfram.com/DihedralGroupD3.html)* **(G, ∗)** where **G = {1, A, B, C, D, E}** and **∗** is defined below (a table like this is called a *[Cayley table](https://en.wikipedia.org/wiki/Cayley_table)*):
```
∗ | 1 A B C D E
--+----------------------
1 | 1 A B C D E
A | A B 1 D E C
B | B 1 A E C D
C | C E D 1 B A
D | D C E A 1 B
E | E D C B A 1
```
In this group, the identity is **1**. Also, **A** and **B** are inverses of each other, while **1**, **C**, **D**, and **E** are the inverses of themselves respectively (the inverse of **1** is **1**, the inverse of **C** is **C**, the inverse of **D** is **D**, and the inverse of **E** is **E**).
Now, we can verify that **(H, ∗)** where **H = {1, A, B}** is a subgroup of **(G, ∗)**. For the closure, refer to the table below:
```
∗ | 1 A B
--+----------
1 | 1 A B
A | A B 1
B | B 1 A
```
where all possible pairs of elements in **H** under **∗** give a member in **H**.
The associativity does not require checking, since elements of **H** are elements of **G**.
The identity is **1**. This must be the same with the group identity. Also, the identity in a group must be unique. (Can you prove this?)
For the inverse, check that the inverse of **A** is **B**, which is a member of **H**. The inverse of **B** is **A**, which is also a member of **H**. The inverse of **1** is still itself, which does not require checking.
---
## Task
### Description
Given a finite group **(G, ∗)**, find the number of its subgroups.
### Input
For a group **(G, ∗)**, you will receive a 2D array of size **n × n**, where **n** is the number of elements in **G**. Assume that index `0` is the identity element. The 2D array will represent the multiplication table. For example, for the group above, you will receive the following 2D array:
```
[[0, 1, 2, 3, 4, 5],
[1, 2, 0, 4, 5, 3],
[2, 0, 1, 5, 3, 4],
[3, 5, 4, 0, 2, 1],
[4, 3, 5, 1, 0, 2],
[5, 4, 3, 2, 1, 0]]
```
For example, you can see that **3 ∗ 1 = 5** because `a[3][1] = 5`, where `a` is the 2D array above.
Notes:
* You can used 1-indexed 2D array.
* The row and the column for the identity can be omitted.
* **You may use other formats as you see fit, but it must be consistent.** (i.e. you may want the last index to be identity instead, etc.)
### Output
A positive number representing the number of subgroups in the group.
For example, for the group above, **(H, ∗)** is a subgroup of **(G, ∗)** whenever **H =**
* **{1}**
* **{1, A, B}**
* **{1, C}**
* **{1, D}**
* **{1, E}**
* **{1, A, B, C, D, E}**
Therefore, there are **6** subgroups, and your output for this example should be `6`.
---
## Hints
You can read the articles that I linked to. Those articles contain theorems about groups and subgroups that might be useful to you.
---
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Answer with lowest byte-count wins.
[Answer]
## Mathematica, 62 48 bytes
```
Count[Subsets@First@#,x_/;Union@@#[[x,x]]==x]-1&
```
Pure function expecting a 1-indexed 2D array. `Count`s the number of `Subsets` of the `First` row of the input array that are closed under the group operation. Since this will include the empty set, we subtract `1`. Note that a nonempty subset of a finite group that is closed under the group operation is [in fact a subgroup](https://math.stackexchange.com/questions/475966/proof-that-a-subset-closed-under-group-operation-of-a-finite-group-is-a-subgroup), (and vice versa, by definition).
Strictly speaking I don't check that the subset `x` is closed under the group operation, I restrict the multiplication table to the subset `x` and check that it contains precisely the elements of `x`. Clearly this implies that `x` is closed with respect to the group operation. Conversely, any subgroup `x` will contain `1` and thus `x` will be a subset of the elements appearing in the restricted multiplication table, and since `x` is closed under the group operation, it must equal `x`.
[Answer]
# [Haskell](https://www.haskell.org/), 79 bytes
Basically a port of ngenisis's Mathematica method. (Except I'm using 0-indexed arrays.)
`c` takes a list of lists of `Int`s and returns an integer.
```
c g=sum[1|l<-foldr(\r->([id,(r!!0:)]<*>))[[]]g,and[g!!x!!y`elem`l|x<-l,y<-l]]-1
```
[Try it online!](https://tio.run/nexus/haskell#JcpBCoMwEIXhfU@RQBdaJmKqbop6kXTAYKwVokK0VMG723SyGZjv/aMepmqY1s7pdr0u7/mbtInrtDlb1lfLZ1TysKV4zda46OlEHanBQOQ4Tx8xlrc6jpVC7EFPRvWcb5zvTWe7sbHHVgoLuz@IQp6nUikwCewOLAOWAysQLkwFSYP4iTCIDOInwozenCYfSMKcgoLivxOGLAuZd8Qf "Haskell – TIO Nexus")
It is assumed that the `Int`s are numbered the same as the rows (outer lists) and columns showing their multiplication. Thus, since 0 is the identity, the first column is the same as the indices of the rows. This allows using the entries of the first column to construct the subsets.
# How it works
* `c` is the main function.
* `g` is the group array as a list of lists.
* `l` is a subset of the elements. The list of subsets is constructed as follows:
+ `foldr(\r->([id,(r!!0:)]<*>))[[]]g` folds a function over the rows of `g`.
+ `r` is a row of `g`, whose first (0th) element is extracted as an element that may be included (`(r!!0:)`) or not (`id`).
+ `<*>` combines the choices for this row with the following ones.
* `and[g!!x!!y`elem`l|x<-l,y<-l]` tests for each pair of elements in `l` whether their multiple is in `l`.
* `sum[1|...]-1` counts the subsets that pass the test, except for one, the empty subset.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 bytes
1 byte thanks to ETHproductions (`LR → J`)
```
ị³Z⁸ịFḟ
JŒPÇÐḟL’
JŒPÇÐḟL’ main link. one argument (2D array)
J [1,2,3,...,length of argument]
ŒP power set of ^
Ðḟ throw away elements that pass the test...
Ç in the helper link
L length (number of elements that do not pass)
’ decrement (the empty set is still closed under
multiplication, but it is not a subgroup, as
the identity element does not exist.)
ị³Z⁸ịFḟ helper link. one argument (1D indexing array)
ị³ elements at required indices of program input (2D array)
Z transpose
⁸ị elements at required indices of ^
F flatten
ḟ remove elements of ^ that are in the argument given
if the set is closed under multiplication, this will
result in an empty set, which is considered falsey.
```
[Try it online!](https://tio.run/nexus/jelly#@/9wd/ehzVGPGncAGW4Pd8zn8gk6OingcPvhCUCOz6OGmf///4@ONtRRMNJRMNZRMNFRMNVRMIvVUYiGCBhCBIAyIDGIgBFEACgDEjMB80zBMkB5I5CYKVjaDKwUJAwSgygygSgCCsfGAgA "Jelly – TIO Nexus") (1-indexed)
[Answer]
# Python 2, ~~297~~ 215 bytes
```
from itertools import*
T=input()
G=T[0]
print sum(all(T[y][x]in g for x,y in product(g,g))*all(any(T[y][x]==G[0]==T[x][y]for y in g)for x in g)*(G[0]in g)for g in chain(*[combinations(G,n)for n in range(len(G)+1)]))
```
[**Try it online**](https://tio.run/nexus/python2#PYwxkoQgEEVzT9EhuAQ6OiGxFzCjCBjXYanSxkKs0tM7DdRs1v/91/9@B7@Ci3OI3i87uHXzIdbVKB1uR2S8GuSoGl1twWGE/ViZWRY2qkurUzsEC28f4BQXUNiC/z2myKywnNdJNHh9ZSkHGpI0d2oi6S0/WZ4XylmzJP1Tm@j0ZxyyWk1@fTk00Xnc2SAwG5iMYNDObJmRDfyn5Zrz@1aqEdAKeAjoBPQCnlqokpuSqSBUclsyFYS6HPpcUN0S6nP5zGKihIrSFYWo1h8)
This program works for the example group without `==T[x][y]`, but I'm still pretty sure it's necessary.
Edit: Now assumes that the identity element of **G** is always the first.
---
**Ungolfed:**
```
from itertools import*
T=input()
G=T[0]
def f(x,y):return T[y][x] # function
def C(g):return all(f(x,y)in g for x,y in product(g,g)) # closure
def E(g):return[all(f(x,y)==y for y in g)for x in g] # identity
a=E(G)
e=any(a)
e=G[a.index(1)]if e else-1 # e in G
def I(G):return all(any(f(x,y)==e==f(y,x)for y in G)for x in G) # inverse
#print e
#print C(G),any(E(G)),I(G)
#for g in chain(*[combinations(G,n)for n in range(len(G)+1)]): # print all subgroups
# if C(g)and I(g)and e in g:print g
print sum(C(g)*I(g)*(e in g)for g in chain(*[combinations(G,n)for n in range(len(G)+1)]))
```
[Ungolfed TIO](https://tio.run/nexus/python2#nVI7b4MwEJ7rX3FSFpu6VWiSJZKnKELds1kMbjCuJbCRMRL8@tQPpXRg6sTd97jvsI7zPYWSwgeFA4UjhVNNEc/APgOBiVgGygwEJmKH1B0TE/gyYsdEn5I0whHLokMWBbiuH62zPWgvnbe2G0H3g3W@QDemzTB5TFDFbnxfo0a20OKZLuTspJ@cgRtfaj5n5oLVLy66DmelNqCgtQ5CA6EZnG2mu8eKKkKS77r6@OpjbEm2ZFIkTUhljZBgV1wRJJkwCxaxqLh416aRMy5JrVuQILtRvpUoJXwG9d/Nou2ZIhlr8UJn8htWrWEhBO0Gp40H@SwuYRiNE@IOhMbZQRQtKlru30IbXPC77b@0EV5bM@KKmjTURIUTRkncSROcr2Fdcka7F53fT5gmbJu/Mv3uOacqhHIxTj2OyiLKCizX5/lvPHk8@MblbRzext1tnN3G1W0c3Q8)
Negative group elements can be supported at no cost by changing `-1` to `''`.
] |
[Question]
[
# Steganographic Squares
Your job is to take in a string, and generate an `NxN` image that represents this string. You must also write the algorithm that takes in the image and turns it back into a string as well. The scoring will be will include the byte count of both algorithms:
**"Encryption" Algorithm + "Decryption" Algorithm**.
You should post each separately, with byte-counts for both the encryption and decryption algorithms displayed individually.
---
# Example Algorithm
For instance, here's the "Programming Puzzles and Code Golf" using a simple ASCII based steganographic algorithm in the Blue channel:
```
#2e7250,#6ea972,#04eb6f,#0fc767,#74ab72,#ee6161
#b73b6d,#1aae6d,#f37169,#bda56e,#1fe367,#e99620
#706450,#0d3575,#146b7a,#4ea47a,#2a856c,#95d065
#3f2d73,#cef720,#bab661,#d1b86e,#f22564,#12b820
#0f3d43,#c86e6f,#1ee864,#a66565,#247c20,#c3bb47
#0e296f,#89d46c,#585b66,#c08f20,#455c20,#136f20
```
Actual Image ( [](https://i.stack.imgur.com/CvOvX.png) )
[](https://i.stack.imgur.com/ROhCT.png)
You can see the blue channel simply holds the ascii values for this image:
```
50 = 80(P) 72 = 114(r) 6f = 111(o) 67 = 103(g) 72 = 114(r) 61 = 97(a)
6d = 109(m) 6d = 109(m) 69 = 105(i) 6e = 110(n) 67 = 103(g) 20 = 32( )
50 = 80(P) 75 = 117(u) 7a = 122(z) 7a = 122(z) 6c = 108(l) 65 = 101(e)
73 = 115(s) 20 = 32( ) 61 = 97(a) 6e = 110(n) 64 = 100(d) 20 = 32( )
43 = 67(C) 6f = 111(o) 64 = 100(d) 65 = 101(e) 20 = 32( ) 47 = 71(G)
6f = 111(o) 6c = 108(l) 66 = 102(f) 20 = 32( ) 20 = 32( ) 20 = 32( )
```
While the rest of the channels hold randomly generated values to "spice up" the variety of colors in the image. When pulling the message back out of the image, we can just simply ignore the other channel values, and pull the hex bit in the blue channel, reconstructing the string:
```
"Programming Puzzles and Code Golf"
```
Notice the spaces that were used to pad the string in the square are not included in the final decrypted output. While you must pad the string in the image, you may assume that the input string will not end with spaces.
---
# Rules
* You must encode 1 character per pixel, the channel chosen to encode the char is arbitrary.
* The channels of the other RGB colors must be randomized, other than the one you're choosing to encode the string into; this means your final non-encoded channels would need to be between `0x0000-0xFFFF` (randomly chosen).
* Expressing the final result as a 2D array of RGB color values is fine `0x000000-0xFFFFFF`, no need to use image creation unless you want to have fun with it or if it's less bytes. If you choose to output as hex strings, prefix the hex string with `#` E.G. `#FFFFFF` or `#05AB1E`. You may separate with tabs, commas, or anything else that would be horizontally sensible, but it must maintain the square pattern; in other words, you must use appropriate newline separation.
* The output must be in a square, and the string must be padded with spaces at the end to accomodate this. This means that `N≈SQRT(Input#Length())`. If the input length is not a perfect square, you should round up on `N` and pad with spaces.
* As stated previously, if you are padding with spaces in the image, you must not include the padded characters in the final "decrypted" output.
* You can assume that:
+ The input string will not end with spaces.
+ The input string will only use printable ASCII characters.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte count wins.
[Answer]
# C, 201 (Encoding) + 175 (Decoding) = 376 bytes
**To Encode:**
```
E(char*J){size_t L=ceil(sqrt(strlen(J)));int U;srand(time(NULL));for(int i=0;i<L;i++){for(int f=0;f<L;f++){printf("#%02X%02X%02X ",rand()%256,(U<strlen(J))?(int)J[U]:32,rand()%256);U+=1;}printf("\n");}}
```
Encodes each character of the input string in the green channel of the RGB spectrum while setting the two other channels as random hex values. Takes input through STDIN as a string and outputs to STDOUT a multiline string of hex color code in the shape of a square. Assuming you have Python 3 and ImageMagick installed, and the above file is compiled into a file named `a.out` in the current working directory (CWD), you can directly get the resulting image, named `Output.png`, to the CWD from the textual output using the following command:
```
./a.out "<Multiline Input>"|python3 -c "import sys,subprocess;Input=sys.stdin.read();print('# ImageMagick pixel enumeration: {0},{0},255,rgb\n'.format(len(Input.split('\n')[1].split()))+'\n'.join(['%d,%d:(%d,%d,%d)'%(g,i,int(j[1:][:2],16),int(j[1:][2:4],16),int(j[1:][4:6],16))for g,h in enumerate(Input.split('\n'))for i,j in enumerate(h.split())]))"|convert - -scale 1000% Output.png
```
Here is a sample output image created by the above commamd using `Programming Puzzles and Code Golf` as the input string:
[](https://i.stack.imgur.com/jcYlU.png)
**To Decode:**
```
D(int c,char**U){char T[c];for(int Y=1;Y<c;Y++){char G[2]={U[Y][3],U[Y][4]};T[Y-1]=(char)strtol(G,NULL,16);}int C=c-1;T[C]='\0';while(T[C]==' '){T[C]='\0';C-=1;}printf("%s\n",T);}
```
Takes input through STDIN a sequence of space-separated hex color code strings with each one enclosed in double quotes (`"`) (`char** argv` in `main`) and also, when called in `main`, `int argc` for the integer input. Outputs to STDOUT a single/multi-line string representing the decoded message.
I will try to golf these more over time whenever and wherever I can.
---
Also, if you same both of the methods into the same file, you can use the following `main` method to put it all together with each function getting the correct inputs:
```
int main(int argc,char**argv){if(strcmp(argv[1],"E")==0){Encode(argv[2]);}else{Decode(argc,argv);}}
```
and using this, for encoding you must provide `E` as the first argument to call the encoding method followed by the single string argument, whereas for decoding, all you need to provide is the sequence of space-separated hex color code strings with each one enclosed in double-quotes (`"`).
---
Finally, if you want, you can get the fully prepared, ready-to-use version [here](https://gist.github.com/ImpregnableProgrammer/87b1702dd14edba057128ec719b0161e), although it is not golfed, but also does not output *any* warnings or errors upon compilation.
[Answer]
# Python 2, ~~164~~ 160 + ~~94~~ 93 = 253 bytes
Saved 1+1 byte thanks to Wheat Wizard.
-5 bytes thanks to Kade
[](https://i.stack.imgur.com/kltHI.png)Encoder: string must be enclosed in quotes, e.g. `"CodeGolf"`, output is a color ascii PPM image.
```
from random import*
s=input()
n=int((len(s)-1)**0.5)+1
s=s.ljust(n*n)
r=randint
print"P3 %d %d 255 "%(n,n)+''.join("%d "*3%(r(0,255),r(0,255),ord(c))for c in s)
```
[](https://i.stack.imgur.com/hI2tP.png)Decoder: Takes input filename as command line argument
```
from sys import*
print''.join(chr(int(c))for c in open(argv[1]).read().split()[6::3]).strip()
```
Usage:
```
python golf_stegansquare_enc.py > stega.ppm
python golf_stegansquare_dec.py stega.ppm
```
Example:
[](https://i.stack.imgur.com/qU51C.png)Programming Puzzles and Code Golf
[](https://i.stack.imgur.com/puhmN.png)Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 34 + 12 = 46 bytes
Uses red channel.
05AB1E uses [CP-1252](http://www.cp1252.com) encoding.
**Encode:**
```
DgDtî©n-Äð×JvyÇh`4F15Ý.Rh«}})'#ì®ä
D # duplicate input
gDtî©n-Ä # abs(len(input)-round_up(sqrt(len(input)))^2)
ð×J # join that many spaces to end of input
v # for each char in string
yÇ # get ascii value
h` # convert to base-16 number
4F # 4 times do:
15Ý.Rh # push random base-16 number
« # concatenate
}} # end inner and outer loop
) # wrap in list
'#ì # prepend a "#" to each element in list
®ä # split in pieces round_up(sqrt(len(input))) long
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RGdEdMOuwqluLcOEw7DDl0p2ecOHaGA0RjE1w50uUmjCq319KScjw6zCrsOk&input=UHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZSBHb2xm)
**Decode:**
```
˜vy3£¦HçJ}ðÜ
˜ # deep flatten input to a list
v # for each color in the list
y3£ # take the first 3 chars
¦ # remove the hash sign
H # convert from base-16 to base-10
ç # get the ascii char with that value
J # join to string
} # end loop
ðÜ # remove trailing spaces
```
[Try it online!](http://05ab1e.tryitonline.net/#code=y5x2eTPCo8KmSMOnSn3DsMOc&input=W1snIzUwQTNENCcsICcjNzI0RkU2JywgJyM2RkRCRkYnLCAnIzY3QjRBMScsICcjNzI2NThGJywgJyM2MTFGRTAnXSwgWycjNkQ3QTEyJywgJyM2RDA1MTknLCAnIzY5RUU5RScsICcjNkVGMTQyJywgJyM2N0NFMUUnLCAnIzIwMEJEMyddLCBbJyM1MDREMEUnLCAnIzc1QjBCRicsICcjN0EwQzNEJywgJyM3QTRBNTAnLCAnIzZDMkZCRCcsICcjNjUxMzY1J10sIFsnIzczNDU2NCcsICcjMjA2OEMwJywgJyM2MTQ1RjcnLCAnIzZFN0I1MScsICcjNjRERUQ5JywgJyMyMEY1M0InXSwgWycjNDNDMDRCJywgJyM2RjY1QjEnLCAnIzY0RDQ0QicsICcjNjVBMjY3JywgJyMyMEJGNTknLCAnIzQ3QjYyMCddLCBbJyM2Rjg4RjUnLCAnIzZDQkRGOCcsICcjNjZCRDYxJywgJyMyMDUwMzgnLCAnIzIwMEU1NCcsICcjMjAyQkNDJ11d)
**Alternative padding method with equal byte-count**
```
Dgð×J¹gtî©n£
```
[Answer]
# Scala, 97 + 68 = 165 bytes
Encryption (97 bytes):
```
s=>s.map(_+((math.random*65535).toInt<<8)).iterator.grouped(math.sqrt(s.size)toInt)withPadding 32
```
Takes a String and retuns an Iterator of Sequences of Integers.
Decryption (68 bytes):
```
a=>" +$".r.replaceAllIn(a.flatten.map(h=>(h&0xFF)toChar)mkString,"")
```
Takes an Iterator of Sequences of Integers and returns a string.
Explanation:
```
s=> //define an anonymous function
s.map( //map each char of the string
_+( //to the ascii value plus
(math.random*65535).toInt) //a random integer between 0 and 65535
<<8 //shifted 8 bits to the left
)
)
.iterator //create an iterator
.grouped( //group them in groups of size...
math.sqrt(s.size)toInt //sqrt of the size of the input, rounded up
)withPadding 32 //pad with spaces to make a square
```
.
```
a=>
" +$" //take this string
.r //parse it as a regex
.replaceAllIn( //replace every occurence of the regex in...
a.flatten //a flattened
.map(h=> //each element mapped
(h&0xFF)toChar) //to the character of the lower 8 bits
mkString, //joined to a string
"" //with an empty string
)
```
[Answer]
# Perl, (103+1) + (36+2) = 142 bytes
Text to image encoder (run with `-p` for a 1-byte penalty; `-p0` (for an additional byte of penalties) is necessary if you want to handle newlines in the input string):
```
$_.=$"while($a=(length)**.5)=~/\./;$_=unpack"H*";s/../sprintf"#%04x$&,",rand+4**8/eg;s/(.*?\K,){$a}/
/g
```
Image to text decoder (run with `-p0` for a 2-byte penalty):
```
$\.=chr hex for/..\W/g;$\=~s/ *$//}{
```
This uses the `#abcdef` text-based image format, and encodes in the blue channel. Here's an example of a possible output given `Programming Puzzles and Code Golf` as the input:
```
#b4d250,#bccb72,#43f06f,#4d6767,#74ba72,#269461
#e4f26d,#f63d6d,#701c69,#bbf56e,#6ef967,#d78d20
#4e0d50,#9b2775,#afd37a,#12a47a,#63e46c,#0e9565
#4cad73,#e43420,#6da761,#5a306e,#8fba64,#58f720
#d52443,#b4446f,#fbaf64,#4a4365,#1a5020,#f3ea47
#354c6f,#52cb6c,#11a766,#4c380a,#553820,#b31120
```
Explanation of the encoder:
```
$_.=$" # append a space ($") to the input ($_)
while # as long as the following condition holds:
(($a=length)**.5) # the square root of the input length (save this in $a)
=~/\./; # has no decimal points in its string represenation
$_=unpack"H*"; # convert the input from base-256 to hexadecimal
s/../ # replace two characters of the input
sprintf # with a string formed from the template
"#%04x$&,", # four hex digits, the two matched characters, and a comma
rand+4**8 # those hex digits are a random number from 0 to 4**8 (= 65536)
/eg; # and do this for every non-overlapping match
s/(.*? # find the minimum number of characters needed to match
\K,) # replacing the part of the match after the last matched comma
{$a}/ # a string containing $a commas
/gx # with a newline, for every non-overlapping match
```
I was really happy this use of `\K` worked; it specifies where to replace, and placing it inside a loop, it seems that the occurrence on the last loop iteration is what counts. So `s/(.*?\K,){$a}/\n/g` will match a minimum-length string of the form *anything* comma *anything* comma … *anything* comma, that has `$a` commas, but the actual replaced part of the match will simply be the last comma. This has the effect of replacing every `$a`th comma with a newline, giving us the square shape for the image.
The big advantage of Perl for this challenge (other than the built-in character string-to-hexadecimal converter, which was incredibly convenient) is that it has a very short decoder (so short, in fact, that although Perl has a builtin for converting hexadecimal to a string, it was shorter not to use it). Here's how it works:
```
$\.=chr # append to $\ the character code
hex # of the hexadecimal-string-to-number-translation
for/..\W/g; # of each two characters that appear before a
# non-alphanumeric character (not counting overlapping matches)
$\=~s/ *$// # delete all spaces at the end of $\
}{ # in this context, this means "implicitly print $\,
# prevent any other implicit printing"
```
The only instances of two characters immediately before a non-alphanumeric character are the blue channels (which we want to unpack), which appear just before commas and newlines; and the two characters that appear before each `#` other than the first. We don't want the latter category of matches, but they inevitably overlap the former category, and thus will be excluded by the overlapping matches check.
[Answer]
# MySQL, 438 + 237 = 675 bytes
There is a trailing new line at the end of the output, but it does not show up after being decrypted. The hex function (integer overload) would chop off leading 0's, so I had to pad it with a string 0. I could save some bytes if I could declare both functions between the delimiters.
**Encrypt**
```
delimiter //create function a(i text)returns text begin declare r int;declare q,p text;while mod(length(i),sqrt(length(i)))<>0 do set i:=concat(i,' ');end while;set r:=1;set q:="";while r<=length(i) do set p:=",";if mod(r,sqrt(length(i)))=0 then set p:="\r\n";end if;set q:=concat(q,'#',right(concat(0,hex(floor(rand()*256))),2),right(concat(0,hex(floor(rand()*256))),2),hex(mid(i,r,1)),p);set r:=r+1;end while;return q;end//
delimiter ;
```
**Decrypt**
```
delimiter //create function b(i text)returns text begin declare x int;declare y text;set x:=0;set y:="";while instr(i,'#')>0 do set i:=substr(i,instr(i,'#')+5);set y:=concat(y,unhex(left(i,2)));end while;return trim(y);end//
delimiter ;
```
Usage:
```
select a('test')
select b('#7D1874,#FFB465')
select b(a('test'))
```
[Answer]
# C#, 312 + 142 = 454 bytes
Encoding:
```
using System;I=>{var r=new Random();int i=I.Length;int N=(int)Math.Floor(Math.Sqrt(i))+1,S=N*N;while(i++<S){I+=' ';}var R="";for(i=0;i<S;){R+=i%N<1&i>0?"\n":i<1?"":" ";R+="#"+r.Next(256).ToString("X").PadLeft(2,'0')+r.Next(256).ToString("X").PadLeft(2,'0')+((int)I[i++]).ToString("X").PadLeft(2,'0');}return R;};
```
Decoding:
```
using System;I=>{var s=I.Replace('\n',' ').Split(' ');var R="";foreach(var t in s)R+=(char)System.Convert.ToInt32(t[5]+""+t[6],16);return R.TrimEnd(' ');};
```
Full program:
```
using System;
class Steganographic
{
static void Main()
{
Func<string, string> E = null;
Func<string, string> D = null;
E=I=>
{
var r=new Random();
int i=I.Length;
int N=(int)Math.Floor(Math.Sqrt(i))+1,S=N*N;
while(i++<S){I+=' ';}
var R="";
for(i=0;i<S;)
{
R+=i%N<1&i>0?"\n":i<1?"":" ";
R+="#"+r.Next(256).ToString("X").PadLeft(2,'0')+r.Next(256).ToString("X").PadLeft(2,'0')+((int)I[i++]).ToString("X").PadLeft(2,'0');
}
return R;
};
D=I=>
{
var s=I.Replace('\n',' ').Split(' ');
var R="";
foreach(var t in s)
R+=(char)Convert.ToInt32(t[5]+""+t[6],16);
return R.TrimEnd(' ');
};
string encoded = E("Programming Puzzles and Code Golf");
Console.WriteLine(encoded);
Console.WriteLine(D(encoded));
encoded = E("Hello, World!");
Console.WriteLine(encoded);
Console.WriteLine(D(encoded));
Console.Read(); // For Visual Studio
}
}
```
[Answer]
# Mathematica, 111 + 65 = 176 bytes
**Encoder**
```
Join[255~RandomInteger~{n=⌈Sqrt@Length@#⌉,n,2},ArrayReshape[#,{n,n,1},32],3]~Image~"Byte"&@*ToCharacterCode
```
**Decoder**
```
StringTrim[""<>FromCharacterCode@ImageData[#,"Byte"][[;;,;;,3]]]&
```
[Answer]
# Processing, ~~220~~ ~~209~~ 194 + ~~171~~ ~~167~~ 151 = ~~391~~ ~~380~~ ~~376~~ ~~361~~ 345 bytes
### Update:
Removed useless `noStroke()` and made both for-loops one-statementers.
Removed useless `image(p,0,0);`, gave the decryptor the filename as the parameter
### Encryption Algorithm
```
void g(String h){int s=ceil(sqrt(h.length()));for(int y=0,x;y<s;y++)for(x=0;x<s;rect(x,y,1,1),x++)stroke(h.length()>y*s+x?h.charAt(y*s+x):32,random(255),random(255));get(0,0,s,s).save("t.png");}
```
Calling the function: `g("Programming Puzzles and Code Golf");`
This is a function that takes in a String, and creates the output, before saving it as `t.png`. It uses the `red` value to store the hidden text.
### Decryption Algorithm
```
void u(String f){PImage p=loadImage(f);f="";for(int j=0,i;j<p.height;j++)for(i=0;i<p.width;i++)f+=(char)red(p.get(i,j));print(f.replaceAll(" +$",""));}
```
Call function by: `u(file_name);`
This is also a function that searches for the image specified by the parameter, and then outputs the hidden string (since it is shorter than returning a string).
### Expanded code
*(Encryption Algorithm)*
```
void g(String h) {
int s=ceil(sqrt(h.length()));
for(int y=0,x;y<s;y++)
for(x=0;x<s;rect(x,y,1,1),x++)
stroke(h.length()>y*s+x?h.charAt(y*s+x):32,random(255),random(255));
get(0,0,s,s).save("t.png");
}
```
The string is passed when the function is called. The first line of the function calculates the side length of the square by taking the `ceil` of its square root. Then we enter a for-loop, where we set the `stroke` (the colour of the edge) to have the ASCII value of the character as red, and random values for blue and green. After we do this, we create a `rect` (rectangle) with width = `1` and height = `1`, ie a pixel (for some weird reason, I can't use `point` properly). In the last line, the resulting image is then saved as `t.png`.
*(Decryption Algorithm)*
```
void u(String f) {
PImage p=loadImage(f);
f="";
for(int j=0,i;j<p.height;j++)
for(i=0;i<p.width;i++)
f+=(char)red(p.get(i,j));
print(f.replaceAll(" +$",""));
}
```
This function has the name of the file as the parameter (as a string). Then the image in the file is stored in a variable to be used later. After we are done with that, we set the string to `""` instead of creating a new string just to hold the hidden string. Then we iterate through the image via two nested for-loops, and we add on to the string the character value of the red value of the pixel. Finally, we print the resulting string after removing leading spaces from it (using a regex). The reason we print the hidden text instead of returning it is because this way it is shorter and we save bytes.
---
Encrypted challenge raw text:
[](https://i.stack.imgur.com/sYepJ.png)
[Answer]
# Jelly, 40 + 20 = 60 bytes in Jelly's codepage
Encoder (text → image):
```
”#;;ØHX¤¥4¡
»⁶x⁹²¤¤Ob⁴‘ịØHÇ€sj€”,Y
L½Ċç@
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCdIzs7w5hIWMKkwqU0wqEKwrvigbZ44oG5wrLCpMKkT2LigbTigJjhu4vDmEjDh-KCrHNq4oKs4oCdLFkKTMK9xIrDp0A&input=&args=UHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZSBHb2xm&debug=on)
Decoder (image → text):
```
ḣ2ØHiЀ’ḅ⁴Ọ
ṣ”#Ç€œr⁶
```
[Try it online!](http://jelly.tryitonline.net/#code=4bijMsOYSGnDkOKCrOKAmeG4heKBtOG7jArhuaPigJ0jw4figqzFk3LigbY&input=&args=IzUwNDIxOSwjNzIwMjAwLCM2RjM4RjEsIzY3MDU1RiwjNzIyOEM3LCM2MUFDOTUKIzZERDc5NywjNkQyMENCLCM2OTYyRkEsIzZFNjlCMSwjNjdDNDFDLCMyMDk0MzYKIzUwQ0IxOSwjNzVDOUZDLCM3QTFCMDYsIzdBNjk1QiwjNkM1RDVCLCM2NTM5QTYKIzczNTkyNSwjMjBDODBGLCM2MTJDMzgsIzZFQkY5RSwjNjRDNzlFLCMyMDA5MTUKIzQzMzdDNSwjNkY0NzA0LCM2NEZCNUYsIzY1QjJEMSwjMjBFMDc1LCM0N0JDN0MKIzZGMEMxNiwjNkNEOEVGLCM2NjA2MEIsIzIwM0M2QywjMjBENkU5LCMyMEMwRDc&debug=on)
An example output the program could produce (it stores information in the red channel):
```
#504219,#720200,#6F38F1,#67055F,#7228C7,#61AC95
#6DD797,#6D20CB,#6962FA,#6E69B1,#67C41C,#209436
#50CB19,#75C9FC,#7A1B06,#7A695B,#6C5D5B,#6539A6
#735925,#20C80F,#612C38,#6EBF9E,#64C79E,#200915
#4337C5,#6F4704,#64FB5F,#65B2D1,#20E075,#47BC7C
#6F0C16,#6CD8EF,#66060B,#203C6C,#20D6E9,#20C0D7
```
In these larger challenges, Jelly's terseness starts to drop off a bit, needing several "structural" characters to resolve parsing ambiguities, but it's nonetheless still very terse. Here's how the encoder works:
```
Subroutine 1: convert digits to randomly padded hex string
”#;;ØHX¤¥4¡
”#; prepend #
ØHX random hexadecimal digit
¤ parse ØH and X as a unit
; append
¥ parse ; and ØHX¤ as a unit
4¡ repeat four times
Subroutine 2: convert string λ to square with size ρ
»⁶x⁹²¤¤Ob⁴‘ịØHÇ€sj€”,Y
⁶ space
⁹² ρ squared
¤ parse ⁹² as a unit
x repeat string (i.e. ρ² spaces)
¤ parse ⁶x⁹²¤ as a unit
» take maximum
Because space has the lowest value of any printable ASCII character,
this has the effect of padding λ to length ρ² with spaces.
O take codepoints of string
b⁴ convert to base 16
ịØH use as indexes into a list of hexadecimal digits
‘ 0-indexed (Jelly uses 1-indexing by default)
Ç€ run subroutine 1 on each element
s split into groups of size ρ
€ inside each group
j ”, join on commas
Y join on newlines
Main program: basically just calculates ρ and lets subroutine 2 do the work
L½Ċç@
L length of input
½ square rooted
Ċ rounded up to the next highest integer
ç@ call subroutine 2 with the original input and the above
```
And here's how the decoder works:
```
Subroutine: convert hexadecimal color string (without #) to character
ḣ2ØHiЀ’ḅ⁴Ọ
ḣ2 take first two characters
ØHi find indexes in a string of hexadecimal digits
Ѐ for each of those characters
’ 0-indexed (Jelly uses 1-indexing by default)
ḅ⁴ convert from base 16
Ọ convert integer to character
Main program:
ṣ”#Ç€œr⁶
ṣ”# split on # signs
Ç€ run the subroutine for each element
œr⁶ remove spaces from the right
```
] |
[Question]
[
We'll define the **ASCII Odd/Even Cipher** via the below pseudocode:
```
Define 'neighbor' as the characters adjacent to the current letter in the string
If the one of the neighbors is out of bounds of the string, treat it as \0 or null
Take an input string
For each letter in the string, do
If the 0-based index of the current letter is even, then
Use the binary-or of the ASCII codes of both its neighbors
Else
If the ASCII code of the current letter is odd, then
Use the binary-or of itself plus the left neighbor
Else
Use the binary-or of itself plus the right neighbor
In all cases,
Convert the result back to ASCII and return it
If this would result in a code point 127 or greater to be converted, then
Instead return a space
Join the results of the For loop back into one string and output it
```
For example, for input `Hello`, the output is `emmol`, since
* The `H` turns to `\0 | 'e'` which is `e`
* The `e` turns to `'e' | 'l'`, or `101 | 108`, which is `109` or `m`
* The first `l` also turns to `101 | 108` or `m`
* The second `l` turns to `108 | 111`, which is `111` or `o`
* The `o` turns to `108 | \0`, or `l`
### Input
* A sentence composed solely of printable ASCII characters, in [any suitable format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* The sentence may have periods, spaces, and other punctuation, but will only ever be one line.
* The sentence will be at least three characters in length.
### Output
* The resulting cipher, based on the rules described above, returned as a string or output.
### The Rules
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
### Examples
Input on one line, output on the following. Blank lines separate examples.
```
Hello
emmol
Hello, World!
emmol, ww~ved
PPCG
PSWG
Programming Puzzles and Code Golf
r wogsmmoonpuu ~ meannncoooeggonl
abcdefghijklmnopqrstuvwxyz
bcfefgnijknmno~qrsvuvw~yzz
!abcdefghijklmnopqrstuvwxyz
aaccgeggoikkomoo qsswuww yy
Test 123 with odd characters. R@*SKA0z8d862
euutu133www|todddchizsscguwssr`jS{SK{z~|v66
```
[Answer]
# Perl, ~~63~~ 62 bytes
Includes +4 for `-lp`
Give input on STDIN
`oddeven.pl`:
```
#!/usr/bin/perl -lp
s%.%(--$|?$n|$':$&|(ord$&&1?$n:$'))&($n=$&,~v0)%eg;y;\x7f-\xff; ;
```
This works as shown, but to get the claimed score this must be put in a file ***without*** final `;` and newline and the `\xhh` escapes must be replaced by their literal values. You can do this by putting the code above in the file and running:
```
perl -0pi -e 's/\\x(..)/chr hex $1/eg;s/;\n$//' oddeven.pl
```
[Answer]
# Python 2, ~~138~~ 131 bytes
```
s="\0%s\0"%input();r=''
for i in range(len(s)-2):L,M,R=map(ord,s[i:i+3]);a=i%2and[R,L][M%2]|M or L|R;r+=chr(a*(a<127)or 32)
print r
```
[**Try it online**](http://ideone.com/nuL9ew) (contains all test cases)
Less golfed:
```
def f(s):
s="\0%s\0"%s
r=''
for i in range(1,len(s)-1):
if i%2: # even (parity is changed by adding \x00 to the front)
a=ord(s[i-1]) | ord(s[i+1])
else: # odd
a=ord(s[i])
if a%2: # odd
a|=ord(s[i-1])
else: # even
a|=ord(s[i+1])
r+=chr(a if a<127 else 32)
print r
```
[**Try it online**](http://ideone.com/UqNMgo) (ungolfed)
I add `\x00` to both sides of the string so that I don't have to worry about that during bitwise or-ing. I loop along the string's original characters, doing bitwise operations and adding them to the result, following the rules for parity.
[Answer]
# C - 101 bytes
```
i,k;f(char*p){for(i=0;*p;++p,++i)putchar((k=i&1?*p&1?*p|p[-1]:*p|p[1]:i?p[-1]|p[1]:p[1])<127?k:' ');}
```
We don't even have to check if it's the last item in the string because strings in C are null-terminated.
# Explanation
Rather simple:
Use &1 to test for odd/evenness and ternary expressions to replace if/elses. Increment the char \*p to reduce the number of brackets required.
[Answer]
# Mathematica, 152 bytes
```
FromCharacterCode[BitOr@@Which[OddQ@Max@#2,#~Drop~{2},OddQ@#[[2]],Most@#,True,Rest@#]/._?(#>126&)->32&~MapIndexed~Partition[ToCharacterCode@#,3,1,2,0]]&
```
# Explanation
```
ToCharacterCode@#
```
Converts string to ASCII codes
```
Partition[...,3,1,2,0]
```
Partitions the ASCII codes to length 3, offset 1 partitions, with padded 0s.
```
...~MapIndexed~...
```
Applys a function for each partition.
```
Which[...]
```
`If...else if... else` in *Mathematica*.
```
OddQ@Max@#2
```
Checks whether the index (#2) is odd. (`Max` is for flattening); since *Mathematica* index starts at 1, I used `OddQ` here, not `EvenQ`
```
Drop[#,{2}]
```
Takes the ASCII codes of the left and right neighbors.
```
OddQ@#[[2]]
```
Checks whether the ASCII code of the corresponding character is odd.
```
Most@#
```
Takes the ASCII codes of the character and the left neighbor.
```
Rest@#
```
Takes the ASCII codes of the character and the right neighbor.
```
BitOr
```
Applys or-operation.
```
/._?(#>126&)->32
```
Replaces all numbers greater than 126 with 32 (space).
```
FromCharacterCode
```
Converts ASCII code back to characters and join them.
[Answer]
# Ruby ~~133~~ ~~128~~ ~~108~~ 106 bytes
Jordan helped me save 20 bytes and cia\_rana helped me save 2 bytes :)
```
->s{p s[-i=-1]+s.bytes.each_cons(3).map{|x,y,z|i+=1;a=i%2>0?x|z :y%2>0?y|x :y|z;a>126?' ':a.chr}*""+s[-2]}
```
`s` is taken as the input string.
Example output with `s="Test 123 with odd characters. R@*SKA0z8d862"`:
```
"euutu133www|todddchizsscguwssr`jS{SK{z~|v66"
```
---
**Explanation**
The above code is very unreadable so here is an explanation. The code is kind of hacky, I'm quit new to ruby so I bet there is a shorter way to do this :)
```
b=s[1] # for the first character we always use the right neighbour
# because `\0 | x` will always return x any way. 0 is the
# left neighbour and x is the right neigbour
s.bytes.each_cons(3).with_index{|c,i| # oh boy, first we convert the string to ascii with each_byte
# we then traverse the resulting array with three elements at
# a time (so for example if s equals "Hello", c will be equal
# to [72, 101, 108])
if (i+1) % 2 < 1 # if the middle letter (which is considered our current letter) is even
a = c[0] | c[2] # we use the result of binary-or of its neighbours
else
if c[1] % 2 > 0 # if the code of the current letter is odd
a = c[1] | c[0] # we use the result of binary-or of itself and its left neighbour
else
a = c[1] | c[2] # we use the result of binary-or of itself and its right neighbour
end
end
if a>126
b<<' ' # if the result we use is greater or equal to 127 we use a space
else
b<<a.chr # convert the a ascii value back to a character
end
}
p b+s[-2] # same as the first comment but now we know that x | \0 will always be x
# this time x is the last characters left neighbour
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~33~~ 31 bytes
```
2ịḂị|2\
|ṚḢ,Ç
O0,0jṡ3µÇ€⁸JḂ¤ị"Ọ
```
A straight-forward approach that can surely be made shorter.
[Try it online!](http://jelly.tryitonline.net/#code=MuG7i-G4guG7i3wyXAp84bma4biiLMOHCk8wLDBq4bmhM8K1w4figqzigbhK4biCwqThu4si4buM&input=&args=J1Byb2dyYW1taW5nIFB1enpsZXMgYW5kIENvZGUgR29sZic)
[Answer]
# J, 42 bytes
```
4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u:
```
Uses the property that verbs in J can be applied in an alternating fashion using a gerund ``` for certain adverbs such as infix `\`.
## Usage
```
f =: 4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u:
f 'Hello'
emmol
f 'Hello, World!'
emmol,ww~ved
f 'PPCG'
PSWG
f 'Programming Puzzles and Code Golf'
rwogsmmoonpuu~meannncoooeggonl
f 'abcdefghijklmnopqrstuvwxyz'
bcfefgnijknmno~qrsvuvw~yzz
f '!abcdefghijklmnopqrstuvwxyz'
aaccgeggoikkomooqsswuwwyy
f 'Test 123 with odd characters. R@*SKA0z8d862'
euutu133www|todddchizsscguwssr`jS{SK{z~|v66
```
## Explanation
```
4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u: Input: string S
3&u: Convert each char to an ordinal
0, Prepend 0
0,~ Append 0
3 \ For each slice of size 3
( )` For the first slice (even-index)
{: Get the tail
{. Get the head
OR Bitwise OR the head and tail
`( ) For the second slice (odd-index)
|. Reverse the slice
2: \ For each pair
OR/ Reduce using bitwise OR
1&{ Get the middle value of the slice
2| Take it modulo 2
{ Index into the bitwise OR pairs and select
Repeat cyclically for the remaining slices
4:u: Convert each ordinal back to a char and return
```
[Answer]
## JavaScript (ES6), ~~125~~ ~~118~~ 114 bytes
Embarrassingly long, but `charCodeAt` and `String.fromCharCode` alone are 29 bytes. :-/
```
s=>[...s].map((_,i)=>String.fromCharCode((x=(C=i=>s.charCodeAt(i))((i-1)|1)|C(i+1-2*(C(i)&i&1)))>126?32:x)).join``
```
### How it works
Each character at position `i` is translated with the following formula, which covers all rules at once:
```
C((i - 1) | 1) | C(i + 1 - 2 * (C(i) & i & 1))
```
where `C(n)` returns the ASCII code of the n-th character of the input string.
### Demo
```
let f =
s=>[...s].map((_,i)=>String.fromCharCode((x=(C=i=>s.charCodeAt(i))((i-1)|1)|C(i+1-2*(C(i)&i&1)))>126?32:x)).join``
console.log(f("Hello"));
console.log(f("Hello, World!"));
console.log(f("PPCG"));
console.log(f("Programming Puzzles and Code Golf"));
console.log(f("abcdefghijklmnopqrstuvwxyz"));
console.log(f("!abcdefghijklmnopqrstuvwxyz"));
console.log(f("Test 123 with odd characters. R@*SKA0z8d862"));
```
[Answer]
# PHP, ~~107~~ 97 bytes
probably golfable.
```
for(;$i<strlen($s=$argv[1]);$i++)echo chr(ord($s[$i-1+$i%2])|ord($s[$i+1-2*($i&ord($s[$i])&1)]));
```
[Answer]
# C#, 145 bytes
```
s=>{var r=s[1]+"";int i=1,l=s.Length,c;for(;i<l;i++){c=i>l-2?0:s[i+1];c=i%2<1?s[i-1]|c:s[i]|(s[i]%2>0?s[i-1]:c);r+=c>'~'?' ':(char)c;}return r;};
```
Full program with ungolfed method and test cases:
```
using System;
namespace ASCIIOddEvenCipher
{
class Program
{
static void Main(string[] args)
{
Func<string,string>f= s=>
{
var r = s[1] + "";
int i = 1, l = s.Length, c;
for(;i < l; i++)
{
c = i>l-2 ? 0 : s[i+1];
c = i%2<1 ? s[i-1]|c : s[i]|(s[i]%2>0 ? s[i-1] : c);
r += c > '~' ? ' ' : (char)c;
}
return r;
};
//test cases:
Console.WriteLine(f("Hello")); //emmol
Console.WriteLine(f("Hello, World!")); //emmol, ww~ved
Console.WriteLine(f("PPCG")); //PSWG
Console.WriteLine(f("Programming Puzzles and Code Golf")); //r wogsmmoonpuu ~ meannncoooeggonl
Console.WriteLine(f("abcdefghijklmnopqrstuvwxyz")); //bcfefgnijknmno~qrsvuvw~yzz
Console.WriteLine(f("!abcdefghijklmnopqrstuvwxyz")); //aaccgeggoikkomoo qsswuww yy
Console.WriteLine(f("Test 123 with odd characters. R@*SKA0z8d862")); //euutu133www|todddchizsscguwssr`jS{SK{z~|v66
}
}
}
```
This turned out to be longer than I thought...
] |
[Question]
[
[](https://i.stack.imgur.com/QDFZn.png)
This geometric spiral looks complicated, but it's fairly simple to draw; take the following box:
[](https://i.stack.imgur.com/Xfuu0.png)
Draw a straight line between the corner of the box and some set distance above the next corner counter-clockwise.
[](https://i.stack.imgur.com/0lOvI.png)
Continue this pattern inward, always staying that set distance away from the corner of the next line. Here's a few more lines in.
[](https://i.stack.imgur.com/I396r.png)
As you can see, as the pattern continues, the spiral approaches the center and the boxes you draw begin to rotate. Note that the distance remains constant, regardless of angle.
## The Challenge
[The Inspiration](https://www.youtube.com/watch?v=S7DxlebZcrk) (and also thanks to the wonderful person who introduced me to this concept <3)
Given a numerical (possibly fractional) input from 1 to 25, write an image to disk that uses this pattern or display the output on the screen, where the distance from each corner is the distance of one initial side of the box divided by the input. Continue the pattern inward until the distance from the corner specified is longer than the length of the next side.
## Rules
* You may not use built-ins for this spiral creation, but you may use image processing builtins.
* If you write to disk, you must output an image in any of .jpg, .gif, .tiff, .pbm, .ppm, and .png.
* The initial side length must be at least 500 pixels.
* The initial corner may be whichever you choose.
* As always, [the Standard Loopholes](http://meta.codegolf.stackexchange.com/q/1061/44713) are disallowed.
[Answer]
# [Shoes](http://shoesrb.com/) (Ruby) 163 bytes
Shoes is a ruby-based GUI toolkit.
```
Shoes.app{n=ask('').to_f
r=s=5E2
a=[0,s*i="i".to_c,s*i+s,s,0]
(q=a[-3]-a[-4]
r=q.abs/s*n
a<<a[-4]+q/r)while r>1
1.upto(a.size-1){|j|line *(a[j-1].rect+a[j].rect)}}
```
**Ungolfed**
```
Shoes.app{
n=ask('').to_f #Open a dialog box with no message, get n from user
r=s=5E2 #Initialize s to sidelength=500. r can be initialized to any vale, we use the same one for convenience.
a=[0,s*i="i".to_c,s*i+s,s,0] #intialize array a with 5 points needed to draw a square, in complex number format (first point=0 is duplicated.)
(
q=a[-3]-a[-4] #find the vector from point plotted 4 before to the following point (plotted 3 before)
r=q.abs/s*n #r is the scale factor
a<<a[-4]+q/r #add a new point derived from a[-4] by moving toward a[-3] by a distance s/n
)while r>1 #break loop when length of line is less than s/n
1.upto(a.size-1){|j| #for all points except 1st and last one
line *(a[j-1].rect+a[j].rect)#take the two complex numbers correspondimg to the current and previous point,
} #convert to 2-element arrays (rectangular coordinates
} #combine to make a 4-element array, use * to splat into 4 parameters, and draw using the line method.
```
**Outputs n=4 and n=25**
[](https://i.stack.imgur.com/1SD6N.png)
Note that the shape always ends in a triangle, which collapses further to a line. Replacing `size-1` with `size` makes no difference to the appearance of the output and would save 2 bytes, but I left it in for theoretical correctness.
**Output n=300**
Inspired by a comment by OP, the higher numbers do look great!
[](https://i.stack.imgur.com/5Ma07.png)
[Answer]
# Java, ~~1056~~ ~~1005~~ ~~985~~ ~~948~~ ~~522~~ ~~508~~ ~~507~~ ~~504~~ ~~502~~ ~~501~~ ~~493~~ ~~492~~ ~~488~~ ~~474~~ ~~465~~ 458 bytes
```
import java.awt.*;interface G{static void main(String[]a){new Frame(){int s=499,o=s,e,i,x,y;{o/=new Float(a[0]);add(new Component(){public void paint(Graphics g){g.drawRect(0,0,s,s);int[]p={s,s,s,0,0,0,0,s};for(double d=s,t;d>o;t=o/d,i=e*2,x=(int)((1-t)*p[i]+t*p[(2+i)%8]+.5),y=(int)((1-t)*p[1+i]+t*p[(3+i)%8]+.5),g.drawLine(p[(6+i)%8],p[(7+i)%8],x,y),p[i]=x,p[1+i]=y,e=++e%4,i=e*2,x=p[(2+i)%8]-p[i],y=p[(3+i)%8]-p[1+i],d=Math.sqrt(x*x+y*y));}});show();}};}}
```
Thanks to CoolestVeto and ECS for yet other ways to reduce size. :-)
[Answer]
# Groovy, ~~412~~ ~~411~~ ~~403~~ 398 bytes
```
import java.awt.*
new Frame(){
def s=499,o=s/(args[0]as float),e=0,i,a,b,d,t
{add new Component(){void paint(Graphics g){g.drawRect 0,0,s,s
p=[s,s,s,0,0,0,0,s]
for(d=s;d>o;d=Math.sqrt(a*a+b*b)){t=o/d
i=e*2
a=(int)((1-t)*p[i]+t*p[(2+i)%8]+0.5)
b=(int)((1-t)*p[1+i]+t*p[(3+i)%8]+0.5)
g.drawLine p[(6+i)%8],p[(7+i)%8],a,b
p[i]=a
p[1+i]=b
e=++e%4
i=e*2
a=p[(2+i)%8]-p[i]
b=p[(3+i)%8]-p[1+i]}}}
show()}}
```
] |
[Question]
[
Create a Pascal's Triangle that is a nested list and contains zeros in the unused spots.
In the output array, the numbers of Pascal's Triangle are separated by zeroes and padded by zeroes on each side so that they are centered. For example, the bottom row (last sub-array) must have no zeroes on the left and the right; the second-last sub-array has one zero padding on each side, and so on.
Here is the output for input `5`:
```
[[0,0,0,0,1,0,0,0,0],
[0,0,0,1,0,1,0,0,0],
[0,0,1,0,2,0,1,0,0],
[0,1,0,3,0,3,0,1,0],
[1,0,4,0,6,0,4,0,1]]
```
As usual, the solution with the fewest bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
Nr=0ṙ-,1S$³Ð¡
```
[Try it online!](https://tio.run/##y0rNyan8/9@vyNbg4c6ZujqGwSqHNh@ecGjh////TQE "Jelly – Try It Online")
### Explanation
```
Nr Get the range [-n -n+1 ... 0 ... n-1 n].
=0 Logical NOT the entire range: [0 0 ... 1 ... 0 0].
$³Ð¡ Repeat n times, and cumulate the results:
·πô-,1 Rotate by both -1 and 1
S Sum the results.
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~20~~ 17 bytes
*-3 bytes thanks to/inspired by [ovs](https://codegolf.stackexchange.com/users/64121/ovs)*
```
{(¬´+¬ª)‚çüùï©0=1‚Üì‚àæÀúùï©}‚Üï
```
Anonymous function that takes an integer and returns a list of lists. [Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjCqyvCuynijZ/wnZWpMD0x4oaT4oi+y5zwnZWpfeKGlQoKPkYgNQ==)
[Answer]
# Mathematica, ~~70~~ 68 bytes
```
NestList[ListConvolve[{1,0,1},#,2]&,Join[#,{1},#],#2]&[0~Table~#,#]&
```
Similar to the MATL solution.
[Answer]
# Mathematica, 48 bytes
```
CellularAutomaton[{#+#3&@@#&,{},1},{{1},0},#-1]&
```
---
`CellularAutomation` is fantastic.
[Answer]
## Haskell, 66 bytes
```
q n|d<-0<$[2..n]=scanl(\(s:t)_->zipWith(+)(0:s:t)$t++[0])(d++1:d)d
```
Usage example: `q 4` -> `[[0,0,0,1,0,0,0],[0,0,1,0,1,0,0],[0,1,0,2,0,1,0],[1,0,3,0,3,0,1]]`.
How it works:
```
d <- 0<$[2..n] -- bind d to a list of (length n)-1 zeros
scanl -- build a list
(d++1:d) -- starting with [d ++ 1 ++ d]
\(s:t)_ d -- by combining the previous element with the
-- elements of d, but ignoring them, i.e.
-- build a list of (length d) by repeatedly
-- modifying the start element by
zipWith(+) -- adding element-wise
(0:s:t) -- the previous element prepended by 0
t++[0] -- and the tail of the previous element
-- followed by a 0
```
[Answer]
# Python 3, ~~172~~ ~~158~~ 133 bytes
```
def p(n):
x=2*n+1;y=range
a=[[0]*x]*n;a[0][n]=1
for i in y(1,n+1):
for j in y(x):a[i][j]=a[i-1][j-1]+a[i-1][(j+1)%(x)]
return a
```
Keeps getting better
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~24~~ ~~22~~ 21 bytes
```
tEq:=Gq:"t5BX+8L)]N$v
```
*EDIT (May 20, 2016): as of version 18.0.0 of the language, the above code needs a few changes to run. The link below includes those modifications*
[**Try it online!**](http://matl.tryitonline.net/#code=dEVxOj1HcToidDVCWSs2TClddg&input=OQ)
This uses a loop to push each new row onto the stack. A new row is computed from the previous row applying convolution with `[1,0,1]` and keeping only the desired size. After the loop, all rows are concatenated into a 2D array, which is displayed. 2D array are displayed in MATL as column-aligned numeric tables.
```
t % implicit input n. Duplicate
Eq % 2*n-1
: % range [1,2,...,2*n-1]
= % gives [0,0,...1,...0,0]. This is the first row
Gq: % range [1,2,...,n-1]
" % for each. Repeat n-1 times
t % duplicate latest row. This duplicate will become the next row
5B % push array [1,0,1] (5 converted to binary)
X+ % convolution
8L % predefined literal [2,-1i]. Used for indexing
) % apply that index: remove one element at each end
] % end for each
N$v % concatenate all rows into a 2D array. Implicitly display
```
[Answer]
# [PHP](https://php.net/), 106 bytes
```
for(;$r++<$a=$argn;)for($c=-$a;++$c<$a;)$t[$r][$c]=$r>1|$c?$t[$r-1][$c-1]+$t[$r-1][$c+1]?:0:1;print_r($t);
```
[Try it online!](https://tio.run/##TcwxC4MwEAXg3Z8hNxgOoRm6eKYZxKFLu3STEEKw6pKEI2PpX0/VqcuD9z14aU2l12lN1cwc2fKcIuctLM13tI/n6z6MgipwvARVX2sq78gNASP24NTpJA4Dr1pwhAh@X0hAnoDNBN4o4Jv8gNcntfLAPfGvojS6u3SSEm8h2/0tCyrlBw "PHP – Try It Online")
[Answer]
# Javascript, ~~152~~ 146 bytes
```
f=i=>[...Array(i)].map((x,j)=>(z=[...Array(i*2-1)].map((_,k)=>+!!~[i-j,i+j].indexOf(k+1)),y=j?z.map((_,k)=>_||(k&&(k+1 in y)?y[k-1]+y[k+1]:_)):z))
```
```
f=i=>[...Array(i)].map(
(x,j)=>(
z=[...Array(i*2-1)].map(
(_,k)=>
+!!~[i-j,i+j]
.indexOf(k+1)
),
y=j?z.map(
(_,k)=>_||
(k&&(k+1 in y)?
y[k-1]+y[k+1]
:_)
):z
)
)
F=i=>JSON.stringify(f(+i)).replace(/],|^.|.(?=.$)/g,'$&\n')
I.oninput()
```
```
<input id=I onInput="O.innerHTML=F(I.value)" value=5><pre id=O>
```
[Answer]
## Seriously, 33 bytes
```
╩╜r`╣;lD0nkdZΣ`M╜rRZ`i0nkd@;)kΣ`M
```
[Try it online](http://seriously.tryitonline.net/#code=4pWp4pWccmDilaM7bEQwbmtkWs6jYE3ilZxyUlpgaTBua2RAOylrzqNgTQ&input=NQ)
I'm relatively certain at least 7 or so of those bytes can be shaved off, so I'm going to wait to post an explanation until I'm done golfing this further.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~27~~ 26 bytes
```
~l{h1&jb}≜!{ẉ&h0&⟨↺z↻⟩+ᵐ↰}
```
Outputs N lists, separated by newlines. [Try it online!](https://tio.run/##ATkAxv9icmFjaHlsb2cy//9@bHtoMSZqYn3iiZwhe@G6iSZoMCbin6jihrp64oa74p@pK@G1kOKGsH3//zU "Brachylog – Try It Online")
### Explanation
This was harder than I expected. :P
```
~l{h1&jb}≜!{ẉ&h0&⟨↺z↻⟩+ᵐ↰}
~l Create a list whose length equals the input
{ } Apply this predicate to it:
h1 The first element of the list is 1
& and the list
j concatenated to itself
b with the first element removed
is the output of this predicate
Based on the order in which Brachylog tries possibilities,
the first list that satisfies these criteria will be
a list of N-1 zeros, a one, and N-1 more zeros
‚âú Instantiate that list
! Cut: prevents backtracking past this point
{ } Apply this recursive predicate:
ẉ Write the list with a newline
& and
h0 The first element of the list must be 0
& and
⟨↺ Take the list rotated left one place
↻⟩ and the list rotated right one place
z and zip them together
+ᵐ Sum each of the resulting pairs
This generates the next row from the current
row, failing once the nonzero numbers reach the edge
of the list
↰ Call the predicate again with this new list as input
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes
```
n->[Vecrev((x+1/x)^i*x^n,2*n+1)|i<-[0..n--]]
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XLjosNbkotUxDo0LbUL9CMy5TqyIuT8dIK0/bULMm00Y32kBPL09XNzb2f0FRZl6JRpqGqabmfwA "Pari/GP – Try It Online")
] |
[Question]
[
When I was younger, I use to play a word game called [Word chain](https://en.m.wikipedia.org/wiki/Word_chain). It was very simple. The first player chooses a word; the next player says another word that starts with the same letter the previous word ended with. This goes on forever until somebody gives up! Trick is, you cannot use the same word twice (unless everybody forgot that word was even used!). Usually we play with a certain topic to make it harder. But now, I want you to make a program to do this for me.
## Challenge
Write a full program or function to find all longest possible word chains using a given set of words and start word.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!
### Input
There are two inputs: a list and a start word. The start word will not be in the list. The inputs are all lowercase ASCII, and the list will not contain duplicate words.
### Output
All sequences of words from the list such that:
* The start word is the first word in the sequence.
* Each subsequent word starts with the same letter as the last letter of the previous word.
* The length of the sequence is the **longest possible**.
If there are multiple longest sequences, output all of them.
The sequence does not necessarily need to contain all of the list words. Sometimes that is not possible (see testcases). Again, no word can be used twice!
**Testcases**
```
In: [hello, turtle, eat, cat, people] artistic
Out: [artistic, cat, turtle, eat]
In: [lemonade, meatball, egg, grape] ham
Out: [ham, meatball, lemonade, egg, grape]
In: [cat, cute, ewok] attic
Out: [attic, cute, ewok]
In:[cat, cute, ewok, kilo, to, otter] attic
Out: [attic, cute, ewok, kilo, otter]
In:[cat, today, yoda, attic] ferret
Out: [ferret, today, yoda, attic, cat]
In: [cancel, loitering, gnocchi, improv, vivic, child, despair, rat, tragic, chimney, rex, xylophone] attic
Out: [[attic, child, despair, rat, tragic, cancel, loitering, gnocchi, improv, vivic, chimney], [attic, cancel, loitering, gnocchi, improv, vivic, child, despair, ra', tragic, chimney]]
In: [cat, today, yoda, artistic, cute, ewok, kilo, to, otter] attic
Out: [attic, cat, today, yoda, artistic, cute, ewok, kilo, otter]
```
[Answer]
# Pyth, ~~25~~ 23 bytes
```
.MlZfqhMtTeMPT+Lzs.pMyQ
```
[Test suite](https://pyth.herokuapp.com/?code=.MlZfqhMtTeMPT%2BLzs.pMyQ&test_suite=1&test_suite_input=attic%0A%5B%22cat%22%2C+%22cute%22%2C+%22ewok%22%2C+%22kilo%22%2C+%22to%22%2C+%22otter%22%5D%0Aattic%0A%5B%22cat%22%2C+%22today%22%2C+%22yoda%22%2C+%22to%22%2C+%22otter%22%5D+&debug=0&input_size=2)
A brute force solution. Far too slow for some of the larger test cases.
Input in the form:
```
attic
["cat", "today", "yoda", "to", "otter"]
```
Output in the form:
```
[['attic', 'cat', 'today', 'yoda'], ['attic', 'cat', 'to', 'otter']]
```
**Explanation:**
```
.MlZfqhMtTeMPT+Lzs.pMyQ
Q = eval(input()) (The list of words)
z = input() (The starting word)
yQ All subsets of the input.
.pM All permutations of the subsets.
s Flatten.
+Lz Add the starting word to the front of each list.
This is all possible sequences.
f Filter on
q The equality of
hMtT The first character of each word but the first
eMPT The last character of each word but the last
.MlZ Take only the lists of maximal length.
```
[Answer]
# JavaScript (ES6), 164 bytes
```
f=(l,s,r=[[]])=>l.map((w,i)=>w[0]==s.slice(-1)&&(x=l.slice(),x.splice(i,1),o=f(x,w),a=o[0].length,b=r[0].length,r=a>b?o:a<b?r:r.concat(o)))&&r.map(q=>[s].concat(q))
```
## Explanation
A recursive function that checks how long the output list will for all possible choices.
Returns an array of arrays of words.
```
f=(l,s,r=[[]])=> // l = list, s = starting word, r is not passed (it is
// here so that it is not defined globally)
l.map((w,i)=> // for each word w at index i
w[0]==s.slice(-1)&&( // if the first letter is the same as the last letter:
x=l.slice(), // x = clone of the list of words
x.splice(i,1), // remove the current word
o=f(x,w), // get the list of words starting from the current word
a=o[0].length,
b=r[0].length,
r=a>b?o: // if o is longer, set r to o
a<b?r: // if o is shorter, keep r
r.concat(o) // if o is same, add it to r
)
)
&&r.map(q=>[s].concat(q)) // return a list of longest lists with the starting word
```
## Test
Default parameter not used in test to make it more cross-browser compatible.
```
f=(l,s,r)=>l.map((w,i)=>w[0]==s.slice(-1)&&(x=l.slice(),x.splice(i,1),o=f(x,w),a=o[0].length,b=r[0].length,r=a>b?o:a<b?r:r.concat(o)),r=[[]])&&r.map(q=>[s].concat(q))
```
```
Word list (space separated) = <input type="text" id="list" value="cancel loitering gnocchi improv vivic child despair rat tragic chimney rex xylophone" /><br />
Starting word = <input type="text" id="word" value="attic" /><br />
<button onclick="result.textContent=f(list.value.split(' '),word.value).join('\n')">Go</button>
<pre id="result"></pre>
```
[Answer]
## Python, 104
```
def f(d,w):
a=[[w]]
while a:b=a;a=[x+[y]for x in a for y in set(d)-set(x)if x[-1][-1]==y[0]]
return b
```
I think it should work now...
[Try it online](https://ideone.com/g4UMcr).
[Answer]
# Perl 5 , 275 bytes
Probably not golfed as much as it can be, but, hey, it's nonwinning anyway, right?
```
use List::Util max;use List::MoreUtils uniq,before;use Algorithm::Permute permute;$i=pop;permute{push@c,[@ARGV]}@ARGV;for$c(@c){unshift@$c,$i;push @{$d{before{(substr$c->[$_],-1)ne(substr$c->[1+$_],0,1)}keys$c}},$c}for$m(max keys%d){say for uniq map{"@$_[0..$m+1]"}@{$d{$m}}}
```
Use it thus:
```
$ perl -M5.010 chain.pl cat tin cot arc
arc cat tin
arc cot tin
```
Warning! Use of this script on a long list requires lots of memory! It worked great for me on seven (six plus the extra one) but not on thirteen (twelve plus one).
It removes the final input, generates an array of arrayrefs, where the arrayrefs are all the permutations, and adds the initial word back on at the start. Then it pushes each such permutation onto another arrayref which is the value of a hash with key the amount of the array that has the chaining property desired. It then finds the maximum such key and prints out all the arrays.
[Answer]
## C, 373 bytes
```
g(char*y){printf("%s, ",y);}z(char*w){int i,k=-1,v=0,j=sizeof(c)/sizeof(c[0]);int m[j],b=0;for(i=0;i<j;i++){m[v++]=c[i][0]==w[strlen(w)-1]?2:1;if(u[i]==6)m[v-1]=1;if(strcmp(w,c[i]))k=i;}printf("%s",w);for(i=0;i<j;i++){if(m[i]!=1){if(v+i!=j){g(s);for(;b<j;b++){if(u[b]==6)g(c[b]);}}else printf(", ");u[i]=6;z(c[i]);u[i]=1;}else v+=-1;}if(k!=-1)u[k]=1;if(v==0)printf(" ; ");}
```
I believe there is probably a lot more golfing I could do here so I will probably update it.
De-golf
```
char *c[9]={"cat","today","yoda","artistic","cute","ewok","kilo","to","otter"};
u[9]={-1};
char *s="attic";
g(char*y){printf("%s, ",y);}
z(char*w){
int i,k=-1,v=0,j=sizeof(c)/sizeof(c[0]);
int m[j],b=0;
for(i=0;i<j;i++){
m[v++]=c[i][0]==w[strlen(w)-1]?i:-1;
if(u[i]==6)m[v-1]=-1;
if(strcmp(w,c[i]))k=i;
}
printf("%s",w);
for(i=0;i<j;i++){
if(m[i]!=-1){
if(v+i!=j){
g(s);
for(;b<j;b++){
if(u[b]==6)g(c[b]);
}
}else printf(", ");
u[i]=6;
z(c[i]);
u[i]=-1;
} else v+=-1;
}
if(k!=-1)u[k]=-1;
if(v==0)printf(" ; ");
}
main(){
z(s);
printf("\n");
return 0;
}
```
[Ideone link](http://ideone.com/e.js/JzWiTn) - If I didn't do this right just let me know :D
] |
[Question]
[
## Introduction
In this challenge, we will simulate a certain [probabilistic cellular automaton](https://en.wikipedia.org/wiki/Stochastic_cellular_automaton) using very bad pseudorandom numbers.
The cellular automaton is defined on binary strings by the following local rule.
Suppose that the left neighbor of a cell and the cell itself have states `a` and `b`.
* If `min(a,b) == 0`, then the new state of `b` is `max(a,b)`.
* If `min(a,b) == 1`, then the new state of `b` is chosen randomly from `{0,1}`.
The following picture shows one possible 10-step evolution of a single `1`.
```
1
11
101
1111
11001
101011
1111111
10001001
110011011
1010111101
```
Note how two adjacent `1`s sometimes evolve to `1`, and sometimes to `0`, and the border-most bits are always `1`s.
Your task is to produce a cellular automaton evolution of this form.
## Inputs
Your inputs are a positive integer `n`, denoting the number of rows to display, and a non-empty list of bits `L`, which we use as a source of randomness.
## Output
Your output is a list of lists or 2D array of bits, depicting the evolution of a single `1` for `n` time steps, as in the above figure.
You can pad the output with `0`s to get rows of equal lengths, if desired, but there must not be leading `0`s.
The random choices in the cellular automaton must be drawn from the list `L`, jumping back to the beginning when it is exhausted.
More explicitly, if the output is traversed one row at a time form top to bottom, left to right, then the successive random choices shall form the list `L` repeated as many times as necessary.
## Example
Suppose the inputs are `n = 7` and `L = [0,1,0]`.
Then the cellular automaton evolves as follows during the 7 steps, where we have put a `v` right above every random choice:
```
[1]
[1,1]
v
[1,0,1]
[1,1,1,1]
v v v
[1,1,0,0,1]
v
[1,1,1,0,1,1]
v v v
[1,0,0,1,1,1,1]
```
If we read all the bits marked with a `v`, we get `01001001`, which is `L` repeated 2.66 times.
The next random bit would be `0`.
## Rules and Scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
The exact format of the inputs and outputs is unimportant (within reason).
## Test Cases
Deterministic version, every random bit is `0`:
```
Inputs: 10 [0]
Output:
1
11
101
1111
10001
110011
1010101
11111111
100000001
1100000011
```
Every random bit is `1`:
```
Inputs: 6 [1,1]
Output:
1
11
111
1111
11111
111111
```
Pseudorandom versions:
```
Inputs: 10 [0,0,1]
Output:
1
11
101
1111
10101
111111
1010011
11110101
101011111
1111101001
Inputs: 10 [1,0,0,1]
Output:
1
11
111
1001
11011
111111
1001101
11010111
111111101
1011001111
Inputs: 15 [1,1,1,0,0,0]
Output:
1
11
111
1111
10001
110011
1110111
11011001
111111011
1100011111
11100100011
111101100101
1001111101111
11011000111111
101101001011101
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 139 bytes
```
^.
1
00:0 01:1 10:1 11:
(m`^(..)((\S*)(?<=0) .*)
$1$3#$1!$2
+m`(?<=^(?<-2>.)*(..).*?#(.)*.)\d!(.)(.*\1:)(.)(\d*)
$5$3!$4$6$5
)`!0
0
.+
<empty>
```
Where `<empty>` indicates that there is a trailing empty line. Each line goes in a separate file and the `#` should be replaced with linefeeds (0x0A).
Expects the input to be `n` in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) (made of zeroes, as in [Unary](http://esolangs.org/wiki/Unary)), followed by a space, followed by the "pseudo-random" string, e.g. `10, [1, 0, 0, 1]` would be read as
```
0000000000 1001
```
Output is as in the challenge, but padded with zeroes, e.g.
```
1000000000
1100000000
1110000000
1001000000
1101100000
1111110000
1001101000
1101011100
1111111010
1011001111
```
This was way trickier than I expected...
[Answer]
# Pyth, 33 bytes
```
jjLk.u++1m?hSde=.<Q1sd.:N2 1tvz]1
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=jjLk.u%2B%2B1m%3FhSde%3D.%3CQ1sd.%3AN2%201tvz%5D1&test_suite_input=10%0A%5B0%5D%0A6%0A%5B1%2C1%5D%0A10%0A%5B0%2C0%2C1%5D%0A10%0A%5B1%2C0%2C0%2C1%5D%0A15%0A%5B1%2C1%2C1%2C0%2C0%2C0%5D&input_size=2&test_suite=0&input=15%0A%5B1%2C1%2C1%2C0%2C0%2C0%5D) or [Test Suite](http://pyth.herokuapp.com/?code=jjLk.u%2B%2B1m%3FhSde%3D.%3CQ1sd.%3AN2%201tvz%5D1&test_suite_input=10%0A%5B0%5D%0A6%0A%5B1%2C1%5D%0A10%0A%5B0%2C0%2C1%5D%0A10%0A%5B1%2C0%2C0%2C1%5D%0A15%0A%5B1%2C1%2C1%2C0%2C0%2C0%5D&input_size=2&test_suite=1&input=15%0A%5B1%2C1%2C1%2C0%2C0%2C0%5D)
### Explanation:
```
jjLk.u++1m?hSde=.<Q1sd.:N2 1tvz]1 implicit: Q = input list
.u tvz]1 reduce N=[1] input-1 times by applying
.:N2 all substrings of length 2
m map each d of ^ to:
?hSd if min(d) = 0 then:
=.<Q1 rotate Q by one
e and use the last element
sd else use sum(d) (=max(d))
++1 1 add a 1 at the front and the back
.u gives all intermediate results
jLk join these lists to strings
j print each string on a line
```
[Answer]
# Python, ~~142~~ ~~135~~ ~~132~~ 131 bytes
### ~~133~~ ~~132~~ 131 byte version
```
f=input;n=f();L=f()*n*n;r=[1];i=1
while i<=n:print r;r=[L.pop(0)if r[x-1]&r[x]else r[x-1]+r[x]for x in range(1,i)];r=[1]+r+[1];i+=1
```
replaced `r[x-1]+r[x]>1` by `r[x-1]&r[x]` were the bitwise operator & yields the minimum value in `(r[x-1],r[x])`
Thanks @ThomasKwa for suggesting `n*n` instead of `n**2` which saves 1 byte!
Thanks @Shebang for the -1 byte
### 135 byte version
```
f=input;n=f();L=f()*n**2;r=[1];i=1
while i<=n:print r;r=[L.pop(0)if r[x-1]+r[x]>1 else r[x-1]+r[x]for x in range(1,i)];r=[1]+r+[1];i+=1
```
Thanks to @Cole for the -7 bytes:
`min(r[x-1],r[x])->r[x-1]+r[x]>1`
`max(r[x-1],r[x])->r[x-1]+r[x]`
### 142 byte version
```
f=input;n=f();L=f()*n**2;r=[1];i=1
while i<=n:print r;r=[L.pop(0)if min(r[x-1],r[x])else max(r[x-1],r[x])for x in range(1,i)];r=[1]+r+[1];i+=1
```
Not even close to @Jakube's answer but I had a lot of fun coding and golfing this one.
Expects two inputs: first input is the **number of rows** and second input is the **pseudorandomness source list**. It prints on console one row after another, each on a new line.
As an example:
```
10 # This is input
[0] # This is input
[1] <- First output row
[1, 1]
[1, 0, 1]
[1, 1, 1, 1]
[1, 0, 0, 0, 1]
[1, 1, 0, 0, 1, 1]
[1, 0, 1, 0, 1, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 0, 0, 0, 0, 0, 0, 1, 1]
```
### Now for a short explanation on how it works:
```
f=input;n=f();L=f()*n*n;r=[1];i=1 First we define the input() function as f
for saving bytes as we have to call it twice.
Then L is defined as a list made of the
pseudorandom numbers in their order *many* times
(were *many* is an upperbound of the canges that
could be done); r as the first row and i as the row
counter.
while i<=n:print r A while loop that exits when the nth row has been
calculated and the printing of the actual row.
r=[L.pop(0)if r[x-1]&r[x] else r[x-1]+r[x] for x in range(1,i)];r=[1]+r+[1];i+=1
^ ^ ^ ^
| | |Same as max(r[x-1],r[x]) | from 2nd to last element
| | Same as min(r[x-1],r[x]) (0->False;1->True)
| get random bit from pseudorandom list
```
The trick here is that we know that the bit list will always start and end with a `1` because the first and last elements are never modified due to the specs. of the question. That's the reason for the statement `[1]+r+[1]`.
But if `r` is initialized as `[1]`, there are no changes on the first row and then we add `[1]+r+[1]` how come the second row is not `[1,1,1]`?
This is due to the fact that on the first iteration `i=1` so `range(1,i)` returns an empty list and, as a result of the `for` in the list comprehension having nothing to iterate over `r` becomes an empty list so `[1]+r+[1]=[1,1]`. This just happens on the first iteration which is just ideal for us!
P.S: Feel free to make any suggestions on how to golf it more.
[Answer]
# MATLAB, 146 143 138
(Also works on Octave online, but you need to sign in to save the function in a file).
```
function o=c(n,L);o=zeros(n);o(:,1)=1;for i=2:n;for j=2:i;a=o(i-1,j-1);b=o(i-1,j);c=a|b;d=a&b;c(d)=L(d);L=circshift(L,-d);o(i,j)=c;end;end
```
The function takes an input `n` and `L`, and returns an array `o` which contains the output.
For the input values, `n` is a scalar, and `L` is a column vector, which can be specified in the format `[;;;]`. Not quite what you show, but you say it is flexible within reason and this seems so.
The output is formatted as an `n x n` array containing 0's and 1's.
And an explanation:
```
function o=c(n,L)
%Create the initial array - an n x n square with the first column made of 1's
o=zeros(n);o(:,1)=1;
%For each row (starting with the second, as the first is done already)
for i=2:n;
%For each column in that row, again starting with the second as the first is done
for j=2:i;
%Extract the current and previous elements in the row above
a=o(i-1,j-1); %(previous)
b=o(i-1,j); %(current)
%Assume that min()==0, so set c to max();
c=a|b;
%Now check if min()==1
d=a&b;
%If so, set c to L(1)
c(d)=L(d);
%Rotate L around only if min()==1
L=circshift(L,-d);
%And store c back to the output matrix
o(i,j)=c;
end;
end
```
---
Update: I have managed to optimise away the if-else statement to save a few bytes. The input format has once again changed back to column vector.
[Answer]
# Haskell, ~~153~~ 149 bytes
```
j[_]o l=(l,o)
j(a:u@(b:c))o q@(l:m)|a*b==0=j u(o++[a+b])q|1<2=j u(o++[l])m
k(r,a)=fmap((1:).(++[1]))$j a[]r
n%l=map snd$take n$iterate k(cycle l,[1])
```
`%` returns a list of bit lists. Usage example:
```
> 10 % [1,0,0,1]
[[1],[1,1],[1,1,1],[1,0,0,1],[1,1,0,1,1],[1,1,1,1,1,1],[1,0,0,1,1,0,1],[1,1,0,1,0,1,1,1],[1,1,1,1,1,1,1,0,1],[1,0,1,1,0,0,1,1,1,1]]
```
Oh dear! Carrying the random list `L` around is pure pain. Let's see if this can be shorter.
[Answer]
# C#, 152 bytes
There's nothing special here. The function returns a 2D array where the first rank is the line and the second is the column.
Indented and new lines for clarity:
```
int[,]F(int n,int[]l){
var o=new int[n,n];
for(int y=0,x,i=0,m;y<n;y++)
for(o[y,x=0]=1;x++<y;)
o[y,x]=(m=o[y-1,x-1]+o[y-1,x])<2?m:l[i++%l.Length];
return o;
}
```
[Answer]
# TI-BASIC, ~~106~~ ~~94~~ ~~87~~ ~~86~~ 87 bytes
```
Prompt N,B
"‚àüB(1+remainder(ùëõ,dim(‚àüB‚Üíu
{1
For(I,1,N
Disp Ans
augment({0},Ans)+augment(Ans,{0
Ans and Ans‚â†2+seq(u(ùëõ-(Ans(X)<2)+2dim(‚àüB)),X,1,dim(Ans
End
```
TI-BASIC doesn't have an increment operator, right? Well, it sort of does. The equation variable `u`, normally used with sequences, has an obscure feature: when `u` is called with an argument, the variable `ùëõ` is set to one greater than that argument. The conditional increment depends on this. (I've been waiting to use it for a long time.)
For list indexing to work properly, `ùëõ` must be its default value of 0, and `ùëõMin` should be its default 1, so either clear your calculator's RAM or set those values manually before running this.
`augment({0},Ans)+augment(Ans,{0` calculates a list of sums of two adjacent elements, so it will return a list of 0s, 1s, and 2s. Then the magic is on this line:
```
Ans and Ans‚â†2+seq(u(ùëõ-(Ans(X)‚â†2)+dim(‚àüB)),X,1,dim(Ans
Ans and ;set 0s to 0
Ans≠ ;set to 0 all sums that equal...
2+
seq(...,X,1,dim(Ans ;execute for each element of the list
u( ;return this element in list of bits (looping)
ùëõ ;current location in the list
-(Ans(X)≠2)+ ;subtract 1 if the element isn't 2
2dim(‚àüB) ;Add twice the dimension of the list
;(because n<nMin on the first iteration, it's out of the domain
;this prevents an error)
) ;set n to one greater than that value
;i.e. increment if element≠2
;Will equal Ans(X) iff Ans(X)=2 and the bit read false
```
The result of this line will be that list elements are 0 if they were 0 or if they were 2 and the bit read was 0.
```
Result of above line
n \ u | 0 | 1
0 0 0
```
Test case:
```
N=?7
B=?{0,1,0
{1}
{1 1}
{1 0 1}
{1 1 1 1}
{1 1 0 0 1}
{1 1 1 0 1 1}
{1 0 0 1 1 1 1}
Done
```
] |
[Question]
[
Consider a triangle *ABC* where each side has integer length (an *integral triangle*). Define a [median](https://en.wikipedia.org/wiki/Median_(geometry)) of *ABC* to be a line segment from a vertex to the midpoint of the opposing side. In the figure below, the red line segments represent the medians. Note that any given triangle has three medians.

Let *n* be some positive integer. How many non-degenerate integral triangles with each side length less than or equal to *n* have at least one integral median?
### Challenge
Write a program to compute the number of integral triangles with at least one integral median for a given maximum side length *n*. The order of the side lengths does not matter, i.e. <6,6,5> represents the same triangle as <5,6,6> and should be counted only once. Exclude degenerate triangles such as <1,2,3>.
### Scoring
The largest *n* for which your program can generate the number of triangles in **60 seconds** on my machine is your score. The program with the highest score wins. My machine is a Sony Vaio SVF14A16CLB, Intel Core i5, 8GB RAM.
### Examples
Let *T*(*N*) be the program with input *N*.
```
T(1) = 0
T(6) = 1
T(20) = 27
T(22) = 34
```
Note that *T*(1) = *T*(2) = *T*(3) = *T*(4) = *T*(5) = 0 because no combination of integral sides will yield an integral median. However, once we get to 6, we can see that one of the medians of the triangle <5,5,6> is 4, so *T*(6) = 1.
Note also that *T*(22) is the first value at which double-counting becomes an issue: the triangle <16,18,22> has medians 13 and 17 (and 2sqrt(85)).
### Computing the medians
The medians of a triangle can be calculated by the following formulas:



```
Current top score: Sp3000 - 7000 points - C
```
[Answer]
# C, brute force - n=6080
This is more a baseline than a serious contender, but at least it should get things started.
n=6080 is as high as I got in a minute of runtime on my own machine, which is a MacBook Pro with an Intel Core i5. The result I got for this value is:
>
> 15041226
>
>
>
The code is purely brute force. It enumerates all the triangles within the size limit, and tests for the condition:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
static inline int isSquare(int v) {
int s = (int)(sqrtf((float)v) + 0.5f);
return s * s == v;
}
static inline int isMedian(int v) {
return v % 4 == 0 && isSquare(v / 4);
}
int main(int argc, char* argv[]) {
int n = atoi(argv[1]);
int nTri = 0;
int a, b, c;
for (c = 1; c <= n; ++c) {
for (b = (c + 1) / 2; b <= c; ++b) {
for (a = c - b + 1; a <= b; ++a) {
if (isMedian(2 * (b * b + c * c) - a * a) ||
isMedian(2 * (a * a + c * c) - b * b) ||
isMedian(2 * (a * a + b * b) - c * c)) {
++nTri;
}
}
}
}
printf("%d\n", nTri);
return 0;
}
```
[Answer]
# C, approx ~~6650~~ 6900
```
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
static inline int is_square(int n) {
if ((n&2) != 0 || (n&7) == 5 || (n&11) == 8) {
return 0;
}
int s = (int) (sqrtf((float) n) + 0.5f);
return (s*s == n);
}
int main(int argc, char **argv) {
int n = atoi(argv[1]);
int count = 0;
for (int a = 1; a <= n; ++a) {
if (a&1) {
for (int b = (a+1)/2; b <= a; ++b){
if (b&1) {
for (int c = a-b+2; c <= b; c += 2) {
if (is_square((a*a + b*b)/2 - (c*c)/4)) {
++count;
}
}
} else {
for (int c = a-b+2; c <= b; c += 2) {
if (is_square((a*a + c*c)/2 - (b*b)/4)) {
++count;
}
}
}
}
} else {
for (int b = (a+1)/2; b <= a; ++b){
if (b&1) {
for (int c = a-b+2; c <= b; c += 2) {
if (is_square((b*b + c*c)/2 - (a*a)/4)) {
++count;
}
}
} else {
for (int c = a-b+2; c <= b; c += 2) {
if (is_square((b*b + c*c)/2 - (a*a)/4) ||
is_square((c*c + a*a)/2 - (b*b)/4) ||
is_square((a*a + b*b)/2 - (c*c)/4)) {
++count;
}
}
}
}
}
}
printf("%d\n", count);
return 0;
}
```
I don't really use C often, but with the amount of arithmetic going on it seemed like a good choice of language. The core algorithm is brute force like [@RetoKoradi's answer](https://codegolf.stackexchange.com/users/32852/reto-koradi), but with a few simple optimisations. I'm not sure our values are comparable though, because @RetoKoradi's computer seems to be faster than mine.
The major optimisation is bypassing the `% 4` check completely. An integer square `n*n` is either 0 or 1 modulo 4, depending on whether `n` itself is 0 or 1 modulo 2. Thus, we can take a look at all possibilities for `(x, y, z) % 2`:
```
x%2 y%2 z%2 (2*(x*x+y*y) - z*z) % 4
----------------------------------------
0 0 0 0
0 0 1 3
0 1 0 2
0 1 1 1
1 0 0 2
1 0 1 1
1 1 0 0
1 1 1 3
```
Conveniently, there are only two cases to consider: `(0, 0, 0)` and `(1, 1, 0)`, which, given the first two sides `a, b`, equates to the third side `c` having parity `a^b`:
```
a%2 b%2 c%2 must be
-----------------------------
0 0 0
0 1 1
1 0 1
1 1 0
```
`a^b` is the same parity as `a-b`, so rather than searching from `c = a-b+1` and going up by 1s, this lets us search from `c = a-b+2` and go up by 2s.
Another optimisation comes from the fact that, for the `(1, 1, 0)` case, we only need to call is\_square once since only one permutation works. This is special cased in the code by unrolling the search.
The other optimisation included is simply a quickfail in the `is_square` function.
Compilation was done with `-std=c99 -O3`.
*(Thanks to @RetoKoradi for pointing out that the `0.5` in is\_square needed to be `0.5f` to avoid a double conversion taking place.)*
[Answer]
# Felix, unknown
```
fun is_square(v: int) => let s = int$ sqrt$ v.float + 0.5f in s*s == v;
fun is_median(v: int) => v % 4 == 0 and (v/4).is_square;
proc main() {
n := int$ System::argv 1;
var ntri = 0;
for var c in 1 upto n do
for var b in (c+1)/2 upto c do
for var a in c - b + 1 upto b do
if is_median(2*(b*b+c*c)-a*a) or
is_median(2*(a*a+c*c)-b*b) or
is_median(2*(a*a+b*b)-c*c) do ++ntri; done
done
done
done
ntri.println;
}
main;
```
Basically a port of the C answer, but it's faster than it, tested with `clang -O3` and `icc -O3`. Felix and Nim are literally the only two languages I know of that can beat C and C++ at benchmarks. I'm working on a parallel version, but it'll be a bit till it's finished, so I decided to post this ahead.
I also put "unknown" because my computer isn't necessarily the fastest on earth...
Command used to build:
```
flx --usage=hyperlight -c --static -o sl0 sl0.flx
```
The generated C++ is pretty interesting to look at:
```
//Input file: /home/ryan/golf/itri/sl0/sl0.flx
//Generated by Felix Version 15.04.03
//Timestamp: 2015/7/16 20:59:42 UTC
//Timestamp: 2015/7/16 15:59:42 (local)
#define FLX_EXTERN_sl0 FLX_EXPORT
#include "sl0.hpp"
#include <stdio.h>
#define comma ,
//-----------------------------------------
//EMIT USER BODY CODE
using namespace ::flxusr::sl0;
//-----------------------------------------
namespace flxusr { namespace sl0 {
//-----------------------------------------
//DEFINE OFFSET tables for GC
#include "sl0.rtti"
FLX_DEF_THREAD_FRAME
//Thread Frame Constructor
thread_frame_t::thread_frame_t(
) :
gcp(0),
shape_list_head(&thread_frame_t_ptr_map)
{}
//-----------------------------------------
//DEFINE FUNCTION CLASS METHODS
#include "sl0.ctors_cpp"
//------------------------------
//C PROC <61624>: _init_
void _init_(FLX_APAR_DECL_ONLY){
int _i63436_v63436_s;
int _i63435_v63435_s;
int s;
int a;
int b;
int c;
int ntri;
int n;
n = static_cast<int>(::std::atoi((::std::string(1<0||1>=PTF argc?"":PTF argv[1])).c_str())); //assign simple
ntri = 0; //assign simple
c = 1; //assign simple
_63421:;
if(FLX_UNLIKELY((n < c))) goto _63428;
b = (c + 1 ) / 2 ; //assign simple
_63422:;
if(FLX_UNLIKELY((c < b))) goto _63427;
a = (c - b ) + 1 ; //assign simple
_63423:;
if(FLX_UNLIKELY((b < a))) goto _63426;
/*begin match*/
/*match case 1:s*/
s = static_cast<int>((::std::sqrt(((static_cast<float>(((2 * (b * b + (c * c ) ) - (a * a ) ) / 4 ))) + 0.5f ))))/*int.flx: ctor*/; //init
/*begin match*/
/*match case 1:s*/
_i63435_v63435_s = static_cast<int>((::std::sqrt(((static_cast<float>(((2 * (a * a + (c * c ) ) - (b * b ) ) / 4 ))) + 0.5f ))))/*int.flx: ctor*/; //init
/*begin match*/
/*match case 1:s*/
_i63436_v63436_s = static_cast<int>((::std::sqrt(((static_cast<float>(((2 * (a * a + (b * b ) ) - (c * c ) ) / 4 ))) + 0.5f ))))/*int.flx: ctor*/; //init
if(!((((2 * (b * b + (c * c ) ) - (a * a ) ) % 4 == 0) && (s * s == (2 * (b * b + (c * c ) ) - (a * a ) ) / 4 ) || (((2 * (a * a + (c * c ) ) - (b * b ) ) % 4 == 0) && (_i63435_v63435_s * _i63435_v63435_s == (2 * (a * a + (c * c ) ) - (b * b ) ) / 4 ) ) ) || (((2 * (a * a + (b * b ) ) - (c * c ) ) % 4 == 0) && (_i63436_v63436_s * _i63436_v63436_s == (2 * (a * a + (b * b ) ) - (c * c ) ) / 4 ) ) )) goto _63425;
{
int* _tmp63490 = (int*)&ntri;
++*_tmp63490;
}
_63425:;
if(FLX_UNLIKELY((a == b))) goto _63426;
{
int* _tmp63491 = (int*)&a;
++*_tmp63491;
}
goto _63423;
_63426:;
if(FLX_UNLIKELY((b == c))) goto _63427;
{
int* _tmp63492 = (int*)&b;
++*_tmp63492;
}
goto _63422;
_63427:;
if(FLX_UNLIKELY((c == n))) goto _63428;
{
int* _tmp63493 = (int*)&c;
++*_tmp63493;
}
goto _63421;
_63428:;
{
_a12344t_63448 _tmp63494 = ::flx::rtl::strutil::str<int>(ntri) + ::std::string("\n") ;
::flx::rtl::ioutil::write(stdout,_tmp63494);
}
}
//-----------------------------------------
}} // namespace flxusr::sl0
//CREATE STANDARD EXTERNAL INTERFACE
FLX_FRAME_WRAPPERS(::flxusr::sl0,sl0)
FLX_C_START_WRAPPER_PTF(::flxusr::sl0,sl0,_init_)
//-----------------------------------------
//body complete
```
[Answer]
## C# (about 11000?)
```
using System;
using System.Collections.Generic;
namespace PPCG
{
class PPCG53100
{
static void Main(string[] args)
{
int n = int.Parse(args[0]);
Console.WriteLine(CountOOE(n) + CountEEE(n));
}
static int CountOOE(int n)
{
// Maps from a^2 + b^2 to (b - a, a + b), which are the exclusive bounds on c.
IDictionary<int, List<Tuple<int, int>>> pairs = new Dictionary<int, List<Tuple<int, int>>>();
for (int a = 1; a <= n; a += 2)
{
int k = 2 * a * a;
for (int b = a; b <= n; b += 2, k += 4 * (b - 1))
{
List<Tuple<int, int>> prev;
if (!pairs.TryGetValue(k, out prev)) pairs[k] = prev = new List<Tuple<int, int>>();
prev.Add(Tuple.Create(b - a, a + b));
}
}
int max = 2 * n * n;
int count = 0;
for (int x = 1; x <= n >> 1; x++)
{
int k = 4 * x * x;
for (int y = x; y <= n; y++, k += 4 * y - 2)
{
if (k > max) break;
List<Tuple<int, int>> ab;
if (pairs.TryGetValue(k, out ab))
{
foreach (var pair in ab)
{
// Double-counting isn't possible if a, b are odd.
if (pair.Item1 < x << 1 && x << 1 < pair.Item2)
{
count++;
}
if (x != y && y << 1 <= n && pair.Item1 < y << 1 && y << 1 < pair.Item2)
{
count++;
}
}
}
}
}
return count;
}
static int CountEEE(int n)
{
// Maps from a^2 + b^2 to (b - a, a + b), which are the exclusive bounds on c.
IDictionary<int, List<Tuple<int, int>>> pairs = new Dictionary<int, List<Tuple<int, int>>>();
for (int a = 2; a <= n; a += 2)
{
int k = 2 * a * a;
for (int b = a; b <= n; b += 2, k += 4 * (b - 1))
{
List<Tuple<int, int>> prev;
if (!pairs.TryGetValue(k, out prev)) pairs[k] = prev = new List<Tuple<int, int>>();
prev.Add(Tuple.Create(b - a, a + b));
}
}
// We want to consider m in the range [1, n] and c/2 in the range [1, n/2]
// But to save dictionary lookups we can scan x in [1, n/2], y in [x, n] and consider both ways round.
int max = 2 * n * n;
int count = 0;
for (int x = 1; x <= n >> 1; x++)
{
int k = 4 * x * x;
for (int y = x; y <= n; y++, k += 4 * y - 2)
{
if (k > max) break;
List<Tuple<int, int>> ab;
if (pairs.TryGetValue(k, out ab))
{
foreach (var pair in ab)
{
// (c1, m1) = (2x, y)
// (c2, m2) = (2y, x)
int a = (pair.Item2 - pair.Item1) / 2, b = (pair.Item2 + pair.Item1) / 2;
int c1 = 2 * x;
if (pair.Item1 < c1 && c1 < pair.Item2)
{
// To deduplicate: the possible sets of integer medians are:
// m_c
// m_a, m_c
// m_b, m_c
// m_a, m_b, m_c
// We only want to add if c is (wlog) the shortest edge whose median is integral (or joint integral in case of isosceles triangles).
if (c1 <= a) count++;
else if (!IsIntegerMedian(b, c1, a))
{
if (c1 <= b || !IsIntegerMedian(a, c1, b)) count++;
}
}
int c2 = 2 * y;
if (c1 != c2 && c2 <= n && pair.Item1 < c2 && c2 < pair.Item2)
{
if (c2 <= a) count++;
else if (!IsIntegerMedian(b, c2, a))
{
if (c2 <= b || !IsIntegerMedian(a, c2, b)) count++;
}
}
}
}
}
}
return count;
}
private static bool IsIntegerMedian(int a, int b, int c)
{
int m2 = 2 * (a * a + b * b) - c * c;
int s = (int)(0.5f + Math.Sqrt(m2));
return ((s & 1) == 0) && (m2 == s * s);
}
}
}
```
`n` is taken as a command-line argument.
### Explanation
We can rewrite \$m = \sqrt{(2a^2 + 2b^2 - c^2) / 4}\$ as \$2a^2 + 2b^2 = 4m^2 + c^2\$, whence it's obvious that \$c^2\$ must be even, and so \$c\$ is even. Let \$c = 2C\$ and we rewrite again as \$a^2 + b^2 = 2(m^2 + C^2)\$. Therefore \$a^2 + b^2\$ must be even, so \$a\$ and \$b\$ must have the same parity.
The equation \$a^2 + b^2 = 2(m^2 + C^2)\$ is the basis for the meet-in-the-middle algorithm employed here.
If \$a\$ and \$b\$ are odd then we have no risk of double-counting, because only one of the three medians can possibly be integral. If all three are even then we need to beware double-counting. Therefore I handle the two cases separately so that the odd-odd-even case can be processed faster than the even-even-even case.
[Answer]
# C, n=3030 here
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define R return
#define u32 unsigned
#define F for
#define P printf
int isq(u32 a)
{u32 y,x,t,i;
static u32 arr720[]={0,1,4,9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361,400,441,484,529,576,625,676,180,241,304,369,436,505,649,160,409,496,585,340,544,145,601,244,580,481,640,385,265};
static char barr[724]={0};
if(barr[0]==0)F(i=0;i<(sizeof arr720)/sizeof(unsigned);++i)
if(arr720[i]<720) barr[arr720[i]]=1;
if(barr[a%720]==0) R 0;
y=sqrt(a);
R y*y==a;
}
int f(u32 a, u32 b, u32 c)
{u32 t,x;
if(c&1)R 0;
t= a*a+b*b;
if(t&1)R 0;
R isq((2*t-c*c)/4);
}
int h(u32 n)
{u32 cnt,a,c,k,ke,kc,d,v,l,aa,bb,cc;
cnt=0;
F(a=1;a<=n;++a)
{ke=(n-a)/2;
F(k=0;k<=ke;++k)
{v=a+k;
d=v*v+k*k;
l=sqrt(d);
v=n/2;
if(l>v)l=v;
v=a+k-1;
if(l>v)l=v;
F(c=k+1;c<=l;++c)
{if(isq(d-c*c))
{bb=a+2*k;cc=2*c;
if(bb>cc && f(a, cc,bb)) continue;
if( a>cc && f(cc,bb, a)) continue;
++cnt;
//P("|a=%u b=%u c=%u", a, bb, cc);
}
}
}
}
R cnt;
}
int main(int c, char** a)
{time_t ti, tf;
double d;
int ni;
u32 n,i;
if(c!=2||a[1]==0){P("uso: questo_programma.exe arg1\n ove arg1 e\' un numero positivo\n");R 0;}
ni=atoi(a[1]);
if(ni<=0){P("Parametro negativo o zero non permesso\n");R 0;}
n=ni;
if(n>0xFFFFF){P("Parametro troppo grande non permesso\n"); R 0;}
F(i=3;i<33;++i)if(i<10||i>21)P("T(%u)=%u|",i, h(i));
ti=time(0);
P("\nT(%u)=%u\n", n, h(n));
tf=time(0);
d=difftime(tf,ti);
P("Tempo trascorso = %.2f sec\n", d);
R 1;
}
```
results:
```
C:\Users\a\b>prog 3030
T(3)=0|T(4)=0|T(5)=0|T(6)=1|T(7)=1|T(8)=2|T(9)=3|T(22)=34|T(23)=37|T(24)=42|T(25)=
45|T(26)=56|T(27)=59|T(28)=65|T(29)=67|T(30)=74|T(31)=79|T(32)=91|
T(3030)=3321226
Tempo trascorso = 60.00 sec
```
the above code would be the traslation in C of the Axiom answer
(if we not count the isq() function).
My compiler not link a function others use sqrtf()... here there is no sqrt function for float...
Are they sure that sqrtf it is a C standard function?
[Answer]
# APL NARS, n=~~239~~ 282 in 59 seconds
```
f←{(a b c)←⍵⋄1=2∣c:0⋄t←+/a b*2⋄1=2∣t:0⋄0=1∣√4÷⍨(2×t)-c*2}
∇r←g n;cnt;c;a;k;kc;ke;d;l;bb;cc
r←⍬⋄cnt←0
:for a :in 1..n
ke←⌊(n-a)÷2
:for k :in 0..ke
d←((a+k)*2)+k*2
kc←⌊⌊/(n÷2),(a+k-1),√d
→B×⍳kc<k+1
:for c :in (k+1)..kc
→C×⍳∼1e¯9>1∣√d-c*2
bb←a+2×k⋄cc←2×c
→C×⍳(bb>cc)∧f a cc bb
→C×⍳( a>cc)∧f cc bb a
cnt+←1
⍝r←r,⊂a bb cc
C: :endfor
B: :endfor
:endfor
r←r,cnt
∇
```
(i traslate the Axiom answer one, in APL) test:
```
g 282
16712
v←5 6 10 20 30 41
v,¨g¨v
5 0 6 1 10 4 20 27 30 74 41 166
```
[Answer]
# Axiom, n=269 in 59 sec
```
isq?(x:PI):Boolean==perfectSquare?(x)
f(a:PI,b:PI,c:PI):Boolean==
c rem 2=1=>false
t:=a^2+b^2
t rem 2=1=>false
x:=(2*t-c^2)quo 4
isq?(x)
h(n)==
cnt:=0 -- a:=a b:=(a+2*k) c:=
r:List List INT:=[]
for a in 1..n repeat
ke:=(n-a)quo 2
for k in 0..ke repeat
d:=(a+k)^2+k^2 -- (a^2+b^2)/2=(a+k)^2+k^2 m^2+c^2=d
l:=reduce(min,[sqrt(d*1.), n/2.,a+k-1])
kc:=floor(l)::INT
for c in k+1..kc repeat
if isq?(d-c^2) then
bb:=a+2*k; cc:=2*c
if bb>cc and f(a,cc,bb) then iterate -- 2<->3
if a>cc and f(cc,bb,a) then iterate -- 1<->3
cnt:=cnt+1
--r:=cons([a,a+2*k,2*c],r)
r:=cons([cnt],r)
r
```
If a,b,cx are length of the sides of one triangle of max lenght side n...
We would know that m:=sqrt((2\*(a^2+b^2)-cx^2)/4)
```
(1) m^2=(2*(a^2+b^2)-cx^2)/4
```
As Peter Taylor had said, 4|(2\*(a^2+b^2)-cx^2) and because 2|2\*(a^2+b^2) than 2|cx^2 =>
cx=2\*c. So from 1 will be
```
(2) m^2=(a^2+b^2)/2-c^2
```
a, and b has to have the same parity, so we could write b in function of a
```
(3) a:=a b:=(a+2*k)
```
than we have that
```
(4)(a^2+b^2)/2=(a^2+(a+2*k)^2)/2=(a+k)^2+k^2
```
so the (1) can be rewritten see (2)(3)(4) as:
```
m^2+c^2=(a+k)^2 + k^2=d a:=a b:=(a+2*k) cx:=2*c
```
where
```
a in 1..n
k in 0..(n-a)/2
c in k+1..min([sqrt(d*1.), n/2.,a+k-1])
```
results
```
(16) -> h 269
(16) [[14951]]
Type: List List Integer
Time: 19.22 (IN) + 36.95 (EV) + 0.05 (OT) + 3.62 (GC) = 59.83 sec
```
[Answer]
VBA 15,000 in TEN seconds!
I expected much less after these other posts. On an Intel 7 with 16 GB RAM I get 13-15,000 in TEN seconds. On a Pentium with 4 GB RAM, I get 5-7,000 in TEN seconds. The code is below. Here is the latest result on the Pentium
```
abci= 240, 234, 114, 7367, 147
abci= 240, 235, 125, 7368, 145
abci= 240, 236, 164, 7369, 164
abci= 240, 238, 182, 7370, 221
abci= 240, 239, 31, 7371, 121
```
It got up to a triangle with sides 240, 239, 31 and a medium of 121. The count of mediums is 7,371.
```
Sub tria()
On Error Resume Next
Dim i As Long, a As Integer, b As Integer, c As Integer, ma As Double, mb As Double, mc As Double, ni As Long, mpr As Long
Dim dtime As Date
dtime = Now
Do While Now < DateAdd("s", 10, dtime) '100 > DateDiff("ms", dtime, Now) '
a = a + 1
' Debug.Assert a < 23
b = 1: c = 1
Do
ma = 0
If a < b + c And b < a + c And c < a + b Then
ma = ((2 * b ^ 2 + 2 * c ^ 2 - a ^ 2) / 4) ^ 0.5
If ma <> 0 Then ni = i + 1 * -1 * (0 = ma - Fix(ma))
If ni > i Then
If ma <> mpr Then
i = ni
mpr = ma
Debug.Print "abci= " & a & ", " & b & ", " & c & ", " & i & ", " & ma
GoTo NextTri 'TO AVOID DOUBLE COUNTING
End If
End If
'End If
mb = 0
'If b < a + c Then
mb = ((2 * a ^ 2 + 2 * c ^ 2 - b ^ 2) / 4) ^ 0.5
If mb <> 0 Then ni = i + 1 * -1 * (0 = mb - Fix(mb))
If ni > i Then
If mb <> mpr Then
i = ni
mpr = mb
Debug.Print "abci= " & a & ", " & b & ", " & c & ", " & i & ", " & mb
GoTo NextTri 'TO AVOID DOUBLE COUNTING
End If
End If
'End If
mc = 0
'IfThen
mc = ((2 * b ^ 2 + 2 * a ^ 2 - c ^ 2) / 4) ^ 0.5
If mc <> 0 Then ni = i + 1 * -1 * (0 = mc - Fix(mc))
If ni > i Then
If mc <> mpr Then
i = ni
mpr = mc
Debug.Print "abci= " & a & ", " & b & ", " & c & ", " & i & ", " & mc
End If
End If
End If
NextTri:
Do While c <= b
'c = c + 1
ma = 0
If a < b + c And b < a + c And c < a + b Then
ma = ((2 * b ^ 2 + 2 * c ^ 2 - a ^ 2) / 4) ^ 0.5
If ma <> 0 Then ni = i + 1 * -1 * (0 = ma - Fix(ma))
If ni > i Then
If ma <> mpr Then
mpr = ma
i = ni
End If
Debug.Print "abci= " & a & ", " & b & ", " & c & ", " & i & ", " & ma
GoTo NextTri2 'TO AVOID DOUBLE COUNTING
End If
'End If
mb = 0
'If b < a + c Then
mb = ((2 * a ^ 2 + 2 * c ^ 2 - b ^ 2) / 4) ^ 0.5
If mb <> 0 Then ni = i + 1 * -1 * (0 = mb - Fix(mb))
If ni > i Then
If mb <> mpr Then
mpr = mb
i = ni
Debug.Print "abci= " & a & ", " & b & ", " & c & ", " & i & ", " & mb
GoTo NextTri2 'TO AVOID DOUBLE COUNTING
End If
End If
'End If
mc = 0
'If c < b + a Then
mc = ((2 * b ^ 2 + 2 * a ^ 2 - c ^ 2) / 4) ^ 0.5
If mc <> 0 Then ni = i + 1 * -1 * (0 = mc - Fix(mc))
If ni > i Then
If mc <> mpr Then
mpr = mc
i = ni
Debug.Print "abci= " & a & ", " & b & ", " & c & ", " & i & ", " & mc
End If
End If
End If
' Debug.Print "abci= " & a & ", " & b & ", " & c & ", " & i
c = c + 1
Loop 'While c <= a
NextTri2:
b = b + 1
c = 1
Loop While b <= a
Loop
Debug.Print i
End Sub
```
[Answer]
# Rust, brute force, 4500
On my computer, the program calculated that the answer at `n=4500` is 7844386, within 60 seconds.
```
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use rayon::prelude::*;
#[inline]
fn is_square(v: i32) -> bool {
let s = (f32::sqrt(v as f32) + 0.5).floor() as i32;
s * s == v
}
#[inline]
fn is_median(v: i32) -> bool {
v % 4 == 0 && is_square(v / 4)
}
#[inline]
fn calculate_triangles(n: i32) -> i32 {
(1..=n)
.into_par_iter()
.map(|c| {
let mut count = 0;
for b in (c + 1) / 2..=c {
for a in (c - b + 1)..=b {
if is_median(2 * (b * b + c * c) - a * a)
|| is_median(2 * (a * a + c * c) - b * b)
|| is_median(2 * (a * a + b * b) - c * c)
{
count += 1;
}
}
}
count
})
.sum()
}
fn main() {
let n: i32 = 4500;
let (tx, rx) = mpsc::channel();
let _computation_thread = thread::spawn(move || {
let n_tri = calculate_triangles(n);
tx.send(n_tri).unwrap();
});
match rx.recv_timeout(Duration::from_secs(60)) {
Ok(n_tri) => println!("Result: {}", n_tri),
Err(_) => println!("Timed out after 60 seconds."),
}
// The thread will be terminated when the main function ends, regardless of whether it has finished its computation.
}
```
] |
[Question]
[
I wanted to fool a friend by giving him a [quine](http://en.wikipedia.org/wiki/Quine_(computing)) that *almost* worked, but became sloppier and sloppier.
Create a program that, when run, will output the program, but one character off. Either one character can be added, removed or both (one character changes). But only **one** character.
Your score will be `(length of your program) / floor(sqrt(number of times the program almost quines))` (Where `/ 0` is infinity)
`number of times the program almost quines` is how many times your program runs while only changing one character in stdout. Your program may not accept input. It may also not print a program it has already printed.
You may also **not** add a character that you have previously added before, or remove a character from the same index. For example, if you have added `1` before, and you add `1` again, that's where the `number of times the program almost quines` stops. If you remove the first character, you may not remove the first character again. If you changed the third character into a `2`, you may not add a `2` or remove the third character.
[Answer]
# CJam, 0.000884
```
{_,6/[{64md}6*](124+\+'�f++`"1$~"}""1$~
```
Here, � denotes the unprintable character with code point 128. [Try it online.](http://cjam.aditsu.net/#code=%7B_%2C6%2F%5B%7B64md%7D6*%5D(124%2B%5C%2B'%C2%80f%2B%2B%60%221%24~%22%7D%22%221%24~ "CJam interpreter")
### Idea
This approach appends all UCS characters (original specification) with code points between U+4000000 and U+7FFFFFFF to the initially empty string that follows the code block.
We choose [UTF-8](http://en.wikipedia.org/wiki/UTF-8#Description "UTF-8 - Wikipedia, the free encyclopedia"), which encodes each of these characters using a 6 byte string as follows:
```
1111110u₂ 10vvvvvv₂ 10wwwwww₂ 10xxxxxx₂ 10yyyyyy₂ 10zzzzzz₂
252 + u 128 + vvvvvv 128 + wwwwww 128 + xxxxxx 128 + yyyyyy 128 + zzzzzz
```
Thus, we can encode the *nth* character in this range by computing its 6 least significant digits in base 64 and adding 252 to the most significant and 128 to the remaining ones.
### Scoring
There are `2 ** 31 = 2,147,483,648` 6 byte UTF-8 characters and the length of the original code is 39, so the score is `39 / floor(2 ** 15.5) = 39 / 46340 = 0.0008416055243849806`.
### How it works
```
{ }"" e# Push the code block and an empty string.
1$~ e# Execute a copy of the code block.
_, e# Push the length of the string.
6/ e# Divide by 6 to get the number of chars.
{64md}6* e# Perform modular division six times.
[ ] e# Collect the results in an array.
(124+\+ e# Add 124 to the first element.
'�f+ e# Add 128 to all and cast each to Char.
+ e# Concatenate the strings.
` e# Push a string representation.
"1$~" e# Push '1$~' to complete the quine.
```
[Answer]
# CJam, 46 bytes, 65504 add, 65505 del, Score 0.127424
```
{`-2<_0c#)!{'#/~(_)\+\+S+]'#*}*W<"
}_~"e#
}_~
```
[Test it here.](http://cjam.aditsu.net/#code=%7B%60-2%3C_0c%23)!%7B'%23%2F~(_)%5C%2B%5C%2BS%2B%5D'%23*%7D*W%3C%22%0A%7D_~%22e%23%20%0A%7D_~)
The basic form is a standard generalised CJam quine. To "almost quine", there's a comment `e#` at the end of the quine's block, where I can freely add characters without affecting the code. Note that the comment initially contains a single space.
The program continues adding characters to the *front* of the comment, starting at `!` and then going in order of ASCII value. CJam's character codes wrap around after 216 so at some point, this will add a null byte. Once that happens, the program starts removing bytes from the *end* of the comment (such that the position of the removed character is always different) until the comment is empty.
[Answer]
# CJam, 19 bytes, 65536 add, 0 del, Score 0.074219
```
"a"{\)_)++`\"_~"}_~
```
Simpler is better.
] |
[Question]
[
Draw a tiled cube of any size, in ASCII art.
You will be given three numbers `a`, `b` and `c`, and the program should output an a\*b\*c sized cube.
**Examples**
`3 3 3` ->
```
____ ____ ____
/____/____/____/|
/____/____/____/||
/____/____/____/|||
|____|____|____|||/
|____|____|____||/
|____|____|____|/
```
`5 2 3` ->
```
____ ____ ____ ____ ____
/____/____/____/____/____/|
/____/____/____/____/____/||
/____/____/____/____/____/||/
|____|____|____|____|____||/
|____|____|____|____|____|/
```
`4 6 5` ->
```
____ ____ ____ ____
/____/____/____/____/|
/____/____/____/____/||
/____/____/____/____/|||
/____/____/____/____/||||
/____/____/____/____/|||||
|____|____|____|____||||||
|____|____|____|____|||||/
|____|____|____|____||||/
|____|____|____|____|||/
|____|____|____|____||/
|____|____|____|____|/
```
Shortest code wins.
[Answer]
## Python, 145 chars
```
a,b,c=map(int,raw_input().split())
for i in range(b+c+1):print(' '*(c-i)+((' /|'[(i>c)+(i>0)]+'_'*4)*(a+1))[:-4]+('|'*(b+c-i))[:b]+'/')[:5*a+c+1]
$ echo "5 6 3" | ./cube.py
____ ____ ____ ____ ____
/____/____/____/____/____/|
/____/____/____/____/____/||
/____/____/____/____/____/|||
|____|____|____|____|____||||
|____|____|____|____|____||||
|____|____|____|____|____||||
|____|____|____|____|____|||/
|____|____|____|____|____||/
|____|____|____|____|____|/
```
[Answer]
# Mathematica 148 143 139 chars
I decided to use transparent glass tiles.
The following code prints ASCII characters "-" in the form of a cuboid with edges, a, b, and c. The only thing you see in the figure below are hyphens.
```
w_~e~_ := {Arrowheads@Table[{1, p/9, Graphics@Style[Text["-"], Red]}, {p, 9}], White,Arrow@w};
GridGraph[{a, b, c} + 1, VertexSize -> 0, EdgeShapeFunction -> e]
```

[Answer]
## C, 226, 212
```
s(x,y){x<1?:putchar(" |/_\n"[y],s(x-1,y));}i,j,x,y,z;main(){for(scanf("%d%d%d",&x,&y,&z);j<=y+z;s(i,1),s(j++>y,2),s(1,4)){s(z-j,0);for(i=x;s(1,j?j>z?1:2:0),i;i--)s(4,3);i=y+z-j;if(i>j)i=j;if(i>z)i=z;if(i>y)i=y;}}
```
Once again a poor score compared to other langs - so any C golf gurus able to improve?
[Answer]
## Python3 (188)
```
a,b,c=map(int,input().split())
x=a+1
k="_"*4
p=print
l=5*a+c+1
p(" "*c+k.join(" "*x))
r=" "*c+k.join("/"*x)+"|"*b+"/"
exec("r=r[1:];p(r[:l]);"*c+'b-=1;p((k.join("|"*x)+"|"*b+"/")[:l]);'*b)
```
It is beaten already, but idea could help someone-else.
] |
[Question]
[
Given a matrix like this:
```
1 1 3 -2
3 -4 1 -1
1 1 1 0
0 -1 0 0
```
By taking a 2×2 "sliding sum", where the sum of every 2×2 region of the matrix is one element of the resulting matrix, we get:
```
1 1 1
1 -1 1
1 1 1
```
We can do this for sliding windows of any size. For example, a 1×3 sliding sum of the same input matrix would be:
```
5 2
0 -4
3 2
-1 -1
```
In this challenge, you'll be given an *output* matrix and a window size, and should return a matrix whose sliding sum with the given window size is the input. The window size will be at least 1×1, but there is no maximum size.
Inputs and outputs will consist only of integers. Note that there are arbitrarily many correct solutions for most window sizes.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer per language (in bytes) wins.
[Answer]
# [Python](https://www.python.org), 130 bytes
```
lambda A,m,n:[g(r,n)for r in zip(*(g(c,m)for c in zip(*A)))]
g=lambda A,k:A and g(A[:-1],k)+[sum(A[::-k])-sum(A[-2::-k])]or[0]*~-k
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVFLTsMwFBTbnMLqym6fK6goQkFZpPv2AiGqTOIEK_5EtlOpLFhwDTaVENwJToOTVJFA4I31xvPmzRu_frRH_2j06a1K7t87X9HbzxfJ1EPJUAoKdJzV2IImlbHIIqHRk2jxHNe4ADWAxQSmhJA8qpOpvYlTxHSJapxmMb3KoSGLzHWqL2Pa5ISOBV2NZW5sdpnPn2kzOvm6qIRqjfVId6o9IuaQbqMz5ArRHpdO1JrJ_sW5KCp5hRRr-N5z5_cFcxyTOELhhE1gCzuUBIWlDaaMGi6hPV7BDeBrIGRgbheJutstEj1U6Z8ddA1rwEHv3LMJLOeWhdEHIw98VeIUQpfR3GEcRhMCswOTopyNfMt9ZzXa9AFHUZ-i6FMM8jXH67PlIf4g_HuhaWKFB8oItLY3FoYyKQtpAvGnoc1_hiB82xj36TTe3w)
This solves the problem dimension by dimension. The function `g` essentially implements multiplication by a pseudoinverse of the 1d convolution matrix which depending on dimensions looks somewhat like
\$\begin{pmatrix}1&0&0&0&0&0\\-1&1&0&0&0&0\\0&-1&1&0&0&0\\1&0&-1&1&0&0\\-1&1&0&-1&1&0\\0&-1&1&0&-1&1\\1&0&-1&1&0&-1\\-1&1&0&-1&1&0\end{pmatrix}\$
which inverts
\$\begin{pmatrix}1&1&1&0&0&0&0&0\\0&1&1&1&0&0&0&0\\0&0&1&1&1&0&0&0\\0&0&0&1&1&1&0&0\\0&0&0&0&1&1&1&0\\0&0&0&0&0&1&1&1\end{pmatrix}\$
[Answer]
# Python3, 556 bytes:
```
from itertools import*
R=range
D=lambda l,y:l*y-(y-1)*(l-1)
def O(V,v):
c=0
while c:=c+1:
for i in product(*[[R(-c,c+1),[a]][b]for a,b in V]):
if sum(i)==v:return[*i]
def f(m,x,y):
q=[([[[0,0]for _ in R(D(len(m[0]),y))]for _ in R(D(len(m),x))],0,0,[j for k in m for j in k])]
while q:
b,X,Y,v=q.pop(0)
if[]==v:return[[a for a,_ in i]for i in b]
r=O([b[j][k]for j in R(X,X+x)for k in R(Y,Y+y)],v[0])
B=eval(str(b))
for j in R(X,X+x):
for k in R(Y,Y+y):B[j][k]=[r.pop(0),1]
q+=[(B,[X+1,X][Y+y<len(b[0])],[0,Y+1][Y+y<len(b[0])],v[1:])]
```
[Try it online!](https://tio.run/##bVJNj9owED3Xv2LEZe1kskpgK1VRfUF77kocViCvtYoh6RryhQkp@fV0HChtxcpRbM17M/Pm2e3QfTT17FvrzufCNRXYLndd05QHsFXbuC5gC@my@mfOnmWZVWaTQYlDWgZDxIcoEQEv6c82eQEv/BV7kTJYy5jBrw9b5rBO5TpMKAZF48CCraF1zea47nig1IJHayRcoMq0VkZ7UobG0161LwVgCzgcK26FlH3q8u7oahVYPXYseIUnHDxxLxVXSsUYj0XefYkFf@ZlXvNKxVoQTXwCCTxRHCkP1XYUufN4NR63/rjTQv8ZZ@8lGVziCnu5f2yblseCeZFK/6NPZXCZZOxl9W12Q5XAyReujNpqtdO3Lgu@xGV4EjcFC77CVTiQtt7Lp7y5zPus5IfOcSPE1dL/kkfD7iqk80svqdxVMSZexz4kz@aolmGCS62I@t1bYnw7jWTlKkzuwr1KUtrPJgEJk8kkAVosgeiy0aIgM9ML@hWmLIboic3oEHmWR/3Vdc27aTK3oVFS9uXiGygVVFnLbd0h2MdDW9qOX29ttK@wJT1P/qOpcwRzJTy81Q9EYqx1lMgL/rc0PSyY0kdu3YNTAhOEmRDn3w)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 150 bytes
```
f(a,m,n)=b=matinverseimage(matrix(#a*H=#a~,(w=#a+n-1)*h=H+m-1,i,j,![m<=x=j--%h-i--%H,x<0,n<=y=j\h-i\H,y<0]),concat(Vec(a)));matrix(h,w,i,j,b[i+j--*h])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVBBToQwFL1KZWLSwm8CgyZmoK5x5U4XnWbSQRhKpNMwjIALj-HGzWyMF_ES3saCYCZ5-f-9_pf32358GVmrzc6cTp_HJqc3P-85llCBJmzLKtko_ZLVh0xVcpdhq2vV4YV0E7aQb4Bb2zxNA-IWLPEqGoCCEi54FbOOlZReFlTZmkAX-6Bj1rNybY_WCfSxLwike53KBj9kKZaEkGhaUEA7Bm258myKWwgy3e5bGvPcY4noLTK10g12HpV-2rfooF6zFXKQ5EuBnG4goSDR7LrTK2dWBksenM3uj835MB_HMCbBXwwBxDkPAA2Ihkr_2QDrW1qIwXZtSYR8a7mKUDgKOnlsC8X8lvnHfwE)
Or 119 bytes if we can output a flatten array:
```
f(a,m,n)=matinverseimage(matrix(#a*H=#a~,(#a+n-1)*h=H+m-1,i,j,![m<=x=j--%h-i--%H,x<0,n<=y=j\h-i\H,y<0]),concat(Vec(a)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBBTsMwEEWvYlIh2e1YShqQUBOzDit2sHCtahSS1hFxrTSlCQsuwqYbxCW4CLfBDglC-hr_P35jy37_tNjozdaezx_HtuQ336eSItRgmKix1ealaA6FrnFbUJcb3dEZzjMxwzdwbmF4xOY7kS1qHoGGCi5knYpOVJxf7rh2NYMuDcGkohfV2rXWGfRpqBjke5NjSx-KnCJjbLz-C6197ikSfktso01Lg0dtnvYnctCvxYoEBOVSkaDzJlYsmag7swqmZCnK6N_e_bH1k-XQhuEE-B1nQKSUERCvxFf-57wct3RSHrt2JiGhQ64SEg-Bj4xbYqXGN0xf-QM)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~62~~ 53 bytes
```
F⊖η⊞υE⊖⁺ζL§θι⁰Fθ«≔E⊖ζ⁰ε⊞υεFι⊞ε⁻κΣE…⮌υη↨¹✂λ⁻⊕Lεζ⊕Lε»Iυ
```
[Try it online!](https://tio.run/##bU5NSwMxED03v2KOE0hBve6prpeCwqLHZQ9hOzbBNNvmo2jF3x5nY4tUHGYOj/fmvTcaHcZJu1JepwD4QGOgHflEGzRSQpejwazgSe@vuM7liCcFj@S3yeAqrf2G3vGgwEoeBTdSNqJaHiR8isUqRrv1@NfnVKUKiNWLS1gF9deeGxA3sJ4j3xS85F21aT9GR62Z9vhMRwqRMLOR4bvXDG5Z6exI6C6/a/@be@5Nc9W5w//czzTiS3TB@oStjolTZFNK3/ecMO@gBMAMlleogkHBHe9Qlkf3DQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⊖η⊞υE⊖⁺ζL§θι⁰
```
Generate zero rows of the final width which will pad the final matrix to the final height.
```
Fθ«
```
Loop over the rows of the input matrix.
```
≔E⊖ζ⁰ε
```
Start a new row of the output matrix with zeros which will pad the row to the final width.
```
⊞υε
```
Append the new row to the output matrix.
```
Fι
```
Loop over the cells of the current input matrix row.
```
⊞ε⁻κΣE…⮌υη↨¹✂λ⁻⊕Lεζ⊕Lε
```
Add the next entry to the output matrix row so that the sliding sum for this cell of the input matrix becomes correct. Note that "base 1" is used to sum the cells in a row because in the case of a window of width 1 the final row's cell does not exist yet.
```
»Iυ
```
Output the resulting matrix in default Charcoal format.
Example: For the given 2×2 sliding sum:
```
1 1 1
1 -1 1
1 1 1
```
First a padding row is constructed, then a padding cell for the first input row:
```
0 0 0 0
0
```
To make the first sliding sum correct, a `1` is needed:
```
0 0 0 0
0 1
```
To make the second sliding sum correct, a `0` is needed:
```
0 0 0 0
0 1 0
```
To make the third sliding sum correct, another `1` is needed:
```
0 0 0 0
0 1 0 1
```
The new row starts again with a padding cell. To make the fourth sliding sum correct, a `0` is needed:
```
0 0 0 0
0 1 0 1
0 0
```
To make the fifth sliding sum correct, a `-2` is needed:
```
0 0 0 0
0 1 0 1
0 0 -2
```
Continuing in this way, the resulting matrix is as follows:
```
0 0 0 0
0 1 0 1
0 0 -2 2
0 1 2 -1
```
] |
[Question]
[
The input for the [continuous knapsack](https://en.wikipedia.org/wiki/Continuous_knapsack_problem) problem is as follows.
For each item 1...n we are given a positive weight and profit. Overall we are also given a positive capacity which is the maximum weight we can carry.
The goal is to pick items so that the profit is maximized without exceeding the capacity. This is hard if you can only pick either 1 or 0 of each item. But in the continuous version we are allowed to pick a fraction of an item as well.
A simple solution is to compute \$d\_i = p\_i/w\_i\$ for each item \$i\$ (\$w\_i\$ is the weight and \$p\_i\$ is the profit for item \$i\$). We can then sort the \$d\_i\$ from largest to smallest, picking each item from biggest to smallest while the capacity has not been reached and possibly a fraction of the final item which is chosen. This take \$O(n\log n)\$ time because of the sorting step.
# Examples
```
Capacity 20
Profit Weight
9 6
11 5
13 9
15 7
```
Optimal profit 37.89.
For the optimal solution in this case we have chosen items with profits 11, 15 and 9 to start with. These have total weight 18 and profit 35. We now have 20-2 = 2 left before we reach weight capacity and the only remaining items has weight 9. So we take 2/9 of that item which gives us 2/9 of the profit 13. 35+(2/9)\*13 = 37.8888....
If you increase the capacity to 50, say, then the optimal profit is 9+11+13+15 = 48.
```
Capacity 879
Profit Weight
91 84
72 83
90 43
46 4
55 44
8 6
35 82
75 92
61 25
15 83
77 56
40 18
63 58
75 14
29 48
75 70
17 96
78 32
40 68
44 92
```
The optimal profit is 1036.93.
Here is a larger example:
```
Capacity 995
Profit Weight
94 485
506 326
416 248
992 421
649 322
237 795
457 43
815 845
446 955
422 252
791 9
359 901
667 122
598 94
7 738
544 574
334 715
766 882
994 367
893 984
633 299
131 433
428 682
700 72
617 874
874 138
720 856
419 145
794 995
196 529
997 199
116 277
908 97
539 719
707 242
569 107
537 122
931 70
726 98
487 600
772 645
513 267
81 972
943 895
58 213
303 748
764 487
536 923
724 29
789 674
479 540
142 554
339 467
641 46
196 710
494 553
66 191
824 724
208 730
711 988
800 90
314 340
289 549
401 196
466 865
689 678
833 570
225 936
244 722
849 651
113 123
379 431
361 508
65 585
486 853
686 642
286 992
889 725
24 286
491 812
891 859
90 663
181 88
214 179
17 187
472 619
418 261
419 846
356 192
682 261
306 514
201 886
385 530
952 849
500 294
194 799
737 391
324 330
992 298
224 790
```
The optimal profit in this example is 9279.65.
# Challenge
You can take the input in any form you like although please make it as easy as possible for me to test. Your code must output the optimal profit correct to within +- 0.01.
Most importantly, your code must run in **linear** time. This means you cannot use sorting to solve the problem. Your code can be either worst case linear or expected running linear.
However, this is still a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest submission in bytes per language wins, but the complexity is restricted to linear.
[Answer]
# Python3, 271 bytes
Runs in expected linear time. Essentially quickselect.
```
from random import *
def k(c,p,V=0):
while p[1:]!=[]:
i=randrange(len(p))
m,l,r=(p[i][0]/p[i][1],i),[],[]
for j,t in enumerate(p):
[r,l][(t[0]/t[1],j)>=m]+=[t]
v,w=map(sum,zip(*l))
c,V,p=[(c,V,l),(c-w,V+v,r)][w<=c]
v,w=(p+[(0,1)])[0]
return V+v*min(c/w,1)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~332~~ \$\cdots\$ ~~242~~ 252 bytes
```
from random import*
def f(l,W):
a,b=choice(l);L=*M,=*S,=[]
for p,w in l:[[M,S][p/w<a/b],L][p/w>a/b]+=(p,w),
N,X=map(sum,zip(*L+[(0,0)]));A=X
while X<W and M:*M,(p,w)=M;X+=w;N+=p
return A>W and f(L,W)or X<W and N+(S>[]and f(S,W-X))or(W-X+w)*p/w+N-p
```
[Try it online!](https://tio.run/##XVVNb@JIEL37V/QNG5qM@7s7iSPNPcklB5BYNCLEDNbyYYEjZjbKb8/WK8MmO0jYbVfVq1evqt3t726935mPj9VhvxWHxe6Fbs223R@6YfZSr8Qq38hJcZ2JhXyulut9s6zzTXFzXw0fZDV8ktVsnonV/iBaeRLNTmyuZ7MH@TSftd9Ot4tvz3N5z@s7rEdVTm6FzMSjnFbbRZsfX7fyn6bNh/ejWV7KspgXxc33apqJ07rZ1GJ6OxFESjxcUz4Orh5upqPqdPM4qtpMHOru9bAT3@96t1V@T2yJzSXucZQ/3c3mve1JTsbTgsw53UenYki8Ro/j9qOrj92P9rBfNd1RVCLPBP3yJIVy9Df0VyDNL5UUQUuRSimsl8KRR5TC0C3Q36s@KAQyk4s3/Xud@rui9yH2Nmv/A7UEVBKaVXRJifC9pQhtAOPoEgFqkdBqsgbQMI5cvCerSwSJuyUgY@gSPAPRKiYDGijCKITDtQQ1cIkBzhpsFCgiQiWODSgbq5IinIG1RA6f8EirZFgLcIooC7I4qBXpfbK0cFCmhAQeFRoPfySMhGEDBLYajFGIVefUFiTAP8JXI31QZIxgbRTecXyJcuDn8RhRotbQGipE6KfAxiCPQWM8NIwc4AGCFAhFGgtFIy7orEIJGqkgkkVlVsWzSMYxBIijZxo8TCTs5KAAWCqUECCSATh3VOvPfv8xWUXGE3iqm5/rrxPopZNJhktYRF0UA2lBGTJBJUoAfNdbwQ5cIT4qsNxw8vFgA@bwv2BaEDdoooaj1SimHzHXZ4qWS4OwqC9BIbQKTn2ZSMZzhKIiC4OpTOCrE1qF3rBiUJJnTiEqMlfGRzaHXaIQoLF/MIFBcX8oSmH4OCkXQ9GepxjRmtMxNnA0hA1cDgYzadNvQI/EDlvPOQiDKGypoPgVutFvb66Ks8R@HgwH8UhBxohJ8oHrhls/2NDWsTLcI4VZ4D5AFaB71MGzEHhOeQAVWPc7GWKjabwxwNxz9RjdCJ6K24xHh8ZGxDvw5GHX3AyoZ/jrAIPmD0MqL93@HKgiWy7axbLpmpoHDp@AiMTcCZK2LLL6V1svu/oFdhOusFVUafwVvihJh3TVbyiCWtfLv@sD/AZ/vepglwMpeKXMgHDaY7PZ78is6rHO@LQ40EFylOeJlxNZ4/DASfD1WyzF130hxSdlKS7kcDbRb0PoMz4gvp5GAPx/qmLO7qi5P9r48ed@jyoXz8f8OK6L2zNjtlH8rstXg7ce6F2KtzPWuzg13VpsF78uzH6Lt8m7GN@JNzK@nWWZAX3@Pig@/gU "Python 3 – Try It Online")
Runs in \$O(n)\$ time and space complexity.
Inputs a list of price and weight tuples along with the maximum capacity.
Returns the optimal profit.
Saved 3 bytes thanks to [Jakque](https://codegolf.stackexchange.com/users/103772/jakque)!!!
Saved 6 bytes thanks to [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)!!!
Saved 8 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
Added 10 bytes to fix a bug kindly pointed out by [Anush](https://codegolf.stackexchange.com/users/98590/anush).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~394~~ 378 bytes
thanks @Anush for finding issues
thanks @pxeger for -16 bytes
```
def f(x,c):
A,B=zip(*x);r=len(x);l=o=0
if c>=sum(B):return sum(A)
while 1:
a,b=x[__import__('random').randint(l,r-1)];t=a/b;W=P=0;i=k=l;j=r
while k<j:
p,w=x[k];u=v=k
if p/w>t:v=i;i+=1;W+=w;P+=p
elif p/w<t:j-=1;v=j;k-=1
k+=1;x[u],x[v]=x[v],x[u]
if W>c:r=i;continue
while W<c and i<j:p,w=x[i];i+=1;W+=w;P+=p
if W>=c:return(c-W+w)*p/w+P-p+o
l=j;c-=W;o+=P
```
[Try it online!](https://tio.run/##fVTLbuJKEN3zFS3dRexQMO53N05HmvmC7FgghIhjJg4EW8YEcn8@95SJZnOlkRJou6tPnUc13efw2h7119dLvRO77EpVvpiIn/Qr/dt02f01L/t0qI8ZFofUpmIimp2oHtPp/J79yhd9PZz7o@Cnn/lEXF6bQy0kEMSWntN1tdk0713bD5tNdtdvjy/t@10@50VzHLID9TOZr8shbX88l8v0lIqySft0KN9SD4gb2v7hjfFERxcA7tflOX2kPb8Bk@7H5XFYfKSmbKZJlstpupRP09Txdn24FTwMi7cZNj/SW7nHgvf2XH1dndd0XX2sE38QP05G1OVjteiBWbXHoTme6z9clg@VAHnRgNONT7P@f@cRIVXf5mTVbDm95PdgMn2addMWFQdQqWZpWbbT9PRVp8P2/fllK670udg@n7Lr7DN/mBdyMtm1vdiI5ijg2e86k0WBeCaiS6tIUpLUJO26vKSVI0uR/LqskirEP13f7prhRJe6@f2K72rbbatm@JyI7elU90NWZ7tsdc8ZQ0e@Ruyk/TzEPP@Gl@QVxYIMkC0F0pa8JYeeWHgyBTnNb1TkT@nJB35pDDwEn2AoaDL4wytyFACmSFl@ax3JQDaQxGYgX1B0pBW5gBocr1Lw8W9MZaHdPOo/XA3ZwpGRjiKaOBNJaVC0ngLYGkgwSpGHJm0jOefJRvQlC2paG/KOT4Jx1FAFT7XECWYGlZAWPGoUxEmIRR1PkIx8xiMFfBeQo7FXANNFrD1FzQ6ic4A1sNIiqyApwhIo1wXMc@CtHaqAHiIZj0yNAiNwNDAaHQy6OXbv1lShkUfuAcQ03FN8rABZ1DisA8grmKwgLBgeEY1YI2nk5uBE4DKHY4BEOVANTAn4R9IS9BRAIdiAsEFG3JNFa8sHQQ02K/TTAdNmIQo8JCh6CNZAY/uV@h4BgyINBxQyNgqHxgwsD0UwfB48gRHRG2KxOQLBSXYbuQVuiKwiZklFCIU4JgFuHIhEaeBRYizAWkziLRgIw4QiGy9Zo8K8@LEBT1ogx6nikGJsBsNhBaM880RaUWmeaoceFhNtLVxCKabIS37EfIy3g9ky4M0mGKi5ml1HcAF2O89iUDKGjMG0rJNvhYRzfAMgEnAOFNk5z8lxNBKkxkGFU7glPBfg5VgNggxgIlE@DgSeLTILOGbBhkNX7CNM0DzveKd41mMxXiwY9beLFZWPc2f5YnU9/0Tftfu7/Os/ "Python 3 – Try It Online")
non-competing. qselect with in-place 3-way partitioning.
`x` list of price-weight pairs
`c` capacity
`l` `r` left and right index in `x` (everywhere it's left inclusive, right exclusive)
`t` pivot
`i` `j` 3-way partitioning:
* `x[l:i]` are larger than `t`
* `x[i:j]` are equal to `t`
* `x[j:r]` are smaller than `t`
`k` current index
`p` price
`w` weight
`P` partial sum of prices
`W` partial sum of weights
`o` accumulator for the result
`u` `v` temporary
[Answer]
# [R](https://www.r-project.org/), ~~172~~ 178 bytes
```
f=function(x,m,y=x$p/x$w,s=sample(c(y,y),1),S=sum,i=`if`)i((v=S((z<-x[y>s,])$w))>m,f(z,m),i((t=v+S((u=x[y==s,])$w))>=m,S(z$p)+(m-v)*s,S(c(z$p,u$p))+i(any(y<s),f(x[y<s,],m-t),0)))
```
[Try it online!](https://tio.run/##ZVTNbhs9DLzzKQgjBylRUv1REoFsXyLHomj9uevCQHbjep3ETtFnT0cp2uJDD4YgLjmcGVI@vL5uh@3jvDnuHmZzcpM7D6eL/bvTxbNbhmU97e9HszFnd7YuWHc3LI@T2w2fd9vPdmfM03BnzMvt9enD@f3iPtqLZ2vfT25rXtxkHRKOw9MVUh4HZAzDn5Rhcnfm5WJvr8x0/WQvF1w3PeAeEbRXO7Oez@Z8u1hgofQWlW66PlrnrbWvp9vrw7j@cnNc/wd6x2GlmXMTEl84xUI5FI65kWrkHAOVrIhHiqlyVaEslXOiFoRbxjUXVsEZI0eJVDWwUhJl9SgulQOKRRtrJiCkRpIzS82UUuYahGop3FpEx8ypVGqaWFumkhJHVQopoGNCi8YFedV7rpFKqNwAgx8HwNbouUkXoBzArAJOQThoYYkKeHDpcF1graQenCpJUrBQoFboBtWCct/jv6grulcPdOhslFvl4nGtkQuaSADHzhmqwUlz4oae0jiGRMknrvCylu5xxwRITADLUEa1KRcoyFVZsqeQI4t0Y5QzQEuG8PImoAZPGYJEEkyFjkANIACiCB01gVIAh9aowR71lALcBGhsHVwp@4Ay2NPdLkLlrTnS4bJAYIzCmgrF3GEjNcy9SIBdCT5AC0jmFCiVwOIbFWHB2uQGuE4KZ4F9ESdWhxrgaxTqShu6Yi1aQLifgmF4LiVRgG@gHME1VIwGlsOm3M3FSHKAjSW8TbTBiCRdOSbf4ls8YWUldAc6Cr43cIITKhH5ipX2sDnDQEjC5CtGmuBcAqnU87DiEUON3Un1K7d5uL@Z19O48MAbs9qvHK@eV9YSHpLry2Tp698XP9vvxIw3/@Ew7s0yfvt0PyJ6eHg2J2vdbN3Hq8P8cJjMfPk7ioLlvBzH6ea4m0azxb8DYC9nfPlBgLnfbdbH0Yj7amRMiP4/Fsb8Tyz22OtP "R – Try It Online")
A function that takes a data frame `x` with columns `w` and `p` and a capacity `m` and returns a double indicating the profit. As far as I can tell, this should be \$O(n)\$ complexity. Thanks to @digEmAll for saving 9 bytes! Thanks to @Anush for pointing out that the original version failed where everything can fit in the knapsack.
[Answer]
# [Common Lisp](http://www.clisp.org/), 421 bytes
```
(defun F(F c)(loop for(p w)across(C F)sum p into R sum w into U until(> U c)finally(return(decf R(* p(min(/(- U c)w)1))))))(defun K(f)(floor(apply'/ f).01))(defun C(F)(reverse(let((C(make-array(1+(reduce'max(mapcar'K F))):initial-element 0))(O(make-array(length F))))(mapc(lambda(f)(incf(elt C(K f))))F)(dotimes(i(1-(length C)))(incf(elt C(1+ i))(elt C i)))(mapc(lambda(f)(setf(elt O(decf(elt C(K f))))f))(reverse F))O)))
```
[Try it online!](https://tio.run/##dVZNb9w2ED3bv2KQwjblVLZIiqIYA70YMFA4qIEgPRU9yFquLURfkLhZ@@K/7r6hdu1Nmy7gSBzOvHnzZkSmbpt5fH0VK7/e9HQjbqhORDsMI62HSYy0Tap6GuZZXNNNMm86Gqnpw0BfiBfbZfEnbfrQtOI3vNXJuumrtn0Wkw@bqQdyvaYv4pxG0TW9uBRp9NomMom/XepbsU7EGpknUY1j@3x2SevkIpNvDtfiJgHmdz/NXrQ@CHEtuuqbT6tpqp6F/IjN1ab2Z131hI2xrqazW5BOkk9N34SmalPf@s73gTKA3h0Gt75/CI/ROYmxoq26@1XFnJq@XgvfBhC4BSX8wGM1hKbzs2iETPfR1xx84C0/UgNLXPDbf5BnHxbfuyjSj0nwz75a5nUH0@vVFd0MU1cFGtZUUfBzSOsKDs1Moq7Gqm7CM33rh22fTn7eAO8Uz0D9prsHUnLMWo7VVHU@@InO3xDm82OiMyFURtpelI4cFSQlGZIa79KQTeBBJEqLZaaLC4cNSWVOVlGJ94xyTXlBORlDeU4lELShUpE15BQVkpRhJDhbSwaeGUl4aTIl@8iclKM8vltsWXIF2ZK0Ys@iZFCndjScY1DrLgo8c0QZMhkSKsDKghRgHJLmSlKRO9gVKW3JIiw3lqmWTCVnqgU5pswuBmxRFQIMNMgQXFiS2DGu5DxA0CUZMDE2J61hYW2KgkoU6uChEVCyNlCm0BolQS8tkRHqKJTLgmQZq1agxBIw/CcBa6F@ybpIhICZBRzXKaGDgTTOgQvDcYGQ0GXgBCW1Awv8ZRZ1g2rBHWL7Qt0hu@WEqBMilpYKzs8EkMSgwYo5o2qYHCuDnGiJwo7O0CxuSZHHSKMBomBTsVkWk1KAfY6hMNxOTm9YGDQSoEUueSS4ACsxII6HQ0NUmDA7Kl@AUIfVoISBc2VJJehhnDQGQgNUlQwOQLSDkXJWG20vYnK4Q1mDAhXGy2nuPcNiKBFTGMSgDgnOGiRzaKExiQYpC64SfS8Bx6TwLMBf4cmjUwLeApIJwpQzYQkzP@NwoAwAQ7eStUIL@cuA5JApj91FOsy3QjruaJnz98CVqzgEbNcYWcNznzEK9nmMoYQzC30DJRREkzx66LxFSzUIaMUaZ5GnQlMVK@lwrCXHx7vj8sH3fqqCT99PCdHzxyNw4gf@3ElMVb8aOnyTWZZQ37R0RW@nCI6Uqufj3T/gpGh6@iuLjn/T6XLCYHve8tZMf/z@OeLFe2Pyo8cJhQO/J5VQPbStr7HGcbhP6JyLRz/y@ap@pHFqan@59c3DY/hJYrQwQ@K30g4qwiXV0ekwhmbApUMC5@X9gA0Uk5CYw@SrjkKy1O3DOQkxcv3HR3u6QKB4AtLQ4xBdrSY2dQndP9MvZ7xmX/zeCuF4ZG4mPGIkZ/L10K92S27DEWevppDyPUHiwYeUS5rAMp02fTQvbjsZcfOOh8iRxOLBvmnAbQWCl4T783/g6D0j4o6O3jwiwAaX4JyOfkoXsgv2ObTvQzrisg7P51G33Qm7fUS@nZ7RQovc6O1O1w9f0Yimf4hlf6KX@eXkc7wK8b56Obk9mBJYflXrl5ProRs3wa/@Zf7KIsUKYVnPL@rkw071vSgyjbXvrtqlQyp5V36x7LR8F2xfzPeq3aDF/B8M8F/ckv3y0D1@QXxPo/m7q5rEE1zfh@6JB@qHuxP36uHoS1oNhwHiJ98iT3TCQK//AA "Common Lisp – Try It Online")
Uses counting sort, should be \$O(n)\$ as far as I can tell.
`F` Main function & the list of input items of type `f`
`f` Individual items of format `(profit weight)`
`c` Capacity
`p` Profit of item
`w` Weight of item
`U` Total weight
`R` Total profit
`K` Helper function for calculating \$\left\lfloor 100\times p\_i/w\_i\right\rfloor\$ to use as index in `C`
`C` The counting sort & the array `count[k+1]`
`O` The output array in `C`
`i` Generic index
[Answer]
# [C++ (clang)](http://clang.llvm.org/), ~~410~~ \$\cdots\$ ~~314~~ 310 bytes
```
#import<bits/stdc++.h>
using V=std::deque<std::pair<float,int>>;float f(int W,V&l){int N=0,X=0,A=0,i=0;auto[a,b]=l[rand()%l.size()];V L,S,M;for(auto[p,w]:l)(p/w>a/b?N+=p,A=X+=w,L:p/w==a/b?++i,M:S).push_back({p,w});for(;i--&X<W;X+=b)std::tie(a,b)=M[i],N+=a;return A>W?f(W,L):X<W?S>V()?f(W-X,S)+N:N:(W-X)*a/b+N;}
```
[Try it online!](https://tio.run/##hVZtb@JGEP5@v2JF1cQ@TGLvqxcD0anqt4QvUUOkXHQyxCTWEaC2CVERf73pvJgc196pSMB4dl6eeWZ217P1ujdb5MvHt7dfyuf1qmoG07Kpz@vmYdbtnj2NPmzqcvkoboag6fcfij83xYDEdV5Wg/lilTdRuWxGo4xkMQ/gSUyim5NFuENxPIyjW/h@gm85jLN806zu8mh6P1zcVfnyIQh/XZzV5V9FEN5nN@Iyuo6usvmqCshwHW3v@4swWJ9vR/n59GLcHa4h1G13uI0u@6AdDlHd7ZbRVf86PFtv6qcv03z2NdiB6z6kSFnZ653cDiYZuE1DQt@URQAgwuHVXXkfQdQ8q4pmUy3Fp9HkYh5MosuwDy4X16ObIERF7za6Drvj/riPcvgR0nbH2f4Na3zOy2UQ7j4I@NRUVFM@F8H4j8vLMMxIPVst60bMnvLqI/wWs69FdXcvhmLX@fz6u/z86n@Dr@lE4vhZdfbsTZhfilmzqgY3I9EUdVN/eQFvWsXPbucjYfeR2CUmEoYEFQlPQhIJt99Hx8agSjUuOgmSQsnHkdAkaQsSCgZiaZLSNroCTSrJESRPkoVg0hxyczDnAAV5aAibpGQHgEx68E0orgTY@l3nYooCvp58HaRV8hDFkp3WlPf7cjRGIQgmtujDqROQJYf3HgrVMiEg2qMNBZYKsjlPvtq4AwUplaJZjXx4w7KUWCwzgCx6ZgUC@piDWwiScHDjoQDPPEMWRUgMVmAcaZUC2SUU2llIkzK5HitS1hEUj43kblkFsvTcVpUgWu6YxAa1jYmBK9d2BtKmnAr@ABdDcBJM0rY/icdmMARM65mMxAMcIz3DwZratESqczwyWB@JRnmsxDMCh7wzBRbDx63NN2o8oud@O4n8cnNTsLAxq3E0LQMzOMyy5QNZ5/q8BnXKeA1AkQmxoWJQu3asLM1Gmx8TSR5QqZFJnjLcO8ySdiAbzXOoAYAxbaNwUBmA1Ui8fSfJJWSukTxjFA8B8kXzkGIiyEbDhnw5xeXhtvQpgUyxZZ7UKsHOMwCZEhjPGyDBkNwymhRLZVsGz2FwOgyTKiXuT0X2UhMEoizF2bcm4VYq7AdzhoVrRXqFO9rEvGnxOOGtpVNM2xaIsuUWS5Q9nwUpwnF8GhDDKSOmAydhE5KNP5w51lLEBPvKdEjkIHH@cBgk3D5NA8EjphNst03eJzjV7flEzPP0p/LdRuGxYNozJ6ZMbJ9ifdwRb/AsZLoNdkTy1k2wsY6n3@EIK@6swgJV64vHi@QhltRxaOf3Z9T/nc9k@4MDH6/X9sif4I1Bexe7BRuVNkv8Aye6jUeieF3Dc/GAfsqdpfih/ajsmZcWd690/sxqbegc5kBwaQq6x0vwizP4GwidCbhlw6Mr50a8wHJ7F8E1mr2v0CvA@9rkuzV@TciX9baowASv2pfw38sFrByg/8D7oZzP0Tef1kEhem20oyjT1Woh1nldgxUZD0RS9OQ3A6Jqtto0YjAQnZazdVXOikhsi/LxCbgbis5PHE53pxmlqJu8arDQalMcgUT6@MLHl5gTQa8xoi9ejun7T9SAo12ITgds8VUgJHS7Dv6tSQYl/m/pYX@Ej6Mxmnm@qI/g7H9SxP70Z3wAB2XzRC2kdBPSit6IH9vmkY4UhxcaZPye9J@XLbb9h/3b37P5In@s33rbfwA "C++ (clang) – Try It Online")
*Saved a whopping ~~24 25 31 33 40~~ 44 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Port of my [Python answer](https://codegolf.stackexchange.com/a/230363/9481).
] |
[Question]
[
## Challenge
Your goal is to find the furthest point on a graph (from a provided start node). Your code doesn't need to handle cycles in the graph properly, but it might pose a fun challenge. For this question, you can assume the graph is actually a tree.
## Input data
Input can be provided in any suitable format for the language. It can be provided either as an adjacency matrix, a list of edges, or an adjacency list. The input data can be directed or undirected as wanted by the program. The program needs to know the starting node - this can be provided in the input data if the program doesn't calculate it.
## Output format
The program must output to stdout, in a human readable format, a list of nodes, starting from the root and leading to the furthest node. If you prefer, this order may be reversed. Your program must be consistent wrt to the ordering.
## Edge cases
If there are multiple longest paths, only return one. If there is a cycle, or the graph has disconnected components, your code may crash or return a valid or invalid output.
## Libraries
All graph related libraries, including built-in language features, are not permitted.
## Test case
Input:
```
{0: (1, 2, 3), 1: (), 2: (4, 5), 3: (6,), 4: (7,), 5: (), 6: (8,), 7: (9,), 8: (), 9: ()}
0
```
The zero on the second line is the starting node. This could be inferred from the adjacency list, but I've included it in the test data anyway, to be clear.
Output:
```
[0, 2, 4, 7, 9]
```
Image:
[](https://i.stack.imgur.com/tMu5x.png)
## Scoring
Shortest code wins.
[Answer]
# [Coconut](http://coconut-lang.org/), 45 bytes
Takes the graph in the format shown in the example test case
```
f=(g,s)->[s]+max(map(f$g,g[s])::[[]],key=len)
```
[Try it online!](https://tio.run/##JczLCoMwEAXQvV8xiy6SdhTfj4D@SMhCxIRijVIVWtp@ezrB1T13ZphhGRZ77M7plhnceNjJTd3m/sXmfmX6YtDQgAshpVI4je/2MVruZADwiQWwBCFFyDhCQo0ipcgRCmJGLJGQEyqP4rwpKWrfK0LjUZ@LxscP6XkcKPheO1ifd7tDFIF2fw "Coconut – Try It Online")
Uses Coconuts lambda syntax, `$` for partial application and `::` as an operator for `itertools.chain`. The same would be 56 bytes in Python:
```
f=lambda g,s:[s]+max([f(g,x)for x in g[s]]+[[]],key=len)
```
[Try it online!](https://tio.run/##JY5LCoQwEET3nqKXCfbC/w9ykpBFhjEZGY1iXCgyZ890cPVeUUXT23V8VleGYMSsl9dbg0U/SK/SRZ9MGmbx5Gbd4YTJgaVCpVIqhd/xEvPoeLAg4M4GYDlCgVByhJwSoSBUCDVpSdogSUXSRqmfTUPoYm5J@ijdU/QRv8TT9SzZ9skdLD4DnvPwBw "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
```
;ⱮịṪ¥¥€Ẏ¥ƬẎṪ
```
[Try it online!](https://tio.run/##y0rNyan8/9/60cZ1D3d3P9y56tDSQ0sfNa15uKvv0NJjIAoo9v///@how9jY/9FGOsY6JrE60UBkqmMGJM2B2AIiYAnEhgYQdiwA "Jelly – Try It Online")
A dyadic link taking the start node as the left argument and the list of lists of child nodes as the right argument. The start node is expected to be supplied as `[[x]]` where `x` is the number of the node. Uses 1-indexing since that’s the way Jelly is written.
Thanks to @JonathanAllan for saving a byte!
## Explanation
```
¥Ƭ | Starting with the start node index, do the following until there’s a repeated value:
¥€ | - For each member of the list:
;Ɱ | - Append each of the following:
ịṪ¥ | - The last member of the list indexed into the original right argument (actually done as index into then tail)
Ẏ | - Flatten lists by one level
Ẏ | Finally, join the top level lists together
Ṫ | Take the last remaining list (which will be one of the longest paths)
```
[Answer]
# Kotlin 1.4.20, 92 bytes
```
fun f(e:Map<Int,Set<Int>>,s:Int):List<Int> =(e[s]?.map{f(e,it)}?.maxBy{it.size}?:setOf())+s
```
## Usage
```
fun main() = println(f(mapOf(0 to setOf(1, 2, 3), 1 to setOf(), 2 to setOf(4, 5), 3 to setOf(6), 4 to setOf(7), 5 to setOf(), 6 to setOf(8), 7 to setOf(9), 8 to setOf(), 9 to setOf()), 0))
```
## Note
This uses a deprecated API that got removed in 1.5, so it requires Kotlin 1.4 or lower.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
⊞υ⟦θ⟧FυF§η§ι⁰⊞υ⁺⟦κ⟧ιI⊟υ
```
[Try it online!](https://tio.run/##NUy7CgIxEOz9ii13YYXz7WElVnbpQ4pwKgmGi@Yh/n1MhBQzszvMzGR0mLx2pYgcDWYG@VZ0Wjx8AMwEfz2n63y7f9Ew9NMyDEQEvSVcjiifisFSrYtg54QXHRMK/6pD1SxFDnVerhjWDJsalQ1bhl3TfaNDd4@Nxv4ppcry434 "Charcoal – Try It Online") Link is to verbose version of code. Takes the root as the first input and an array of lists of adjacencies as the second input and outputs the longest route in reverse order. Explanation:
```
⊞υ⟦θ⟧
```
Start a breadth first search with a list of just the root node.
```
Fυ
```
Process the lists in the order they are found.
```
F§η§ι⁰
```
For each list, loop over the nodes adjacent to the first node in the list...
```
⊞υ⁺⟦κ⟧ι
```
... pushing a new list with the adjacent node at the beginning to the search.
```
I⊟υ
```
Output the last, and therefore longest, list.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 92 bytes
```
a=>g=(h,...t)=>v=1/h?a[h].map((n,j)=>g[j]?0:g[j]=n&&t.push(j))[g(...t)[0]]?[h,...v]:v||[h]:0
```
[Try it online!](https://tio.run/##TZBNTsMwEIX3OYVXlS2MSVpooZVbsWDJCawRmqbOn9Kkik1UoJw9TNyoYvNZM3rz5o0r7NGlXXny9017sEOmB9TbXPNCKqW80NteJw/FDk0B6ognzhtZUTc3Fezi9fjoZjbz6vTpCl4JYXIeBk0MsDPBpYd1f7mQwToevHU@RWcd08xExphYJiCJ88AFcS4fA5@IC7kkPsoVcSmfiSv5AiBZDBFsopubytruDdOCc2MPuXWSOY@dB8H0lv1EjNXWM1d@W1r7jr6gU85jziBWWY2eC8HuWLKZtEf0XXkeQ5Lqtevwi4/j4voJH6Ptv67KyrrmsRDj@OR5C4SS7acgk61BMHsg86ncA3WoTDbsN1ikbePa2qq6zXnGryrBw0njDhINfw "JavaScript (Node.js) – Try It Online")
Input the adjacency matrix of graph and the start node currily.
This one works on graphs with cycles.
---
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes
```
a=>s=>(g=(h,...t)=>v=h&&g(...t,...a[h[0]].map(j=>[j,...h]))||h)([s])
```
[Try it online!](https://tio.run/##TY/NasMwEITvfoo9hV2qivw1aQky9NBjn0CIsnFky8aNgyRCf9JndyUnlF4@0OzszqjjM4fKt6d4fxwOdqzVyKoMqsRGoRNSykiqPCs3mzWYX1li7fTcGPnOJ@xUqbssOkN0uThCHQyN0YZYcbABFOhCaz0XCyMSlxNXiUuxnviQuBKbxLXYJm7EY@JWPBkjYG4Ksyv@rsl68C9cOURtD40NAkJkHw2BKuG7AOhthNB@2RT7ytGlih@59mSWdc8RieAOFrubt/F8crljMj17z5@Yt@n6N3wT0E6nb/ttH61P2Sxgf81kUCp5rvZ/@p4oR1TDMQy9lf3QYI1TGOFUOc9/aDf@Ag "JavaScript (Node.js) – Try It Online")
This one works on directed graph without cycles.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
Pick[#,#,#&@@#~Level~{Depth@#-1}]//._[]:>Set@$&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyAzOTtaWQcI1RwclOt8UstSc@qqXVILSjIclHUNa2P19fXio2Ot7IJTSxxU1P4HFGXmlUQr69qlOSjHqtUFJyfm1VVzGURzKRjqcCkYAWkFExChYA4mFSyBZGwsUErBlEsBRBuDxM3AkhZcsbGxXLX/AQ "Wolfram Language (Mathematica) – Try It Online")
Input an expression - Mathematica's expressions are trees. For example:
[![TreeForm of 0[1, 2[4[7[9]], 5], 3[6[8]]]](https://i.stack.imgur.com/0YOiq.png)](https://i.stack.imgur.com/0YOiq.png)
`Pick` almost does the job, but non-leaf nodes with successors still remain. Then we remove all empty nodes.
### Also 47 bytes
```
Select@Not@*FreeQ[#&@@#~Level~{Depth@#-2}]//@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg1JzW5xMEvv8RBy60oNTUwWlnNwUG5zie1LDWnrtoltaAkw0FZ16g2Vl/fQVntf0BRZl5JtLKuXZqDcqxaXXByYl5dNZdBNJeCYXSsDpeCEZClYAIiFMzBpIJldCyQjgVJKpiC2CCWMUjODKzAAigWGxvLVfsfAA "Wolfram Language (Mathematica) – Try It Online")
Input leaves as e.g. `9[]` instead of `9`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~114 109 104~~ ~~103~~ 96 bytes
```
param($s,$e)$e|%{$p=($p+,"$_"*!(($a=$_[0])-$s))-replace"\b$a$",$_}
$p|sort{(-split$_).count}-b 1
```
[Try it online!](https://tio.run/##tZPbbuMgEIbveYppdtpAF1c2yTbNRaRIfYBW28u2shybtl75wALWrpT42bOA3ZNvV@XCPwzDfD9jodo/UpsXWVVHfIIN7I8q01lN0XCUDOXhdI9qQ1F95zNMZ@cnlGK2wfQ@fmQRGsYiLVWV5XL2sMMMZxzTnqA6mFbbPY2MqkqLKbvI266xfbSD5NgTsqWEcBpzgC11kjA3cypGXQT1USr4MiwE/@GXC37pZclXIRpil/zKy4qvvYT5mrnvPAYBS1jBes4cLXE4R0sGnFcx6iLoSBODfqKJgJvQkjie8JIAFI7o9uYMvkHT1TvXXg5Na6Eon0trvJPh3okrEcjjvZPJvf/HydSIZ/k8yLQMZurM5i/Oixi9fF1XJk6MzbSFJ93WUDamLKT@0JEv/DdTuGwK1ZaNJYTBAU5hT8ANDBkcUBbP0nj9q2RuZeGeBqZDipamq6wLnLkXMxwY88P@/e3ddWdsW9/sfrmjj9uhsh93XZ5LY3ytsUgkf78z3vJ@vhLGtLDRk/74Dw "PowerShell – Try It Online")
Stores paths as an array of strings. Each path contains a list of vertices separated by spaces.
---
Less golfed:
```
param($startVertex,$edges)
$edges|%{
$fromVertex = $_[0]
$pathes += ,"$_"*($fromVertex -eq $startVertex) # add $null or an edge
$pathes = $pathes -replace "\b$fromVertex$",$_
}
$pathes|sort{(-split$_).count} -Bottom 1
```
The dump of `$pathes` before sorting for the test case:
```
"0 1"
"0 2 4 7 9"
"0 3 6 8"
```
[Answer]
# [Red](http://www.red-lang.org), 95 bytes
```
f: function[x s][m: []foreach i select x s[p: f x i if(length? p)> length? m[m: p]]rejoin[m s]]
```
[Try it online!](https://tio.run/##NY29DsIwDIRf5UbYWvrfgb4Dq@UBtQ4NapMoDRJvH9yB5fTpzueLsuSHLMTZjDAfNyfrHX1xMO0jiI2P8pxXWByyyZygEQU9VbCw5rKJe6V1Qrje8ef97AbmKG9vHe36jXOI1iXtUQEqcUPFKHVAiWo0jArUMmpQx2jOoAX1jA40MPrTGFQYRf4B "Red – Try It Online")
Takes input as an adjacency list plus the starting node in the same form as in challenge specification. Returns the longest path in reverse order.
[Answer]
# [R](https://www.r-project.org/), 89 bytes
```
R=function(G,p={})`if`(!is.list(G),p,(A=lapply(G,R,c(p,el(G))))[[which.max(lengths(A))]])
```
[Try it online!](https://tio.run/##jVE9b8IwEN3zK67KgC1Z4ftryMDE1gF1qARIuOEglowT2Y4oKv3t6SWGsNaS791793TWnW1db9JTZTKvCsPWokx/fvlBnQ7sTblEK@fZmotSsFWqZVnqG3k2ImOlQE0VOtvtNVdZnlzkN9Nozj53bMX5fs/rGD4sIlgsLTo0Ho8gHUQxALSdbVF44aovT66hSJLkSd5547rmaBEe0ifk0gmQZ6mMAJ9TQV4oeFtlvrL4r67ROm0tA9HCkAccBZgEmAdY0mwhmz6TcYBZgEUzfftsOIMu78Mddk/WB2IdJdZQ2IU1wLAJoyaMX636VCZbJ0zoTgFmnXB/QCfMAyxeji5bRnEUbeivIpKcMmeNYIojQrsoKIy@cWjWQ6Z2rt6qR3PVfw "R – Try It Online")
Recursive function taking a tree as input (for the input format see the TIO) and returning the subtree of maximum length.
] |
[Question]
[
Inspired by [this Puzzling challenge](https://puzzling.stackexchange.com/q/100507), and easier version of [my previous challenge](https://codegolf.stackexchange.com/q/209142/78410).
## Challenge
A 2D rectangular grid is given, where each cell is either an empty space or a wall. You start at the top left cell, and you need to exit through the bottom right cell. You can move to one of four adjacent cells in one step.
You have some bombs, so that using one bomb will let you break exactly one cell-sized wall and go through it. Can you exit the maze using just what you have?
## Input and output
The input is the maze and the initial number of bombs. The maze can be taken as a matrix (or any equivalent) containing two distinct values to represent empty spaces and walls. The top left and bottom right cells are guaranteed to be empty. The number of bombs `n` is always a non-negative integer.
The output should be truthy if you can exit the maze using `n` or fewer bombs, falsy otherwise. You can output truthy/falsy using your language's convention (swapping is allowed), or use two distinct values to represent true or false respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Uses `.#` for spaces and walls.
```
Input maze
..#..#..
Output: false (for 0 or 1 bomb), true (≥2 bombs)
Input maze
.....
####.
.....
.####
.....
Output: true (for any bombs)
Input maze
.
Output: true (for any bombs)
Input maze
.#.#.
##.##
.###.
Output: false (for ≤2 bombs), true (≥3 bombs)
Input maze
.####
#####
##.##
#####
####.
Output: false (for ≤5 bombs), true (≥6 bombs)
```
[Answer]
# JavaScript (ES7), ~~126 125~~ 119 bytes
Expects `(matrix)(bombs)`, where the `matrix` is filled with `-1` for an empty cell and `-2` for a wall.
Returns *false* if we can exit the maze, or *true* if we can't.
```
m=>g=(b,X=0,Y=0)=>m.every((r,y)=>m[Y+1]||r[X+1]?r.every((v,x)=>r[x]*=v>0|(X-x)**2+(Y-y)**2!=1||g(b-~v,x,y,r[x]=1)):b<0)
```
[Try it online!](https://tio.run/##fYvNToQwEMfvPEUNB6a7ZQJr9KAWT/oCe9kNcgC2IIbC2iJZIvrq2CLGPRinTfv/@M1L2qc6V9Wx85v2IKaCT5JHJYeM7XjA9jygPJIoeqEGAMUGa@P9OkzGUcU789@rn7ZnJ9Oq@JSseB8FI@z8E12tNmvY@4MVFzwcxxIy/9OgbGAW5SGlN9ldQCclXt8qJcArtEdRifTwWNViOzQ5BBS7dtupqimBoj7WVQfeU/PUGLBo1UOaP4MmPCLvDiFxxggiyoRwon9hj96aUppQokyP33xsQJ3MPrfeD4lPrOTEcz1K5528bXRbC6zbEgqQFNaZLT7oFDiI7nwdZ3OmbW7Gcc3gotGaRVtg3nDNMRTaZmady7/Cq2XbXV480zNw/T/wBQ "JavaScript (Node.js) – Try It Online")
### Commented
```
m => // m[] = matrix
g = ( // g is a recursive function taking:
b, // b = number of bombs
X = 0, Y = 0 // (X, Y) = current position, starting at (0, 0)
) => //
m.every((r, y) => // for each row r[] at position y in m[]:
m[Y + 1] || // if there's a row below the current cell
r[X + 1] ? // or there's a column on the right:
r.every((v, x) => // for each value v at position x in r[]:
r[x] *= // restore r[x] if any of these tests is true:
v > 0 | // - v is greater than 0 (this cell was visited)
(X - x) ** 2 + // - the squared distance between
(Y - y) ** 2 != 1 // (x, y) and (X, Y) is not equal to 1
|| //
g( // - this recursive call is truthy:
b - ~v, // decrement b if v = -2
x, y, // use the new position (x, y)
r[x] = 1 // mark r[x] as visited by setting it to 1
) // end of recursive call
) // end of inner every()
: // else (bottom-right cell):
b < 0 // return true if we've used too many bombs
) // end of outer every()
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 81 bytes
```
≔⟦⟧θWS⊞θι⊞υ⟦⊕Nω⟧≔⁰ηFυ«⪫θ¶←F§ι¹✳κ+¿∨ⅈⅉFruld«≔⌕….#§ι⁰∨⊟KD²✳κ+ζ¿⊕ζ⊞υEι⁺λ⎇μκ±ζ»≔¹η⎚»η
```
[Try it online!](https://tio.run/##TVDBTgIxED1vv2JSLm2sBDx40BPBmGAEN9GDBjmsuwPbULrQ7YJg@PZ1uqxxe2hnpq/vvb40T1xaJKauR2WpV1bMFwp28p4dcm0QxMRuK//qnbYrISXEVZmLnQJNiKauFMwnNnW4Qesxu@Bn1eYLHeEVHBaEbKkHCnLqloUDUUn4YVFMvF48FdoGUv5puSRANC32KO6ecelD1@BHfmIz/BZawTD4aB4@aIep14UVa5LiVzzA9RLEixPvgkYf5EFCQ8BdZTLeqEatn0dtMzE@pgbHebEVvN/jCjpCg/ABoorpMkZc/8vdKOhqy1adjlOw0HjopnL6i47imibbQB6bqhRGwRs6m7ij2ChYK5jhKvEY8LJJ4swiNCVC63h4STAaG0wo33t2ZpckaFrX/R4t1mv3fqemjrHb@npvfgE "Charcoal – Try It Online") Link is to verbose version of code. Based on my answer to the previous challenge. Works better on grids with lots of walls. Bomb count is separated from the grid by a blank line. Outputs a Charcoal boolean, i.e. `-` for a path, nothing if not. Explanation:
```
≔⟦⟧θWS⊞θι
```
Input the grid.
```
⊞υ⟦⊕Nω⟧
```
Start with an initial state of `n+1` bombs and no moves. (This is because the algorithm stops when you run out of bombs, rather than when you need a bomb to move.)
```
≔⁰η
```
We haven't found a path yet.
```
Fυ«
```
Perform a breadth-first search of the states.
```
⪫θ¶←
```
Draw the input to the canvas, leaving the cursor at the end point.
```
F§ι¹✳κ+
```
Draw the path so far.
```
¿∨ⅈⅉ
```
If the start hasn't been reached, then:
```
Fruld«
```
Loop over the orthogonal directions.
```
≔⌕….#§ι⁰∨⊟KD²✳κ+ζ
```
Look at the next character in that direction to see how many bombs we need (`-1` for an illegal move, including running out of bombs).
```
¿⊕ζ⊞υEι⁺λ⎇μκ±ζ
```
If the move is legal then create a new state by subtracting the number of bombs and adding the current direction.
```
»≔¹η
```
But if the start was reached, then record that we found a path.
```
⎚»
```
Clear the canvas ready for the next state (or the final output).
```
η
```
Output the flag for whether we found a path.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 34 or 37 bytes
```
⎕≥⊃⌽,(0@0@0⊢⌊⎕+(⍉g∘⍉)⌊g←3⌊/,,⊣)⍣≡⍨9e9
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkGXI862tNA3EedSx91NT/q2aujYeAAhI@6Fj3q6QJKaGs86u1Mf9QxA0hpAoXSgdqMgbS@js6jrsWaj3oXP@pc@Kh3hWWq5X@gYf/TuNSV1W1NFUwf9W5R11NGABS2OpcZAA "APL (Dyalog Unicode) – Try It Online")
this shorter version works in dyalog v18 but not on tio:
```
⎕≥⊃⌽,(0@0@0⊢⌊⎕+g⍤1⌊g←3⌊⌿⍪⍪⊣)⍣≡⍨9e9
```
`⎕` `⎕` inputs
`9e9` a very large number, used as a substitute for infinity
`(` `)⍣≡⍨9e9` apply the function train in parens until convergence, using `9e9` both as a constant always passed on the left, and a starting value initially passed on the right
`g←3⌊/,,⊣` helper function to compute the minimum of each cell and its two horizontal neighbours, using `9e9` for the boundary around the matrix
`(⍉g∘⍉)` same for vertical - this is `g` under transposition
`⎕+`..`⌊`.. min of horizontals and verticals, and add the original matrix (this accounts for the cost of 1 bomb when we encounter a wall)
`⊢⌊`.. update the matrix of best known path costs
`0@0@0` put a 0 in the top left cell
on the first iteration of `(` `)⍣≡`, the scalar `9e9` is extended to a matrix (the matrix of best costs) because of `⎕+`, and then it remains a matrix until the end.
`⊃⌽,` lower right cell
`⎕≥` compare with the number of bombs available
[Answer]
# [Python 3](https://docs.python.org/3/), 130 bytes
```
def f(g,b,x=0,c=0):w=len(g[0])+1;l=w*len(g);return~x%w*(b>-1<x<l>c)and any(f(g,b-g[x//w][x%w],x+a,c+1)for a in(1,-1,w,-w))or-~x==l
```
[Try it online!](https://tio.run/##vY9Bi8IwEIXv/opchIyd4MyKe1iNfyTkUGvbFUoqoUvixb/eLd1VkMYFPWwGAnl8ee/N6dx9tm7V94eyEpWscY9RExaa4CPopnSyNmQh402jw2J8w8aX3Zd3lzgPC7nfKd7GbbMrIHcHkbuzHG1UbeJyGawZKIsxy7HIGKrWi1wcnWRUjAFVAGi9ukStm/7kj64bfhtDSMh4u61FwQCzP4G3CTCOxZm4HsP4M/dqmqVflh@wQyTdRyaksR4nWlDC@dotscyLNquJzXQjfqjSE@wtcv3/ke8A/Tc "Python 3 – Try It Online")
Recursive function to find all paths. Takes a 2D matrix as input, with `0` for empty spaces and `1` for walls. The number of bombs `b` is reduced by 1 each time it encounters a wall. Recursion stops immediately when the edge of the grid `g` is detected, more steps `c` have been taken than the size `l` of the grid, or the number of bombs remaining falls below zero. Returns `True` when any of the paths reaches the final space and `False` otherwise.
Adaptation from my answer to [Find the shortest route on an ASCII road](https://codegolf.stackexchange.com/a/195042/87681).
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~235~~ ~~233~~ ~~227~~ ~~222~~ 211 bytes
```
int c(int[][]m,int x,int y,int b){int a=0,v;try{m[x][y]=(b-=v=m[x][y])*v<0?v/0:-1;a+=(x==m.length-1&y==m[0].length-1?1:0)+c(m,x+1,y,b)+c(m,x-1,y,b)+c(m,x,y+1,b)+c(m,x,y-1,b);if(a<1)m[x][y]=v;}finally{return a;}}
```
[Try it online!](https://tio.run/##nZLLbsMgEEX3/YpRFpWpcQp5bEJQv6DddGl5gR3S0tqksokVF/HtKX71XTWKkEbcueIMM/AkahE9bZ6PWS6qCm6F0lZpI8utyCTc2XtTKv0AWeCToBFzlRFGZcdWdsk4iZMCt/LQxaaLKWopIDjBNTNlY4v4kMRNwoM04jUfFLqq1@SmviariDIR8uDAeTHNpX4wjxG9bLyKSfKeuKErgsIsKPAhpLjB6SCizwI33vsQUSuY2gZiTdF4iZq5rdIizxtbSrMvNQjm3JG97NNcZdC3CPVObaDwAwn6IcSJQPYCoG1M0bZvbi3BBFM8ROdw6896z2@h87vVWWAp7teov/tk8OkPv2fPx7qDXnypRYd7fNQiX1hj7f7s8tvZz3XpL5r8449sxXxquysDxQlTa@pDGCL/Bv7D9LNSiHOK7H1TGVlMd3szffETNrkOJrfiVQJdwSRU4QTSXZFWoKXcyM0EsbSU4pm5v/Gzk/Czc/Hzk/Dzc/GLk/CLc/HLk/DL//Duwh3fAA "Java (JDK) – Try It Online")
Requires an `int[][]` with `0` as field and `1` as wall.
Returns `0` on failure and `1` on success. I'm unsure if this is a vaild truthy/falsy value for Java though.
A rather simple approach: Walk around and bomb walls until you reach the exit or run out of bombs.
I removed the explaination, it got too messy for me to update because of line length.
### EDIT:
-2 thanks to ceilingcat!
-4, again thanks to ceilingcat!
-2 by optimising the goal check
-5, again thanks to ceilingcat! They also fixed the awful formatting in the TIO link.
-11 thanks to Kevin Cruijssen!
[Answer]
# Javascript, 186 bytes
Is a function `(maze, width, height, bombs) => boolean` returning whether or not the maze can be solved with the given number of bombs. The `maze` should be supplied as a flatten list of booleans, `true` for walls and `false` for empty spaces.
```
(m,w,h,b)=>{s=Array(w*h).fill(1/0);i=d=s[0]=0;l:for(;;){for(i=0;i<w*h;i++)for(d of[-w,-1*!!(i%w),1*!!((i+1)%w),w])if(s[i+d]+m[i]<s[i]){s[i]=s[i+d]+m[i];continue l}return s[w*h-1]<=b;}}
```
[Try it online!](https://tio.run/##bVLBbtswDL37K1gEg6VYUZ0F2KGOWuy4w049egbq2EqsQbYDW5nTBbnvK/Zx@5GUlL0mA@YEEvn4KD6J/J7/yPuiM3u3aNpSXy7PitViEJXYcPV46tXnrstf2TCvuNwaa9nyPuaJUaXq0zhTcWIftm3HkoSfaDeImDWyExNFnJAS2m26GMRiOb@7Y@bDwIW3mImWnLwh42bL@tREZRbVqcnWaGf8RKu6gZOibZxpDhrsudPu0DXQp1hpsczWapOcz5ftoSmcaRso9eawY3XuBAwCKg6nAABdULTKOt@zI6hHwEUp@NJsTWPcKzxB@OfX7xAe4MgTzED5wKx2YDAxTnBb@3yrm52r4B4GxPCaSAVAdX1rtbTtjoUhRJ7ZW1NoZmBOOnCPYMnJ4f78f1MQOgfBPu96jeWcPjqSSLt0nakZl/3eGsfCb03I/R2saTRxUikl2ZlHC20toTFWmxy8ZDgLOVUNirzXPRZIUUAaSjnz/1DAx0wEhL0Ekr5ghp@cbEnOaL8IiCdmSGnxNW2GP0yTRKVkpK5uonTEbFrljT0yPxEzQ4H@1elpHKR1/lMLqE2zaetNkeEogdc/dtS/VYl38QYj8tg361s9hiV5zOODKbFtfwM4vlMnKVZps6tusq6R9ynwGpDxNXcVvvSRxVdpsIAVTybK@gpHsJrQ/80JKZ6aK0aWAGqvgGdGssUoWUzqruWQHqonFU5Z8KjeQ/4EGhEcp8sb "JavaScript (Node.js) – Try It Online")
Sadly, I wasn't able to get this below the other JS answer. I tip my hat to @Arnauld and look forward to reading how his works.
Degolfed and annotated:
```
S = (m, w, h, b) => {
s = Array(w*h).fill(1/0); // initialize the scoreboard to infinity the scoreboard
// .. which holds the running minimum for number of
// .. bombs required to reach a certain grid cell
i = d = s[0] = 0; // declare variables i and d and note on the scoreboard
// .. that we can reach the top-left cell with 0 bombs
l: for(;;) { // repeat infinitely
for (i = 0; i < w*h; i++) // loop over all grid cells
for (d of [-w, // for direction of [up,
-1*!!(i%w), // left, (note: if the cell is at the start of a row
// .. then -1 could wrap; handle this with `*!!(i%w)`)
1*!!((i+1)%w), // right, (likewise here for the end of a row)
w]) // down].
if (s[i+d] + m[i]<s[i]) { // if moving from the given direction onto this cell
// .. would take less bombs than what's currently in
// the scoreboard,
s[i] = s[i + d] + m[i]; // then update the scoreboard
continue l // we've made a change to the scoreboard, so ensure we
// .. don't reach the below `return`
}
return s[w * h - 1] <= b; // return the score value for the bottom-right cell.
// .. due to the above `continue`, this statement will
// .. only be reached once no more changes to the
// .. scoreboard can be made
}
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes
```
Last@GraphDistance[GridGraph[#2,EdgeWeight->{_b_:>#[[b]]}],1]>#3&
```
[Try it online!](https://tio.run/##dYyxasMwFEV3fYWJILRwSyUHQ0ip0ZCSpUO2DkIEOXHiN9gutjahb@jS/@wnuGmsum2gXHjw7rmc2rqqrK2jvR2Oj8Oz7Z3adPa1WlPvbLMv9aajw6XRPMXT4VS@lHSq3F3udx9v78VulXOtC2OCgTQ5X8yHG7btqHH3ams7R47aRnPw1DywdatHpgmzpGjrol8lMxzP3HOeBpAxYJ4gsAzM3M6VUp55L86FxHQDlpABEYxhSSIx5vL8IQLf7DcJyJBFjYzuqBE/4@j8Gi@m8SST14/4l0yaLLAwfAI "Wolfram Language (Mathematica) – Try It Online")
Returns `True` if there are not enough bombs, and `False` otherwise. Takes `[maze, {w,h}, bombs]`, where `maze` is a 1d list of `0`s (no wall) and `1`s (wall).
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.