text
stringlengths 180
608k
|
---|
[Question]
[
# Prelude:
I wanted to train making test cases, so I'm gonna try them on something easy.
# Challenge:
Take any given (string) input (within visible ASCII range) and deduce if it's a number and output something that could be used to evaluate.
# Rules:
* A number will only contain the characters `-0123456789,.`
* Answers are only required to recognise numbers between -1000000000 and 1000000000 (exclusive), but may recognise arbitrarily large numbers.
* You can write a full program or a function.
* If a number, return anything that could be used to discern it and document the output in the description (ex. `My program outputs T if a number, F if not.`).
* Input will be any amount of characters within ASCII range or empty (if empty return whatever you'd output if not a number).
* Numbers could include a decimal point (ex. `3.14`). If they do, they must have at least one digit before the decimal point and at least one after it.
* Numbers could have leading or trailing zeros (ex. `000001.00000`).
* The integer part of a number could be divided for readability into chunks of three digits with commas (ex. `1,000.23456`). In this case they must be divided every three digits from right to left (ex. `1,234,567`, `10,000.202`, `123,234.00`, `0,123.293`).
* Negatives numbers are indicated by a leading `-` (ex. `-1.23`). A leading `+` to indicate a positive number is not permitted, and should result in the falsy output.
* Exceptions are NOT counted as valid and discernible output (except when they can pass outputs to standard out stream (ex. `Exception on line N [...]` can be put in as output for a number/nonnumber if the string is put to standard out stream.
# Test cases:
(assuming the `My program outputs T if a number, F if not.` version)
```
123 -> T [on integer]
-123 -> T [negative numbers need to be handled]
0 -> T [on zero]
123.456 -> T [on floating point]
123,456.789 -> T [on evenly divided by 3 digits with comas]
123456789 -> T [thousand separators are not required]
0000001.00000 -> T [on leading/trailing zeros]
00.00 -> T [on zero and leading/trailing zeros]
999999999.9999999999999999999999999999999999999999999999999999 -> T [on close to the maximum value]
-999999999.9999999999999999999999999999999999999999999999999999 -> T [on close to the minimum value]
-> F [on empty]
lolz -> F [on non-number value]
n4melyh4xor -> F [on non-number with digits]
1.2 -> F [on space-padded]
9.3 1.3 -> F [on anyhow separated multiple numbers]
1e5 -> F [no scientific notation]
50cl05e.buty3ts0f4r -> F [on input with letters obscuring the number]
1,2,3,4.5678 -> F [on badly readability-divided number]
1,234.5,678 -> F [on readability-divided floating point part]
.234 -> F [on no leading zero]
+1 -> F [no leading + sign]
1.234.3 -> F [only one decimal point]
12345,678 -> F [on separator stopping mid-way]
```
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), least characters is the winner.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~28~~ ~~29~~ ~~31~~ ~~40~~ 34 bytes
```
^-?\d{1,3}((,\d{3})*|\d*)(\.\d+)?$
```
Outputs `1` if truthy, `0` otherwise. As far as I understand, in this case Retina outputs the number of matches the regex has on the input.
[Try it online!](https://tio.run/nexus/retina#@x@nax@TUm2oY1yroaEDZBnXamrVxKRoaWrE6MWkaGvaq/z/b2hkrGNiagLEZgA "Retina – TIO Nexus")
[Test Suite](https://tio.run/nexus/retina#NY1BDoIwEEX3c4ouiAEsk5a2Iisu0hgValgUSAATUTk7TkmcxX/vb@Zv3fWSVbb5SK7WOOZkak3Sr23SJLZom2NSRRAdWMa621y3bto2mSvIQgigRG1OgZyIxbkMThpM7CdxBzUSAD/4N/S6c35p9WsYgTGJOZSoiAqkM2BE7YVxeH/Oi5on8dAjSJ5z2sDwORRFyoMj6X@/@AE "Retina – TIO Nexus")
### Edits
* Fixed to comply with the "there should be digits after the decimal place" rule
* Fixed to comply with the "handle negatives" rules
* Fixed to comply with the optional comma separators
* Fixed bug with thousands separators as noted by @MartinEnder
* Golfed by removing conditional lookahead
### RegExplanation
```
^-?\d{1,3}((,\d{3})*|\d*)(\.\d+)?$
^ $ This marks the start and end of regex
-? Optional hyphen for negative number
\d{1,3} Matches between 1 and 3 digits
( ) Capturing group
(,\d{3})* Matches at least zero of comma and three numbers (in the case of separators)
| OR
\d* Matches at least zero digits (in the case of no separators)
(\.\d+)? Matches an optional . and at least one digit (for decimal numbers)
```
[Answer]
# JavaScript, ~~46~~ 49 bytes
This is a direct port of my Retina answer. The only reason I used JS is so that there is an easy way to test the regex using the Snack Snippet below
```
f=s=>/^-?\d{1,3}((,\d{3})*|\d*)(\.\d+)?$/.test(s)
```
---
```
f=s=>/^-?\d{1,3}((,\d{3})*|\d*)(\.\d+)?$/.test(s)
```
```
<input oninput=p.innerText=f(value)><p id=p></p>
```
[Answer]
# [Perl 6](https://perl6.org), 42 bytes
```
{?/^\-?[\d**1..3[\,\d**3]+|\d+][\.\d+]?$/}
```
[Try it](https://tio.run/nexus/perl6#dVPbctowEH3XV@xMMyUhtoEY2mZok7d8AW/gzsjWgjUjS44kkzq3X6crg@OkkzIMhj179uyeXRqHsELnl6xWXMN4yVjVwtfCCIRfcHi6nfzexLfrjRiPZ0mSrjdR@Jpml88bcZmtN0l43J5NXg5bY0FJje78Ap4YA/gCNbdU3lP5gjt0FKsm9AFw9lPquvE3JJGMu8gI4hsYnUBvG18GcL16vstO@HoErzDKRoQLdEUHJ@OATpZBjto@66oCIa@9wvKEWHSN8oS8Vcd7GK1GPR5KwonZlQ8AvaWD4MV5X/si6mtFRxJ7YUwYjXEYU@rdYXaVhllWsDYapPa4Q5uxeAhr3HEv9wi6qXK0DjSiAG8gRyi5FgpFxqZDjUe0JmPET@aLb0N4qwwPglAbUukSIkpIvv@4HpJwj1q1IOReChLJW0jpx056Bw/SlzRbxV3HJerA9KVpHLUCDmmH3Bvqklvq2HiweN9I2/XYvWZJ9xg0FXJBfU285VKFBsMALqQn03/GgqDxn3xyn3LvjmNUtW8zpox6HILa6PhoIey5ajBjel6hasv5HzrFz9K6kY/jh7uZJVdDmqt5gXHNhQijXScpwekAc92W5qH3g6ys6ARkrd62SCbi4pSvDbhCovZyK4tgGi3K6IwtpoWaLjDJG9@m3k2383d9Hu@ra1Gh9@EwTO6KxgZLfNkLkU50FdGqk7CwgZ5zQYu25CXPyUbfxv3S3/FSYkUfaJ8RPl5W@BfTeSVEfm8qbK0hsDvOvw)
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
? # turn the following into a Bool result
/ # match implicitly against 「$_」
^ # beginning of string
\- ? # optional leading 「-」
[
\d ** 1..3 # 1 to 3 digits
[
\, # comma
\d ** 3 # three digits
]+ # repeat at least once
| # or
\d+ # at least one digit
]
[ \. \d+ ]? # 「.」 followed by at least one digit optionally
$ # end of string
/
}
```
[Answer]
# PHP, 62 bytes
```
<?=preg_match("#^-?(\d+|\d{1,3}(,\d{3})*)(\.\d+)?$",$argv[1]);
```
The builtin cannot handle commas and it accepts scientific notation; so I had to walk the regex way. `<?=is_numeric($argv[1]);` would have been 24 bytes.
[Answer]
# bash/Unix tools, 64 bytes
```
egrep -c '^-?([0-9]+|[0-9]{1,3}(,[0-9]{3})+)(\.[0-9]+)?$'<<<"$1"
```
Save this as a file, and pass the string to be tested as the first argument to the command.
Output is 0 for a non-number, 1 for a number.
If you're willing to accept input from stdin and if you can guarantee that the input consists of just one line, then you can remove the <<<"$1" at the end, resulting in **57 bytes**.
As for the code itself, the -c option to egrep counts the number of matching lines (which will be either 0 or 1).
[Answer]
# Pyth, 25 characters
```
:zCiCM"૧祥쪤"^T6
```
Compresses [Kritixi Lithos’ regex](https://codegolf.stackexchange.com/a/103445/3852).
[Try it online.](https://pyth.herokuapp.com/?code=%3AzCiCM%22%E0%AB%A7%F2%A1%8A%AA%F1%9B%A8%AE%F2%B6%9F%89%F1%A0%AB%8A%F2%86%BB%9B%F1%93%B0%9A%E7%A5%A5%F1%AF%AF%8F%F3%AA%AC%A1%F2%A2%9D%89%F1%81%98%8D%F1%B2%B2%82%EC%AA%A4%22%5ET6&input=-123.45&debug=0) Uses Unicode characters outside the Basic Multilingual Plane, which TIO apparently can’t handle? This little app reports the wrong size for the string, though. [This character/byte counter](https://mothereff.in/byte-counter#:zCiCM"%E0%AB%A7%F2%A1%8A%AA%F1%9B%A8%AE%F2%B6%9F%89%F1%A0%AB%8A%F2%86%BB%9B%F1%93%B0%9A%E7%A5%A5%F1%AF%AF%8F%F3%AA%AC%A1%F2%A2%9D%89%F1%81%98%8D%F1%B2%B2%82%EC%AA%A4"%5ET6) gets it right.
[Answer]
# C89, 195 bytes
```
b,d,c,i;f(char*s){b=*s;for(d=c=i=0;i++,*(s++),d+=*s=='.',c+=*s==',',b=c?i&(i%4!=3)&*s==','?0:b:b;)if(*s==45&!i);else if((*s==32)|(*s==46)|*s==43|!isdigit(*s)&*s!=46&*s!=44)||!(d-1))b=0;return b;}
```
Ungolfed:
```
bool is_base10_number (const char* const str) {
if(!str[0])return false;
size_t
dpts = 0,
cmas = 0;
for (size_t i = 0; i < strlen(str); i++) {
if ((str[i] == '-') && (!i)){
continue;
}
if (
(str[i] == ' ')
|| (str[0] == '.')
|| (str[0] == '+')
||
(
(!isdigit(str[i]))
&& (str[i] != '.')
&& (str[i] != ',')
)
) {
return false;
}
dpts += str[i] == '.';
cmas += str[i] == ',';
if (cmas) {
if (i & ((i % 4) != 3) & str[i] == ',') {
return false;
}
}
}
if (dpts > 1) { return false; }
return true;
}
```
[Answer]
## Python 2, 79 bytes
Regex solution
```
import re
lambda s:[s]==re.findall('-?(?:\d{1,3}(?:,\d{3}\d+)(?:\.?\d+)?',s)
-? | Starts with 0-1 dashes
(?:\d{1,3}(?:,\d{3})+ | Have 1-3 digits and 1+ (comma followed by 3 digits)
|\d+) | or 1+ digits
(?:\.?\d+)? | Ends with dot and 1+ digits or nothing
```
[Try it online](https://tio.run/nexus/python3#pZBdboUgEIXfZxXzhubCBETbamJcSO2Dt2pqgj8BmvS2vWu3YOMG2kngfAMMmTMj1tjuppuvfYeuenYvdW0HGqel74xJmGiSpmr7L8X1PRAPqO/p5bvtL2m8oSZSw7hLYZq31Xq0w@4H5134mTEmlORSSpIZSFCZjovy4gEyzYPQ41MZjwJGkkcoOgRimYTyDCr/ECD@WY9w9MdDgyThtANxP40JocSvs7zgwQeY1XzCks@Dub3lH6sFREUZlKSDhodDAYV8NbIY6Prub9o7OeYWFMeMo@aYUxzHkevAHGNGgeGiQEUgHWZLbjOTT1i7sBRgXC3GweO0HOoqwM1Oi0/GJOZpuv8A)
[Answer]
# c#, 75 bytes
```
bool t(string n){double v;return double.TryParse(n.Replace(",",""),out v);}
```
] |
[Question]
[
# Definition
Here is the process to describe a number:
* For each number from `0` to `9` that is present in the number:
* Write down the frequency of that digit and then the digit.
For example, for the number `10213223`:
* There is `1` occurrence of `0`,
* `2` occurrences of `1`,
* `3` occurrences of `2`,
* `2` occurrences of `3`.
Therefore, the number that describes `10213223` is `10213223` (`10` from the first property, `21` from the second, etc.).
Note that the number of occurrences of a digit **may be greater than 9**.
# Task
You are to print/output all numbers that describe themselves.
# Specs
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/48934) apply, except that you are **allowed** to hardcode the output or store information related to the output in your program.
* The numbers in the output can be in **any order**.
* The numbers in the output are **allowed** to have duplicates.
* You may use **any separator**, if you choose to print instead of output.
* You are **allowed** to prefix and/or postfix output if you choose to print instead of output.
* The separator and the prefix and the postfix may **not** contain any digits (U+0030 to U+0039).
* The solution must compute in **one day**.
# Full list (109 items)
```
22
10213223
10311233
10313314
10313315
10313316
10313317
10313318
10313319
21322314
21322315
21322316
21322317
21322318
21322319
31123314
31123315
31123316
31123317
31123318
31123319
31331415
31331416
31331417
31331418
31331419
31331516
31331517
31331518
31331519
31331617
31331618
31331619
31331718
31331719
31331819
1031223314
1031223315
1031223316
1031223317
1031223318
1031223319
3122331415
3122331416
3122331417
3122331418
3122331419
3122331516
3122331517
3122331518
3122331519
3122331617
3122331618
3122331619
3122331718
3122331719
3122331819
10413223241516
10413223241517
10413223241518
10413223241519
10413223241617
10413223241618
10413223241619
10413223241718
10413223241719
10413223241819
41322324151617
41322324151618
41322324151619
41322324151718
41322324151719
41322324151819
41322324161718
41322324161719
41322324161819
41322324171819
1051322314251617
1051322314251618
1051322314251619
1051322314251718
1051322314251719
1051322314251819
1051322325161718
1051322325161719
1051322325161819
1051322325171819
5132231425161718
5132231425161719
5132231425161819
5132231425171819
5132232516171819
106132231415261718
106132231415261719
106132231415261819
106132231426171819
106132231526171819
613223141526171819
1011112131415161718
1011112131415161719
1011112131415161819
1011112131415171819
1011112131416171819
1011112131516171819
1011112141516171819
1011113141516171819
1111213141516171819
10713223141516271819
101112213141516171819
```
# References
* Autobiographical numbers: [OEIS A047841](http://oeis.org/A047841)
* Biographical number: [OEIS A047842](http://oeis.org/A047842)
[Answer]
# gawk, 161 bytes
```
BEGIN{
for(split("0 10 2 2 1 1 1 1",a);c=c<11;n=o=_){
while(++$c>a[c]+1)$(c++)=0;
for(i in a)n=$i?n$i i-1:n;
for(i=10;i--;)if(d=gsub(i,i,n))o=d i o;
if(n==o)print n
}
}
```
(line breaks and tabs for clarity)
It's a simple counter which uses the fact that each number has a limited occurrence. For instance is 0 no more than one time in any number, 1 no more than 11 times, 2 no more than 3 times ... and so on.
This way there are only 124415 numbers to check.
It then creates all numbers and checks their validity.
Completes in a few seconds.
[Answer]
# dc, 487 bytes
Hardcoded the solution. I start with 22 and add the differences to get the the next numbers. Some returning operations like adding 1 five times in a row are stored in registers.
This is my first program ever written in dc so it can probably golfed a lot more.
`[1+d1+d1+d1+d1+d]sa[1+d1+d1+d1+d97+d]sb[1+d1+d99+d1+d100+d]sc[1+d1+d1+d98+dlcx]sd[1+d100+d10000+d]se22d10213201+d98010+d2081+dlax11008995+dlax9800995+dlax208096+dlbxldx999891495+dlax2091108096+dlbxldx10410100909697+dldx30909100909798+dlcx9899+dlex1009999990079798+dlcx10909899+dlex4080909099989899+dlex1091000000+d100999998899089899+d1+d100+d10910000+d10 8^+d50709091 10 10^*+d397888989888989899+dlex10 6^+d10 8^+d10 10^+d10 12^+d1001 10 14^*+d9602010000000100000+d90398989999999900000+f`
You can execute the program using `dc -e "[solution]"`, where [solution] is the string above. It outputs the numbers in reverse order. `dc -e "[solution]" | sort -n` for output in the same order as the list.
[Answer]
# [Haskell](https://www.haskell.org/), 157 bytes
```
c=concat
d!n=['1'..n]>>[d]
r n=['0'..n]
a=r '9'
b s=c[shows n[d]|d<-a,n<-[sum[1|x<-s,x==d]],n>0]
main=print[x|x<-b.c.zipWith(!)a<$>mapM r"1;33222211",x==b x]
```
[Try it online!](https://tio.run/##HYzRCoMgGEbvfQqLgRuU5LoaU99g17sQL0wHSfUX2piM3t3VzuU5H19v4vAax5ytsDNYsyJXgFCEEUpBS6mcRgEfpvkbZETA5EZQh6OwKvbzJ2LYV5vjtamA1yq@J8W2xOtYJSGc1hXIRqPJeBBL8LCqdNSOWvr1y9Ov/bm4GH6Sk1keOJTs3rbXHcbK46DDSef8Aw "Haskell – Try It Online")
Inspired by the gawk answer, this loops over all strings of 0–1 zeros, then 0–11 ones, then 0–3 twos, .... It "biographs" the string (`b "01111122" == "105122"`) and prints that result if is, itself, autobiographical (`b x == x`).
[Answer]
# Ruby, 776 bytes
The rules say that "you are allowed to hardcode the output", so this solution does just that.
```
x="m|62wkn|65075|651sy|651sz|651t0|651t1|651t2|651t3|cp0ei|cp0ej|cp0ek|cp0el|cp0em|cp0en|ij2wi|ij2wj|ij2wk|ij2wl|ij2wm|ij2wnAh3Ah4Ah5Ah6Ah7AjwAjxAjyAjzAmpAmqAmrApiApjAsb|h1yp02|h1yp03|h1yp04|h1yp05|h1yp06|h1yp07Bc7Bc8Bc9BcaBcbBf0Bf1Bf2Bf3BhtBhuBhvBkmBknBnfFh8Fh9FhaFhbFk1Fk2Fk3FmuFmvFpnC08xC08yC08zC0bqC0brC0ejC81iC81jC84bCfu3EsxkfohEsxkfoiEsxkfojEsxkfraEsxkfrbEsxkfu3Et429yuEt429yvEt42a1nEt42hrf|1ej82kg93hy|1ej82kg93hz|1ej82kg93kr|1ej82kg9baj|1ej832ht8a3|t10qi0rmwpi|t10qi0rmwpj|t10qi0rmwsb|t10qi0y4qzv|t10qi2lo3hn|4nq1gm5kd1grG4p2zeraG4p2zerbG4p2zeu3G4p2zmjvG4p3l25nG4qr4enfG9c4v417|7ojtp0qb1maz|8fxg6lw9mtyj|29e6onjxe94gb|lc7bc5zbz4je3";a="|inj,|1fmye,|enb7ow,|enb7,|acnu,|3ovro98,|7ojtc".split',';b="ABCDEFG";7.times{|i|x.gsub! b[i],a[i]};x.split('|').map{|x|p x.to_i 36}
```
---
# Ruby, 116 bytes
A much shorter program that takes way too long to run, but given long enough should be able to do it. I do not know if it fits the time constraint.
```
f=->n{(?0..?9).map{|x|[n.to_s.chars.count{|c|c==x},x]}.select{|a|a[0]>0}.join.to_i}
(10**9).times{|i|p i if i==f[i]}
```
[Answer]
# [///](//esolangs.org/wiki////), 542 bytes
```
/:/\/\///^/13223:!/31:*/
10:#/!223!:&/4^241:$/1819:(/51617:)/
!3!:%/5^142:@/111:-/*@121!:_/51:+/
!123!:=/41:A/617:B/19:C/*!3!:D/18:E/6^1=52:F/
#:G/
2^:H/*5^2:I/1!=($:J/_6:K/
&:L/*&:M/_7/22*2^*!1233C4C5C6C7C8C9G14G15G16G17GDGB+4+5+6+7+8+9)=5)=6)=7)=8)=9)J)M)_8)_9)A)6D)6B)7D)7B)8B*#4*#5*#6*#7*#8*#9F=5F=6F=7F=8F=9FJF_7F_8F_9FAF6DF6BF7DF7BF8BLJLML_8L_9LAL6DL6BL7DL7BL8BK(KJDKJBKMDKMBK5$KADKABK6$K7$*%(*%JD*%JB*%MD*%MB*%5$H(DH(BHJ$HM$
%(D
%(B
%J$
%M$
5^2($*EAD*EAB*E6$*6^142A$*6^152A$
EA$-=(D-=(B-=J$-=_7$-=617$-($*@121=($*@I
@12I*7^1=_627$*@22I
```
[Try it online!](http://slashes.tryitonline.net#code=LzovXC9cLy8vXi8xMzIyMzohLzMxOiovCjEwOiMvITIyMyE6Ji80XjI0MTokLzE4MTk6KC81MTYxNzopLwohMyE6JS81XjE0MjpALzExMTotLypAMTIxITpfLzUxOisvCiExMjMhOj0vNDE6QS82MTc6Qi8xOTpDLyohMyE6RC8xODpFLzZeMT01MjpGLwojOkcvCjJeOkgvKjVeMjpJLzEhPSgkOkovXzY6Sy8KJjpMLyomOk0vXzcvMjIqMl4qITEyMzNDNEM1QzZDN0M4QzlHMTRHMTVHMTZHMTdHREdCKzQrNSs2KzcrOCs5KT01KT02KT03KT04KT05KUopTSlfOClfOSlBKTZEKTZCKTdEKTdCKThCKiM0KiM1KiM2KiM3KiM4KiM5Rj01Rj02Rj03Rj04Rj05RkpGXzdGXzhGXzlGQUY2REY2QkY3REY3QkY4QkxKTE1MXzhMXzlMQUw2REw2Qkw3REw3Qkw4QksoS0pES0pCS01ES01CSzUkS0FES0FCSzYkSzckKiUoKiVKRColSkIqJU1EKiVNQiolNSRIKERIKEJISiRITSQKJShECiUoQgolSiQKJU0kCjVeMigkKkVBRCpFQUIqRTYkKjZeMTQyQSQqNl4xNTJBJApFQSQtPShELT0oQi09SiQtPV83JC09NjE3JC0oJCpAMTIxPSgkKkBJCkAxMkkqN14xPV82MjckKkAyMkk)
**Definitely** less than 1440 bytes for sure!!! Uses 28 constants along with the literal, an unusually high amount for ///.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~21~~ 20 bytes
```
f₁N
=⁰dΣf←Ṡzem#d⁰ŀ10
```
[Try it online!](https://tio.run/##yygtzv7/P@1RU6Mfl@2jxg0p5xanPWqb8HDngqrUXOUUoMjRBkOD////GxoYGRobGRkBAA "Husk – Try It Online")
Not sure if it will complete in one day, but it does a straightforward test and filters the infinite list of natural numbers by it. No hardcoding.
Theoretically, it will definitely print all autobiographical numbers, and proceed to check till the heat death of the universe.
-1 byte after correcting the algorithm.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes
```
DFṢŒrU
3x8“¢¿‘;µ,€"J’$ŒPŒp€ẎḊÇƑƇVV
```
This program is too slow for TIO, but finished in 2 minutes 8.375 seconds on my computer (thus, less than one day, as required by the question). It can easily be optimized to work on TIO too:
## [Jelly](https://github.com/DennisMitchell/jelly) (Try It Online!), 36 bytes
```
DFṢŒrU
2x6“¢¿¤¤‘;µ,€"J’$ŒPŒp€ẎḊÇƑƇVV
```
[Try it online!](https://tio.run/##y0rNyan8/9/F7eHORUcnFYVyGVWYPWqYc2jRof2Hlhxa8qhhhvWhrTqPmtYoeT1qmKlydFLA0UkFQO7DXX0Pd3Qdbj828Vh7WNj/w@2HtkY@3NnycOfsRw1zD22DMA9t9fkPAA "Jelly – Try It Online") (The footer prints the list of results, plus a count of how many results there are.)
## Algorithm
The basic idea is to generate lists of (frequency, number) pairs and then check to see if they correspond to an autobiographical number (by collapsing them into a list of digits, then calculating how many times each digit appears and seeing if it matched the original list of (frequency, number) pairs). We have to generate every list that corresponds to an autobiographical number, but are allowed to also generate extras, as long as we can check and reject them within the time limit.
Any answer has at most one 0, eleven 1s, three 2s, three 3s, and two of any other digit. \$2×12×4×4×3^6=279936\$, a small enough list to check in a minute, so we can just generate all (frequency, number) lists with less than these frequencies to get the TIO version of the program. For the "main" submission, we also generate (useless) lists which can have up to four copies of digits in the 4…9 range, because doing so is slightly shorter to express in Jelly; that's \$2×12×4^8=1572864\$ lists which is still a small enough number to check within a day.
## Explanation
### Helper function `1Ŀ`
The helper function takes an arbitrary list of (frequency, digit) pairs, counts how many times each digit appears within the frequencies and digits, and returns the appropriate list of (frequency, digit) pairs, sorted by the digit.
If this function is run on a list of (frequency, digit) pairs that represent those of an autobiographical number and are sorted by the digit, the output will be the same as the input. Otherwise, the output will differ from the input.
```
DFṢŒrU
D Split each number within the frequencies and digits into digits
F Recursive flatten, into a flat list of digits
Ṣ Sort the list of digits
Œr Run-length-encode, into (element, frequency) format
U Reverse each interior list, producing (frequency, digit) format
```
### Main program
```
3x8“¢¿‘;µ,€"J’$ŒPŒp€ẎḊÇƑƇVV
3x8 [3,3,3,3,3,3,3,3]
; prepend
“¢¿‘ [1,11]
" to each element
€ for all numbers from 1 to that element
, pair that number with
µ the element's
J’$ 0-based index
ŒP €Ỷ for each subsequence of the resulting list
Œp take its Cartesian product
Ḋ discard the first result (the empty list [])
Ƈ filter the lists, keeping those that
Ƒ are unchanged upon
Ç running the helper function 1Ŀ
V numerical concatenation of frequency with digit
V numerical concatenation of those concatenations
```
This is mostly very straightforward, with the only confusing part being the various amounts of flattening and unflattening that go on. In particular, the `ŒPŒp€Ẏ` portion is the best way I found to write "from these sublists, select one or possibly no elements from each, and concatenate them"; the `ŒP` chooses which sublists will have no elements selected, the `Œp€` selects one element from each of the rest, and the `Ẏ` collapses the structure which the `ŒP` introduced.
## If there were no time limit…
you could do the task in 13 bytes:
```
ṢŒrUFV
2*JÇƑƇ
```
[Try it online!](https://tio.run/##y0rNyan8///hzkVHJxWFuoVxGRoYG4BAEZBhBGIoHG4/NvFY@///AA "Jelly – Try It Online") (starts the search from just before a valid answer, and returns only 7 answers, so that you can see the program working)
The idea here is to search every possible number from 1 to 21000, returning only those which are autobiographical. Obviously, this won't finish in a reasonable length of time. (The choice of 21000 is mostly arbitrary – it's a number that can be calculated in Jelly using only three bytes. I couldn't find a way to calculate a number large enough using only two.)
I have a suspicion that there are a range of possible answers to this question which make different speed/brevity tradeoffs, so it's probably going to be possible to beat 34 bytes by making a program that takes longer to run but still fits within a single day. It's hard to know exactly where the byte savings should go, though.
[Answer]
# Python 2.7 - 684 bytes
```
o=[22]
i=[[10213223,100096],[21322314,5],[31123314,5],[31331415,404],[1031223314,5],[3122331415,404],[10413223241516,303],[41322324151617,20202],[1051322314251617,202],[1051322325161718,10101],[5132231425161718,10101],[5132232516171819,0],[106132231415261718,101],[106132231426171819,0],[106132231526171819,0],[613223141526171819,0],[1011112131415161718,10101]]
l=[1011112131416171819,1011112131516171819,1011112141516171819,1011113141516171819,1111213141516171819,10713223141516271819,101112213141516171819]
for n in i:
for x in range(n[0],n[0]+n[1]):
m="";x=str(x)
for v in range(10):
v=str(v);c=x.count(v)
if c!=0:
m=m+str(c)+v
if m==x:o.append(m)
o+=l
print o
```
Kind of half hard coded and half computed. It takes the approach of splitting the numbers into groups of a manageable size with an upper and lower limit. The list i stores the lower limit and the difference between it and the upper limit as a nested list, All potential candidates are then checked within the range added to the output list o. The last 7 numbers are so far apart that it is cheaper to store them in their own list and add it at the end.
It currently runs in a couple of seconds and obviously increasing the group size would reduce the byte count but increase the run time. Not sure what it would come down to and still be within the one day limit.
] |
[Question]
[
Given a Gaussian integer \$a+bi\$ where \$a\$,\$b\$ are integers and \$i = \exp\left(\pi i/2\right)\$ is the imaginary unit, return the closest (w.r.t to the Euclidean distance) Eisenstein integer \$k+l\omega\$ where \$k\$,\$l\$ are integers and \$\omega = \exp(2\pi i/3) = (-1+i\sqrt{3})/2\$.
### Background
It is probably quite obvious that every Gaussian integer can uniquely be written as \$a+bi\$ with \$a\$,\$b\$ integers. It is not so obvious but nonetheless true: Any Eisenstein integer can uniquely be written as \$k+l\omega\$ with \$k\$,\$l\$ integers. They both form a \$\mathbb{Z}\$-module within the complex numbers, and are both p-th cyclotomic integers for \$p=2\$ or \$3\$ respectively. Note that \$3+2i \neq 3+2\omega\$

Source: commons.wikimedia.org
### Details
* In case the given complex number has two or three closest points, any of those can be returned.
* The complex number is given in rectangular coordinates (basis \$(1,i)\$), but other than that in any convenient format like `(A,B)` or `A+Bi` or `A+B*1j` etc.
* The Eisenstein integer has to be returned as coordinates of the basis \$(1,\omega)\$ but other than that in any convenient format like `(K,L)` or `K+Lω` or `K+L*1ω` etc.
### Examples
All real integers should obviously be mapped to the real integers again.
```
6,14 -> 14,16
7,16 -> 16,18
-18,-2 ->-19,-2
-2, 2 -> -1, 2
-1, 3 -> 1, 4
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 16 bytesSBCS
```
⎕0+⌈3÷⍨1 2×⌊⎕×√3
```
[Try it online!](https://tio.run/##PYwxDsIwDEX3nMI7sYSTqC0Ld6mUlKUCBgY4ARVquyEkJHY2RnZ6k1wkOEbUkuX/n79d71v0p7rdbTAcD2Hrg0@xOzcpjtflIvadnd5xeBKY6Rb7C1Oe3d3mUAKpRpFThZpNocrZfF6Gm6oZGEF/Z/NSqTg8AApNDnAN5DS/EFSyEsS7KiOkSqNhhLRiISk0GjICJBY/xMrKoQb3BQ "APL (Dyalog Extended) – Try It Online")
A full program that takes `y` then `x` from standard input and prints a 2-element vector of integers.
### How it works: the math
First of all, note that any Gaussian integer will be placed on the vertical diagonal of a diamond, with the point \$Z\$ placed at \$(x,\sqrt3y)\$ for some integer \$x,y\$.
```
+ W
/|\
/ | \
/ | \
/ + X \
/ | \
+-----|-----+V
\ | /
\ + Y /
\ | /
\ | /
\|/
+ Z
```
In the figure, \$\overline{WZ}=\sqrt3\$ and \$\overline{WX}=\overline{XY}=\overline{YZ}=\overline{XV}=\overline{YV}=\frac{1}{\sqrt3}\$. So, given the vertical position of a point, we can identify the nearest Eisenstein point as follows:
$$
\text{Given a point }P \in \overline{WZ}, \\
\left\{
\begin{array}{c}
P \in \overline{WX} \implies \text{the nearest point is } W \\
P \in \overline{XY} \implies \text{the nearest point is } V \\
P \in \overline{YZ} \implies \text{the nearest point is } Z
\end{array}
\right.
$$
Given a Gaussian point \$P\$, we first determine which diamond \$P\$ belongs to, measured by how many diamonds (denoted \$h\$) \$Z\$ is away from the \$x\$-axis.
$$
h = \lfloor P.y \div \sqrt3 \rfloor
$$
Then the Eisenstein coordinates of \$Z\$ are
$$
Z.x\_E = P.x+h, \quad Z.y\_E = 2h
$$
Now, we determine which of the segments \$\overline{WX},\overline{XY},\overline{YZ}\$ \$P\$ belongs to. For this, we can calculate the indicator \$w\$ as follows:
$$
w = \lfloor P.y \times \sqrt3 \rfloor \% 3
$$
Then the cases \$ w = 0, 1, 2 \$ correspond to \$\overline{YZ},\overline{XY},\overline{WX}\$ respectively. Finally, the nearest Eisenstein point of \$P\$ (which is one of \$Z\$, \$V\$, or \$X\$) can be calculated as:
$$
P\_E.x\_E = P.x+h+\lceil \frac{w}2 \rceil, \quad P\_E.y\_E = 2h+w
$$
Using the identities for \$h\$ and \$w\$, we can further simplify to:
$$
y' = \lfloor P.y \times \sqrt3 \rfloor, \quad P\_E.x\_E = P.x+\lceil y' \div 3 \rceil, \quad P\_E.y\_E = \lceil 2y' \div 3 \rceil
$$
### How it works: the code
```
⎕0+⌈3÷⍨1 2×⌊⎕×√3
⌊⎕×√3 ⍝ Take the first input (P.y) and calculate y'
⌈3÷⍨1 2× ⍝ Calculate [ceil(y'/3), ceil(2y'/3)]
⎕0+ ⍝ Take the second input(P.x) and calculate [P.x+ceil(y'/3), ceil(2y'/3)]
```
[Answer]
## JavaScript (ES6), 112 bytes
```
(a,b,l=b/Math.pow(.75,.5),k=a+l/2,f=Math.floor,x=k-(k=f(k)),y=l-(l=f(l)),z=x+y>1)=>[k+(y+y+z>x+1),l+(x+x+z>y+1)]
```
ES7 can obviously trim 9 bytes. Explanation: `k` and `l` initially represent the floating-point solution to `k+ωl=a+ib`. However, the coordinates needed to be rounded to the nearest integer by Euclidean distance. I therefore take the floor of `k` and `l`, then perform some tests on the fractional parts to determine whether incrementing them would result in a nearer point to `a+ib`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~39~~ ~~38~~ 35 bytes
```
t|Ekt_w&:2Z^tl2jYP3/*Zeh*!sbw6#YkY)
```
Input format is `6 + 14*1j` (space is optional). Output format is `14 16`.
[**Try it online!**](http://matl.tryitonline.net/#code=dHxFa3RfdyY6MlpedGwyallQMy8qWmVoKiFzYnc2I1lrWSk&input=NiArIDE0KjFq)
### Explanation
The code first takes the input as a complex number. It then generates a big enough hexagonal grid in the complex plane, finds the point that is closest to the input, and returns its Eisenstein "coordinates".
```
t % Take input implicitly. This is the Gauss number, say A. Duplicate
|Ek % Absolute value times two, rounded down
t_ % Duplicate and negate
w&: % Range. This is one axis of Eisenstein coordinates. This will generate
% the hexagonal grid big enough
2Z^ % Cartesian power with exponent 2. This gives 2-col 2D array, say B
t % Duplicate
l % Push 1
2jYP3/* % Push 2*j*pi/3
Ze % Exponential
h % Concatenate. Gives [1, exp(2*j*pi/3)]
* % Multiply by B, with broadcast.
!s % Sum of each row. This is the hexagonal grid as a flattened array, say C
bw % Bubble up, swap. Stack contains now, bottom to top: B, A, C
6#Yk % Index of number in C that is closest to A
Y) % Use as row index into B. Implicitly display
```
[Answer]
# [Haskell](https://www.haskell.org/), 128 bytes
```
i=fromIntegral;r=[floor,ceiling];a!k=(i a-k)**2;c(a,b)|l<-2*i b/sqrt 3,k<-i a+l/2=snd$minimum[(x k!k+y l!l,(x k,y l))|x<-r,y<-r]
```
[Try it online!](https://tio.run/##FYzBboMwEETvfMUS5WDDWhG0SiOBe6/UnnpEqHIISSyv7dQmKpHy79RcZt/s7OxVRTMSLYuW5@Dth5vGS1DUBNmdyfuAw6hJu0vfqNxIpkEJw4uibgam8Mif1Iq60HDcxd8wwQuaVqSbkna1jO60tdppe7cdm8HkpnwA5YSrwYScP@dWBHwk6ZchjjCDhJPPAG736XsKnw62EK/@LwVlCRsQ70kSrTs2wMyzzCrtUsuq29cPrD86tsfqlSN7w2qfhqgOKGreL/8 "Haskell – Try It Online")
For input Gaussian integer (a,b), convert it into Eisenstein coordinates, floor and ceil both components to get four candidates for closest Eisenstein integer, find the one with minimal distance and return it.
[Answer]
# [Tcl](http://tcl.tk/), ~~124~~ ~~116~~ 106 bytes
```
{{a b f\ int(floor(2*$b/3**.5)) {l "[expr $f+(1-$f%2<($b-$f)*3**.5)]"}} {subst [expr $l+$a-($f+1)/2]\ $l}}
```
[Try it online!](https://tio.run/##ZcxRC8IgAATg937FMQzUYUOr1UP/ZPNhxoRAmkwHhfjbbVBP7e34uLt4dyWMERZ9SWmAge3xeEZq3TTNVHFimiPnhzNjSA5VN778DGJrKgWxe3WjxKyB8W9JVzkjhcWEiF/V1WQQdF1I1ijdr5Bz8UsM6Abv3Xs9Qwt50rs/vEC2GxTyCqG2rKB0@QA "Tcl – Try It Online")
This is somewhat inspired by the three-year old post from @Neil
The floor function returns the corner of the rhombus whose edges are the vectors 1 and \$\omega\$. With respect to this rhombus, the Gaussian integer lies on the perpendicular bi-sector of either the top (if l is even) or bottom (if l is odd). This is important because it means that either the lower left corner or the upper right corner will be an acceptable solution. I compute k for the lower left corner, and do one test to see if the Gaussian integer lies above or below the diagonal separating the two corners; I add 1 to k when above the diagonal, and I do likewise for l.
Saved 10 bytes by using the "sign of the cross-product v x d of the diagonal d with the vector v joining the lower right corner and (a,b)" as the test for which side of the diagonal the point lies.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 24 bytes
```
pe@3r@2././J2./x/.+CL)R_
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/INXBuMjBSE9fT98LSFbo62k7@2gGxf//b65gaAYA "Burlesque – Try It Online")
Pretty sure this can be shorter. Input read as `a b`
```
pe # Parse input to two ints
@3r@2./ # sqrt(3)/2
./ # Divide b by sqrt(3)/2
J2./ # Duplicate and divide by 2
x/.+ # swap stack around and add to a
CL # Collect the stack to a list
)R_ # Round to ints
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
*Port of [Bubbler's APL answer](https://codegolf.stackexchange.com/a/198092/6484)*
```
3t*ïx‚3/îR΂+
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fuETr8PqKRw2zjPUPrws63Adkaf//r2vEpWtoAQA "05AB1E – Try It Online")
Input and output are both y first, x second.
] |
[Question]
[
Given an `m` by `n` chocolate bar, `m,n` positive, output the number of ways to break the bar into `mn` 1 by 1 pieces where each break occurs on a gridline.
Order is important. Pieces are also distinguishable, so the two pieces on either end of a 1 by 3 chocolate bar are not equivalent.
For instance, for a 2 by 2 block we have:
```
_ _ _ _ _ _ _ _
|_‖_| -> |‗| |_| -> |_| |‗| -> |_| |_|
|_‖_| |_| |_| _ |_| _ _
|_| |_| |_|
_ _ _ _ _ _ _ _
|_‖_| -> |_| |‗| -> |‗| |_| -> |_| |_|
|_‖_| |_| |_| |_| _ _ _
|_| |_| |_|
_ _ _ _ _ _ _ _
|‗|‗| -> |_‖_| -> |_| |_| -> |_| |_|
|_|_| _ _ _ _ _ _
|_|_| |_‖_| |_| |_|
_ _ _ _ _ _ _ _
|‗|‗| -> |_|_| -> |_‖_| -> |_| |_|
|_|_| _ _ _ _ _ _
|_‖_| |_| |_| |_| |_|
```
Hence there are 4 ways to break up a 2 by 2 chocolate bar.
### Rules
* Input will be two integers via function input, STDIN, command line or similar. Output a single number, the number of ways to break up the chocolate bar.
* Since the numbers go up pretty quickly, don't worry if the output exceeds the integer limits of your language – your submission will be valid as long as the algorithm theoretically works for all possible inputs.
### Test cases
The output doesn't depend on the order of `m,n`, so the test cases are listed such that `m <= n`.
```
1 1 -> 1
1 2 -> 1
1 3 -> 2
1 4 -> 6
1 5 -> 24
1 10 -> 362880
2 2 -> 4
2 3 -> 56
2 4 -> 1712
2 5 -> 92800
2 10 -> 11106033743298560
3 3 -> 9408
3 4 -> 4948992
3 5 -> 6085088256
3 10 -> 76209753666310470268511846400
4 4 -> 63352393728
```
[A261964](https://oeis.org/A261964) is the chocolate numbers arranged in a triangle such that each row corresponds to the sum `m+n`.
[Answer]
# Mathematica, 85 bytes
```
f=If[##==1,1,Tr[Sum[Binomial[1##-2,i#-1]f[i,#]f[#2-i,#],{i,#2-1}]&@@@{{##},{#2,#}}]]&
```
**Test case**
```
f[4,4]
(* 63352393728 *)
```
[Answer]
# Python 3, ~~168~~, ~~156~~, 147 bytes
Made improvements thanks to chat
```
f=lambda n:n<1or n*f(n-1);a=lambda m,n,c=lambda m,n:sum(f(m*n-2)/f(i*n-1)/f((m-i)*n-1)*a(i,n)*a(m-i,n)for i in range(1,m)):+(m+n<4)or c(m,n)+c(n,m)
```
Ungolfed:
```
f=lambda n:n<1or n*f(n-1) # Factorial
def a(m, n):
if m+n < 4:
return 1
first = 0
for i in range(1,m):
first += f(m*n-2) * 1/f(i*n-1) * 1/f((m-i)*n-1) * a(i,n) * a(m-i,n)
second = 0
for i in range(1,n):
second += f(m*n-2) * 1/f(i*m-1) * 1/f((n-i)*m-1) * a(i,m) * a(n-i,m)
return first + second
```
Algorithm was based on [this paper](http://www.emis.de/journals/JIS/VOL19/Khovanova/khova9.pdf).
I could probably cut it down a lot more, I'm just not sure where
[Answer]
# R, ~~208~~ 198 bytes
```
f=function(m,n){g=function(i,j){a=0;if(j>1)for(x in 2:j-1)a=a+choose(j*i-2,x*i-1)*M[x,i]*M[j-x,i];a};s=max(m,n);M=matrix(1,s,s);for(i in 1:s)for(j in 1:s)if(i*j>2)M[i,j]=M[j,i]=g(i,j)+g(j,i);M[m,n]}
```
Indented, with newlines:
```
f = function(m,n){
g=function(i,j){
a = 0
if(j>1) for(x in 2:j-1) a = a + choose(j*i-2,x*i-1) * M[x,i] * M[j-x,i]
a
}
s = max(m,n)
M = matrix(1,s,s)
for(i in 1:s) for(j in 1:s) if(i*j>2) M[i,j] = M[j,i] = g(i,j) + g(j,i)
M[m,n]
}
```
Usage:
```
> f(3,1)
[1] 2
> f(3,2)
[1] 56
> f(3,3)
[1] 9408
> f(4,3)
[1] 4948992
> f(5,3)
[1] 6085088256
```
[Answer]
# Python 2, 135 bytes
```
C=lambda A:sum(C(A[:i]+A[i+1:]+[(c,H),(W-c,H)])for i,Q in enumerate(A)for W,H in(Q,Q[::-1])for c in range(1,W))or 1
print C([input()])
```
Here's what I came up with. It's really slow, but here's a faster version (needs [repoze.lru](https://pypi.python.org/pypi/repoze.lru/0.6)):
```
from repoze.lru import lru_cache
C=lru_cache(maxsize=9999)(lambda A:sum(C(tuple(sorted(A[:i]+A[i+1:]+((c,H),(W-c,H)))))for i,Q in enumerate(A)for W,H in(Q,Q[::-1])for c in range(1,W))or 1)
print C((input(),))
```
### Examples
```
$ time python2 chocolate.py <<< 2,5
92800
real 0m2.954s
user 0m0.000s
sys 0m0.015s
$ time python2 chocolate-fast.py <<< 3,5
6085088256
real 0m0.106s
user 0m0.000s
sys 0m0.015s
```
### Explanation
The code defines a function `C` that takes an array of pieces. The algorithm is as such:
1. `for i,Q in enumerate(A)`: loop through the array of pieces.
2. `for W,H in(Q,Q[::-1])`: calculate ways twice, rotating 90 degrees.
3. `for c in range(1,W)`: loop through possible positions to split at.
4. `A[:i]+A[i+1:]+[(c,H),(W-c,H)]`: get a list without the split piece and with the two new pieces.
5. `C(…)`: call the function again on that list.
6. `sum(…)`: sum the results for each possible split.
7. `or 1`: if no splits are possible, there is exactly one way to split the chocolate.
Finally, the code is called with an array containing the input.
[Answer]
## ES6, 141 bytes
```
c=(m,n)=>(f=n=>n<2||n*f(n-1),h=(m,n)=>[...Array(m-1)].reduce((t,_,i)=>t+f(m*n-2)/f(++i*n-1)/f((m-i)*n-1)*c(i,n)*c(m-i,n),0),h(m,n)+h(n,m))||1
```
Based on the formula found by @CameronAavik. Ungolfed:
```
function fact(n) {
return n < 2 ? 1 : n * f(n - 1);
}
function half(m, n) {
total = 0;
for (i = 1; i < m; i++)
total += fact(m * n - 2) / fact(i * n - 1) / fact((m - i) * n - 1) * choc(i, n) * choc(m - i, n)
return total;
}
function choc(m, n) {
total = half(m, n) + half(n, m);
if (!total) total = 1;
return total;
}
```
] |
[Question]
[
```
+--+
+--+ | | +--+ +--+
| | | | | | | |
+--+ +--+ +--+ +--+
```
The people of ASCIIville are rebuilding their city and are sketching out new blueprints. Your job is to draw their new city based on how many buildings they want.
The input will be how many buildings there are. Each building is half the hight of the input (rounded up if odd), not including the top and bottom of the building.
Let's draw a basic example of `4`
```
+--+ +--+ +--+ +--+
| | | | | | | |
| | | | | | | |
+--+ +--+ +--+ +--+
```
As you can see here, there are two `|`s in every building because the input was four. *But there's a catch!* (meaning the example above is incorrect, and the example at the top of this post is the *real* output for 4)
For each building that isn't a prime number, its height goes down by one. If the number is divisible by *3*, *5*, or *10*, it goes down one more. If it's divisible by two or more of those numbers, the amount deducted adds up (*10 is divisible by 10 and 5, and it's not a prime, so it gets deducted by 3*).
Let's look at an example with an input of `5`.
```
+--+
+--+ | | +--+ +--+ +--+
| | | | | | | | | |
| | | | | | | | | |
+--+ +--+ +--+ +--+ +--+
```
Here's an example of `7`
```
+--+ +--+
+--+ | | +--+ +--+ +--+ | |
| | | | | | | | | | +--+ | |
| | | | | | | | | | | | | |
| | | | | | | | | | | | | |
+--+ +--+ +--+ +--+ +--+ +--+ +--+
```
And an example of `10`
```
+--+ +--+
+--+ | | +--+ +--+ +--+ | | +--+
| | | | | | | | | | +--+ | | | | +--+
| | | | | | | | | | | | | | | | | | +--+
| | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | |
+--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+
```
And back to `6`
```
+--+
+--+ | | +--+ +--+ +--+
| | | | | | | | | | +--+
| | | | | | | | | | | |
+--+ +--+ +--+ +--+ +--+ +--+
```
**Rules:**
* If a number gets deducted so much that it's height is less than or equal to zero, it is not shown but a space is left for it (I don't believe this is possible, `6` is the closest I've found to reaching zero).
* Trailing spaces are allowed.
* The width of each building must be 2.
* Your input can be from stdin or encoded into the program.
* Your program must be a *full program*, no functions.
* Your program must be able 4-15 builds. 0-3 and negative numbers aren't needed and are not specified to do anything, meaning they can throw an error, print garbage, or do nothing.
[Answer]
# CJam, ~~68 66 58~~ 55 bytes
This is too long for now. But a start.
```
ri:K"!;tK"206b4b<{S5*a*"+--+ "a:I+K)2/)"| | "e]I+}%zN*
```
*UPDATE: Now hardcoding for inputs till 15 instead of calculating the offset. Suggestion by Sp3000*
[Try it online here](http://cjam.aditsu.net/#code=ri%3AK%22!%3BtK%22206b4b%3C%7BS5*a*%22%2B--%2B%20%22a%3AI%2BK)2%2F)%22%7C%20%20%7C%20%22e%5DI%2B%7D%25zN*&input=10)
[Answer]
# Python 2, 247 245 237 229 bytes
```
I=input()
R=range
B=[(-~I/2)-(x%3<1)-(x%5<1)-(x%10<1)-(~all([x%a for a in R(2,x)]or[x==2])+2)for x in R(1,I+1)]
E='+--+'
O=['\n']*I
for r in R(I):
for h in B:O[r]+=['| |',' '*4,E][(r==h)+(r>=h)]
print ''.join(O[::-1])+'\n'+E*I
```
[Answer]
## C#, 223 205 bytes
This takes advantage of the need to only go to 15 buildings.
```
class P{
static void Main(string[]a){
int w=int.Parse(a[0]),
h=(w+3)/2,
b,
x,
y=-1;
for(;++y<=h;)
for(x=-2;++x<w;)
System.Console.Write(x<0?"\n":(b=y-("012021101211102"[x]&7))<0?" ":b>0&y<h?"| | ":"+--+ ");
}
}
```
### 260 bytes
And a more generic answer that will work for any number of buildings.
```
class P{
static void Main(string[]a){
int w=int.Parse(a[0]),
h=(w+3)/2,
b,
x,
y=-1;
for(;++y<=h;)
for(x=-2;++x<w;){
if(x<1)
b=-1;
else
for(b=1;++b<x;)
if((x+1)%b<1)break;
System.Console.Write(x<0?"\n":(b=y-x%3/2-x%5/4-x%10/9-(b<x?0:1))<0?" ":b>0&y<h?"| | ":"+--+ ");
}
}
}
```
[Answer]
# Python 2, 163 bytes
```
n=input()
k=-~n/2
for i in range(k+2):
s="";p=j=1
while~n+j:a=(j%3<1)+(j%5<1)+(j%10<1)+(p%j<1);s+=" |+ - - |+ "[(i>=a)+(i in{a,k+1})::3];p*=j*j;j+=1
print s
```
The primality checking part borrows @xnor's algorithm from [here](https://codegolf.stackexchange.com/a/27022/21487).
If we hardcode the first 15 offsets, we can get **137 bytes**:
```
n=input()
k=-~n/2
for i in range(k+2):
s=""
for j in range(n):a=881740113>>2*j&3;s+=" |+ - - |+ "[(i>=a)+(i in{a,k+1})::3]
print s
```
I'm assuming trailing spaces at the end of each line is okay, but if the question meant trailing spaces after the entire output then it's +9 bytes for `.rstrip()`.
[Answer]
# Groovy, ~~234~~, ~~225~~, ~~223~~ 219 bytes
Abusing the 15 building limit
```
b=args[0]as int
m={n->(n!=2&(2..n-1).any{n%it==0}?1:0)+([3,5,10].sum{n%it==0?1:0})}
(9..0).each{println((1..b).collect{d=((b/2)as int)+1-m(it);(0..9).collect{it!=d&it!=0?it<d?"| |":" ":"+--+"}}*.get(it).join(" "))}
```
[Answer]
# Swift, ~~375~~, 350 bytes
```
import Darwin;let(B,u,z,d)=(4.0,1.0,0.0,2.0);let H=ceil(B/d);func p(n:Double)->Double{var D=d;while D<n{if n%D==0{return 1};D++};return n==1 ?1:0};for var h=z;h<H+2;h++ {for var b=u;b<=B;b++ {var m=b%3==0 ?u:z+b%5==0 ?1:0;m=min(2,b%10==0 ?m+1:m);m += p(b);if h<m {print(" ")}else if h==H+1||h==m {print("+--+ ")}else{print("| | ")}};print("\n")}
```
Here is the indented code
```
import Darwin
let(B,u,z,d)=(4.0,1.0,0.0,2.0)
let H=ceil(B/d)
func p(n:Double)->Double{
var D=d
while D<n{
if n%D==0{
return 1
}
D++
}
return n==1 ?1:0
}
for var h=z;h<H+2;h++ {
for var b=u;b<=B;b++ {
var m=b%3==0 ?u:z+b%5==0 ?1:0
m=min(2,b%10==0 ?m+1:m)
m += p(b)
if h<m {
print(" ")
}
else if h==H+1||h==m {
print("+--+ ")
}
else{
print("| | ")
}
}
print("\n")
}
```
`B` contains the number of buildings.
`p` returns 1 when a number is not prime.
I need to import Foundation in order to use the `ceil` function.
I didn't managed to optimize the code for just the fifteen cases, but I will eventually make it later.
edit: Taking @Kametrixom advice and optimize the `mod` part (I forgot to reduce var name length).
] |
[Question]
[
Write the shortest program possible that takes in a set of distinct positive integers and outputs an ASCII rendering of [concentric](http://en.wikipedia.org/wiki/Concentric) hexagons with those side lengths, made from slashes, underscores, spaces, and newlines.
The shortest program in bytes as counted by <https://mothereff.in/byte-counter> wins.
# Examples
(They look better with less line spacing.)
If the input is `1` the output should be the hexagon with side length 1:
```
__
/ \
\__/
```
Notice that two underscores are used for the top and bottom of the hexagon so it is better proportioned.
In general, the size N hexagon contains N slashes on each angled side and 2\*N underscores on on both the top and bottom.
If the input is `1 2` the output should be the concentric hexagons with side length 1 and 2:
```
____
/ __ \
/ / \ \
\ \__/ /
\____/
```
If the input is `1 3` the output should be:
```
______
/ \
/ __ \
/ / \ \
\ \__/ /
\ /
\______/
```
If the input is `1 3 2` the output should be:
```
______
/ ____ \
/ / __ \ \
/ / / \ \ \
\ \ \__/ / /
\ \____/ /
\______/
```
etc.
# I/O Rules
Input must come from either the command line or stdin but may be in whatever format is most convenient.
For example, you might give each number as a command line argument: `> myprogram 1 3 2`, or you might prompt the user to input the numbers as a preformatted list: `[1, 3, 2]`.
Output must go to stdout or your language's closest equivalent.
# Additional Rules
* The input will always be a set of distinct positive integers, **not necessarily in any order**.
* The output must...
+ not contain any characters besides `/\ _` and newlines.
+ have no trailing spaces or unnecessary leading spaces.
+ not contain extraneous leading newlines but may have one *optional* trailing newline.
* If nothing is input then output nothing (except possibly one newline).
* If it helps you may assume that the input integers are less than 216.
[Answer]
# Python - ~~251, 240, 239~~ 228
```
l=input()+[0];m=max(l);A=abs;R=range
for j in R(2*m+1):print''.join([[' \\'[(A(j-i+m-1)/2.in l)*(2*m-i)/(j-m-.5)>1],'/'][(A(3*m-i-j)/2.in l)*(i-m-j+.5)/(j-.5-m)>0],'_'][(A(m-j)in l)*(A(2*m-i-.5)<A(m-j))]for i in R(4*m)).rstrip()
```
---
**Alternative approach (251):**
```
l=input()+[0]
l.sort()
m=max(l)
M=2*m
s=[[' ']*m*4for j in' '*(M+1)]
for i in l:
I=2*i;s[m-i][M-i:M+i]=s[m+i][M-i:M+i]='_'*I
for k in range(i):K=k+1;s[m-k][M-I+k]=s[m+K][M+I-K]='/';s[m-k][M+I-K]=s[m+K][M-I+k]='\\'
for t in s:print''.join(t).rstrip()
```
[Answer]
# CJam, ~~148~~ ~~116~~ 109 bytes
This took a lot longer than I expected. Originally, I just wanted to iteratively build the upper left quadrant, as in the diamond challenges, and then get the rest from mirroring. But I didn't notice that the underscores don't obey mirror symmetry between the upper and lower half. So I had to redo most of that, to generate the right half iteratively and then only mirror once (to the left).
```
S]2[l~]:(f#:+2bW%{_,2/~:T;{IT):T1<'\'/?S?S++}%__,2/=,2/I'_S?*_S+a@+\I'/S?S++a+}fI{)T)2*2$,-*1$W%"\/"_W%er@N}/
```
[Test it here.](http://cjam.aditsu.net/)
A Fibonacci-esque example:
```
8 3 1 5 2
```
```
________________
/ \
/ \
/ __________ \
/ / \ \
/ / ______ \ \
/ / / ____ \ \ \
/ / / / __ \ \ \ \
/ / / / / \ \ \ \ \
\ \ \ \ \__/ / / / /
\ \ \ \____/ / / /
\ \ \______/ / /
\ \ / /
\ \__________/ /
\ /
\ /
\________________/
```
## Explanation:
As stated at the top, I start by building the right half iteratively. That is, initially I've got only a single space in the grid, and then for each possible ring, I either surround the existing grid in spaces or a new semi-hexagon.
Once that's done, I mirror each line to the left and pad it with leading spaces for correct alignment. Here is a breakdown of the code:
```
"Prepare the input and the grid:";
S]2[l~]:(f#:+2bW%
S] "Push string with a space and wrap it in an array. This is the grid.";
2 "Push a 2 for future use.";
[l~] "Read and evaluate the input, wrap it in an array.";
:( "Decrement each number by 1.";
f# "Map each number i to 2^i.";
:+ "Sum them all up.";
2b "Get the base two representation.";
W% "Reverse the array.":
"At this point, the stack has the proto-grid at the bottom, and an array of 1s and
0s on top, which indicates for each hexagon if it's present or not.";
"Next is a for loop, which runs the block for each of those 0s and 1s, storing the
actual value in I. This block adds the next semi-hexagon or spaces.";
{ ... }fI
"First, append two characters to all existing lines:";
_,2/~:T;{IT):T1<'\'/?S?S++}%
_ "Duplicate the previous grid.";
,2/ "Get its length, integer-divide by 2.";
~:T; "Get the bitwise complement and store it in T. Discard it.";
{ }% "Map this block onto each line of the grid.";
I "Push the current hexagon flag for future use.";
T):T "Push T, increment, store the new value.";
1<'\'/? "If T is less than 1, push \, else push /.";
S? "If the current flag is 0, replace by a space.";
S++ "Append a space and add it to the current line.";
"So for hexagons this appends '\ ' to the top half and '/ ' to the bottom half.
For empty rings, it appends ' ' to all lines.";
"Now add a new line to the top and the bottom:"
__,2/=,2/I'_S?*_S+a@+\I'/S?S++a+
__ "Get two copies of the grid.";
,2/ "Get its length, integer-divide by 2.";
= "Get that line - this is always the middle line.";
,2/ "Get ITS length, integer'divide by 2.";
I'_S?* "Get a string of that many _ or spaces depending on the
current flag.";
_S+ "Duplicate and a space.";
a@+ "Wrap in an array, pull up the grid, and prepend the line.";
\ "Swap with the other copy.";
I'/S? "Choose between / and a space depending on the flag.";
S++ "Append a space, and add both characters to the line.";
a+ "Wrap in an array, and append line to the grid.";
"This is all. Rinse and repeat for all rings. The result will look something like this:
_____
\
___ \
__ \ \
_ \ \ \
\ \ \ \
_/ / / /
__/ / /
___/ /
/
_____/
Note that there are still trailing spaces.";
"Finish up all lines. These will not be joined together any more, but simply left
on the stack in pieces to printed out back-to-back at the end of the program.
The following runs the given block for each line:";
{ ... } /
"This generates the necessary indentation, then mirrors the lines and puts them
in the right order:"
)T)2*2$,-*\_W%"\/"_W%er\N
) "Slice off that trailing space, but leave it on the stack.";
T "Remember T? That still has something like the the size of
the grid from the last iteration. In fact it's N-1, where
N is the largest visible hexagon. We can use that to figure
out how many spaces we need.";
)2* "Increment and double.";
2$ "Copy the current line.";
,- "Subtract its length from 2*N.";
* "Repeat the space that often. This is our indentation.";
\_ "Swap with the line and duplicate.";
W% "Reverse the line.";
"\/"_W%er "Replace slashes with backslashes and vice versa.";
\ "Swap with the original line.";
N "Push a line break.";
```
[Answer]
## APL (222 bytes in UTF-8)
(and 133 chars)
Since this question specifically asks for amount of bytes in UTF8 representation, I had to actually *ungolf* it a bit so that it is longer but its UTF8 representation is shorter. (In particular, the commute operator's character `⍨` is three bytes while `()` is only two, so that optimalisation doesn't work anymore, and it also makes assignment very expensive.)
```
{⎕←(~⌽∧\⌽⍵=' ')/⍵}¨↓⊃{⍵{⍺=' ':⍵⋄⍺}¨K↑(-.5×(K←⍴⍵)+⍴⍺)↑⍺}/{Z⍪⌽⊖Z←↑(⊂(⍵/' '),(2×⍵)/'-'),⍵{((-⍵)↑'/'),((2 4-.×⍵⍺)/' '),'\'}¨⌽⍳⍵}¨N[⍋N←,⎕]
```
Previous version, which is shorter in characters (124) but uses more bytes when represented in UTF-8 (230, which would put it in second place):
```
M←' '⋄{⎕←⍵/⍨~⌽∧\⌽⍵=M}¨↓⊃{⍵{⍺=M:⍵⋄⍺}¨K↑⍺↑⍨-.5×(K←⍴⍵)+⍴⍺}/{Z⍪⊖⌽Z←↑(⊂(⍵/M),'-'/⍨2×⍵),⍵{('/'↑⍨-⍵),'\',⍨M/⍨2 4-.×⍵⍺}¨⌽⍳⍵}¨N[⍋N←,⎕]
```
Test:
```
{⎕←(~⌽∧\⌽⍵=' ')/⍵}¨↓⊃{⍵{⍺=' ':⍵⋄⍺}¨K↑(-.5×(K←⍴⍵)+⍴⍺)↑⍺}/{Z⍪⌽⊖Z←↑(⊂(⍵/' '),(2×⍵)/'-'),⍵{((-⍵)↑'/'),((2 4-.×⍵⍺)/' '),'\'}¨⌽⍳⍵}¨N[⍋N←,⎕]
⎕:
3 1 5 2
----------
/ \
/ ------ \
/ / ---- \ \
/ / / -- \ \ \
/ / / / \ \ \ \
\ \ \ \ / / / /
\ \ \ -- / / /
\ \ ---- / /
\ ------ /
\ /
----------
```
[Answer]
# Perl 5, 352 (349 bytes + 3 for `anE` flags)
This could probably be golfed down a lot more..
```
@b=sort{$a>$b}@F;map{$_<$j||($j=$_)}@b;$k=++$j;for(;$j--;){$z=$"x$j;for($e=$k;--$e>$j;){$z.=$e~~@b?'/ ':' '} $z.=($j~~@b?'_':$")x(2*$j);$z.=$_~~@b?' \\':' 'for($j+1..$k-1);say$z}for(0..$k-2){$z=$"x$_;for($e=$k;--$e>$_;){$z.=($e-$k+1?$":'').($e~~@b?'\\':$")}$z.=(($_+1)~~@b?'_':$")x(2*$_+2);$z.=($_~~@b?'/':$").($_-$k+1?$":'')for($_+1..$k-1);say$z}
```
Ungolfed:
```
# sort list of side lengths
@b=sort{$a>$b}@F;
# set $k and $j to max side length + 1
map{$_<$j||($j=$_)}@b;$k=++$j;
for(;$j--;){
$z=$"x$j;
for($e=$k;--$e>$j;){$z.=$e~~@b?'/ ':' '}
$z.=($j~~@b?'_':$")x(2*$j);
$z.=$_~~@b?' \\':' 'for($j+1..$k-1);
say$z
}
for(0..$k-2){
$z=$"x$_;
for($e=$k;--$e>$_;){$z.=($e-$k+1?$":'').($e~~@b?'\\':$")}
$z.=(($_+1)~~@b?'_':$")x(2*$_+2);
$z.=($_~~@b?'/':$").($_-$k+1?$":'')for($_+1..$k-1);
say$z
}
```
Example (`1 5 3 14`):
```
____________________________
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ __________ \
/ / \ \
/ / ______ \ \
/ / / \ \ \
/ / / __ \ \ \
/ / / / \ \ \ \
\ \ \ \__/ / / /
\ \ \ / / /
\ \ \______/ / /
\ \ / /
\ \__________/ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\____________________________/
```
[Answer]
# C# - ~~388~~ 316 bytes
*Edit: Changed how it avoids printing trailing spaces and threw in some LINQ*
Simple program that takes command line arguments. It iterates through every possible char in each line of a rectangle defined by the maximum hexagon dimension and appends it to the current line, before trimming the lines and printing them successively (it produces the optional trailing new-line).
Golfed Code:
```
using System.Linq;class P{static void Main(string[]A){var I=A.Select(int.Parse);int m=I.Max(),i,j,y,x;for(j=m+1;j-->-m;){var r="";for(i=-2*m-1;++i<2*m-(y=j<0?-j-1:j);)r+="/\\_- "[(x=i<0?-i-1:i)>y&(x+=y)%2>0&x/2<m&&I.Contains(x/2+1)?(i^j)&1:x-y<(y=j<0?-j:j)&y<=m&I.Contains(y)?j<0?2:3:4];System.Console.WriteLine(r);}}}
```
Ungolfed code:
```
using System.Linq; // all important
class P
{
static void Main(string[]A)
{
var I=A.Select(int.Parse); // create int array
for(int m=I.Max(),j=m+1,i,y,x;j-->-m;) // for each line...
{
var r=""; // current line
for(i=-2*m-1;++i<2*m-(y=j<0?-j-1:j);) // for each char...
r+="/\\_- "[// append something to the current line
(x=i<0?-i-1:i)>y&(x+=y)%2>0&x/2<m&&I.Contains(x/2+1)?
(i^j)&1: // slashes as appropriate - I can't work out why this bit works, but it seems to
x-y<(y=j<0?-j:j)&y<=m&I.Contains(y)?
j<0?2:3: // _ or - if required
4]; // otherwise a space
System.Console.WriteLine(r); // print current line
}
}
}
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 151 bytes (93 with the classic APL encoding)
```
{a←0⍴⍨1 0+1 2×n←⌈/⍵⋄a[⊃,/i,¨¨⍵+⍵-1+i←⍳¨⍵]←1⋄a←(⊖⍪-)a⋄a[⊃,/(n+⍵,-⍵),¨¨,⍨i]←2⋄' /_\'[4|(⌽,-)a]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04BkdSKI@ah3y6PeFYYKBtqGCkaHp@cBxR71dOg/6t36qLslMfpRV7OOfqbOoRWHVgCFtIFY11A7E6SodzNYKBbINgQpBdIaj7qmPepdpauZiNCrkQfSpKMLJDTBxugArcsE6TICKlJX0I@PUY82qdF41LNXB6gxtvb//zQFCwVjBUMFUwUjAA "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
[Curling](https://en.wikipedia.org/wiki/Curling) is a sport where two teams aim to place stones as close to the centre of a target as possible. The winner of a curling end is the team whose stone is closest to the centre – they score as many points as the number of their stones closer to the centre than any of their opponents.
## Task
Given two lists of pairs of integers representing the Cartesian coordinates of both teams' stones, with the origin as target centre, output a positive integer if one team wins and a negative integer if the other wins; the sign must be consistent with input order. The magnitude of this integer is the number of points scored.
Ties are broken as follows:
* If there are no stones at all or there is a tie between teams for the closest stone, no points are scored and 0 should be returned.
* If there is a winning team, any of their stones at *exactly the same distance* as their opponent's closest stone do not count for points.
Input formatting is flexible – you may use a complex number to represent a stone's coordinates or tag the coordinates with their corresponding teams, for example. The distance of (x,y) from the origin is \$\sqrt{x^2+y^2}\$ – scaling is equal in both directions.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
## Test cases
These assume the team whose stones' coordinates are listed **first** is associated with a **positive** output.
```
[],[] -> 0
[(1,0)],[] -> 1
[],[(0,1)] -> -1
[(2,0),(2,1),(2,2),(2,-1),(2,-2),(-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2)],[(0,1),(0,-1)] -> -2
[(4,3),(3,3),(-3,-3),(-1,0)],[(4,1)] -> 1
[(-3,2)],[(2,2),(0,-8),(-1,-1),(3,6)] -> -2
[(0,0),(1,0),(0,1)],[(1,1),(1,-1),(-1,1),(-1,-1)] -> 3
[(-7,1)],[(5,5)] -> 0
[(1,0),(2,0)],[(-2,0)] -> 1
[(-3,-4),(0,5)],[(-1,2),(4,3),(4,-3),(-3,0)] -> -2
```
---
Obviously this question was inspired by the curling events at the 2022 Winter Olympics.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 14 bytes [SBCS](https://github.com/abrudz/SBCS)
```
(¯1⊥1⊥¨⌽<⌊/¨)|
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=0zi03vBR11IQPrTiUc9em0c9XfqHVmjWAAA&f=TU/JDcMwDPt3Cj1twA/LR9sZNEi2ySYFskNG6SQlGQfog5YtUSS92Xf/EI/NUvGoeT3YTqWGZ05aVGvhQAPOw3U2A/6qq1ad171lS9CwyqmURnTrwHl09FhlmspYVoUT7tGLe29xqN7jKUqFB7aM6Sw59H25e/jNvsVeIpUZUx3XT@SosGpeYQYEZ@bLYc2gY0Xs4P0A&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
A tacit function which takes the coordinates as a pair of vectors of complex numbers.
`|` Absolute value on each of the complex numbers in the input.
`(...)` Apply the inner function on the absolute values.
`⌊/¨` Get the minimum of each of the vectors.
`⌽<` For each value in a vector, check if it is less than the minimum of the other vector.
`1⊥¨` Sum each boolean vector.
`¯1⊥` Get the difference between the two results.
The two uses of *Decode* `⊥` are usually the reductions `+/¨` and `-⍨/`, but they don't work so well in a tacit function as they have to be called monadically.
[Answer]
# Python3, 79 bytes:
```
f=lambda x,y,w=1:sum(y==[]or abs(j)<min(map(abs,y))for j in x)-(w and f(y,x,0))
```
[Try it online!](https://tio.run/##fVLBbtswDD3HX0H4EmmlCstOuiKY9wn9AS8YlEbGHNiOITmrhSDfnlKSDaSXXkiQj3x8FDW48d@5L14Hc7/XZau6w1HBhA4/Srmzl465sqz2ZwPqYNmJ/@qannVqYBSi47wm5ARNDxMX7ANUf4SaOZww4/xuyzRNqz1WexC/IUsqJim/xDLxEMtQ8hALSrCcCpCsDDYPVsRA@Eg8eBl9Ft0c5XwhRbJi4c6Je4MFJYtgRYEi@FkRgXOpV0Fo5IkSiOc11oaZBb48sGZBgAw27IJ@TRlyUWKMYnfoK/yIn3PtFrf8y/tgeAQPheUeRYlNGLKNqAzi4labeZ1i6RA5vX3SdMPZjKDsmPhLNf5SddOO2rC3c68R7LMd2mZk6z/9mvNdsmJ0e45goIRwZjs@E66Nav/q/6pFaJYOP4V6ktVEtZWCJzjAD5An8JMUUuS/xT5ZuW9wR7jR9tKOVFTTcHDEqKzVJHsBSjAIdVqz63RDuLobp@JrRG8gQE@Dfh/1kXK3NBlM05O8d2W1hcFTHdf8/gk)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
FθUMιΣXκ²I↨EθLΦ§θ¬κ⬤ι‹λν±¹
```
[Try it online!](https://tio.run/##HYzLCoMwEEX3/YosZ2AEX125skKhYIvQpbgImqoYkxrTx9@nSWdxh8N99BM3vebSuYc2DDZkV/6s9LpyNcBM7P5aodEfYWAhliJicWjMrCxUfLdw4rsAX4CNWC3UaCc4z9L6dGkvahDfYNy0hQWRWCllmKzFvoMkpjCc98XIrYAkUOFc27YQZRTlSBDTETvynFDqMafsr1F4PhNj13Uuessf "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a pair of lists of tuples. Explanation:
```
Fθ
```
Loop over each team.
```
UMιΣXκ²
```
Replace each stone with its squared distance from the origin.
```
I↨EθLΦ§θ¬κ⬤ι‹λν±¹
```
For each team, count how many stones are nearer than all of the other team's stones, then output the difference between the two values. (This particular formulation has been chosen because it works with empty lists.)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 144 bytes
```
(n,k,Z=Math.min,N=(F=L=>L.map(([x,y])=>x*x+y*y))(n),K=F(k),Q=Z(...N),R=Z(...K),G=(c,d)=>c.filter(e=>d.every(E=>e<E)).length)=>Q<R?G(N,K):-G(K,N)
```
[Try it online!](https://tio.run/##VVFNT9tAEL37V@yhkmdh1vgjgaph0xPkEJoKjhhLsex1cDG25Zg0EeK3p@MdB9HDzuy8ffP2jeZPuku3WVe2vaqb3BwLfYQaX/BR/0r7Z@@1rHGl4Vbf6fmd95q2APEeD4nU8/3Z/vxwdpASaolLfQsvEu/1I3iet5L4wLelxIWGDHNqyLyirHrTgdHz3DM70x3gRs/N9Y2UXmXqTf9MrPvrh58LWOFS/lALWOJKHrOm3vairNu3XmixjhOMEyeGAH3JV4rgYyAHNCQUKQY2hjYqLtRQqS854OxzGqtQnuSQomLVCUZURjaqCJXNowF6ZBI9cDP/S83fmWY/ivDSsnz7X2CjNY3DKIHF2BFX3Gd1r0baFKfyNDnaSQfUTjD@ryZWdcoPgfXB3iej6Wggr73OtFWaGbh4gosNCjd25RdMEuYmBG3bquzBfapdOXMcXoTZtybrTf77reeNxD6KAIUaTshXShGKEQ@TmVMZ2iBxfZIpmk7A51JFU/BupXh3BMPNSdrs0grWBXx7J8qHXJMLS2kq41XNBtzRBEm6OMjQKH/TLd1Zgsq0zj8tn4SZ8v8gcZkM6qU41yKYOR/Hfw "JavaScript (Node.js) – Try It Online")
I hope it can be golfed further.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 49 bytes
```
m{m{)S[++}}Jqnuay{)L[}{J)<]<-{bxq.<_+fl}Z]}IE^p.-
```
[Try it online!](https://tio.run/##TVBNC8IwDL3vVxRvY0T6sang8OZB8eZBUKY40NMUpwyUkN8@26QToSR9zevLS@ru2VxebXfpcQSL0XwO1ePV3/CG6faQZUTr9t6dP5huDoTrtKxKwPrdjstTdm1oX9FqeXyMoadd0yMpf2ChdBKuaJQmxmCSAQkhYOux8tFwtBxBAAQEf9lI1pIiskEONUMdONLLeu1cOf/oOIJTwDka8MVIDS58VXTEgteZCZd7OjX5U9VswHDULBKmMvwmFgXJb/7nQotp5BaqoGE/UcZGT2CHXUVTkHOTQqqGzclUeRzH/bZrky8 "Burlesque – Try It Online")
There are issues with finding the minimum of an empty vector, so there needs to be a workaround.
```
m{ # Map
m{ # Map
)S[ # Square each
++ # Sum
} # -- Calc Mag sq
} # -- Of each input
J # Duplicate
qnuay # If any empty
{ #
)L[ # Map to length
} #
{ # Else
J # Duplicate
)<] # Map to minima
<- # Reverse
{ #
bx # Box Number
q.<_+ # Append <
fl # Count
} # -- Count those less than minimum of other side
Z] # Zip with apply
}IE # If Else (stack based)
^p # Push to stack
.- # Subtraction
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 23 bytes
I'd like to make code that works with strictly nested array-input,
include empty arrays: `[ [], [] ], [ [], [[0, 1]] ]` etc.
I’d appreciate it if someone would do the refactoring,
but with that condition in mind.
```
:vL:A[_vƛ∆/;:vgṘ¨Z<∑]÷-
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCI6dkw6QVtfdsab4oiGLzs6dmfhuZjCqFo84oiRO13Dty0iLCIiLCJbW10sW1stMiwwXV1dIl0=)
```
# ḋ flag (Print rationals in their decimal form) useful for debugging
:vL:A # Check if all arrays are not empty (and get lenghts)
[ # If so
_vƛ∆/; # Remove lengths and calculate all norms in both arrays
:vg # Find minima
Ṙ # Reverse
¨Z‹∑ # Zip, check for "less than" and sum boolean
]÷- Find difference (in both cases: lengths or sums)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 85 bytes
```
c=Count[#1,u_/;u<Min@#2]&;
f=c@@#-c@@Reverse@#&@Map[Norm,#/.{{}->{\[Infinity]}},{2}]&
```
[Try it online!](https://tio.run/##RYqxCsIwFEX3/kYgU2pt11p54ORQEdcYJJQEMySVmAjyeN8eo4vLuffA8TrdjdfJLbqUZTqsOSTJepFv3Zh3swvABsXHxk4LAGsrLuZl4tMA4zDrhzyt0QvWbRCp3eNVHoN1waW3IhI4kOLlHF1IYKEWAomav2Mvtt@qsg62v0PlAw "Wolfram Language (Mathematica) – Try It Online")
This works with strictly nested array-input, include empty arrays: `[ [], [] ], [ [], [[0, 1]] ]` etc.
Mathematica has built-in `Infinity`, so I use it to replace empty results (as if stones cast far away).
Code is clumsy so I hope someone post more well-built answer
] |
[Question]
[
Magic the gathering has many unique names for colour combinations in decks, as an example when Blue and White appear together in a deck, the deck maye sometimes be named after the Ravnican Guild that features those colours, namely 'Azorius'. There are some exceptions, and oddities though.
Below is a list of colour letters (one of WUBRG) combinations, and a list of their corresponding example colour deckname part (the order of letters is not fixed for this challenge):
```
W: Monowhite/Mono-White
U: Monoblue/Mono-Blue
B: Monoblack/Mono-Black
R: Monored/Mono-Red
G: Monogreen/Mono-Green
WU: Azorius
WB: Orzhov
WR: Boros
WG: Selesnya
UB: Dimir
UR: Izzet
UG: Simic
BR: Rakdos
BG: Golgari
RG: Gruul
GWU: Bant
WUB: Esper
UBR: Grixis
BRG: Jund
RGW: Naya
WBG: Abzan/Indatha/Necra
URW: Jeskai/Raka/Raugrin
BUG: Sultai/Ana/Bug/Zagoth
RWB: Mardu/Dega/Savai
URG: Temur/Ceta/Rug/Ketria
UBRG: Chaos/Glint/Glint-Eye/Non-White
BRGW: Aggression/Dune/Dune-Brood/Non-Blue
RGWU: Altruism/Ink/Ink-Treader/Non-Black
GWUB: Growth/Witch/Witch-Maw/Non-Red
WUBR: Artifice/Yore/Yore-Tiller/Non-Green
WUBRG: Domain/Five-Color
C: Colorless/Monobrown/Mono-Brown
```
The challenge is to take in any of the letter combination entries above as *input*, and then output only *one* of the listed names. As previously started, the order of letters is not important, so BWRG is the same as BRGW etc, and should output one of Aggression/Dune/Dune-Brood/Non-Blue.
Input and output should be case insensitive, so that it will accept either as input, but either case of output (or both!) is fine.
Nonsense input is allowed to error or give a nonsense output. e.g. inputting 'wubrger' can throw an error or output 'Mark Rosewater' (or any string, even valid output) for example.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~136~~ ~~135~~ ~~133~~ 132 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
“ƒÏˆ¨†¾‡—„¸ ŽÌ“#'Î×ì.•вO₁ŸĀ0Ð뜴0+Eм/#‰TôbHüÆΣÇÐζfβq₅([²åOÇηB₂È¥ƶ]9í$µÅ–tå(h0!Ãα9½êT₄Ì€+µxΩ;'Äçî9©ÙÝ“R_Ÿ U„δ
ÅíÂu•#5ǝ˜.•Iλβ•æé¦Il{kè
```
Outputs in full lowercase; uses the shortest outputs if multiple are allowed.
[Try it online](https://tio.run/##AfcACP9vc2FiaWX//@KAnMaSw4/LhsKo4oCgwr7igKHigJTigJ7CuCDFvcOM4oCcIyfDjsOXw6wu4oCi0LJP4oKBxbjEgDDDkMOrxZPCtDArRdC8LyPigLBUw7RiSMO8w4bOo8OHw5DOtmbOsnHigoUoW8Kyw6VPw4fOt0LigoLDiMKlxrZdOcOtJMK1w4XigJN0w6UoaDAhw4POsTnCvcOqVOKChMOM4oKsK8K1eM6pOyfDhMOnw645wqnDmcOd4oCcUl/FuCBV4oCezrQKw4XDrcOCdeKAoiM1x53LnC7igKJJzrvOsuKAosOmw6nCpklse2vDqP//UndC) or [verify all test cases](https://tio.run/##LY5NS0JBFIb3/YrbNVBQyk0LaSHcCGslDF5mIRIJRVEQ0QdFm@nmR4so0SACjT7QvKVSFzUhbTGnawth8DfMH7nNOC3emXPec@aZd3d/Lb217h2duCVmUzuqazxX1PSox0l5WITrUY7WOXmg35w8cnLDyT3tae4ALsXc54cruIXGLCdPYyfOrTO390PCUIA3t0Tb4eDSuD/n4@Q9Ae30MvQhx54hDwXW3WDOHreygSR1oBqHPPs0uGXBBa0Ou6kINGdoB7KclA6gGtgMT8M5@4jQAbwmuJURX1uNIO0cM3vBDxl4gVaE2nAHFREJrbo9zRQpWXsKstAE61CE883/VkZlGXOFfTFH3FADm9Zoa@d0G@peyEvqWA/pppAhhIRiQlgaWDpYWlh6pmxN2ZqyNWRlyArJI6aeqCU1Q2qIJ6gJAcnamDxHWOEUGSniZBcpVEyxsILh/51FPfUH) (uses a random permutations for each test case input).
**Explanation:**
```
“ƒÏˆ¨†¾‡—„¸ ŽÌ“ # Push dictionary string "black green red blue white brown"
# # Split it on spaces: ["black","green","red","blue","white","","brown"]
'Î×ì '# Prepend dictionary string "mono" to each string
.•вO₁ŸĀ0Ð뜴0+Eм/#‰TôbHüÆΣÇÐζfβq₅([²åOÇηB₂È¥ƶ]9í$µÅ–tå(h0!Ãα9½êT₄Ì€+µxΩ;'Äçî9©ÙÝ“R_Ÿ U„δ\nÅíÂu•
# Push compressed string "golgari rakdos gruul dimir simic izzet orzhov selesnya boros azorius jund ana grixis rug abzan dega naya esper bant raka chaos dune witch yore ink domain"
# # Split on spaces as well
5ǝ # Insert this list at 0-based index 5
˜ # And flatten the list to complete the list of deck-names
.•Iλβ• # Push compressed string "bgruw"
æ # Pop and push all its permutations
é # Sort them by length: ["","b","g","r","u","w","bg","br","gr","bu","gu","ru","bw","gw","rw","uw","bgr","bgu","bru","gru","bgw","brw","grw","buw","guw","ruw","bgru","bgrw","bguw","bruw","gruw","bgruw"]
¦ # Remove the first empty string
I # Push the input-string
l # Convert it to lowercase
{ # Sort its characters
k # Get the index of this string in the list of permutations,
# or -1 if it isn't present in the case of input "c"/"C"
è # And use that index to index into the list of deck-names
# (0-based, where -1 will wrap around to the end)
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compressed strings work.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~133~~ 132 bytes
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -1 byte!
```
.•αćðoвÍ‘óÉp₂›qt8¬Ôтõ—qФöôI‚¦æâ\₄²5₃1.Ćåuc[âY™FŒ¸VOœ₂9>îÓ‰ìîʒO=|e₁e²Ì¯ß₅m4ÖāHŠBÌz©?Ωć¨_¶∊á‘ÂΔHÓÄ÷U}úÙÕF„k{%ì6?“:Rƒá•#¬æIl{kèIgi'Î×ì
```
[Try it online!](https://tio.run/##AfAAD/9vc2FiaWX//y7igKLOscSHw7Bv0LLDjeKAmMOzw4lw4oKC4oC6cXQ4wqzDlNGCw7XigJRxxaDCpMO2w7RJ4oCawqbDpsOiXOKChMKyNeKCgzEuxIbDpXVjW8OiWeKEokbFksK4Vk/Fk@KCgjk@w67Dk@KAsMOsw67Kkk89fGXigoFlwrLDjMKvw5/igoVtNMOWxIFIxaBCw4x6wqk/zqnEh8KoX8K24oiKw6HigJjDgs6USMOTw4TDt1V9w7rDmcOVRuKAnmt7JcOsNj/igJw6UsaSw6HigKIjwqzDpklse2vDqElnaSfDjsOXw6z//0M "05AB1E – Try It Online")
**Commented**:
```
.•α...á• -- compressed alphabet string
-- "bgruw black ... domain brown"
# -- split on spaces
¬ -- get the first element "bgruw"
æ -- take the powerset ["", "b", "g", ..., "bgruw"]
I -- push the input
l -- convert to lowercase
{ -- sort it
k -- find the index of this string in the powerset
-- b -> 1, ..., bgruw -> 31, c -> -1
è -- index with this integer into the word list
Ig -- push the length of the input
i -- if this is truthy (equal to 1):
'Î×ì -- prepend compressed string "mono"
```
[Answer]
# JavaScript (ES6), 254 bytes
Expects an array of characters as input.
```
a=>`SelesnyaXXGolgariChaosXDuneXXXXMonoblackColorlessEsperRakdosXMonogreenDimirJundOrzhovDomainAnaXAbzanGrixisInkDegaMonoredXIzzetMonoblueBorosMonowhiteRugAzoriusNayaXWitchBantGruulYoreRakaSimic`.match(/.[a-z]*/g)[parseInt(a.sort().join``,33)%472%244%44]
```
[Try it online!](https://tio.run/##VVRrb9owFP3Or4iQqiZbE2st2qRNVGqARXRqkUIr2BASbmISF2MjP8rK1N/ObMdOaSQsc3zu9X2c62f4AkXB8U7GlJXouO4fYf96NUUECfoK5/OMkQpyPKghE/OhomiuvztG2ROBxWbACOOaKkZih3gON6VmmdOKI0SHeIv5raLlhB9q9jJkW4jpDYXzm6cDpBnHf7EY080QVdDYcFTOx4cDko17hVLGmTB/9jWWKFfVzYFxrMQ91JHNsCzqFFKZcaXIb22tr4dTfWWxSrZQH4YgWcD4sPwEqmixg1ygMZUhTATjMoySZ4bpanVxdRWd9b5dnl32eme93vI4CfrBv06gv4FZvgdBt80S2Mg421O7i1Oz7V5Y9syz24AbzsxsHefxlGMydG70zjHSjwxdYk/R227QkPJTkq5aQ8lR6Zxkp@e2Ew0jM1sf7qPjuJp6OHVw0zKP5g61HfFg5kAvFp@kd2Hb70HvwTbYg60H0zVfAc9s1ORRT3V6dHDewkYEPn2Tm41Wq6NNN20wK9Q20txbGym2AWQNapTb3jNrMCO9tlSOZ9UMxrSEsobgHhW8LUXuzG6R2EAMjEL1oiqOfR/SR@dlqojUFD0eIFUV@AMrJmt//cxFfwd5qYAZGDDVk4vbe5yTB7RVHAyQ1NdoJ7@Q5Pi9L5pl5WxmGWQEU9ms8egVgXtGP2g1NTnb9CotISEwo8DMv12M8llpbU7Em5vKWxMiucJiq4uyMb/4gSNYIu4MjJTbVqWuA2wva2CHulnjO7i3/Hddz0zDrH8u8RoXCJixt0v8gAlxF3yUuc7DitE@PuAnfkGxnedu560zeXpGhUw26FWEkyhZMz6C@t0QQf/avgEFo4IRlBBWhSLZwXJEy/Br9DkIdUX0O7EOF0mSiGUU@cMvl1GgjycLsUzEjmAZnoPzKMG0IKpEwthFUfSj8xYd/wM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 138 bytes
```
×›²Lθmono§⪪”&⌈⧴ν;IjWκ,êQD↷$εe⪫_S�✂σ¶⍘↶Ja↧ ‖wυ^z‖U›ï^?F$←P↗Wιº+F|γaÀ⁹?t*a≕∨0]X‹75·¡≔⁸“↨⊟E⦃⌈&?q⍘⌕�,QDπnB ✂a|⁹℅Uξ⟲ⅈK´φN›~t\`$⊕ζ⊕”q↨Ewubrg№↧θι²
```
[Try it online!](https://tio.run/##JVDLTsNADLzzFVVOG6lceuUEHCokkJCAD3B2rY1pYtfe3abNzwdX3MbzkDUTR7AoMG3bpxHX8E0zlnA0hIoWDvvdO3KuY9C@3@@6WVi6vn96@Dc/1zdOeA1f54lq6AaThTUbIqthctTapMME8aRZpgxGanBKUvS3cXKloRaaKSqtK1a1ljX5bQoMHqcrFY0jeGAZqboZJyx8Ax3EnGRwKLaOclEYVmBNmEFTY1RYxagVHYDr/Sso8UmxnNF0oRpHvYmhJpmBuPNu2nnDFygYPuAcuqUNlp1/leZN32VBi3dR3UX3MQ69D7FtP8ft8TL9AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
×›²Lθmono
```
Print `mono` if the number of characters in the input is less than 2.
```
§⪪”...”q↨Ewubrg№↧θι²
```
Split the compressed string of colour names on `q` and index it by taking the counts of each of the colour letters in the input and interpreting them as a number in base 2.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 149 bytes
```
“®×bẒAJ²ṘẈ!sỵḷ:-Þ5M£LƇ(¥Ḋg½Bm%³ḣʠĊ¢*¶|ƭ⁾Ḳ¹øṡ(:d,g5ṚVW]t;/ẓẇpⱮṄḟɗæ(ƓYẎĖẹḲA’b27ṣ0ịØa
“-e“ẠỤ“¡cy“/⁷“¡ḷọ»µ“ċ¦⁶»;Ɱ;¢;Ṛ“ċ=€»;ⱮƊ;“ÐOẈ“µƬḞ»
ŒuṢ“BGRUW”ŒPḊ¤iị¢
```
[Try it online!](https://tio.run/##JY/PSgJhFMX3vkWLYIjECCRwaKGbIIpCKGnRIkukMAjKhdBiJgJjpIgR0qJMZ8yVCRmj3x9qcWccqLe434tMV9vcyzlw7/mdk0KpVIkiZTzDwG/kUdjpdRgib6K4mTtH6SEbp@J@K7kJ7kZY1eANmVWEr8zpPHwic3/bgQXOAowuw3dlfiMbAvcZ8o6WOlosJpE/7eb2L/QEijqK6pn6GCC/Rvb60/B7WljfQ3EXPKDgdJhWxmN@eQW5u4Sy5jcPYkQVL9BA0UbZnTJ2Diu0EsoczxTBobwFCR7JoAY9ZY5A6pSig6NT@MxeVVf9fze0dHL8@y1qN33ghX1kLZCxiV1G7pCVWcvu5JTxMrG3qSh0jwkFnCiKytn8Hw "Jelly – Try It Online")
## Explanation
```
“...’b27ṣ0ịØa Auxiliary niladic link
“...’ A big number in base 250
b27 Convert to base 27
ṣ0 Split on zeros
ịØa Index into the lowercase alphabet
=> ["golgari", "rakdos", ..., "bant", "raka"]
“...»µ“ċ¦⁶»;Ɱ;¢;Ṛ“ċ=€»;ⱮƊ;“ÐOẈ“µƬḞ» Auxiliary niladic link
“...» ["Black", "Green", "Red", "Blue", "White"]
µ Use as new argument
“ċ¦⁶»; Prepend "Mono-"
Ɱ to each
;¢ Join with link above
; Join with
Ɗ (
Ṛ Reverse [the list of colors]
“ċ=€»; Prepend "Non-"
Ɱ to each
Ɗ )
; Join with
“ÐOẈ“µƬḞ» ["Domain", "Colorless"]
ŒuṢ“BGRUW”ŒPḊ¤iị¢ Main monadic link
Œu Uppercase
Ṣ Sort
i Find index in
¤ (
“BGRUW” "BGRUW"
ŒP Power set
Ḋ Remove first element [the empty string]
¤ )
ị Index into
¢ Link above
```
] |
[Question]
[
# Challenge
I've recently gotten into 8-bit computers and are fascinated with the workings of them and others alike; thus the objective of this code golf, is to replicate a portion of the Woz Monitor, designed by Steve Wozniak for the Apple I.
You are to store an array of 22 hexadecimal values with a width of two bytes, (min value **$10**, max value **$FF**), and then take in *n*-amount of inputs. (Normally two; languages like Brainfuck might have a hard time).
The inputs will refer to where in the array to start printing from, and where to stop; an input with *defined behaviour* will have their starting value less or equal to the ending value. Your program must then be capable of printing every hexadecimal value between, **and including**, the hexadecimals inputted.
An example of this:
```
Array
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15
Values
FF F4 B6 D7 40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6 A5
```
```
input first num:
04
input second num:
14
40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6
```
Now the interesting part of this exercise, is that you can use whatever you want to check the bounds of the users input. Person inputs `hello` and your program has undefined behaviour? It quits without notice? They are both valid.
The only rules are:
**1.** You must include the values of the 22 hexadecimal values as part of your program before it starts, (can't ask the user for inputs).
**2.** The output of the hexadecimal values must follow the exact format:
`00 FF 00 FF 00` Trailing spaces, tabs or lines are OK. Characters are not.
**3.** The program ***doesn't*** have to ask for the inputs with a message. Leave the "message" blank if you wish. The user must input the hex-bounds however.
**4.** As with the values of the 22 hexadecimals are up to you to decide, you must make a program that actually fetches the values from storage, opposed to ***mimicking*** a program by simply printing values. (such as a list of **$00**'s).
**5.** *n-amount* of inputs, refers to the amount of inputs required for your language of choice to recognise a hexadecimal of two byte-width. **eg. (Brainfuck will require two inputs per hex, making it four for the two).**
Feel free to comment if you need clarification.
**This is code golf, so the shortest answer in the number of bytes is the winner.**
# Leaderboard
Here is a leaderboard generating snippet courtesy of [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender).
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/95080/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=49042;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
w@€ØHḅ⁴
ɠǵɠÇr@b⁴ịØHK
```
Chosen values: `[00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 1F 10 11 12 13 14 15]`
**[TryItOnline](http://jelly.tryitonline.net/#code=d0DigqzDmEjhuIXigbQKyaDDh8K1yaDDh3JAYuKBtOG7i8OYSEs&input=MDQKMTQ&args=)**
If the second input is less than the first it outputs the reversed sequence.
Out of bounds behaviour is undefined (e.g. "foo", "14" returns 38 values, most of which are not even in the array and many of which are not length 2)
How?
```
w@€ØHḅ⁴ - Link 1, parse a string as a 1-based hex value e.g. "14"
w@€ - first index (1-based) of each character in
ØH - hex digits: "0123456789ABCDEF" [2,5]
ḅ⁴ - convert from base 16 37
ɠǵɠÇr@b⁴ịØHK - Main link
ɠ ɠ - read a line from stdin e.g. "04" "14"
Ç Ç - call the last link (1) as a monad 21 37
µ - monadic chain separation
r@ - inclusive range, with reversed arguments [ 21, 22,..., 36, 37]
b⁴ - convert to base 16 [[1,5],[1,6],...,[2,4],[2,5]]
ị - index into
ØH - hex digits: "0123456789ABCDEF" [ "04", "05",..., "13", "14"]
K - join with spaces
```
[Answer]
## JavaScript (ES6), ~~118~~ ~~115~~ ~~112~~ ~~102~~ ~~82~~ 81 bytes
*Saved 1 byte thanks to ETHproductions*
Chosen values:
```
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
10 10 11 14 10 10 15 15 11 14 10 10 15 15 11 14 10 10 15 15 10 11
```
* Prompts for the lower bound, then for the upper bound (e.g. `0x04` / `0x0f`).
* An invalid lower bound will be interpreted as `0x00` (minimum value).
* An invalid upper bound will be interpreted as `0x15` (maximum value).
* Outputs nothing if the lower bound is greater than the upper bound.
```
alert((1/7+'789').replace(/./g,(v,i)=>i<a|i>b?'':(v|10)+' ',p=prompt,b=p(a=p())))
```
### Previous version (97 bytes)
Generating a pseudo-random list of 'true' hexadecimal values:
```
alert((1/7+'789').replace(/./g,(v,i)=>i<a|i>b?'':(v*7|16).toString(16)+' ',p=prompt,a=p(),b=p()))
```
Sequence:
```
10 10 17 1c 1e 38 33 31 17 1c 1e 38 33 31 17 1c 1e 38 33 31 38 3f
```
[Answer]
# Python, ~~88~~ ~~87~~ 86 bytes
1 byte save thanks to @JonathanAllan
1 byte save *again* to @JonathanAllan
Also changed the base of the code, much nicer now.
```
a,b=[int(x,16)for x in raw_input().split()];l=[0]*22
while a<=b:print"%02x"%l[a],;a+=1
```
Chosen values: `00` for everything.
Same idea as my C answer. This time however, the code takes a single input from the user, requiring a space between both values, split them, cast them to hex values, and print every hex in the `l` array including and between the two inputted values. Since Python has a magnificent error-catching system, no buffer overflows are present and the code is therefore much more secure. The program is safe from *undefined behaviour* in a sense that it will not execute when a higher value is submitted before a lower value.
This should work on both Python 2.x and 3.x; Please correct me if I am wrong, as I don't have access to both interpreters due to my system not supporting both of them.
[Answer]
# JavaScript (ES6), ~~107 152~~ 137 bytes
```
p=prompt,f=(a=+p(),b=+p(),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())
```
```
var
p=prompt,f=(a=+p(),b=+p(),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())
;
//input 0x04 then 0x14 will print 40 to D6
//input 0x00 then 0x00 will print FF
//input 0x13 then 0x17 will print E7 D6 A5 NaN NaN
```
Chosen values:
```
FF F4 B6 D7 40 20 11 A4 F0 D0 FF 3D 9C 21 65 C4 A2 28 90 E7 D6 A5
```
Inputs:
* Input format is `0x14`
* If any input is negative or the 1st input is greater than the 2nd : `InternalError: too much recursion`
* Will print `NaN` for out of bounds.
---
Previous solutions:
152 bytes:
```
i=parseInt,p=prompt,f=(a=i(p()),b=i(p()),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())
```
107 bytes, invalid solution (inputs missing):
```
f=(a,b,[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'')
```
[Answer]
# Perl, 79 45 41 bytes
"min value $10" - the example has minimum of $00- is that a typo?
Here's a rather boring perl answer in 41 bytes (Was 46 and then I kept seeing spaces, parens I could elide). Takes input in two lines.
```
printf'%02X ',$_ for(4..26)[hex<>..hex<>]
```
The data is a list 04..1A
Before I was being too clever with pack & unpack. Its input bytes are entered at once smushed together, eg "020E' will print the 2nd-14th entries
```
printf'%02X ',$_ for sub{(4..26)[shift..shift]}->(unpack'CC',pack'H4',<>)
```
Might try golfing it more using all 0's, `substr`, and `printf'%*vX'` ... nope that is making my answer longer. 48 characters (using a string of ascii '7', hex 37 as the data)
```
printf'%*vX',' ',substr 7x22,$s=hex<>,1+hex<>-$s
```
[Answer]
# Scala, 45 bytes
```
(_:Int)to(_:Int)map(x=>f"$x%02X")mkString " "
```
Ungolfed:
```
(a:Int,b:Int)=>a.to(b).map(x=>f"$x%02X").mkString(" ")
```
Uses `00` to `FF` as values, but works up to 2147483647.
[Answer]
# C, ~~176~~ ~~175~~ 161 bytes
1 byte save thanks to @JonathanAllan
Massive help thanks to @Downvoter for saving me **14** bytes!
```
int main(){int a[44]={0};char s[2];scanf("%s",s);int b=(int)strtol(s,0,16);scanf("%s",s);int c=(int)strtol(s,0,16);while(b<=c){printf("%d%d ",a[b],a[b+1]);b++;}}
```
[**Try it online!**](http://ideone.com/XxIG4h)
Chosen values: `00` for everything.
Un-golfed answer:
```
int main() {
int a[44] = {0};
char s[2];
scanf("%s", s);
int b = (int) strtol(s, 0, 16);
scanf("%s", s);
int c = (int) strtol(s, 0, 16);
while (b <= c) {
printf("%d%d ", a[b], a[b+1]);
b++;
}
}
```
The trick to this, is taking in two inputs and attempting to convert them to hexadecimal strings and then cast to integers. Since there is no error-checking or anything likewise, *undefined behaviour* is simply throwing errors and breaking the program.
The user needs to enter two inputs, however my Eclipse CDT compiler seems to let me input them both on the same line with a space between.
They must be in the correct order, as requesting a bigger value before a smaller value will not run the `while`-loop at all.
The thing is, there is also no buffer-overflow protection, so I can simply request something absurd such as a range from $0 to $FFFF, and I will get everything in my computers memory from the beginning of the allocation of memory for the `a[44]` array, all the way to 65536 values later.
[Answer]
# C++, ~~98~~ ~~95~~ 93 bytes
```
#include <iostream>
int _[22],a,b;int main(){for(std::cin>>a>>b;b/a++;)printf("%02x ",_[a]);}
```
My chosen values are all 0's
[Answer]
# PHP, ~~106 105 104~~ 96+2 bytes
```
eval($s='for($a=a;$a++<c;)$$a=hexdec($argv[++$i]);while($b<=$c)printf("%02X ",ord($s[$b++]));');
```
or
```
eval($s='for($a=a;$a++<c;)$$a=hexdec($argv[++$i]);');while($b<=$c)printf("%02X ",ord($s[$b++]));
```
Run with `php -nr '<code>' <lowindex> <highindex>`; escape the single quotes in the code.
... or [test it online](http://sandbox.onlinephpfunctions.com/code/2dd4efe4bc2bf063f9b3f8f8536f0367cacccac4).
`dechex` interpretes input as hexadecimal strings as far as characters are hex digits,
`0` if the input starts with something else.
prints nothing if first value is larger than second.
chosen values:
```
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
66 6F 72 28 24 61 3D 61 3B 24 61 2B 2B 3C 63 3B 29 24 24 61 3D 68
```
(first 22 ascii codes of the executed code)
or
```
for($a=a;$a++<c;)eval($s='$$a=hexdec($argv[++$i]);');while($b<=$c)printf("%02X ",ord($s[$b++]));
```
with these values:
```
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
24 24 61 3D 68 65 78 64 65 63 28 24 61 72 67 76 5B 2B 2B 24 69 5D
```
[Answer]
# CJam, 22 bytes
```
{r:~Gb}2*37m!s2/\)<>S*
```
Chosen values:
```
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15
-----------------------------------------------------------------
13 76 37 53 09 12 26 34 50 46 31 59 79 58 15 80 90 24 00 00 00 00
```
[Try it online](http://cjam.tryitonline.net/#code=e3I6fkdifTIqMzdtIXMyL1wpPD5TKg&input=MDQgMTQ)
[Answer]
# GNU sed, 209 + 1(r flag) = 210 bytes
```
1{h
s:.*:,00 FF,01 F4,02 B6,03 D7,04 40,05 00,06 00,07 A4,08 F0,09 00,0A FF,0B 0D,0C 9C,0D 21,0E 65,0F C4,10 02,11 28,12 90,13 E7,14 D6,15 A5:
H;d}
G;s:\n(.*)\n.*(,\1.*):\n\2:
s:(.*)\n(.*,\1 ..).*:\2:
s:,..::g
```
[**Try it online!**](http://sed.tryitonline.net/#code=MXtoCnM6Lio6LDAwIEZGLDAxIEY0LDAyIEI2LDAzIEQ3LDA0IDQwLDA1IDAwLDA2IDAwLDA3IEE0LDA4IEYwLDA5IDAwLDBBIEZGLDBCIDBELDBDIDlDLDBEIDIxLDBFIDY1LDBGIEM0LDEwIDAyLDExIDI4LDEyIDkwLDEzIEU3LDE0IEQ2LDE1IEE1OgpIO2R9Ckc7czpcbiguKilcbi4qKCxcMS4qKTpcblwyOgpzOiguKilcbiguKixcMSAuLikuKjpcMjoKczosLi46Omc&input=MDYKMEY&args=LXI) One leading space is present in the output, I hope it's allowed.
**Run examples:**
```
me@LCARS:/PPCG$ echo -e "06\n0F" | sed -rf table_lookup.sed
00 A4 F0 00 FF 0D 9C 21 65 C4
me@LCARS:/PPCG$ echo -e "13\n13" | sed -rf table_lookup.sed
E7
```
**Explanation:** the 22 hexadecimal values stored are the same as the ones from the OP's example
```
value | FF F4 B6 D7 40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6 A5
-------------------------------------------------------------------------
index | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15
```
The start and end indexes are read on separate lines. The output is a single line with the table values in that index range (inclusive). *Undefined input will write multiple lines of invalid output.*
```
# store START index in hold space
1{h
# generate the table
s:.*:,INDEX1 VALUE1,INDEX2 VALUE2,°°°:
# append table to hold space and delete pattern space
H;d}
# read END index, append hold space (pattern space format is: END\nSTART\nTABLE)
G
# delete table entries up to, but excluding, the START index (END\nTABLE')
s:\n(.*)\n.*(,\1.*):\n\2:
# delete table entries starting from, but excluding, the END index (TABLE'')
s:(.*)\n(.*,\1 ..).*:\2:
# remove the indexes and print (implicitly) the resulting values
s:,..::g
```
[Answer]
## Apple II 6502 assembly, 75 bytes
Byte code:
```
A9 46 85 36 A9 10 85 37 A0 00 98 20 DA FD A9 A0
20 ED FD C0 42 D0 F3 20 93 FE A2 FC 20 1B FD 9D
04 01 E8 D0 F7 86 31 A9 8D 8D 04 02 20 A7 FF B5
3C 0A 75 3C 95 3C CA 10 F6 A6 3D BD 05 02 20 ED
FD E8 E4 3C D0 F5 99 05 02 C8 60
```
Disassembly:
```
LDA #<+
STA CSWL
LDA #>+
STA CSWH ;redirect stdout
LDY #$00
- TYA
JSR PRBYTE ;print number
LDA #$A0 ;space
JSR COUT ;print space
CPY #$42 ;22*3
BNE -
JSR SETVID ;restore stdout
LDX #$FC
- JSR KEYIN ;fetch a key
STA $0104,X ;store to $200+
INX
BNE - ;four keys
STX MODE ;set internal flags
LDA #$8D
STA $0204 ;set key delimiter
JSR GETNUM ;convert keys to hex values
- LDA A1L,X ;fetch value
ASL
ADC A1L,X ;multiply by 3
STA A1L,X ;store value
DEX
BPL - ;both inputs
LDX A1H ;first input
- LDA $0205,X ;fetch from index
JSR COUT ;print character
INX
CPX A1L
BNE - ;until second input
+ STA $0205,Y ;fall through to save a byte
INY
RTS
```
It forms an array in memory that looks like the output.
The chosen values are:
```
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
00 03 06 09 0C 0F 12 15 18 1B 1E 21 24 27 2A 2D 30 33 36 39 3C 3F
```
User presses four keys to set the inputs.
] |
[Question]
[
## Background
[Actually](https://github.com/Mego/Seriously) (the successor to [Seriously](https://github.com/Mego/Seriously/tree/v1)) is a stack-based imperative golfing language I created in November of 2015. Like many other golfing languages, it has one-byte commands that perform different functions based on the contents of the stack. One of its specialties is mathematics - it has a wide variety of mathematics-based commands. However, in order to perform math operations, you have to put (one or more) numbers on the stack. Pushing a specific value in as few bytes as possible is tricky, because there are many different options. In this challenge, you will be doing exactly that: representing numbers (specifically, integers) in Actually in as few bytes as possible.
## The Challenge
Given an integer `N` as input, output valid Actually code that results in `N` being pushed to the stack.
* The input will be within the range of a 32-bit signed two's complement integer (i.e. the integers in the inclusive range `[-2147483648, 2147483647]`).
* The result must be an integer (not a float, string, list, or function), and must be on top of the stack.
* You may not make any assumptions about the contents of the stack (like whether or not it is empty). Any existing values on the stack must not be modified or rearranged.
* [The latest commit of Actually at the time I am writing this challenge](https://github.com/Mego/Seriously/commit/3236c0fcc93207be2f6fdc404f2781d6a9bccac4) is to be used. If I make bug fixes or performance enhancements (or any other minor change that does not remove or change functionality of the allowed commands), I will update this version.
* Your solution must do at least as well as the trivial solution (prepend `:` to the input to make a numeric literal).
* Your score will be the sum of the lengths of the trivial solutions minus the sum of the lengths of the outputs for the selection of 1000 32-bit signed two's complement integers used for scoring, which can be found below. I reserve the right to change the scoring integers at any time, if there is a need (such as optimizing for the test cases or the test cases not being thorough enough).
* Solutions must output a valid answer within 30 seconds for each input. Timing will be done on a standard free [Cloud9 workspace](https://c9.io/).
## Commands
For simplicity, only 141 out of the (currently) 208 commands may be used, and many overloads of those 141 that are unrelated to number-crunching have been removed. Here is the list of allowed commands (format is `<hex code> (<symbol>): <descriptions of functions based on stack values and types>`:
```
0B (♂): take the next command and map it over the top of the stack (for example, ♂A is equivalent to `A`M)
1F (▼): pop a,b: push b//gcd(a,b),a//gcd(a,b); pop [a]: push [x//gcd([a]) for x in [a]]
20 ( ): push the # of elements on the stack (push len(stack))
21 (!): pop a: push a! (factorial(a))
22 ("): string literal, reads until next " and pushes value onto stack. An implied " is present at EOF if needed.
23 (#): pop a: push list(a)
25 (%): pop a,b: push a%b
26 (&): pop a,b: push a & b (bitwise AND)
27 ('): pushes next character onto stack as character literal (length-1 string)
28 ((): rotates stack right by 1
29 ()): rotates stack left by 1
2A (*): pop a,b: push a*b; pop a,[b] or [b],a: apply a* to each element in the array; pop [a],[b]: push dot product of [a] and [b] (sum([a[i]*b[i] for i in len(a)])) (shorter is padded with 0s)
2B (+): pop a,b: push a+b; pop [a],[b]: push [a][b] (append [b] to [a]); pop a,[b] or [b],a: apply a+ to each element in the array
2D (-): pop a,b: push a-b; pop [a],[b]: push [a]-[b] (all elements of [a] not in [b])
2F (/): pop a,b: push a/b (float division); pop [a]: rotate [a] right by 1, push [a]
30 (0): push 0
31 (1): push 1
32 (2): push 2
33 (3): push 3
34 (4): push 4
35 (5): push 5
36 (6): push 6
37 (7): push 7
38 (8): push 8
39 (9): push 9
3A (:): numeric literal delimiter: pushes the longest string of characters in '0123456789+-.ij' as a numeric
3B (;): pop a: push a,a (duplicates top element)
3C (<): pop a,b: push 1 if a<b else 0
3D (=): pop a,b: push 1 if a==b else 0
3E (>): pop a,b: push 1 if a>b else 0
40 (@): pop a,b: push a,b (rotate top 2 elements)
41 (A): pop a: push abs(a)
43 (C): pop a: push cos(a)
44 (D): pop a: push a-1; pop [a]: push stddev([a])
45 (E): pop a: push erf(a); pop [a],b: push [a][b] (bth item in [a])
46 (F): pop a: push Fib(a) (Fib(0)=0, Fib(1)=Fib(2)=1); pop [a]: push a[0]
48 (H): pop [a],b: push [a][:b]
49 (I): pop a,b,c: push b if a is truthy, else push c
4B (K): pop a: push ceil(a)
4C (L): pop a: push floor(a)
4D (M): pop f,[a], execute f for each element in [a], using the element as a temporary stack, push [a] (similar to map(f,[a])); pop [a]: push max([a])
4E (N): pop [a]: push a[-1]
50 (P): pop a: push the a-th prime (zero-indexed)
52 (R): pop f,[a]: call f, using [a] as a temporary stack, push [a] (similar to reduce(f,[a])); pop [a]: push [a][::-1] (reverse); pop a: push [1,2,...,a] (range(1,a+1))
53 (S): pop a: push sin(a); pop [a]: push sorted(a)
54 (T): pop a: push tan(a); pop [a],b,c: set [a][b] to c, push [a]
55 (U): pop [a],[b]: push union of [a] and [b]
57 (W): loop delimiter: peek top of stack, repeat code in loop while a evaluates to true
58 (X): pop a: discard
59 (Y): pop a: push !bool(a) (logical negate, opposite of b)
5A (Z): pop [a],[b]: push zip([a],[b]); pop a, zip the next a lists
5B ([): begin list literal, values are delimited by commas (,)
5C (\): pop a,b: push a/b (integer division); pop [a]: rotate [a] left by 1, push [a]
5D (]): end list literal
5E (^): pop a,b: push a XOR b
5F (_): pop a: push ln(a)
60 (`): function literal delimiter, pushes function whose body contains all of the commands until the next `. An implied ` is present at EOF if needed.
61 (a): invert the stack ([a,b,c,d] -> [d,c,b,a])
62 (b): pop a: push 0 if a==0 else 1; pop "a" or [a]: push 0 if len(a)==0 else 1; pop f: push 0 if len(f)==0 else 1
63 (c): pop a: push character at ordinal a%256; pop [a],b: push [a].count(b)
64 (d): pop [a]: dequeue b from [a], push [a],b
65 (e): pop a: push exp(a)
66 (f): pop a: push the Fibonacci index of a if a is a Fibonacci number, else -1
67 (g): pop a,b: push gcd(a,b); pop [a]: push gcd([a])
68 (h): pop a,b: push sqrt(a*a+b*b) (Euclidean norm)
69 (i): pop [a]: push each element from [a], starting from end (flatten)
6B (k): pop all elements from stack, convert to list (in the order they were on the stack, starting from the top), and push
6C (l): pop [a]: push len([a])
6D (m): pop a: push int(a),frac(a) (modf(a)); pop [a]: push min([a])
6E (n): pop a,b: push a b times
6F (o): pop [a],b: push b to [a], push [a]
70 (p): pop a: push 1 if a is prime else 0; pop [a]: pop b from [a], push [a],b
71 (q): pop [a],b: enqueue b in [a], push [a]
72 (r): pop a: push [0,1,...,a-1] (range(0,a))
75 (u): pop a: push a+1
77 (w): pop a: push the full positive prime factorization of |a| (18 -> [[2,1],[3,2]], -5 -> [[5,1]])
78 (x): pop a,b: push [a,b) (range(a,b)); pop [a]: push range(*a)
79 (y): pop a: push the positive prime factors of |a| (18 -> [2,3], -5 -> [5])
7B ({): pop a: rotate stack right a times
7C (|): pop a,b: push a | b (bitwise OR)
7D (}): pop a: rotate stack left a times
7E (~): pop a: push ~a (unary bitwise negate)
80 (Ç): pop a,b: push a+bi; pop [a]: pop pairs of real numerics b,c from [a] and push b+ci (appending 0 to [a] if len([a]) is odd)
83 (â): pop a: push asin(a)
84 (ä): pop a: push acos(a)
85 (à): pop a: push atan(a)
86 (å): pop a,b: push atan2(a,b)
87 (ç): pop a: push asinh(a)
88 (ê): pop a: push acosh(a)
89 (ë): pop a: push atanh(a)
8B (ï): push i, the imaginary unit (sqrt(-1) or 0+1i)
8C (î): pop a, push 0+ai; pop [a], push [a] with every element multiplied by i
8D (ì): pop a: push 1/a
8E (Ä): pop a: push sinh(a)
8F (Å): pop a: push cosh(a)
90 (É): pop a: push tanh(a)
91 (æ): pop [a]: push mean([a])
9A (Ü): pop [a]: push mode([a])
9B (¢): pop a,b: push abs(a)*sgn(b)
9D (¥): pop [a],[b]: push the result of pairwise addition of [a] and [b], padding the shorter with 0s
9E (₧): pop z: push phase(z)
A0 (á): pop z: push the complex conjugate of z
A1 (í): pop [a],b: push [a].index(b) (0-based, -1 if not found)
A7 (º): pop a: push degrees(a)
A8 (¿): pop a,b: push int(a,b) (interpret a as a base-b int)
A9 (⌐): pop a: push a+2
AA (¬): pop a: push a-2
AB (½): pop a: push a/2 (float division)
AC (¼): pop a: push a/4 (float division)
AD (¡): pop a,b: push a string representing a in base b
B0 (░): pop [a],[b]: push [[b][i] if [a][i] for i in len(b)], pads [a] with 0s if necessary
B1 (▒): pop a: push totient(a) (# of integers <= a that are coprime with a)
B2 (▓): pop a: push pi(a) (# of primes <= a)
B3 (│): duplicate stack ([a,b,c] => [a,b,c,a,b,c])
B4 (┤): pop a,b: push 1 if a and b are coprime else 0
B9 (╣): pop a: push the ath row in Pascal's triangle
C5 (┼): duplicate each element on stack ([a,b,c] => [a,a,b,b,c,c])
C6 (╞): pop a: make a total copies of each element on stack (3 [a,b,c] -> [a,a,a,b,b,b,c,c,c])
C7 (╟): pop a: pop a elements and push a list containing those elements in their original order
CB (╦): push pi
CC (╠): push e
D1 (╤): pop a: push 10**a
D2 (╥): pop a: push log(a) (log base 10)
D3 (╙): pop a: push 2**a
D4 (╘): pop a: push lg(a) (log base 2)
D5 (╒): push ln(2)
DB (█): pop a,b: push C(a,b) (aCb)
DC (▄): pop a,b: push P(a,b) (aPb)
E2 (Γ): pop a: push Gamma(a)
E3 (π): pop [a]: push product([a])
E4 (Σ): pop [a]: push sum([a])
E7 (τ): pop a: push 2*a
ED (φ): push phi (golden ratio)
F1 (±): pop a: push -a (unary negate)
F2 (≥): pop a,b: push a>=b
F3 (≤): pop a,b: push a<=b
F7 (≈): pop a: push int(a)
F8 (°): pop a: push radians(a)
FB (√): pop a: push sqrt(a)
FC (ⁿ): pop a,b: push pow(a,b)
FD (²): pop a: push a*a
[a] refers to an iterable (list, string, etc.), "a" refers to a string, f refers to a function, and a (and b, and c, and so on) refers to a numeric (or any data type, if the command is type-agnostic).
```
It is likely that many of these commands will not be used, but I have included them just in case they are useful.
## Scoring
Here are the integers that will be used for scoring:
```
-2124910654
-2117700574
-2098186988
-2095671996
-2083075613
-2058271687
-2052250777
-2024215903
-2019485642
-2016095616
-2009838326
-2009173317
-2007673992
-2000014444
-1999825668
-1992515610
-1989566707
-1975506037
-1955473208
-1950731112
-1949886423
-1920624450
-1918465596
-1916287469
-1905036556
-1903956118
-1888944417
-1865221863
-1856600057
-1842797147
-1835637734
-1812631357
-1805740096
-1798015647
-1726688233
-1723609647
-1713776890
-1700307138
-1687644479
-1645515069
-1617635994
-1610444000
-1579053372
-1556891649
-1549652116
-1537732956
-1535180388
-1527162056
-1524851611
-1524658412
-1523244369
-1521379172
-1520191198
-1519035741
-1516978241
-1508892332
-1489938422
-1482102944
-1481823232
-1470621147
-1469145091
-1446844485
-1441790509
-1437843276
-1435359182
-1434186947
-1429816311
-1429393781
-1419752032
-1400387846
-1385152926
-1372620863
-1369257355
-1361933674
-1360480816
-1334846204
-1323741718
-1323660173
-1312800992
-1308824840
-1304658551
-1287829999
-1283767920
-1276288210
-1264275838
-1263965596
-1262866901
-1255421887
-1251428680
-1244825786
-1243200329
-1235305532
-1233977691
-1220537074
-1214100716
-1199414474
-1190725823
-1190401800
-1178717689
-1172378149
-1147869245
-1142875190
-1138538768
-1137864183
-1124917489
-1102987222
-1095920186
-1083001017
-1080902655
-1047122002
-1031842676
-1029877334
-1020849489
-1001684838
-998419619
-990915088
-985235989
-982515261
-979074894
-974195629
-973832940
-965324937
-944246431
-938387588
-933873331
-932692878
-928039285
-927947459
-914008773
-907981688
-906376330
-903502449
-898112547
-887444438
-862658502
-843628573
-822463032
-786051095
-776932426
-776033951
-752042328
-746532472
-743149468
-740225710
-734414418
-725435852
-708101516
-699674783
-694869277
-693246525
-690571518
-689249770
-688581912
-686864294
-681445866
-647992869
-641101583
-631409299
-624686189
-613079884
-593711206
-591688546
-591331185
-574790069
-573024823
-565387051
-565137163
-556338668
-556291492
-541411509
-538932064
-500479857
-482419890
-468050561
-424532545
-420534171
-408741873
-406973874
-387664799
-382084509
-367095703
-352332569
-352195997
-346430007
-324596389
-320119776
-306594578
-305952425
-283718911
-267302378
-243302738
-242955859
-232180029
-225394407
-217418127
-212286453
-208344820
-191300139
-186177744
-175765723
-161763935
-157025501
-140389149
-132298608
-126175769
-70566352
-68748576
-53985905
-52674668
-50228620
-39678495
-19825663
-8349922
-8186722
-8125700
-8073135
-8043230
-7994382
-7874433
-7863624
-7784916
-7782477
-7696343
-7607278
-7531250
-7388060
-7368780
-7367625
-7353084
-7334489
-7281141
-7267149
-7140057
-7119066
-7010389
-6992089
-6975258
-6863360
-6784772
-6741079
-6585985
-6550401
-6520011
-6495144
-6459702
-6294273
-6178342
-6169344
-6139663
-6090928
-6022637
-5992707
-5971334
-5925304
-5880940
-5873707
-5807953
-5703992
-5692895
-5535131
-5488812
-5468330
-5404148
-5290247
-5274221
-5264144
-5234715
-5224048
-5179837
-5084014
-5043990
-5028537
-5011679
-4998333
-4922901
-4880159
-4874060
-4787390
-4749096
-4736217
-4502308
-4480611
-4424319
-4363262
-4349743
-4290050
-4240069
-4239657
-4174072
-4093051
-4045363
-4037689
-4033352
-3839265
-3766343
-3716899
-3680075
-3679053
-3581776
-3539227
-3461158
-3282526
-3205947
-3183427
-3169708
-3166430
-3089822
-3061531
-2947574
-2930733
-2919246
-2872882
-2830770
-2739228
-2713826
-2634018
-2613990
-2525529
-2439507
-2432921
-2376201
-2335005
-2307524
-2265548
-2176176
-2123133
-2108773
-2105934
-2075032
-2073940
-2045837
-2045648
-1978182
-1945769
-1935486
-1881608
-1654650
-1602520
-1506746
-1505294
-1475309
-1457605
-1327259
-1312217
-1178723
-1027439
-880781
-833776
-666675
-643098
-593446
-468772
-450369
-443225
-418164
-402004
-319964
-307400
-279414
-190199
-176644
-66862
-32745
-32686
-32352
-32261
-32035
-31928
-31414
-31308
-30925
-30411
-29503
-29182
-28573
-28500
-28093
-27743
-27716
-27351
-27201
-26834
-25946
-25019
-24469
-24341
-24292
-24151
-23732
-22769
-22242
-22002
-20863
-20762
-20644
-20189
-20009
-19142
-19036
-18980
-18616
-18196
-18123
-17942
-17915
-17601
-17494
-16669
-16417
-16317
-15051
-14796
-14742
-14600
-14443
-14159
-14046
-13860
-13804
-13745
-13634
-13498
-13497
-12688
-12471
-12222
-11993
-11467
-11332
-10783
-10250
-10114
-10089
-9930
-9434
-9336
-9128
-9109
-8508
-8460
-8198
-8045
-7850
-7342
-7229
-6762
-6302
-6245
-6171
-5957
-5842
-4906
-4904
-4630
-4613
-4567
-4427
-4091
-4084
-3756
-3665
-3367
-3186
-2922
-2372
-2331
-1936
-1683
-1350
-1002
-719
-152
-128
-127
-124
-122
-121
-119
-116
-113
-112
-111
-107
-104
-102
-101
-100
-95
-94
-91
-90
-87
-81
-80
-79
-78
-73
-72
-69
-68
-66
-65
-63
-57
-54
-52
-51
-48
-47
-46
-45
-43
-41
-37
-33
-31
-30
-27
-25
-21
-18
-15
-12
-8
-1
0
1
3
4
5
6
11
14
17
23
25
26
27
28
29
31
32
39
41
46
49
51
52
56
58
61
64
66
67
70
74
79
80
86
88
89
92
93
99
102
104
109
113
117
120
122
123
127
695
912
1792
2857
3150
3184
4060
4626
5671
6412
6827
7999
8017
8646
8798
9703
9837
10049
10442
10912
11400
11430
11436
11551
11937
12480
13258
13469
13689
13963
13982
14019
14152
14259
14346
15416
15613
15954
16241
16814
16844
17564
17702
17751
18537
18763
19890
21216
22238
22548
23243
23383
23386
23407
23940
24076
24796
24870
24898
24967
25139
25176
25699
26167
26536
26614
27008
27087
27142
27356
27458
27800
27827
27924
28595
29053
29229
29884
29900
30460
30556
30701
30815
30995
31613
31761
31772
32099
32308
32674
75627
80472
103073
110477
115718
172418
212268
242652
396135
442591
467087
496849
675960
759343
846297
881562
1003458
1153900
1156733
1164679
1208265
1318372
1363958
1411655
1522329
1559609
1677118
1693658
1703597
1811223
1831642
1838628
1884144
1931545
2085504
2168156
2170263
2239585
2308894
2329235
2364957
2432335
2435551
2596936
2684907
2691011
2705195
2738057
2851897
2925289
2995414
3051534
3216094
3267022
3271559
3338856
3440797
3638325
3651369
3718696
3724814
3811069
3854697
3866969
3893228
3963455
3984546
4098376
4100957
4128113
4200719
4256344
4286332
4306356
4316314
4438803
4458063
4461638
4552228
4563790
4584831
4607992
4884455
4907501
5045419
5066844
5150624
5157161
5190669
5314703
5337397
5434807
5440092
5502665
5523089
5547122
5566200
5582936
5634068
5690330
5776984
5778441
5818505
5826687
5827184
5885735
6010506
6084254
6131498
6138324
6250773
6292801
6306275
6315242
6331640
6484374
6502969
6545970
6666951
6690905
6763576
6766086
6895048
6912227
6929081
6941390
6978168
7045672
7085246
7193307
7197398
7270237
7276767
7295790
7375488
7472098
7687424
7840758
7880957
7904499
7948678
7974126
8015691
8037685
8112955
8131380
8140556
8142384
8220436
8308817
8331317
22581970
45809129
48103779
78212045
79674901
97299830
110308649
131744428
136663461
138485719
139842794
152061792
152685704
153070991
156228213
164884737
174776199
189346581
193148547
208582124
223891881
227308187
237373798
241214067
242476929
245495851
260606593
275202667
285717038
317009689
322759532
325369206
339724742
340122632
345010859
352375176
355826263
359695034
366118516
370008270
382712922
386379440
401153345
404986391
426084981
442843409
473909474
475192613
492302667
494747879
506279889
509813998
537558350
548423414
548467404
566383324
574188786
574792333
591678147
596558084
597423476
602432742
603067874
629552047
630893263
635249783
644959276
650710927
664859367
669433203
684329599
699991513
714451929
723556530
739294558
750895264
757618344
781123405
796973385
801637715
804776709
829003666
829219068
840167037
854882202
860066192
864304878
864808449
867107161
871871263
880591851
883020336
883178082
920223781
936008673
939417822
956776353
958281059
962183717
964059257
967860573
974322643
974999286
980009921
1032949015
1044249483
1064892676
1075628270
1080848022
1085571657
1173635593
1174809080
1176744978
1209783795
1212074975
1252323507
1254757790
1301450562
1302240953
1314501797
1315121266
1339304157
1364304289
1376260506
1383883477
1395158643
1411117754
1440755058
1448365702
1466814914
1468433821
1490105126
1493912601
1495600372
1509536621
1511014977
1545693948
1548924199
1566583103
1569747154
1574097219
1597784674
1610710480
1618324005
1646105187
1649417465
1655649169
1660619384
1668826887
1671093718
1672456990
1673477565
1678638502
1682302139
1682515769
1687920300
1690062315
1706031388
1713660819
1772170709
1778416812
1833443690
1861312062
1876004501
1876358085
1882435551
1916050713
1944906037
1950207172
1951593247
1973638546
1976288281
1994977271
2020053060
2025281195
2029716419
2033980539
2052482076
2058251762
2069273004
2073978021
2111013213
2119886932
2134609957
2140349794
2143934987
```
Here is a Python 3 program that can be used to verify and score a submission:
```
#!/usr/bin/env python3
import shlex
import os
import sys
import subprocess
try:
from seriously import Seriously
except:
print("Unable to load Seriously. Run 'pip3 install seriously' to install it.")
exit()
if len(sys.argv) < 2:
print("Usage: python3 {} 'command_to_call_your_program'".format(sys.argv[0]))
exit()
sys.stdin = open(os.devnull, 'r')
with open('nums.txt') as f:
nums = [int(x) for x in f]
total = 0
for num in nums:
p = subprocess.Popen(shlex.split(sys.argv[1]), stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
try:
out = p.communicate(str(num), timeout=30)[0].strip()
except subprocess.TimeoutExpired:
print("Program failed to finish within 30 seconds for {}".format(num))
exit()
val = Seriously().eval(out)[0]
if not len(out) <= len(':'+str(num)):
print("Failed to do at least as well as naive on {} ({})".format(num, out))
exit()
elif val != num or not isinstance(val, int):
print("Incorrect output: {} instead of {}".format(val, num))
exit()
else:
print("{}: {} ({})".format(num, out, len(out)))
total += len(out)
print("Total:", total)
```
[Answer]
## Python 3, 51 52 57 bytes saved
This program brute forces its way through a significant number of 1-5 character programs, using a limited set of 54 56 instructions and a lot of pruning based on the state of the stack before adding each new instruction. It takes about one minute to run on my laptop. 6 characters would take hours.
```
#!/usr/bin/env python3
# -*- coding: cp437 -*-
import os
import sys
import json
import math
import time
import random
import timeit
try:
from seriously import Seriously,chr_cp437,ord_cp437
except:
print("Unable to load Seriously. Run 'pip3 install seriously' to install it.")
exit()
MAXLEN=5
MAX=2**31
future_alphabet=[
chr_cp437(0x4D), # (M): pop f,[a], execute f for each element in [a], using the element as a temporary stack, push [a] (similar to map(f,[a])); pop [a]: push max([a])
chr_cp437(0x52), # (R): pop f,[a]: call f, using [a] as a temporary stack, push [a] (similar to reduce(f,[a])); pop [a]: push [a][::-1] (reverse); pop a: push [1,2,...,a] (range(1,a+1))
chr_cp437(0x57), # (W): loop delimiter: peek top of stack, repeat code in loop while a evaluates to true
chr_cp437(0x60), # (`): function literal delimiter, pushes function whose body contains all of the commands until the next `. An implied ` is present at EOF if needed.
]
def next_instruction(program,stack):
plen = len(program)
slen = len(stack)
if plen>0 and program[-1]==chr_cp437(0x0B): # introspect the list on top of the stack
maybes = set(next_instruction(program[:-1],[stack[0][0]]))
# print(maybes)
for i in stack[0][1:]:
maybes = maybes & set(next_instruction(program[:-1],[i]))
# print(maybes)
maybes.discard(chr_cp437(0x72)) # no ranges of lists
maybes.discard(chr_cp437(0xB9)) # no pascal rows of lists
return list(maybes)
candidates = []
if plen==MAXLEN-1 and slen>1:
if any(isinstance(x,list) for x in stack):
return [] # lost cause
if slen==2 and isinstance( stack[0], int ) and isinstance( stack[1], int ):
candidates = candidates + [
chr_cp437(0x2A), # (*): pop a,b: push a*b; pop a,[b] or [b],a: apply a* to each element in the array; pop [a],[b]: push dot product of [a] and [b] (sum([a[i]*b[i] for i in len(a)])) (shorter is padded with 0s)
chr_cp437(0x2B), # (+): pop a,b: push a+b; pop [a],[b]: push [a][b] (append [b] to [a]); pop a,[b] or [b],a: apply a+ to each element in the array
chr_cp437(0x2D), # (-): pop a,b: push a-b; pop [a],[b]: push [a]-[b] (all elements of [a] not in [b])
chr_cp437(0x2F), # (/): pop a,b: push a/b (float division); pop [a]: rotate [a] right by 1, push [a]
chr_cp437(0x5C), # (\): pop a,b: push a/b (integer division); pop [a]: rotate [a] left by 1, push [a]
]
if stack[0]>1 and stack[0]<int(math.pow(MAX,1.0/3))+1 and stack[1]>2 and stack[1]<int(math.log(MAX)/math.log(3))+1:
candidates.append(chr_cp437(0xFC)) # (ⁿ): pop a,b: push pow(a,b)
if stack[0]>2 and stack[0]<1000 and stack[1]>2 and stack[1]<stack[0]:
candidates = candidates + [
chr_cp437(0xDB), # (█): pop a,b: push C(a,b) (aCb)
chr_cp437(0xDC) # (▄): pop a,b: push P(a,b) (aPb)
]
return candidates
if plen==MAXLEN-1 and slen==1 and isinstance(stack[0],list):
candidates = candidates + [
chr_cp437(0xE3), # (π): pop [a]: push product([a])
chr_cp437(0xE4) # (Σ): pop [a]: push sum([a])
]
return candidates
candidates = candidates + [
chr_cp437(0x30), # (0): push 0
chr_cp437(0x31), # (1): push 1
chr_cp437(0x32), # (2): push 2
chr_cp437(0x33), # (3): push 3
chr_cp437(0x34), # (4): push 4
chr_cp437(0x35), # (5): push 5
chr_cp437(0x36), # (6): push 6
chr_cp437(0x37), # (7): push 7
chr_cp437(0x38), # (8): push 8
chr_cp437(0x39) # (9): push 9
]
if plen==0 or (plen>0 and program[-1]!=":"):
candidates.append(chr_cp437(0x3A)) # (:): numeric literal delimiter: pushes the longest string of characters in '0123456789+-.ij' as a numeric
# if plen>0 and program[-1]==":":
# candidates.append(chr_cp437(0x2D)) # negative literal coming
if slen>0:
candidates.append(chr_cp437(0xB3)) # (│): duplicate stack ([a,b,c] => [a,b,c,a,b,c])
if slen>0 and isinstance( stack[0], int ):
candidates = candidates + [
chr_cp437(0x44), # (D): pop a: push a-1; pop [a]: push stddev([a])
chr_cp437(0x54), # (T): pop a: push tan(a); pop [a],b,c: set [a][b] to c, push [a]
chr_cp437(0x65), # (e): pop a: push exp(a)
chr_cp437(0x75), # (u): pop a: push a+1
chr_cp437(0xA9), # (⌐): pop a: push a+2
chr_cp437(0xAA), # (¬): pop a: push a-2
chr_cp437(0xAB), # (½): pop a: push a/2 (float division)
chr_cp437(0xAC), # (¼): pop a: push a/4 (float division)
chr_cp437(0xE7), # (τ): pop a: push 2*a
chr_cp437(0xF1), # (±): pop a: push -a (unary negate)
chr_cp437(0xFD), # (²): pop a: push a*a
chr_cp437(0x7E) # (~): pop a: push ~a (unary bitwise negate)
]
candidates.append(chr_cp437(0x3B)) # (;): pop a: push a,a (duplicates top element)
if stack[0]>=0:
if stack[0]<13:
candidates.append(chr_cp437(0x21)) # (!): pop a: push a! (factorial(a))
candidates.append(chr_cp437(0xD1)) # (╤): pop a: push 10**a
if stack[0]<32:
candidates.append(chr_cp437(0xD3)) # (╙): pop a: push 2**a
candidates.append(chr_cp437(0xB9)) # (╣): pop a: push the ath row in Pascal's triangle
if stack[0]<100:
candidates.append(chr_cp437(0x46)) # (F): pop a: push Fib(a) (Fib(0)=0, Fib(1)=Fib(2)=1); pop [a]: push a[0]
candidates.append(chr_cp437(0x50)) # (P): pop a: push the a-th prime (zero-indexed)
if stack[0]<500 and plen<MAXLEN-1:
candidates.append(chr_cp437(0x72)) # (r): pop a: push [0,1,...,a-1] (range(0,a))
if slen>0 and isinstance( stack[0], float ):
candidates = candidates + [
chr_cp437(0x4B), # (K): pop a: push ceil(a)
chr_cp437(0x4C) # (L): pop a: push floor(a)
]
if slen>0 and isinstance( stack[0], list ) and len(stack[0])>0:
candidates = candidates + [
chr_cp437(0xE3), # (π): pop [a]: push product([a])
chr_cp437(0xE4) # (Σ): pop [a]: push sum([a])
]
candidates.append(chr_cp437(0x69)) # (i): pop [a]: push each element from [a], starting from end (flatten)
if plen<MAXLEN-2:
candidates.append(chr_cp437(0x0B)) # (♂): take the next command and map it over the top of the stack (for example, ♂A is equivalent to `A`M)
if slen>1:
candidates.append(chr_cp437(0x6B)) # (k): pop all elements from stack, convert to list (in the order they were on the stack, starting from the top), and push
if slen>1 and isinstance( stack[0], int ):
candidates = candidates + [
chr_cp437(0x61), # (a): invert the stack ([a,b,c,d] -> [d,c,b,a])
chr_cp437(0xC5), # (┼): duplicate each element on stack ([a,b,c] => [a,a,b,b,c,c])
chr_cp437(0xC7) # (╟): pop a: pop a elements and push a list containing those elements in their original order
]
if stack[0]<100:
candidates.append(chr_cp437(0xC6)) # (╞): pop a: make a total copies of each element on stack (3 [a,b,c] -> [a,a,a,b,b,b,c,c,c])
if slen>1 and isinstance( stack[0], int ) and isinstance( stack[1], int ):
candidates = candidates + [
chr_cp437(0x2A), # (*): pop a,b: push a*b; pop a,[b] or [b],a: apply a* to each element in the array; pop [a],[b]: push dot product of [a] and [b] (sum([a[i]*b[i] for i in len(a)])) (shorter is padded with 0s)
chr_cp437(0x2B), # (+): pop a,b: push a+b; pop [a],[b]: push [a][b] (append [b] to [a]); pop a,[b] or [b],a: apply a+ to each element in the array
chr_cp437(0x2D), # (-): pop a,b: push a-b; pop [a],[b]: push [a]-[b] (all elements of [a] not in [b])
chr_cp437(0x2F), # (/): pop a,b: push a/b (float division); pop [a]: rotate [a] right by 1, push [a]
chr_cp437(0x5C), # (\): pop a,b: push a/b (integer division); pop [a]: rotate [a] left by 1, push [a]
]
if stack[0]>1 and stack[0]<int(math.pow(MAX,1.0/3))+1 and stack[1]>2 and stack[1]<int(math.log(MAX)/math.log(3))+1:
candidates.append(chr_cp437(0xFC)) # (ⁿ): pop a,b: push pow(a,b)
if stack[0]>2 and stack[0]<1000 and stack[1]>2 and stack[1]<stack[0]:
candidates = candidates + [
chr_cp437(0xDB), # (█): pop a,b: push C(a,b) (aCb)
chr_cp437(0xDC) # (▄): pop a,b: push P(a,b) (aPb)
]
if stack[1]-stack[0]>0 and stack[1]-stack[0]<500:
candidates.append(chr_cp437(0x78)) # (x): pop a,b: push [a,b) (range(a,b)); pop [a]: push range(*a)
if slen>1 and (isinstance( stack[0], list ) or isinstance( stack[1], list )):
candidates = candidates + [
chr_cp437(0x2A), # (*): pop a,b: push a*b; pop a,[b] or [b],a: apply a* to each element in the array; pop [a],[b]: push dot product of [a] and [b] (sum([a[i]*b[i] for i in len(a)])) (shorter is padded with 0s)
chr_cp437(0x2B), # (+): pop a,b: push a+b; pop [a],[b]: push [a][b] (append [b] to [a]); pop a,[b] or [b],a: apply a+ to each element in the array
chr_cp437(0x2D), # (-): pop a,b: push a-b; pop [a],[b]: push [a]-[b] (all elements of [a] not in [b])
chr_cp437(0x2F), # (/): pop a,b: push a/b (float division); pop [a]: rotate [a] right by 1, push [a]
chr_cp437(0x5C), # (\): pop a,b: push a/b (integer division); pop [a]: rotate [a] left by 1, push [a]
]
return candidates
# p = "8"+chr_cp437(0x72)+chr_cp437(0x0B)
# res = Seriously().eval(p)
# print(p)
# print(res)
# print(next_instruction(p,res))
# sys.exit()
programs = [[['',None]]]
best = {}
def l(n,force_colon=False):
if force_colon:
return ':'+str(n)
if n>=0 and n<10:
return str(n)
elif n<0 and n>-10:
return str(-n)+'±'
return ':'+str(n)
def cand(n,rep):
# print(n,rep,len(rep),l(n),len(l(n)),best[n] if n in best else "")
if n<=MAX and n>=-MAX and (len(rep)==1 or len(rep)<len(l(n))) and (n not in best or len(rep)<len(best[n])):
best[n] = rep
# print("woot")
return True
return False
for proglen in range(0,MAXLEN+1):
print(proglen,"/",MAXLEN)
if proglen<MAXLEN:
programs.append([])
first = ""
for p in programs[proglen]:
try:
if first!=p[0][0]:
first=p[0][0]
print(" ",p[0][0],"/",9)
except:
pass
if chr_cp437(0x7E) in p[0]:
print(p[0])
now = time.clock()
try:
res = Seriously().eval(p[0])
elapsed = time.clock()-now
if elapsed>0.0005:
timed = timeit.timeit('Seriously().eval("'+str(p[0].encode('unicode_escape'))+'")','from seriously import Seriously',number=1000)
if elapsed>0.01:
print("SLOW:")
print(p[0])
print(res)
print(elapsed)
if chr_cp437(0x7E) in p[0]:
print(res)
if len(res)==1 and isinstance( res[0], int ):
# print("cand",res[0],p[0])
cand(res[0],p[0])
p[1] = res
if proglen<MAXLEN:
# bail out if the stack is too complex to collapse in time
if proglen==MAXLEN-1:
if len(res)>0 and isinstance( res[0], list ) and not isinstance( res[0][0], int ):
continue
if len(res)>1 and isinstance( res[0], list ):
continue
if len(res)>2:
continue
for c in next_instruction(p[0],res):
programs[proglen+1].append([p[0]+c,None])
except:
pass
# print(programs)
def best_or_l(n,force_colon=False):
if n in best:
return best[n]
if n<0 and -n in best:
return best[-n]+chr_cp437(0xF1)
return l(n,force_colon)
# for key,value in sorted(best.items()):
# # if random.random()<0.01:
# print(key,value)
score = 0
for i in [-2124910654, -2117700574, -2098186988, -2095671996, -2083075613, -2058271687, -2052250777, -2024215903, -2019485642, -2016095616, -2009838326, -2009173317, -2007673992, -2000014444, -1999825668, -1992515610, -1989566707, -1975506037, -1955473208, -1950731112, -1949886423, -1920624450, -1918465596, -1916287469, -1905036556, -1903956118, -1888944417, -1865221863, -1856600057, -1842797147, -1835637734, -1812631357, -1805740096, -1798015647, -1726688233, -1723609647, -1713776890, -1700307138, -1687644479, -1645515069, -1617635994, -1610444000, -1579053372, -1556891649, -1549652116, -1537732956, -1535180388, -1527162056, -1524851611, -1524658412, -1523244369, -1521379172, -1520191198, -1519035741, -1516978241, -1508892332, -1489938422, -1482102944, -1481823232, -1470621147, -1469145091, -1446844485, -1441790509, -1437843276, -1435359182, -1434186947, -1429816311, -1429393781, -1419752032, -1400387846, -1385152926, -1372620863, -1369257355, -1361933674, -1360480816, -1334846204, -1323741718, -1323660173, -1312800992, -1308824840, -1304658551, -1287829999, -1283767920, -1276288210, -1264275838, -1263965596, -1262866901, -1255421887, -1251428680, -1244825786, -1243200329, -1235305532, -1233977691, -1220537074, -1214100716, -1199414474, -1190725823, -1190401800, -1178717689, -1172378149, -1147869245, -1142875190, -1138538768, -1137864183, -1124917489, -1102987222, -1095920186, -1083001017, -1080902655, -1047122002, -1031842676, -1029877334, -1020849489, -1001684838, -998419619, -990915088, -985235989, -982515261, -979074894, -974195629, -973832940, -965324937, -944246431, -938387588, -933873331, -932692878, -928039285, -927947459, -914008773, -907981688, -906376330, -903502449, -898112547, -887444438, -862658502, -843628573, -822463032, -786051095, -776932426, -776033951, -752042328, -746532472, -743149468, -740225710, -734414418, -725435852, -708101516, -699674783, -694869277, -693246525, -690571518, -689249770, -688581912, -686864294, -681445866, -647992869, -641101583, -631409299, -624686189, -613079884, -593711206, -591688546, -591331185, -574790069, -573024823, -565387051, -565137163, -556338668, -556291492, -541411509, -538932064, -500479857, -482419890, -468050561, -424532545, -420534171, -408741873, -406973874, -387664799, -382084509, -367095703, -352332569, -352195997, -346430007, -324596389, -320119776, -306594578, -305952425, -283718911, -267302378, -243302738, -242955859, -232180029, -225394407, -217418127, -212286453, -208344820, -191300139, -186177744, -175765723, -161763935, -157025501, -140389149, -132298608, -126175769, -70566352, -68748576, -53985905, -52674668, -50228620, -39678495, -19825663, -8349922, -8186722, -8125700, -8073135, -8043230, -7994382, -7874433, -7863624, -7784916, -7782477, -7696343, -7607278, -7531250, -7388060, -7368780, -7367625, -7353084, -7334489, -7281141, -7267149, -7140057, -7119066, -7010389, -6992089, -6975258, -6863360, -6784772, -6741079, -6585985, -6550401, -6520011, -6495144, -6459702, -6294273, -6178342, -6169344, -6139663, -6090928, -6022637, -5992707, -5971334, -5925304, -5880940, -5873707, -5807953, -5703992, -5692895, -5535131, -5488812, -5468330, -5404148, -5290247, -5274221, -5264144, -5234715, -5224048, -5179837, -5084014, -5043990, -5028537, -5011679, -4998333, -4922901, -4880159, -4874060, -4787390, -4749096, -4736217, -4502308, -4480611, -4424319, -4363262, -4349743, -4290050, -4240069, -4239657, -4174072, -4093051, -4045363, -4037689, -4033352, -3839265, -3766343, -3716899, -3680075, -3679053, -3581776, -3539227, -3461158, -3282526, -3205947, -3183427, -3169708, -3166430, -3089822, -3061531, -2947574, -2930733, -2919246, -2872882, -2830770, -2739228, -2713826, -2634018, -2613990, -2525529, -2439507, -2432921, -2376201, -2335005, -2307524, -2265548, -2176176, -2123133, -2108773, -2105934, -2075032, -2073940, -2045837, -2045648, -1978182, -1945769, -1935486, -1881608, -1654650, -1602520, -1506746, -1505294, -1475309, -1457605, -1327259, -1312217, -1178723, -1027439, -880781, -833776, -666675, -643098, -593446, -468772, -450369, -443225, -418164, -402004, -319964, -307400, -279414, -190199, -176644, -66862, -32745, -32686, -32352, -32261, -32035, -31928, -31414, -31308, -30925, -30411, -29503, -29182, -28573, -28500, -28093, -27743, -27716, -27351, -27201, -26834, -25946, -25019, -24469, -24341, -24292, -24151, -23732, -22769, -22242, -22002, -20863, -20762, -20644, -20189, -20009, -19142, -19036, -18980, -18616, -18196, -18123, -17942, -17915, -17601, -17494, -16669, -16417, -16317, -15051, -14796, -14742, -14600, -14443, -14159, -14046, -13860, -13804, -13745, -13634, -13498, -13497, -12688, -12471, -12222, -11993, -11467, -11332, -10783, -10250, -10114, -10089, -9930, -9434, -9336, -9128, -9109, -8508, -8460, -8198, -8045, -7850, -7342, -7229, -6762, -6302, -6245, -6171, -5957, -5842, -4906, -4904, -4630, -4613, -4567, -4427, -4091, -4084, -3756, -3665, -3367, -3186, -2922, -2372, -2331, -1936, -1683, -1350, -1002, -719, -152, -128, -127, -124, -122, -121, -119, -116, -113, -112, -111, -107, -104, -102, -101, -100, -95, -94, -91, -90, -87, -81, -80, -79, -78, -73, -72, -69, -68, -66, -65, -63, -57, -54, -52, -51, -48, -47, -46, -45, -43, -41, -37, -33, -31, -30, -27, -25, -21, -18, -15, -12, -8, -1, 0, 1, 3, 4, 5, 6, 11, 14, 17, 23, 25, 26, 27, 28, 29, 31, 32, 39, 41, 46, 49, 51, 52, 56, 58, 61, 64, 66, 67, 70, 74, 79, 80, 86, 88, 89, 92, 93, 99, 102, 104, 109, 113, 117, 120, 122, 123, 127, 695, 912, 1792, 2857, 3150, 3184, 4060, 4626, 5671, 6412, 6827, 7999, 8017, 8646, 8798, 9703, 9837, 10049, 10442, 10912, 11400, 11430, 11436, 11551, 11937, 12480, 13258, 13469, 13689, 13963, 13982, 14019, 14152, 14259, 14346, 15416, 15613, 15954, 16241, 16814, 16844, 17564, 17702, 17751, 18537, 18763, 19890, 21216, 22238, 22548, 23243, 23383, 23386, 23407, 23940, 24076, 24796, 24870, 24898, 24967, 25139, 25176, 25699, 26167, 26536, 26614, 27008, 27087, 27142, 27356, 27458, 27800, 27827, 27924, 28595, 29053, 29229, 29884, 29900, 30460, 30556, 30701, 30815, 30995, 31613, 31761, 31772, 32099, 32308, 32674, 75627, 80472, 103073, 110477, 115718, 172418, 212268, 242652, 396135, 442591, 467087, 496849, 675960, 759343, 846297, 881562, 1003458, 1153900, 1156733, 1164679, 1208265, 1318372, 1363958, 1411655, 1522329, 1559609, 1677118, 1693658, 1703597, 1811223, 1831642, 1838628, 1884144, 1931545, 2085504, 2168156, 2170263, 2239585, 2308894, 2329235, 2364957, 2432335, 2435551, 2596936, 2684907, 2691011, 2705195, 2738057, 2851897, 2925289, 2995414, 3051534, 3216094, 3267022, 3271559, 3338856, 3440797, 3638325, 3651369, 3718696, 3724814, 3811069, 3854697, 3866969, 3893228, 3963455, 3984546, 4098376, 4100957, 4128113, 4200719, 4256344, 4286332, 4306356, 4316314, 4438803, 4458063, 4461638, 4552228, 4563790, 4584831, 4607992, 4884455, 4907501, 5045419, 5066844, 5150624, 5157161, 5190669, 5314703, 5337397, 5434807, 5440092, 5502665, 5523089, 5547122, 5566200, 5582936, 5634068, 5690330, 5776984, 5778441, 5818505, 5826687, 5827184, 5885735, 6010506, 6084254, 6131498, 6138324, 6250773, 6292801, 6306275, 6315242, 6331640, 6484374, 6502969, 6545970, 6666951, 6690905, 6763576, 6766086, 6895048, 6912227, 6929081, 6941390, 6978168, 7045672, 7085246, 7193307, 7197398, 7270237, 7276767, 7295790, 7375488, 7472098, 7687424, 7840758, 7880957, 7904499, 7948678, 7974126, 8015691, 8037685, 8112955, 8131380, 8140556, 8142384, 8220436, 8308817, 8331317, 22581970, 45809129, 48103779, 78212045, 79674901, 97299830, 110308649, 131744428, 136663461, 138485719, 139842794, 152061792, 152685704, 153070991, 156228213, 164884737, 174776199, 189346581, 193148547, 208582124, 223891881, 227308187, 237373798, 241214067, 242476929, 245495851, 260606593, 275202667, 285717038, 317009689, 322759532, 325369206, 339724742, 340122632, 345010859, 352375176, 355826263, 359695034, 366118516, 370008270, 382712922, 386379440, 401153345, 404986391, 426084981, 442843409, 473909474, 475192613, 492302667, 494747879, 506279889, 509813998, 537558350, 548423414, 548467404, 566383324, 574188786, 574792333, 591678147, 596558084, 597423476, 602432742, 603067874, 629552047, 630893263, 635249783, 644959276, 650710927, 664859367, 669433203, 684329599, 699991513, 714451929, 723556530, 739294558, 750895264, 757618344, 781123405, 796973385, 801637715, 804776709, 829003666, 829219068, 840167037, 854882202, 860066192, 864304878, 864808449, 867107161, 871871263, 880591851, 883020336, 883178082, 920223781, 936008673, 939417822, 956776353, 958281059, 962183717, 964059257, 967860573, 974322643, 974999286, 980009921, 1032949015, 1044249483, 1064892676, 1075628270, 1080848022, 1085571657, 1173635593, 1174809080, 1176744978, 1209783795, 1212074975, 1252323507, 1254757790, 1301450562, 1302240953, 1314501797, 1315121266, 1339304157, 1364304289, 1376260506, 1383883477, 1395158643, 1411117754, 1440755058, 1448365702, 1466814914, 1468433821, 1490105126, 1493912601, 1495600372, 1509536621, 1511014977, 1545693948, 1548924199, 1566583103, 1569747154, 1574097219, 1597784674, 1610710480, 1618324005, 1646105187, 1649417465, 1655649169, 1660619384, 1668826887, 1671093718, 1672456990, 1673477565, 1678638502, 1682302139, 1682515769, 1687920300, 1690062315, 1706031388, 1713660819, 1772170709, 1778416812, 1833443690, 1861312062, 1876004501, 1876358085, 1882435551, 1916050713, 1944906037, 1950207172, 1951593247, 1973638546, 1976288281, 1994977271, 2020053060, 2025281195, 2029716419, 2033980539, 2052482076, 2058251762, 2069273004, 2073978021, 2111013213, 2119886932, 2134609957, 2140349794, 2143934987]:
print(i,best_or_l(i,True),len(l(i)),len(best_or_l(i,True)))
score = score + (len(l(i))-len(best_or_l(i,True)))
print("Score:",score)
with open("brute_serious.json","w") as outfile:
outfile.write(json.dumps(best,sort_keys=True,indent=2))
```
Here's a random sampling of the sorts of Actually programs that end up found by this algorithm:
```
-387420483 99ⁿ6-
-16777208 4!╙8-
-999999 6╤1-
-362864 9!4²-
-46369 4!Fu±
-5045 57!±-
8101 9eL¬
19900 2╤τrΣ
46367 4!FD
68072 5╙│F\
99990 1╤5╤-
156246 75ⁿ¬τ
518393 76!²-
1814399 59!*D
6534927 35╙F*
14930357 56²F+
19999995 57╤τ-
25396560 7!│D*
65691025 9eKu²
100001000 3╤8╤+
200000002 8╤uτ
800000008 88╤u*
1626347584 88!+²
2000000018 99╤+τ
```
[Answer]
# Ruby, 52 chars saved
based off my [answer](https://codegolf.stackexchange.com/a/64249/31203) to a similar question. This builds up a big list of ways to get to a number and selects the shortest. Unlike the other answers posted, It gets most of its savings on small numbers. In fact i do not try numbers with absolute values over 2000.
```
$s = {};
Fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
Fib = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903]
Prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999]
def shortest a,b=nil
return $s[[a,b]] if $s[[a,b]]
return $s[[a,b]] = ":#{a}" if (b||a).abs > 2000 #gives up on big inputs
$s[[a,b]] = ":#{a}" #set a temp value to block calling with the same paramiters recursivly.
l = []
if b
if a == b
return $s[[a,b]] = ""
elsif a > b
l.push shortest(a-b)+"-"
l.push "X"+shortest(b)
l.push "¬" if b+2==a
l.push "D" if b+1==a
elsif a < b
l.push shortest(b-a)+"+"
l.push "²"+shortest(a*a,b) if a*a>a && a*a<=b+2
l.push "τ"+shortest(a+a,b) if a+a<=b+2 && a+a>a
l.push shortest(b/a)+"*" if a>2 && b%a == 0
l.push ";"+shortest(a,b/a)+"*" if a>2 && b%a == 0
l.push "╙"+shortest(2**a,b) if 2**a<=b+2
l.push "╤"+shortest(10**a,b) if 10**a<=b+2
l.push "F"+shortest(Fib[a],b) if Fib[a] and Fib[a]<=b+2 and a > 5
l.push "P"+shortest(Prime[a],b) if Prime[a] and Prime[a]<=b+2
l.push "!"+shortest(Fact[a],b) if Fact[a] and Fact[a]<=b+2 and a > 3
end
else
return ($s[[a,b]] = a.to_s) if a<10 and a>-1
l.push ":#{a}"
if a<0
l.push shortest(-a)+"±"
l.push shortest(~a)+"~"
l.push shortest(a+1)+"D"
l.push shortest(a+2)+"¬"
else
l.push shortest(a-1)+"u"
l.push shortest(a-2)+"⌐"
(1..[a/2,100].min).each {|n|
l.push shortest(n)+shortest(n,a)
}
end
end
return $s[[a,b]] = l.min_by{|x|x.length}
end
a = [-4427,-4091,-4084,-3756,-3665,-3367,-3186,-2922,-2372,-2331,-1936,-1683,-1350,-1002,-719,-152,-128,-127,-124,-122,-121,-119,-116,-113,-112,-111,-107,-104,-102,-101,-100,-95,-94,-91,-90,-87,-81,-80,-79,-78,-73,-72,-69,-68,-66,-65,-63,-57,-54,-52,-51,-48,-47,-46,-45,-43,-41,-37,-33,-31,-30,-27,-25,-21,-18,-15,-12,-8,-1,0,1,3,4,5,6,11,14,17,23,25,26,27,28,29,31,32,39,41,46,49,51,52,56,58,61,64,66,67,70,74,79,80,86,88,89,92,93,99,102,104,109,113,117,120,122,123,127,695,912,1792,2857,3150,3184,4060,4626,5671,6412,6827,7999,8017]
a.sort_by!{|x|x.abs}
c = a.map{
|i|
p [i,shortest(i)]
shortest(i)
}
p c.inject(0){|a,b|a+b.length}
```
And a complete list of all shortened numbers (sorted by absolute value):
```
[0, "0"]
[-1, "1±"]
[1, "1"]
[3, "3"]
[4, "4"]
[5, "5"]
[6, "6"]
[-8, "8±"]
[11, "9⌐"]
[-12, "6τ±"]
[14, "7τ"]
[-15, "7τ~"]
[17, "6P"]
[-18, "9τ±"]
[-21, "8F±"]
[23, "8P"]
[25, "5²"]
[-25, "5²±"]
[29, "9P"]
[-30, "9P~"]
[32, "5╙"]
[-33, "5╙~"]
[-37, "6²~"]
[49, "7²"]
[64, "6╙"]
[-65, "6╙~"]
[-81, "9²±"]
[-100, "2╤±"]
[-101, "2╤~"]
[-102, "2╤⌐±"]
[102, "2ѩ"]
[113, "9PP"]
[-113, "9PP±"]
[-119, "5!D±"]
[120, "5!"]
[-121, "5!~"]
[122, "5!⌐"]
[-122, "5!⌐±"]
[127, "7╙D"]
[-127, "7╙D±"]
[-128, "7╙±"]
[-719, "6!D±"]
[-1002, "3╤⌐±"]
[-1683, "9P²τ~"]
[1792, "78╙*"]
[-1936, ":44²±"]
```
Note: These have not bean tested as I do not have access to Actually.
[Answer]
## Python 3, 52 55 bytes saved
This solution works backwards from the previous two. Instead of assembling programs left to right, I start at the end and work backwards. To make this work, I've got to actually run my programs, and I can't prune instructions based on their parameters because their parameters don't exist yet when they get added. My workaround for that is not present in this answer; it involves telling SeriouslyCommands.py to throw an IOError any time the craziness-producing functions get called with large arguments, and to raise that exception so I can catch it.
Here's how this program works:
I start with an empty stack and know I want a single number. What instructions can accomplish that? 0-9 get me an integer and don't require anything on the stack, so those are complete programs. K,L,T,e and a bunch of others get me a number and need a number (I don't differentiate between floats and ints until the output is checked). \*,+,etc turn two numbers into a number. And so on.
Now I have a few complete programs and a list of incomplete program-suffixes that can turn some known arrangement of types on the stack into the single number I want. Repeat the process and prepend to each them every instruction that can fulfill one/some/all of their stack requirements, save the ones that are complete programs, and send the incomplete ones to the next step.
In the last two steps I prune the possibilities a lot because I know I can't have any stack requirements left when I'm done (so 0-9 are the only valid instructions to be prepended to the program last) and prior to that I can only have a single number as a requirement.
Not surprisingly, this solution produces exactly the same score as the better of my other two solutions. They find almost exactly the same set of results.
This program can probably go up to 6 characters in less time than the other one, but it would still be prohibitive.
I think a great solution could be made by combining the two, assembling prefixes and suffixes and joining them in the middle if their stacks are compatible.
```
#!/usr/bin/env python3
# -*- coding: cp437 -*-
import os
import sys
import json
import math
import time
import random
import timeit
#!/usr/bin/env python3
# -*- coding: cp437 -*-
# instruction, pops, pushes,
instructions = [
[0x30, [], ['number']], # (0): push 0
[0x31, [], ['number']], # (1): push 1
[0x32, [], ['number']], # (2): push 2
[0x33, [], ['number']], # (3): push 3
[0x34, [], ['number']], # (4): push 4
[0x35, [], ['number']], # (5): push 5
[0x36, [], ['number']], # (6): push 6
[0x37, [], ['number']], # (7): push 7
[0x38, [], ['number']], # (8): push 8
[0x39, [], ['number']], # (9): push 9
[0x4B, ['number'], ['number']], # (K): pop a: push ceil(a)
[0x4C, ['number'], ['number']], # (L): pop a: push floor(a)
[0x54, ['number'], ['number']], # (T): pop a: push tan(a); pop [a],b,c: set [a][b] to c, push [a]
[0x65, ['number'], ['number']], # (e): pop a: push exp(a)
[0xAB, ['number'], ['number']], # (½): pop a: push a/2 (float division)
[0xAC, ['number'], ['number']], # (¼): pop a: push a/4 (float division)
[0x21, ['number'], ['number']], # (!): pop a: push a! (factorial(a))
[0x44, ['number'], ['number']], # (D): pop a: push a-1; pop [a]: push stddev([a])
[0x46, ['number'], ['number']], # (F): pop a: push Fib(a) (Fib(0)=0, Fib(1)=Fib(2)=1); pop [a]: push a[0]
[0x50, ['number'], ['number']], # (P): pop a: push the a-th prime (zero-indexed)
[0x75, ['number'], ['number']], # (u): pop a: push a+1
[0x7E, ['number'], ['number']], # (~): pop a: push ~a (unary bitwise negate)
[0xA9, ['number'], ['number']], # (⌐): pop a: push a+2
[0xAA, ['number'], ['number']], # (¬): pop a: push a-2
[0xD1, ['number'], ['number']], # (╤): pop a: push 10**a
[0xD3, ['number'], ['number']], # (╙): pop a: push 2**a
[0xE7, ['number'], ['number']], # (τ): pop a: push 2*a
[0xF1, ['number'], ['number']], # (±): pop a: push -a (unary negate)
[0xFD, ['number'], ['number']], # (²): pop a: push a*a
[0x2A, ['number','number'], ['number']], # (*): pop a,b: push a*b; pop a,[b] or [b],a: apply a* to each element in the array; pop [a],[b]: push dot product of [a] and [b] (sum([a[i]*b[i] for i in len(a)]) (shorter is padded with 0s)
[0x2B, ['number','number'], ['number']], # (+): pop a,b: push a+b; pop [a],[b]: push [a][b] (append [b] to [a]); pop a,[b] or [b],a: apply a+ to each element in the array
[0x2D, ['number','number'], ['number']], # (-): pop a,b: push a-b; pop [a],[b]: push [a]-[b] (all elements of [a] not in [b])
[0x2F, ['number','number'], ['number']], # (/): pop a,b: push a/b (float division); pop [a]: rotate [a] right by 1, push [a]
[0x5C, ['number','number'], ['number']], # (\): pop a,b: push a/b (integer division); pop [a]: rotate [a] left by 1, push [a]
[0xFC, ['number','number'], ['number']], # (ⁿ): pop a,b: push pow(a,b)
[0xDB, ['number','number'], ['number']], # (█): pop a,b: push C(a,b) (aCb)
[0xDC, ['number','number'], ['number']], # (▄): pop a,b: push P(a,b) (aPb)
[0x3B, ['number'], ['number','number']], # (;): pop a: push a,a (duplicates top element)
[0xE3, ['list'], ['number']], # (π): pop [a]: push product([a])
[0xE4, ['list'], ['number']], # (Σ): pop [a]: push sum([a])
[0x69, ['list'], ['numbers']], # (i): pop [a]: push each element from [a], starting from end (flatten)
[0xC6, ['numbers'], ['numbers']], # (╞): pop a: make a total copies of each element on stack (3 [a,b,c] -> [a,a,a,b,b,b,c,c,c])
[0xC7, ['numbers'], ['list']], # (╟): pop a: pop a elements and push a list containing those elements in their original order
[0x0B, ['list'], ['list']], # (♂): take the next command and map it over the top of the stack (for example, ♂A is equivalent to `A`M)
[0x61, ['numbers'], ['numbers']], # (a): invert the stack ([a,b,c,d] -> [d,c,b,a])
[0xB3, ['numbers'], ['numbers']], # (│): duplicate stack ([a,b,c] => [a,b,c,a,b,c])
[0xC5, ['numbers'], ['numbers']], # (┼): duplicate each element on stack ([a,b,c] => [a,a,b,b,c,c])
[0x72, ['number'], ['list']], # (r): pop a: push [0,1,...,a-1] (range(0,a))
[0xB9, ['number'], ['list']], # (╣): pop a: push the ath row in Pascal's triangle
[0x78, ['number','number'], ['list']], # (x): pop a,b: push [a,b) (range(a,b)); pop [a]: push range(*a)
[0x78, ['list'], ['list']], # (x): pop a,b: push [a,b) (range(a,b)); pop [a]: push range(*a)
[0x6B, ['numbers'], ['list']],# (k): pop all elements from stack, convert to list (in the order they were on the stack, starting from the top) and push
# 0x3A, # (:): numeric literal delimiter: pushes the longest string of characters in '0123456789+-.ij' as a numeric
# 0x4D, # (M): pop f,[a], execute f for each element in [a], using the element as a temporary stack, push [a] (similar to map(f,[a])); pop [a]: push max([a])
# 0x52, # (R): pop f,[a]: call f, using [a] as a temporary stack, push [a] (similar to reduce(f,[a])); pop [a]: push [a][::-1] (reverse); pop a: push [1,2,...,a] (range(1,a+1))
# 0x57, # (W): loop delimiter: peek top of stack, repeat code in loop while a evaluates to true
# 0x60, # (`): function literal delimiter, pushes function whose body contains all of the commands until the next `. An implied ` is present at EOF if needed.
]
provides = {
'number':[],
'numbers':[],
'list':[]
}
wants = [[]]*256
for i in instructions:
wants[i[0]] = i[1]
provides[i[2][0]].append(i[0])
from seriously import Seriously,chr_cp437,ord_cp437
MAX=2**31
# returns ([finished programs],[new programs]), one of which will be empty
def extend_program(p):
finished_programs=[]
new_programs=[]
# print(p)
for i in provides[p[1][-1]]:
new_p = chr_cp437(i)+p[0]
new_wants = p[1][:-1]+wants[i]
if new_wants==[]: # we've reached a complete program! run it
# print(p[0])
now = time.clock()
# print(p[0])
try:
res = Seriously().eval(new_p)
except:
return ([],[])
# print(res)
elapsed = time.clock()-now
if elapsed>0.001:
try:
elapsed = timeit.timeit('Seriously().eval("'+str(new_p.encode('unicode_escape'))+'")','from seriously import Seriously',number=1000)
except:
continue
if elapsed>0.005:
print("SLOW:")
print(new_p)
print(res)
print(elapsed)
# print(res)
finished_programs.append([new_p,res])
continue
if len(new_p)==MAXLEN and new_wants!=[]: # no room left to fulfill any wants
continue
if len(new_p)==MAXLEN-1 and new_wants != ['number']: # no room left to fulfill complex wants
continue
new_programs.append([new_p,new_wants])
if len(p[1])>1 and p[1][-1]=='number' and p[1][-2]=='number':
for i in provides['numbers']:
new_p = chr_cp437(i)+p[0]
old_wants = p[1]
while len(p[1]) and p[1][-1]=='number':
p[1].pop()
new_wants = old_wants+wants[i]
if len(new_p)==MAXLEN and new_wants!=[]:
continue
if len(new_p)==MAXLEN-1 and \
new_wants != ['list'] and \
new_wants != ['number'] and \
new_wants != ['numbers']:
continue
new_programs.append([new_p,new_wants])
return (finished_programs,new_programs)
unfinished_programs = [['',['number']]]
best = {}
def l(n,force_colon=False):
if force_colon:
return ':'+str(n)
if n>=0 and n<10:
return str(n)
elif n<0 and n>-10:
return str(-n)+'±'
return ':'+str(n)
def cand(n,rep):
# print(n,rep,len(rep),l(n),len(l(n)),best[n] if n in best else "")
if n<=MAX and n>=-MAX and (len(rep)==1 or len(rep)<len(l(n))) and (n not in best or len(rep)<len(best[n])):
best[n] = rep
# print("woot")
return True
return False
MAXLEN = 5
for i in range(MAXLEN):
print(i+1,"/",MAXLEN)
new_unfinished_programs = []
c = ''
for p in unfinished_programs:
if len(p[0]) and p[0][-1]!= c:
print(c)
c=p[0][-1]
(finished_programs,new_programs) = extend_program(p)
for f in finished_programs:
# print(f[0])
# print(f[1][0])
if len(f[1])==0:
# print("TOO MANY RESULTS")
continue
if isinstance(f[1][0],int):
cand(f[1][0],f[0])
# if isinstance(f[1][0],list):
# print("LIST RESULT")
new_unfinished_programs = new_unfinished_programs + new_programs
unfinished_programs = new_unfinished_programs
def best_or_l(n,force_colon=False):
if n in best:
return best[n]
if n<0 and -n in best:
return best[-n]+"±"
return l(n,force_colon)
for key,value in sorted(best.items()):
# if random.random()<0.01:
print(key,value)
score = 0
for i in [-2124910654, -2117700574, -2098186988, -2095671996, -2083075613, -2058271687, -2052250777, -2024215903, -2019485642, -2016095616, -2009838326, -2009173317, -2007673992, -2000014444, -1999825668, -1992515610, -1989566707, -1975506037, -1955473208, -1950731112, -1949886423, -1920624450, -1918465596, -1916287469, -1905036556, -1903956118, -1888944417, -1865221863, -1856600057, -1842797147, -1835637734, -1812631357, -1805740096, -1798015647, -1726688233, -1723609647, -1713776890, -1700307138, -1687644479, -1645515069, -1617635994, -1610444000, -1579053372, -1556891649, -1549652116, -1537732956, -1535180388, -1527162056, -1524851611, -1524658412, -1523244369, -1521379172, -1520191198, -1519035741, -1516978241, -1508892332, -1489938422, -1482102944, -1481823232, -1470621147, -1469145091, -1446844485, -1441790509, -1437843276, -1435359182, -1434186947, -1429816311, -1429393781, -1419752032, -1400387846, -1385152926, -1372620863, -1369257355, -1361933674, -1360480816, -1334846204, -1323741718, -1323660173, -1312800992, -1308824840, -1304658551, -1287829999, -1283767920, -1276288210, -1264275838, -1263965596, -1262866901, -1255421887, -1251428680, -1244825786, -1243200329, -1235305532, -1233977691, -1220537074, -1214100716, -1199414474, -1190725823, -1190401800, -1178717689, -1172378149, -1147869245, -1142875190, -1138538768, -1137864183, -1124917489, -1102987222, -1095920186, -1083001017, -1080902655, -1047122002, -1031842676, -1029877334, -1020849489, -1001684838, -998419619, -990915088, -985235989, -982515261, -979074894, -974195629, -973832940, -965324937, -944246431, -938387588, -933873331, -932692878, -928039285, -927947459, -914008773, -907981688, -906376330, -903502449, -898112547, -887444438, -862658502, -843628573, -822463032, -786051095, -776932426, -776033951, -752042328, -746532472, -743149468, -740225710, -734414418, -725435852, -708101516, -699674783, -694869277, -693246525, -690571518, -689249770, -688581912, -686864294, -681445866, -647992869, -641101583, -631409299, -624686189, -613079884, -593711206, -591688546, -591331185, -574790069, -573024823, -565387051, -565137163, -556338668, -556291492, -541411509, -538932064, -500479857, -482419890, -468050561, -424532545, -420534171, -408741873, -406973874, -387664799, -382084509, -367095703, -352332569, -352195997, -346430007, -324596389, -320119776, -306594578, -305952425, -283718911, -267302378, -243302738, -242955859, -232180029, -225394407, -217418127, -212286453, -208344820, -191300139, -186177744, -175765723, -161763935, -157025501, -140389149, -132298608, -126175769, -70566352, -68748576, -53985905, -52674668, -50228620, -39678495, -19825663, -8349922, -8186722, -8125700, -8073135, -8043230, -7994382, -7874433, -7863624, -7784916, -7782477, -7696343, -7607278, -7531250, -7388060, -7368780, -7367625, -7353084, -7334489, -7281141, -7267149, -7140057, -7119066, -7010389, -6992089, -6975258, -6863360, -6784772, -6741079, -6585985, -6550401, -6520011, -6495144, -6459702, -6294273, -6178342, -6169344, -6139663, -6090928, -6022637, -5992707, -5971334, -5925304, -5880940, -5873707, -5807953, -5703992, -5692895, -5535131, -5488812, -5468330, -5404148, -5290247, -5274221, -5264144, -5234715, -5224048, -5179837, -5084014, -5043990, -5028537, -5011679, -4998333, -4922901, -4880159, -4874060, -4787390, -4749096, -4736217, -4502308, -4480611, -4424319, -4363262, -4349743, -4290050, -4240069, -4239657, -4174072, -4093051, -4045363, -4037689, -4033352, -3839265, -3766343, -3716899, -3680075, -3679053, -3581776, -3539227, -3461158, -3282526, -3205947, -3183427, -3169708, -3166430, -3089822, -3061531, -2947574, -2930733, -2919246, -2872882, -2830770, -2739228, -2713826, -2634018, -2613990, -2525529, -2439507, -2432921, -2376201, -2335005, -2307524, -2265548, -2176176, -2123133, -2108773, -2105934, -2075032, -2073940, -2045837, -2045648, -1978182, -1945769, -1935486, -1881608, -1654650, -1602520, -1506746, -1505294, -1475309, -1457605, -1327259, -1312217, -1178723, -1027439, -880781, -833776, -666675, -643098, -593446, -468772, -450369, -443225, -418164, -402004, -319964, -307400, -279414, -190199, -176644, -66862, -32745, -32686, -32352, -32261, -32035, -31928, -31414, -31308, -30925, -30411, -29503, -29182, -28573, -28500, -28093, -27743, -27716, -27351, -27201, -26834, -25946, -25019, -24469, -24341, -24292, -24151, -23732, -22769, -22242, -22002, -20863, -20762, -20644, -20189, -20009, -19142, -19036, -18980, -18616, -18196, -18123, -17942, -17915, -17601, -17494, -16669, -16417, -16317, -15051, -14796, -14742, -14600, -14443, -14159, -14046, -13860, -13804, -13745, -13634, -13498, -13497, -12688, -12471, -12222, -11993, -11467, -11332, -10783, -10250, -10114, -10089, -9930, -9434, -9336, -9128, -9109, -8508, -8460, -8198, -8045, -7850, -7342, -7229, -6762, -6302, -6245, -6171, -5957, -5842, -4906, -4904, -4630, -4613, -4567, -4427, -4091, -4084, -3756, -3665, -3367, -3186, -2922, -2372, -2331, -1936, -1683, -1350, -1002, -719, -152, -128, -127, -124, -122, -121, -119, -116, -113, -112, -111, -107, -104, -102, -101, -100, -95, -94, -91, -90, -87, -81, -80, -79, -78, -73, -72, -69, -68, -66, -65, -63, -57, -54, -52, -51, -48, -47, -46, -45, -43, -41, -37, -33, -31, -30, -27, -25, -21, -18, -15, -12, -8, -1, 0, 1, 3, 4, 5, 6, 11, 14, 17, 23, 25, 26, 27, 28, 29, 31, 32, 39, 41, 46, 49, 51, 52, 56, 58, 61, 64, 66, 67, 70, 74, 79, 80, 86, 88, 89, 92, 93, 99, 102, 104, 109, 113, 117, 120, 122, 123, 127, 695, 912, 1792, 2857, 3150, 3184, 4060, 4626, 5671, 6412, 6827, 7999, 8017, 8646, 8798, 9703, 9837, 10049, 10442, 10912, 11400, 11430, 11436, 11551, 11937, 12480, 13258, 13469, 13689, 13963, 13982, 14019, 14152, 14259, 14346, 15416, 15613, 15954, 16241, 16814, 16844, 17564, 17702, 17751, 18537, 18763, 19890, 21216, 22238, 22548, 23243, 23383, 23386, 23407, 23940, 24076, 24796, 24870, 24898, 24967, 25139, 25176, 25699, 26167, 26536, 26614, 27008, 27087, 27142, 27356, 27458, 27800, 27827, 27924, 28595, 29053, 29229, 29884, 29900, 30460, 30556, 30701, 30815, 30995, 31613, 31761, 31772, 32099, 32308, 32674, 75627, 80472, 103073, 110477, 115718, 172418, 212268, 242652, 396135, 442591, 467087, 496849, 675960, 759343, 846297, 881562, 1003458, 1153900, 1156733, 1164679, 1208265, 1318372, 1363958, 1411655, 1522329, 1559609, 1677118, 1693658, 1703597, 1811223, 1831642, 1838628, 1884144, 1931545, 2085504, 2168156, 2170263, 2239585, 2308894, 2329235, 2364957, 2432335, 2435551, 2596936, 2684907, 2691011, 2705195, 2738057, 2851897, 2925289, 2995414, 3051534, 3216094, 3267022, 3271559, 3338856, 3440797, 3638325, 3651369, 3718696, 3724814, 3811069, 3854697, 3866969, 3893228, 3963455, 3984546, 4098376, 4100957, 4128113, 4200719, 4256344, 4286332, 4306356, 4316314, 4438803, 4458063, 4461638, 4552228, 4563790, 4584831, 4607992, 4884455, 4907501, 5045419, 5066844, 5150624, 5157161, 5190669, 5314703, 5337397, 5434807, 5440092, 5502665, 5523089, 5547122, 5566200, 5582936, 5634068, 5690330, 5776984, 5778441, 5818505, 5826687, 5827184, 5885735, 6010506, 6084254, 6131498, 6138324, 6250773, 6292801, 6306275, 6315242, 6331640, 6484374, 6502969, 6545970, 6666951, 6690905, 6763576, 6766086, 6895048, 6912227, 6929081, 6941390, 6978168, 7045672, 7085246, 7193307, 7197398, 7270237, 7276767, 7295790, 7375488, 7472098, 7687424, 7840758, 7880957, 7904499, 7948678, 7974126, 8015691, 8037685, 8112955, 8131380, 8140556, 8142384, 8220436, 8308817, 8331317, 22581970, 45809129, 48103779, 78212045, 79674901, 97299830, 110308649, 131744428, 136663461, 138485719, 139842794, 152061792, 152685704, 153070991, 156228213, 164884737, 174776199, 189346581, 193148547, 208582124, 223891881, 227308187, 237373798, 241214067, 242476929, 245495851, 260606593, 275202667, 285717038, 317009689, 322759532, 325369206, 339724742, 340122632, 345010859, 352375176, 355826263, 359695034, 366118516, 370008270, 382712922, 386379440, 401153345, 404986391, 426084981, 442843409, 473909474, 475192613, 492302667, 494747879, 506279889, 509813998, 537558350, 548423414, 548467404, 566383324, 574188786, 574792333, 591678147, 596558084, 597423476, 602432742, 603067874, 629552047, 630893263, 635249783, 644959276, 650710927, 664859367, 669433203, 684329599, 699991513, 714451929, 723556530, 739294558, 750895264, 757618344, 781123405, 796973385, 801637715, 804776709, 829003666, 829219068, 840167037, 854882202, 860066192, 864304878, 864808449, 867107161, 871871263, 880591851, 883020336, 883178082, 920223781, 936008673, 939417822, 956776353, 958281059, 962183717, 964059257, 967860573, 974322643, 974999286, 980009921, 1032949015, 1044249483, 1064892676, 1075628270, 1080848022, 1085571657, 1173635593, 1174809080, 1176744978, 1209783795, 1212074975, 1252323507, 1254757790, 1301450562, 1302240953, 1314501797, 1315121266, 1339304157, 1364304289, 1376260506, 1383883477, 1395158643, 1411117754, 1440755058, 1448365702, 1466814914, 1468433821, 1490105126, 1493912601, 1495600372, 1509536621, 1511014977, 1545693948, 1548924199, 1566583103, 1569747154, 1574097219, 1597784674, 1610710480, 1618324005, 1646105187, 1649417465, 1655649169, 1660619384, 1668826887, 1671093718, 1672456990, 1673477565, 1678638502, 1682302139, 1682515769, 1687920300, 1690062315, 1706031388, 1713660819, 1772170709, 1778416812, 1833443690, 1861312062, 1876004501, 1876358085, 1882435551, 1916050713, 1944906037, 1950207172, 1951593247, 1973638546, 1976288281, 1994977271, 2020053060, 2025281195, 2029716419, 2033980539, 2052482076, 2058251762, 2069273004, 2073978021, 2111013213, 2119886932, 2134609957, 2140349794, 2143934987]:
# print(i,best_or_l(i,True))
score = score + (len(l(i))-len(best_or_l(i,True)))
print("Score:",score)
with open("brute_serious_reverse.json","w") as outfile:
outfile.write(json.dumps(best,sort_keys=True,indent=2))
```
[Answer]
## Python 3, 34 39 bytes saved
This program simply calculates every number it can reach using simple combinations of the binary and unary operators, which covers 366k out of 4B integers, for a total of a couple of dozen of the test cases. Then I output those results or the trivial solution. This is technically against the rules, because it is certain there is a better solution for some of the cases, but I am confident no one is going to come up with a solution that certainly passes that rule.
Also, I'm just producing all the output at once, because 30 seconds of setup time is bearable once, not 1000 times. The commented out sections increase the runtime significantly while barely reducing the score.
```
#!/usr/bin/env python3
# -*- coding: cp437 -*-
import math
import gmpy
import json
import random
from seriously import chr_cp437
# MAX=2**31
MAX = 2**31
best = {}
def l(n,force_colon=False):
if force_colon:
return ':'+str(n)
if n>=0 and n<10:
return str(n)
elif n<0 and n>-10:
return str(-n)+chr_cp437(0xF1)
return ':'+str(n)
def l2(n,m):
if n<10 or best_or_l(n)[-1] in "0123456789":
rep = l(n)+best_or_l(m)
else:
rep = best_or_l(n)+best_or_l(m,True)
return rep
def cand(n,rep):
# print(n,rep,len(rep),best[n] if n in best else "")
if n!=int(n):
return False
n=int(n)
if n<=MAX and len(rep)<len(l(n)) and (n not in best or len(rep)<len(best[n])):
best[n] = rep
return True
return False
def best_or_l(n,force_colon=False):
if n in best:
return best[n]
if -n in best and n>0:
return best[-n]+chr_cp437(0xF1)
return l(n,force_colon)
# digits
for i in range(0,10):
best[i]=str(i)
# factorials
for i in range(4,13):
cand(math.factorial(i),l(i)+'!')
# 10**i
for i in range(2,12):
cand(10**i,l(i)+chr_cp437(0xD1))
# 2**i
for i in range(2,32):
cand(2**i,best_or_l(i)+chr_cp437(0xD3))
# a choose b
for a in range(2,1000): # 466 is the highest a for MAX=2**24
for b in range(2,int(a/2+1)):
n = math.factorial(a)/(math.factorial(b)*math.factorial(a-b))
if n>MAX:
break
cand(n,l2(b,a)+chr_cp437(0xDB))
# a P b
for a in range(2,1000): # 257 is the highest a for MAX=2**24
for b in range(2,int(a/2+1)):
n = math.factorial(a)/math.factorial(a-b)
if n>MAX:
break
cand(n,l2(b,a)+chr_cp437(0xDC))
# fibonacci
def fib_formula(n):
golden_ratio = (1 + math.sqrt(5)) / 2
val = (golden_ratio**n - (1 - golden_ratio)**n) / math.sqrt(5)
return int(round(val))
for i in range(3,47):
cand(fib_formula(i),best_or_l(i)+'F')
# i^2 and ^4
for i in range(5,int(math.sqrt(MAX)+1)):
cand(i*i,best_or_l(i)+chr_cp437(0xFD))
# a^b
for a in range(2,int(math.pow(MAX,1.0/3))+1):
for b in range(3,int(math.log(MAX)/math.log(3))+1):
n = a**b
cand(n,l2(b,a)+chr_cp437(0xFC))
# exp(i)
for i in range(3,22):
cand(int(math.ceil(math.exp(i))),best_or_l(i)+'eK')
cand(int(math.floor(math.exp(i))),best_or_l(i)+'eL')
# primes
def primes():
n = 2
while True:
yield n
n = gmpy.next_prime(n)
n = 0
for p in primes():
# print(p)
if p>MAX/1000:
break
rep = best_or_l(n)+'P'
cand(p,rep)
n=n+1
# +1 +2 -1 -2 *2 /2 /4
for key,value in sorted(best.items()):
cand(key+1,value+'u')
cand(key+2,value+chr_cp437(0xA9))
cand(key-1,value+'D')
cand(key-2,value+chr_cp437(0xAA))
cand(key*2,value+chr_cp437(0xE7))
if float(key)/2 == int(float(key)/2):
cand(int((float(key)/2)),value+chr_cp437(0xAB))
cand(int(math.floor(float(key)/2)),value+chr_cp437(0xAB)+'L')
cand(int(math.ceil(float(key)/2)),value+chr_cp437(0xAB)+'K')
if float(key)/4 == int(float(key)/4):
cand(int((float(key)/4)),value+chr_cp437(0xAC))
cand(int(math.floor(float(key)/4)),value+chr_cp437(0xAC)+'L')
cand(int(math.ceil(float(key)/4)),value+chr_cp437(0xAC)+'L')
# bitwise invert
for key,value in sorted(best.items()):
cand(~key,value+'~')
# arithmetic with small second operands
for key,value in sorted(best.items()):
for op in ["+","-","/","/K","\\","*"]:
for i in range(3,10):
if op == "+":
n = key+i
elif op == "-":
n = key-i
elif op == "/":
if i==4:
continue
n = float(key)/i
if int(n)!=n:
continue
n = int(n)
elif op == "/K":
if i==4:
continue
n = int(math.ceil(float(key)/i))
if n == float(key)/i:
continue
elif op == "\\":
if i==4:
continue
n = int(math.floor(float(key)/i))
if n == float(key)/i:
continue
elif op == "*":
n = key*i
rep = value+best_or_l(i)+op
cand(n,rep)
# for key,value in sorted(best.items()):
# print(key,value)
# def maybe(n,rep):
# if len(rep)<len(best_or_l(n)):
# return True
# return False
# b=[]
# for k in sorted(best.keys()):
# b.append(k)
# if k>100000000:
# break
# def search_for_better(n):
# if n in best:
# return best[n]
# for i in b:
# if n+i in best:
# rep = best[n+i]+best[i]+'-'
# if maybe(n,rep):
# return rep
# for i in b:
# if n-i in best:
# rep = best[n-i]+best[i]+'+'
# if maybe(n,rep):
# return rep
# return l(n)
for key,value in sorted(best.items()):
if random.random()<0.001:
print(key,value)
score = 0
for i in [-2124910654, -2117700574, -2098186988, -2095671996, -2083075613, -2058271687, -2052250777, -2024215903, -2019485642, -2016095616, -2009838326, -2009173317, -2007673992, -2000014444, -1999825668, -1992515610, -1989566707, -1975506037, -1955473208, -1950731112, -1949886423, -1920624450, -1918465596, -1916287469, -1905036556, -1903956118, -1888944417, -1865221863, -1856600057, -1842797147, -1835637734, -1812631357, -1805740096, -1798015647, -1726688233, -1723609647, -1713776890, -1700307138, -1687644479, -1645515069, -1617635994, -1610444000, -1579053372, -1556891649, -1549652116, -1537732956, -1535180388, -1527162056, -1524851611, -1524658412, -1523244369, -1521379172, -1520191198, -1519035741, -1516978241, -1508892332, -1489938422, -1482102944, -1481823232, -1470621147, -1469145091, -1446844485, -1441790509, -1437843276, -1435359182, -1434186947, -1429816311, -1429393781, -1419752032, -1400387846, -1385152926, -1372620863, -1369257355, -1361933674, -1360480816, -1334846204, -1323741718, -1323660173, -1312800992, -1308824840, -1304658551, -1287829999, -1283767920, -1276288210, -1264275838, -1263965596, -1262866901, -1255421887, -1251428680, -1244825786, -1243200329, -1235305532, -1233977691, -1220537074, -1214100716, -1199414474, -1190725823, -1190401800, -1178717689, -1172378149, -1147869245, -1142875190, -1138538768, -1137864183, -1124917489, -1102987222, -1095920186, -1083001017, -1080902655, -1047122002, -1031842676, -1029877334, -1020849489, -1001684838, -998419619, -990915088, -985235989, -982515261, -979074894, -974195629, -973832940, -965324937, -944246431, -938387588, -933873331, -932692878, -928039285, -927947459, -914008773, -907981688, -906376330, -903502449, -898112547, -887444438, -862658502, -843628573, -822463032, -786051095, -776932426, -776033951, -752042328, -746532472, -743149468, -740225710, -734414418, -725435852, -708101516, -699674783, -694869277, -693246525, -690571518, -689249770, -688581912, -686864294, -681445866, -647992869, -641101583, -631409299, -624686189, -613079884, -593711206, -591688546, -591331185, -574790069, -573024823, -565387051, -565137163, -556338668, -556291492, -541411509, -538932064, -500479857, -482419890, -468050561, -424532545, -420534171, -408741873, -406973874, -387664799, -382084509, -367095703, -352332569, -352195997, -346430007, -324596389, -320119776, -306594578, -305952425, -283718911, -267302378, -243302738, -242955859, -232180029, -225394407, -217418127, -212286453, -208344820, -191300139, -186177744, -175765723, -161763935, -157025501, -140389149, -132298608, -126175769, -70566352, -68748576, -53985905, -52674668, -50228620, -39678495, -19825663, -8349922, -8186722, -8125700, -8073135, -8043230, -7994382, -7874433, -7863624, -7784916, -7782477, -7696343, -7607278, -7531250, -7388060, -7368780, -7367625, -7353084, -7334489, -7281141, -7267149, -7140057, -7119066, -7010389, -6992089, -6975258, -6863360, -6784772, -6741079, -6585985, -6550401, -6520011, -6495144, -6459702, -6294273, -6178342, -6169344, -6139663, -6090928, -6022637, -5992707, -5971334, -5925304, -5880940, -5873707, -5807953, -5703992, -5692895, -5535131, -5488812, -5468330, -5404148, -5290247, -5274221, -5264144, -5234715, -5224048, -5179837, -5084014, -5043990, -5028537, -5011679, -4998333, -4922901, -4880159, -4874060, -4787390, -4749096, -4736217, -4502308, -4480611, -4424319, -4363262, -4349743, -4290050, -4240069, -4239657, -4174072, -4093051, -4045363, -4037689, -4033352, -3839265, -3766343, -3716899, -3680075, -3679053, -3581776, -3539227, -3461158, -3282526, -3205947, -3183427, -3169708, -3166430, -3089822, -3061531, -2947574, -2930733, -2919246, -2872882, -2830770, -2739228, -2713826, -2634018, -2613990, -2525529, -2439507, -2432921, -2376201, -2335005, -2307524, -2265548, -2176176, -2123133, -2108773, -2105934, -2075032, -2073940, -2045837, -2045648, -1978182, -1945769, -1935486, -1881608, -1654650, -1602520, -1506746, -1505294, -1475309, -1457605, -1327259, -1312217, -1178723, -1027439, -880781, -833776, -666675, -643098, -593446, -468772, -450369, -443225, -418164, -402004, -319964, -307400, -279414, -190199, -176644, -66862, -32745, -32686, -32352, -32261, -32035, -31928, -31414, -31308, -30925, -30411, -29503, -29182, -28573, -28500, -28093, -27743, -27716, -27351, -27201, -26834, -25946, -25019, -24469, -24341, -24292, -24151, -23732, -22769, -22242, -22002, -20863, -20762, -20644, -20189, -20009, -19142, -19036, -18980, -18616, -18196, -18123, -17942, -17915, -17601, -17494, -16669, -16417, -16317, -15051, -14796, -14742, -14600, -14443, -14159, -14046, -13860, -13804, -13745, -13634, -13498, -13497, -12688, -12471, -12222, -11993, -11467, -11332, -10783, -10250, -10114, -10089, -9930, -9434, -9336, -9128, -9109, -8508, -8460, -8198, -8045, -7850, -7342, -7229, -6762, -6302, -6245, -6171, -5957, -5842, -4906, -4904, -4630, -4613, -4567, -4427, -4091, -4084, -3756, -3665, -3367, -3186, -2922, -2372, -2331, -1936, -1683, -1350, -1002, -719, -152, -128, -127, -124, -122, -121, -119, -116, -113, -112, -111, -107, -104, -102, -101, -100, -95, -94, -91, -90, -87, -81, -80, -79, -78, -73, -72, -69, -68, -66, -65, -63, -57, -54, -52, -51, -48, -47, -46, -45, -43, -41, -37, -33, -31, -30, -27, -25, -21, -18, -15, -12, -8, -1, 0, 1, 3, 4, 5, 6, 11, 14, 17, 23, 25, 26, 27, 28, 29, 31, 32, 39, 41, 46, 49, 51, 52, 56, 58, 61, 64, 66, 67, 70, 74, 79, 80, 86, 88, 89, 92, 93, 99, 102, 104, 109, 113, 117, 120, 122, 123, 127, 695, 912, 1792, 2857, 3150, 3184, 4060, 4626, 5671, 6412, 6827, 7999, 8017, 8646, 8798, 9703, 9837, 10049, 10442, 10912, 11400, 11430, 11436, 11551, 11937, 12480, 13258, 13469, 13689, 13963, 13982, 14019, 14152, 14259, 14346, 15416, 15613, 15954, 16241, 16814, 16844, 17564, 17702, 17751, 18537, 18763, 19890, 21216, 22238, 22548, 23243, 23383, 23386, 23407, 23940, 24076, 24796, 24870, 24898, 24967, 25139, 25176, 25699, 26167, 26536, 26614, 27008, 27087, 27142, 27356, 27458, 27800, 27827, 27924, 28595, 29053, 29229, 29884, 29900, 30460, 30556, 30701, 30815, 30995, 31613, 31761, 31772, 32099, 32308, 32674, 75627, 80472, 103073, 110477, 115718, 172418, 212268, 242652, 396135, 442591, 467087, 496849, 675960, 759343, 846297, 881562, 1003458, 1153900, 1156733, 1164679, 1208265, 1318372, 1363958, 1411655, 1522329, 1559609, 1677118, 1693658, 1703597, 1811223, 1831642, 1838628, 1884144, 1931545, 2085504, 2168156, 2170263, 2239585, 2308894, 2329235, 2364957, 2432335, 2435551, 2596936, 2684907, 2691011, 2705195, 2738057, 2851897, 2925289, 2995414, 3051534, 3216094, 3267022, 3271559, 3338856, 3440797, 3638325, 3651369, 3718696, 3724814, 3811069, 3854697, 3866969, 3893228, 3963455, 3984546, 4098376, 4100957, 4128113, 4200719, 4256344, 4286332, 4306356, 4316314, 4438803, 4458063, 4461638, 4552228, 4563790, 4584831, 4607992, 4884455, 4907501, 5045419, 5066844, 5150624, 5157161, 5190669, 5314703, 5337397, 5434807, 5440092, 5502665, 5523089, 5547122, 5566200, 5582936, 5634068, 5690330, 5776984, 5778441, 5818505, 5826687, 5827184, 5885735, 6010506, 6084254, 6131498, 6138324, 6250773, 6292801, 6306275, 6315242, 6331640, 6484374, 6502969, 6545970, 6666951, 6690905, 6763576, 6766086, 6895048, 6912227, 6929081, 6941390, 6978168, 7045672, 7085246, 7193307, 7197398, 7270237, 7276767, 7295790, 7375488, 7472098, 7687424, 7840758, 7880957, 7904499, 7948678, 7974126, 8015691, 8037685, 8112955, 8131380, 8140556, 8142384, 8220436, 8308817, 8331317, 22581970, 45809129, 48103779, 78212045, 79674901, 97299830, 110308649, 131744428, 136663461, 138485719, 139842794, 152061792, 152685704, 153070991, 156228213, 164884737, 174776199, 189346581, 193148547, 208582124, 223891881, 227308187, 237373798, 241214067, 242476929, 245495851, 260606593, 275202667, 285717038, 317009689, 322759532, 325369206, 339724742, 340122632, 345010859, 352375176, 355826263, 359695034, 366118516, 370008270, 382712922, 386379440, 401153345, 404986391, 426084981, 442843409, 473909474, 475192613, 492302667, 494747879, 506279889, 509813998, 537558350, 548423414, 548467404, 566383324, 574188786, 574792333, 591678147, 596558084, 597423476, 602432742, 603067874, 629552047, 630893263, 635249783, 644959276, 650710927, 664859367, 669433203, 684329599, 699991513, 714451929, 723556530, 739294558, 750895264, 757618344, 781123405, 796973385, 801637715, 804776709, 829003666, 829219068, 840167037, 854882202, 860066192, 864304878, 864808449, 867107161, 871871263, 880591851, 883020336, 883178082, 920223781, 936008673, 939417822, 956776353, 958281059, 962183717, 964059257, 967860573, 974322643, 974999286, 980009921, 1032949015, 1044249483, 1064892676, 1075628270, 1080848022, 1085571657, 1173635593, 1174809080, 1176744978, 1209783795, 1212074975, 1252323507, 1254757790, 1301450562, 1302240953, 1314501797, 1315121266, 1339304157, 1364304289, 1376260506, 1383883477, 1395158643, 1411117754, 1440755058, 1448365702, 1466814914, 1468433821, 1490105126, 1493912601, 1495600372, 1509536621, 1511014977, 1545693948, 1548924199, 1566583103, 1569747154, 1574097219, 1597784674, 1610710480, 1618324005, 1646105187, 1649417465, 1655649169, 1660619384, 1668826887, 1671093718, 1672456990, 1673477565, 1678638502, 1682302139, 1682515769, 1687920300, 1690062315, 1706031388, 1713660819, 1772170709, 1778416812, 1833443690, 1861312062, 1876004501, 1876358085, 1882435551, 1916050713, 1944906037, 1950207172, 1951593247, 1973638546, 1976288281, 1994977271, 2020053060, 2025281195, 2029716419, 2033980539, 2052482076, 2058251762, 2069273004, 2073978021, 2111013213, 2119886932, 2134609957, 2140349794, 2143934987]:
print(i)
print(best_or_l(i,True))
score = score + (len(l(i))-len(best_or_l(i,True)))
print("Score:",score)
# print(len(best))
with open("aim.json","w") as outfile:
outfile.write(json.dumps(best,sort_keys=True,indent=2))
```
Here's a random sampling of the sorts of Actually programs that end up found by this algorithm:
```
15875 49█²D
178085 :422²u
6195119 :2489²¬
11276166 :3358²⌐
14516098 :3810²¬
32924643 :5738²D
35003345 :8367²½K
66438802 :8151²u
95664294 3:363ⁿτ
100915813 3:847۪
111894084 :10578²
219662043 :14821²⌐
220849321 :14861²
236390625 :15375²
282710596 :16814²
296511180 :34439²¼L
375584401 :19380²u
460188303 :21452²D
465157056 :43135²¼L
509991890 :22583²u
510963420 :45209²¼L
606981768 :24637²D
659407868 8FeK½K
697212482 :18671²τ
805764994 :28386²¬
852225612 :41285²½L
941078331 :30677²⌐
1034715540 :45491²½L
1193771602 :34551²u
1326125054 :36416²¬
2030403600 :45060²
2078904023 :45595²¬
```
] |
[Question]
[
There are *popular* check digit algorithms such as Luhn and then there are *good* ones, for example the Damm algorithm. The only possible reason behind the popularity of algorithms such as Luhn is that there exist code golfed implementations of them. This means that we as a community have the power to change the world by providing golfed implementations of better algorithms.
So this challenge is to change the world by writing a function or a complete program in your language of choice that calculates a check digit using the **Damm algorithm**. The answer with the smallest number of **characters** (not bytes) will be chosen as a winner in a few weeks. Note that all helping functions and the declaration of the operation table must be included in the character count. In case of a tie the most popular answer will be chosen.
This algorithm revolves around an operation table that must be a weakly totally anti-symmetric quasigroup of order 10. The operation table that can be found in the [Wikipedia article](http://en.wikipedia.org/wiki/Damm_algorithm) about the Damm algorithm is the one which is to be used in this challenge. For completeness sake I will reproduce it below:
```
| 0 1 2 3 4 5 6 7 8 9
----+----------------------------------------
0 | 0 3 1 7 5 9 8 6 4 2
1 | 7 0 9 2 1 5 4 8 6 3
2 | 4 2 0 6 8 7 1 3 5 9
3 | 1 7 5 0 9 8 3 4 2 6
4 | 6 1 2 3 0 4 5 9 7 8
5 | 3 6 7 4 2 0 9 5 8 1
6 | 5 8 6 9 7 2 0 1 3 4
7 | 8 9 4 5 3 6 2 0 1 7
8 | 9 4 3 8 6 1 7 2 0 5
9 | 2 5 8 1 4 3 6 7 9 0
```
In short (for details see the [Wikipedia article](http://en.wikipedia.org/wiki/Damm_algorithm)) the algorithm works as follows:
1. You start with a list of digits to be processed and an interim digit which is set to 0.
2. For every digit in the list you calculate a new interim digit by using the digit as the column index and the previous interim digit as the row index.
3. The final interim digit is the check digit. If you are validating a number that already has an added check digit the final interim digit is 0 if the number is valid.
Your program or function must accept a string that can contain any characters except null, but it should only concern itself with the digits in the string. It must either print (if a program) or return (if a function) the original string with the calculated check digit appended. If you chose to write a program the program may either accept the input as an argument or as standard input. If the input string is empty or doesn't contain any digits you must return or append a zero.
Some examples:
```
Input | Output
------------+-------------
42 | 427
427 | 4270
2 to 2 | 2 to 29
23 42 76- | 23 42 76-5
- | -0
```
[Answer]
# Pyth, 49 characters
```
+z`u@sm>+0jCdT_6"ƒΩÚíâ≤Ú≠âüÒ∂ØÜ걩ÚêûÜÛ∞ÜÇÚïüêÚëΩåÚµãèÛáãΩÚØ¥ÜÛöôà±ëÇÒûëºÏµ•Ò™®∂"+*TGvH:z"\D"k0
```
Contains god knows what characters, so here's a Python3 program to generate the above program accurately on your machine:
```
N = 317598642709215486342068713591750983426612304597836742095815869720134894536201794386172052581436790
M = 1000000
l = []
while N:
l.insert(0, N % M)
N //= M
n = "".join(chr(c) for c in l)
s = '+z`u@sm>+0jCdT_6"' + n + '"+*TGvH:z"\D"k0'
with open("golf.pyth", "wb") as f:
f.write(s.encode("utf-8"))
print("Program length is {} characters.".format(len(s)))
```
Explanation:
```
+z` Output the input followed by a
stringified...
u :z"\D"k0 Reduction starting with 0 of digits
in input...
@ +*TGvH Indexing ... by 10*prev + int(next).
sm "ZALGO" Sum all digits created by ... over the
unicode garbage.
>+0 6 Prepend 0 if needed to...
jCdT_ Codepoint converted to sequence of
digits.
```
[Answer]
# CJam, 54 characters
```
q_o{A,s&},{~0"끼´慜䪝膞䝮芜㮜ꡞ靓渏縰蒆㣉倔쵶"2G#bAb+A/T==:T;}/T
```
There is one unprintable character in there, so you might want to use the permalink below.
[Test it here.](http://cjam.aditsu.net/#code=q_o%7BA%2Cs%26%7D%2C%7B~U%22%C2%94%EB%81%BC%EE%89%AB%C2%B4%E6%85%9C%E4%AA%9D%E8%86%9E%E4%9D%AE%E8%8A%9C%E3%AE%9C%EA%A1%9E%EE%83%B2%E9%9D%93%E6%B8%8F%E7%B8%B0%EE%96%98%E8%92%86%EE%86%A2%E3%A3%89%E5%80%94%EC%B5%B6%222G%23bAb%2BA%2FT%3D%3D%3AT%3B%7D%2FT&input=23%2042%2076-)
## Explanation
The interim digit is being tracked in `T`, which CJam initialises to 0.
```
q_o "Read STDIN, duplicate it and print it.";
{A,s&}, "Filter out all non-digit characters.";
{ }/ "For each digit character.";
~ "Eval to get the digit itself.";
0 "Push a zero.";
"..."2G#b "Push that long string and interpret the character
codes as the digits of a base-2^16 number.";
Ab+ "Get base-10 digits and prepend the 0.";
A/ "Split into rows of 10.";
T= "Select row based on interim digit.";
= "Select column based on current digit.";
:T; "Store in T and discard.";
T "Push the interim digit to be printed.";
```
[Answer]
# Python 3, ~~149 141~~ 138 characters
```
import re
l=""
for c in"ĽᝢႮ⏿ዿၮ∉᜝Ꮺൢ៫Njẜ᳼╭᛭ᰡඡᆸߡⓞ᠜ȍ῏᪆":l+="%04d"%ord(c)
def D(b):
a="0"
for i in re.sub("\D","",b):a=l[int(a+i)]
return b+a
```
---
Examples:
```
Input | Output
-------+--------
42 | 427
427 | 4270
2 to 2 | 2 to 29
123 | 1234
1234 | 12340
- | -0
```
Thanks to @MegaTom and @Sieg for helping to remove a total of 11 characters
[Answer]
# Ruby, 149 characters
```
i="0";t="0#{'2uleblnnz0nbpv3kqkaufbjqebm57jdj6ubaba1mc2fyucqff69tbllrcvw393li'.to_i 36}";puts(gets.chomp.each_char{|c|i=(c=~/\d/?t[(i+c).to_i]:i)}+i)
```
Tested on [repl.it](http://repl.it/languages/Ruby)
[Answer]
# J, 117 bytes
Contains only printable ascii. (I had a hard time with J and unicode.) Generates the transition table from the permutation-indices of the rows.
```
3 :'y,":(((_4(87)&#:inv\40-~a.i.''(3/3+wGf*Dl:(zaW+Hhw*(1p+;~.,y>m-<MZ)JCs'')A.i.10){~<@,~)/|.0,(#~10>])(1":i.10)i.y'
```
Usage:
```
damm=.3 :'y,":(((_4(87)&#:inv\40-~a.i.''(3/3+wGf*Dl:(zaW+Hhw*(1p+;~.,y>m-<MZ)JCs'')A.i.10){~<@,~)/|.0,(#~10>])(1":i.10)i.y'
damm '23 42 76-'
23 42 76-5
damm ''
0
```
[Try it online here.](http://tryj.tk/)
[Answer]
# Haskell, 131 characters
```
import Data.Char
f n=n++(show$foldl(\x y->read[('0':(show.ord=<<"‡±ß‚öà‡™ï√ó·ãø·ÅÆ‚àâ…è·µï‚Çñ·ßîƒ∞…ïS ¢Âáû„∑Ω·∞°Ë°éÌÖ¥‰òó‚Ü©ÂÄ≠·øè·™Ü"))!!(x*10+y)])0[read[i]|i<-n,isDigit i])
```
Test run:
```
> mapM_ (putStrLn.f) ["42", "427", "2 to 2", "23 42 76-", "-"]
427
4270
2 to 29
23 42 76-5
-0
```
[Answer]
# k, 36 characters
```
/ declare quasi-group
M:"H"$'"0317598642709215486342068713591750983426612304597836742095815869720134894536201794386172052581436790"
/ declare function
f:{x,$0{M y+10*x}/"H"$'x@&x in .Q.n}
/ get length of function
#$f
36
/ execute function against test input
.q.show f@'{x!x}("42";"427";"2 to 2";"23 42 76-";,"-")
"42" | "427"
"427" | "4270"
"2 to 2" | "2 to 29"
"23 42 76-"| "23 42 76-5"
,"-" | "-0"
```
### q, 40 characters (equivalent implementation to k)
```
f:{x,string 0{M y+10*x}/"H"$'x inter .Q.n}
```
] |
[Question]
[
A curious kid uses a program which can factorize a number or an expression into the following form: `p1^e1 * p2^e2 * ... * pn^en` . Exponents equal to `1` are omitted e.g. `360 = 2^3 * 3^2 * 5`
The kid types this output into the program as new input but they don't understand the `^` sign so sometimes they skip one or more of those concatenating the corresponding prime-base and exponent. E.g. `(360 =) 2^3 * 3^2 * 5 => 2^3 * 32 * 5 (= 1280)`
Because of these mistakes she might get a different factorization which they can input again (with skipping 0 or more `^`'s). They repeat the process until the factorization doesn't change anymore (maybe there are no more `^`'s or they copied the output correctly).
You should write a program or function which given an integer `n` (`n>1`) outputs all the possible numbers in increasing order whose factorization could be the one the kid ended up with (including `n`). E.g. for input `16` the possible final factorizations are `(16 =) 2^4, (24 =) 2^3 * 3, (23*3 =) 3 * 23`
## Input details:
* input is a single integer bigger than `1`
* no input will be given which generates output number greater than `2^31-1`
* no input will be given which generates more than `1000` output numbers
## Output details:
* a list of integers in a convenient form for your language
## Examples:
Input => Output
```
11 => 11
16 => 16 24 69
360 => 140 360 770 1035 1219 1280 2875 3680
605 => 560 605 840 2415
2048 => 211 2048
58564 => 230 456 1311 2508 9975 12768 13794 20748 58564 114114 322102
```
This is code-golf so shortest program wins.
[Answer]
# CJam - 66
```
ria{_{:XmF{1=1>},La\{a1$\f++}/La-{XI{~#}%:*/I{si}%:**}fI}%|}1e3*$p
```
Try it at <http://cjam.aditsu.net/>
**Explanation:**
```
ria read token, convert to integer and wrap in array
{…}1e3* repeat 1000 times
_ duplicate array
{…}% transform each array item (number) using the block
:X store the number in X
mF factorize with exponents
{1=1>}, keep only the factors with exponent > 1
La\{a1$\f++}/ get all the subsets (*)
La- remove the empty subset
{…}fI for I = each subset of prime factors with exponent > 1
XI{~#}%:*/ divide X by all the factors in I
I{si}%:** multiply with the primes from I
concatenated with their exponents
| add the new numbers to the array, removing duplicates
$ sort
p print the final array
```
(\*) [Thanks Martin](https://codegolf.stackexchange.com/a/42325/7416)
[Answer]
# Ruby, 219
To get this started:
```
s=->(x){A=[];def k(x)A<<x
y=Prime.prime_division x;n=0..y.size-1
n.each{|i|n.to_a.combination(i+1).each{|c|c.each{|z|v=y.dup
v[z][1]>1?v[z]=[v[z].join.to_i,1]:next
k v.inject(1){|s,b|s*b[0]**b[1]}}}}end;k x;A.uniq.sort}
```
Creates a function s returning an Array of numbers.
<https://ideone.com/iOMGny>
Use it like this:
```
#usage
#load from the standard library
require"prime"
#read from stdin and print to stdout
p s.call $<.read.to_i
```
So much fun writing this all of this on a mobile phone...
[Answer]
# Perl, 193 bytes
```
sub R{my($k,$v,@z)=@_;map{$k**$v*$_,$v>1?($k.$v)*$_:()}@z?R(@z):1}
@q=(0+<>);
while($x=pop@q){
my%f;@r=sort{$a<=>$b}@r,$x;
for(2..$x){$x/=$_,$f{$_}++while$x%$_<1}
$_~~@r||push@q,$_ for R%f
}
print"@r"
```
Newlines are just added for readability.
The for loop factorises the next number (`$x`) into a hash (`%f`) of primes and powers. The recursive function (`R`) uses this hash to generate all the numbers that could be attained by removing `^` signs. These numbers are added to a queue (`@q`), and the process is repeated by the outer while loop. Each number from the queue is also kept in a unique, sorted array (`@r`) for printing.
[Answer]
# Pyth, ~~46~~ ~~45~~ 44
```
Su{smmu*/N^T/PdTv+`T`/PdTkdyft/PdT{PdGU^T3]Q
```
[Try it here.](http://pyth.herokuapp.com/)
Fixed the multiple `^` bug. For instance:
```
Input: 58564
Output: [230, 456, 1311, 2508, 9975, 12768, 13794, 20748, 58564, 114114, 322102]
```
Note that this code relies on a couple of bugfixes to the official compiler that were pushed after the question was asked. However, it does not use any new language features.
] |
[Question]
[
A lazy physicist has the job to perform the double slit experiment. However, they are lazy and can't be bothered to set up all the equipment themselves and so are going to simulate the effects. They can't program though so are going to need some help. As they are lazy your program should be as short as possible.
---
Given an odd positive integer `n` (`n >= 1` and `n % 2 == 1`), perform the simulation.
**How it works**
You will start off with an empty canvas and each frame a single particle of light will go through the slits and land on the canvas. The particle will land at a maxima with a chance of:
`n = 1`:
```
+-----+
| |
| 1/2 |
| |
+-----+
```
`n = 3`:
```
+-----+ +-----+ +-----+
| | | | | |
| 1/4 | | 1/2 | | 1/4 |
| | | | | |
+-----+ +-----+ +-----+
```
`n = 5`:
```
+-----+ +-----+ +-----+ +-----+ +-----+
| | | | | | | | | |
| 1/8 | | 1/4 | | 1/2 | | 1/4 | | 1/8 |
| | | | | | | | | |
+-----+ +-----+ +-----+ +-----+ +-----+
```
etc.
For example for `n=5` we check the middle box, there's a 50% chance of falling in it. If it falls end of frame, if not move to the next two, there's a 25% chance of falling in those. If it falls end of frame, if not move to the next two, there's a 12.5% chance of falling in those. If it doesn't fall it doesn't matter, it's still the end of the frame.
**There has been some confusion over how to calculate the chances, most of this is due to people thinking of them as probabilities that should add up to 1. Remove that idea from your mind and it should clear it up a bit for you.**
* At most one particle will lad per frame, this means a particle may not land at all on that frame.
* A particle can be represented by any printable character.
* The particle will land anywhere in the box with a random chance.
* The width of the boxes should be `2n-1` the size of the canvas. So for `n=5` they should be `1/9`th of the canvas's width.
* The height of the boxes should be the height of the canvas.
* The particle should not land outside of the boxes at all.
* If a particle has already landed at a spot that is chosen that doesn't matter it can land there again.
* The above ascii boxes are for clarity, they should not be drawn.
* You may choose your own canvas size as long as it is reasonable. For example, it mustn't just be a few pixels high. It also should be able to fit all of the boxes on it.
* If your code sleeps between frames you do not need to add that into your byte count.
There should be gaps between each of the maxima, a minima. This should be the same width as a box but no particles will land there. See the following diagram:
```
+---+---+---+---+---+
| | | | | |
|max|min|max|min|max|
| | | | | |
+---+---+---+---+---+
```
The program should run until it is stopped manually.
**Rules**
* A pseudo random number generator (pRNG) is fine.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Input may be taken by any reasonable format.
* You should output to STDOUT.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer wins.
**Example**
The following GIF is an example run for `n = 5`. I only knocked it up quickly so the chances may be off slightly.
[](https://i.stack.imgur.com/MlQCN.gif)
[Answer]
# Python 2, ~~207~~ 200 bytes
There is a method to this madness, I promise. Follows the probability interpretation I commented in the OP.
*Edit: -7 bytes through some clever lazy evaluation (and removing some signs)*
```
import time # not counted for byte total
import random as R,curses as C
r=R.randint
c=C.initscr()
h,w=c.getmaxyx()
n=input()
w/=2*n-1
while 1:
all(r(0,1)or c.addch(r(0,h-1),(i*(2-4*r(0,1))+n)*w-r(1,w),42)for i in range(n/2+1))
c.refresh()
time.sleep(0.1) # not counted for byte total
```
[Answer]
# BASH, *396 - 11* = 385 bytes
```
E='echo -en';$E "\e[2J\e[99A";while :;do sleep 0.01;for i in `seq $((($1+1)/2)) -1 1`;do p=$(((($1+1)/2 - $i)));[ $p -lt 0 ]&&p=$((-$p));p=$((2**(p+1)));if [ $RANDOM -lt $((32768/$p)) ];then [ $(($RANDOM%2)) -eq 1 ]&&i=$((($1+1)-i));sector=$(((i*2-1)-1));C=`tput cols`;R=`tput lines`;SS=$((C/($1*2-1)));SX=$((SS*sector));X=$((SX+(RANDOM%SS)));Y=$((RANDOM%R));$E "\e[$Y;${X}H*";break;fi;done;done
```
Unfortunately I cannot demonstrate this on TryItOnline because of the endless loop & ANSI escape sequences that move cursor, but you can still copy-paste it into your terminal!
Unminified version:
```
E='echo -en'
$E "\e[2J\e[99A"
while :
do
sleep 0.01
for i in `seq $((($1+1)/2)) -1 1`
do
p=$(((($1+1)/2 - $i)))
[ $p -lt 0 ] && p=$((-$p));
p=$((2**(p+1)))
if [ $RANDOM -lt $((32768/$p)) ]
then
[ $(($RANDOM%2)) -eq 1 ] && i=$((($1+1)-i));
sector=$(((i*2-1)-1))
C=`tput cols`
R=`tput lines`
SS=$((C/($1*2-1)))
SX=$((SS*sector))
X=$((SX+(RANDOM%SS)))
Y=$((RANDOM%R))
$E "\e[$Y;${X}H*"
break
fi
done
done
```
[Answer]
# Mathematica, 231 bytes
```
(R=RandomInteger;p=20(#+1)+10;s=Array[0&,{20,6p-3}];i=(#+1)/2;Monitor[While[1<2,y=RandomChoice[Join[q=Riffle[Array[2^#&,i,0],Table[0,i-1]],Reverse@Most@q]->Array[Range[4#+1]&,i,0][[i]]];s[[R@19+1,10y-R@9]]=1;s],Grid[s//. 0->" "]])&
```
**input**
>
> [5]
>
>
>
**output**
[](https://i.stack.imgur.com/2bGlD.gif)
[Answer]
# C# (.NET 4.5), ~~319~~ 254 bytes
*Saved 65 bytes thanks to TheLethalCoder!*
```
namespace System{using static Console;n=>{for(var r=new Random();;)for(int w=WindowWidth/(2*n-1),i=(n-1)/2,c=0,m=2,l;i>-1;i--,c+=2)if((l=r.Next(0,(m*=2+1)*2))<2){SetCursorPosition((i+(l<1?c:0))*2*w+r.Next(0,w),r.Next(0,WindowHeight));Write('*');break;}}}
```
Phew, that was a lot of work, but it works somehow.
Since this uses `Console` specific functions and Thread sleeping, it won't work on TIO, sadly.
[Answer]
# Clojure + Quil, 394 bytes
```
(use '[quil.core])(defn -main[n](let[w 999 h 100 c(/ w(-(* n 2)1))s(range 0 w c)a(vec(take-nth 2 s))v(fn[x](<(rand)x))q(fn[a b](+ a(rand-int(- b a))))g(for[i(range(int(/ n 2))-1 -1)][i(- n 1 i)])z(for[[j i](map vector(range 1(inc(count g)))g)][(/ 1(Math/pow 2 j))i])](defsketch m :size[w h]:draw #(loop[[[p i]& r]z](when p(if(v p)(let[o(a(rand-nth i))](point(q o(+ o c))(q 0 h)))(recur r)))))))
```
Well, I certainly didn't win, but this was a good brain workout! I may have picked a overly roundabout way of doing this, but it works! Basically, how it works is:
1. The x-values of each column are calculated based on `n`. Then, the "active colums" that will contain the dots are filtered out. The columns are then zipped with the possibilities that they'll be chosen.
2. The animation starts, and each frame, a loop is entered. Starting from the middle, each pair of columns is tried. Once one pair of columns is chosen, one column from the pair is randomly chosen.
3. A dot is drawn at a random position within the chosen column, the inner loop exits, and a new frame begins.
Uses the Quil graphics library, which is essentially a Processing wrapper for Clojure.
Note, the golfed code doesn't produce the same animation as shown in the GIF. In the golfed code, the background is grey, and the window and dots are smaller. It has the same effect, it's just not as pretty.
[](https://i.stack.imgur.com/qrnF0.gif)
See the ungolfed code for an in-depth explanation:
```
(ns bits.golf.interference.interference
(:require [quil.core :as q]))
; Canvas size
(def width 1800)
(def height 800)
(defn -main [n]
(let [col-width (/ width (- (* n 2) 1))
; The left-most x of each column
col-starts (range 0 width col-width)
; The columns that need to be drawn. Need "vec" so I can index it later.
active-cols (vec (take-nth 2 col-starts))
; Function taking a decimal percentage, and returning whether or not it's satisfied.
; (chance? 0.5) would be used to simulate a coin toss.
chance? (fn [perc] (< (rand) perc))
; Function that returns a random int between a and b
r-int (fn [a b] (+ a (rand-int (- b a))))
; Generates index pairs for each complimentary column.
indices (for [i (range (int (/ n 2)) -1 -1)]
[i (- n 1 i)])
; Zips each index pair from above with the chance that it will be" chosen"
zipped-perc (for [[j i] (map vector (range 1 (inc (count indices))) indices)]
[(/ 1 (Math/pow 2 j)) i])]
; Animation boilerplate
(q/defsketch Interference
:size [width height]
:draw
; The animation loop. It contains a loop over each complimentary column. It tries each column pair starting
; from the middle, and works outward. Once it picks a pair of columns, it randomly chooses one of them.
#(loop [[[p i] & r] zipped-perc]
(when p
; Pick this column?
(if (chance? p)
; Pick one of the column pairs
(let [col (active-cols (rand-nth i))]
; Set the coloring and dot size
(q/fill 0 0 0)
(q/stroke-weight 5)
; And finally draw the dot
(q/point (r-int col (+ col col-width))
(r-int 0 height)))
; If the column wasn't chosen, loop again to try the next one
(recur r)))))))
```
[Answer]
# C#, 238 bytes
```
namespace System{using static Console;n=>{for(var r=new Random();;)for(int i=0,p=1,w=WindowWidth/(2*n-1),x;i<n+1;i+=2)if(r.Next(p*=2)<1){SetCursorPosition(r.Next(x=(n-1+(r.Next(2)<1?i:-i))*w,x+w),r.Next(WindowHeight));Write("*");break;}}}
```
[Try it online!](https://tio.run/##RZBNb4MwDIbv/Iqop5iPbVTaZWk6Tb3ssqlaD5wzGlprxUFJWpgQv51Bod17sGI/j2wpuUtKQ6YnVWpXqVyz3a/zugzagA05O6QDc155zNnGkDMnLYIryk/KOba9vid5zKxeDO7Zh0LicEf/0pi33KOhFZJfs4LJnuS6LYzlF2WZlaRr9qVob0oOQsAIBpOhfIormca1zHCAdYZ7f3zky5CSFOJG4IqiVGAkl4AFtw@fuvG8Cod2lUK7035zts7YrXE4Xr8ZjeTDgujWjvYrviQIENZxE9UQz2S6@q7xcPQAIrPoNV@ECxDfVqsf0XX9/Du3FPwZxH3SBVPt@j8 "C# (Mono) – Try It Online") (It won't work but y'know).
Full/Formatted version:
```
namespace System
{
using static Console;
class P
{
static void Main()
{
Action<int> f = n =>
{
for (var r = new Random(); ;)
{
for (int i = 0, p = 1, w = WindowWidth / (2 * n - 1), x; i < n + 1; i += 2)
if (r.Next(p *= 2) < 1)
{
SetCursorPosition(r.Next(x = (n - 1 + (r.Next(2) < 1 ? i : -i)) * w, x + w), r.Next(WindowHeight));
Write("*");
break;
}
Threading.Thread.Sleep(25);
}
};
f(5);
}
}
}
```
] |
[Question]
[
Write a program that keeps track of the number of consecutive days it has been run.
The day resets at midnight (the local time of the computer on which the program is run).
If there is a day that the program is not run, the counter is reset to zero.
Every time the program is run, the counter should go up by one day if it is the first time the program is run that day. This means that the first time the program is run, it should say, "You have a 1 day streak!"
The output of the program is in the form: `You have a [streak_length] day streak!`
You are allowed to store data externally or modify the source code––your choice.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# Bash, ~~92~~, ~~90~~, 82 bytes
**Golfed**
```
grep `date -d-1day -I` h||>h
date -I>>h
echo You have a `uniq h|wc -l` day streak!
```
**EDITS**
* Truncate file, instead of removing it, -8 bytes;
* Replaced *-daystart* with *! -newermt* to save 2 bytes.
**How It Works !**
Each time you launch it will append a line with the current date to the file *h*, e.g:
```
2017-02-03
2017-02-04
2017-02-05
2017-02-05
```
It will then use `uniq` to filter out duplicates (i.e. multiple launches, within the same day), and count the lines to get the *streak* length.
```
uniq h|wc -l
```
To reset a *streak*, it will grep for 'yesterday' in *h*, and truncate it if not found.
```
grep `date -d-1day -I` h||>h
```
[Answer]
# Bash, 102 bytes
```
find ! -newerat 0-1day -delete
touch -a a
echo You have a $((1+(`stat -c %X-%Y a`)/86400)) day streak!
```
**Warning, do *not* run in any folder you care about. It deletes any file not accessed in the last day in the working directory.**
Uses a file `a` to store data, using the accessed/modified timestamps.
[Answer]
# Goruby, 85 Bytes
Run with the interpreter flag `-rdate`.
```
c,t=0,Dae.y
op t.ts,?w
dw{c+=1;t=t.p;Fil.f t.ts}
s"You have a #{c} day streak!"
```
It works by storing a new file for each day on which it's invoked, then counts the number of consecutive files backwards to obtain the length of the streak. It doesn't ever delete files, so it will, eventually, after a very, very, very, very, very long time, fill your hard drive, a handful of bytes at a time.
Here's an ungolfed version of it:
```
streak, current_date = 0, Date.today
open(current_date.to_s, 'w')
while File.file?(current_date.to_s)
streak += 1
current_date = current_date.prev_day;
end
puts "You have a #{streak} day streak!"
```
[Answer]
**Python 3, 213 bytes**
```
import time
t=time.time()
try:
r=open("a").read().split(":")
open("a","w").write((str(int(r[0])+1)+":"+t)if(t>float(r[1])+86400)and(t<float(r[1])+172800)else("1:"+str(t)))
except:open("a","w").write("1:"+str(t))
```
[Answer]
# Bash + coreutils, ~~120~~ 97 bytes
```
read d n<f;c=`date -d0 +%s`;echo $c $[c>d?c>d+86399?n=1:++n:n]>f;echo You have a $n day streak!
```
The bash line above has 95 bytes in it.
There's a second file called f that just contains a single character:
```
0
```
(The program writes to f.)
So I think the total number of bytes should be scored as 97 (95 bytes for the contents of the bash file, 1 byte for the contents of the external file, and 1 byte because 1 file other than the program is used). This is based on [Counting bytes for multi-file programs](http://meta.codegolf.stackexchange.com/questions/4933/counting-bytes-for-multi-file-programs/4934).
Note: Thanks to @orlp for pointing out that an earlier answer to this that I posted was nonsense; I had misread the problem completely. (It was posted as a different answer, which I've deleted.)
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 95 bytes
```
(date -f 'd')>>z
gc z|gu|%{$c=(1,++$c)[($d=date $_)-eq$n]
$n=$d+1D}
"You have a $c day streak!"
```
[Try it online!](https://tio.run/nexus/powershell#@6@RkliSqqCbpqCeoq5pZ1fFlZ6sUFWTXlqjWq2SbKthqKOtrZKsGa2hkmILVqkSr6mbWqiSF8ulkmerkqJt6FLLpRSZX6qQkViWqpCooJKskJJYqVBcUpSamK2o9P8/AA "PowerShell – TIO Nexus")
### Explanation
I start by writing the current date (in short date format) out to a file (named `z`). `>>` works as usual; appends, but creates if it doesn't exist.
Next, I read the contents of the file line by line with `Get-Content` (`gc`), pipe through `Get-Unique` (`gu`) since there could be multiple entries from the same date, then pipe through `ForEach-Object` (`%`).
In the loop, I create a 2 element array with the value `0` in the first element, and the current value of `$c` (`+1`) in the second element. Using `++$c` allows me to avoid wrapping something like `$c+1` in parentheses.
Then I index into the two element array with a boolean comparison, which will get coalesced to `0` for `$false` or `1` for `$true`. Within the comparison, I'm assigning to `$d` a `[datetime]` object created from the date read from the current line in the file. That object gets compared to `$n`, which on the first run hasn't been assigned yet, so it will never match, and `$c` will be initialized to `1`, since the value of the indexing is being assigned to `$c`.
Next, `$n` is populated with the next expected date, by adding `1` to the current datetime object. The key here is that `1D` means it's a `[decimal]` literal. For some reason when you add integer numbers to a `[datetime]`, it's interpreted as ticks, but when you add floating point numbers, they are interpreted as days. So this populates `$n` for the next iteration.
The effect is that the counter gets reset every time the current date doesn't match the "next" date (which is the previous date plus 1 day).
Finally the message is output.
] |
[Question]
[
## Introduction
Long story short: a few days ago I accidentally started knitting a sock and the pretty logical structure of the plain stitches lead me to the idea: Why don't we just ASCII-knit a sock?
## Input
The input is an even integer N in the range `[2,30]`.
## Output
The output is a sock, obviously.
## Structure
Because we will only use plain stitches you will only use `v` for a downward stitch and `>` for a stitch to the right. Let me explain the full structure with an example for `N=8`:
```
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvv>>>
vvvvvv>>>>>>
vvvvv>>>>>>>>>
vvvv>>>>>>>>>>>>
vvvv>>>>>>>>>>>>>>>>>>>>>>>>
vvvv>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvv>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvv>>>>>>>>>>>>>>>>>>>>>>>>
```
* The first block is the upper part. It has the width `N` and the height `N*1.5`
* Afterwards the heel begins. You subtract one `v` per row from the right side until you have `N/2` as width. Then you add `N/2` rows with the width `N/2` beneath to finish the downward knits. Note that it gives a total of `N/2 + 1` rows with the width `N/2`
first part:
```
vvvvvvvv //begin with width N
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv // N*1.5 times
vvvvvvv // reduce
vvvvvv
vvvvv
vvvv // till here
vvvv // repeat N/2 times
vvvv
vvvv
vvvv
```
* Now the side wards knits begin. You start with the first reduced row, fill `>` till you have the width `N` and add two more. Continue that process including the first row with `N/2` width
* Fill the rows beneath to that level and add `N*1.5` times `>` to that
* Let the outer parts as they are and add on the row beneath the first and over the lase two more `>'s` until it is finished
second part:
```
vvvvvvvv
vvvvvvv>>> //fill to N and add two >
vvvvvv>>>>>> //repeat
vvvvv>>>>>>>>>
vvvv>>>>>>>>>>>> //till here
vvvv>>>>>>>>>>>>>>>>>>>>>>>> //fill to the row above and add N*1.5 times >
vvvv>>>>>>>>>>>>>>>>>>>>>>>>>> //add two more '>' than the row above
vvvv>>>>>>>>>>>>>>>>>>>>>>>>>> //add two more '>' than the row beneath
vvvv>>>>>>>>>>>>>>>>>>>>>>>>
```
## Rules
Trailing new lines are ok.
You can choose between uppercase or lowercase `V` but it has to be consistent.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
## Test cases
```
N=2
vv
vv
vv
v>>>
v>>>>>>
N=4
vvvv
vvvv
vvvv
vvvv
vvvv
vvvv
vvv>>>
vv>>>>>>
vv>>>>>>>>>>>>
vv>>>>>>>>>>>>
N=6
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvv>>>
vvvv>>>>>>
vvv>>>>>>>>>
vvv>>>>>>>>>>>>>>>>>>
vvv>>>>>>>>>>>>>>>>>>>>
vvv>>>>>>>>>>>>>>>>>>
N=12
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvv>>>
vvvvvvvvvv>>>>>>
vvvvvvvvv>>>>>>>>>
vvvvvvvv>>>>>>>>>>>>
vvvvvvv>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 54 bytes
```
1.*(\v*,)½(n-\v*₴n:d+\>*,)½½ʁ(½\v*?T\>*Jnd\>*J:⅛,)¾(¼,
```
Boy oh boy, this is my new favorite answer now.
The satisfaction when I got it down from 79 bytes to 54 bytes was immense.
I bet you can't golf this anymore.
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxLiooXFx2Kiwpwr0obi1cXHYq4oK0bjpkK1xcPiosKcK9wr3KgSjCvVxcdio/VFxcPipKbmRcXD4qSjrihZssKcK+KMK8LCIsIiIsIjgiXQ==)
## Explanation
```
1.*(\v*,)½(n-\v*₴n:d+\>*,)½½ʁ(½\v*?T\>*Jnd\>*J:⅛,)¾(¼,
1.*(\v*,) <Top part>
1. Evaluates to 1.5
* Times input i
( ) Loop (with loop var n)
\v*, Repeat "v" n times and print it
½(n-\v*₴n:d+\>*,) <Diagonal part>
½ Halve input i
( ) Loop (with loop var n)
n-\v*₴ Repeat "v" i minus n times and print it (without a newline)
n:d Duplicate n and double it
+\>*, Repeat ">" 2n plus n times
½½ʁ(½\v*?3*\>*Jnd\>*J:⅛,) <Top half bumpy part>
½½ʁ Create range 0 to input i/4
( ) Loop
½\v* Repeat "v" i/2 times
?T\>*J Repeat ">" 3i times and join it
nd\>*J: Repeat ">" 2n times, merge and duplicate it
⅛, Push it to the global array and print it
¾(¼, <Bottom half bumpy part>
¾( Loop through the length of the global array
¼, Pop from the global array (to reverse it)
```
[Answer]
**Pyth - 93 Bytes**
```
J/Q2K"V"P*s*Q1.5+*QKbVJp*+Q_+1NK*+3*3N">";InQ2VJp*JK*+s*2aaNc-J 1 2c-J 1 2+3*Q3">";IqQ2pK*6">
```
Explanation:
```
J/Q2 sets J to half of input
K"V" sets K to "V"
P prevents newline after main block of sock
* multiply the next 2 items
s*Q1.5 rounds up input*1.5 (columns in main block)
+ adds the next 2 item (this item gets multiplied by the previous item)
*QK multiplies "V" by input (resulting in each row)
b New line
VJ For all the numbers 0-((Q/2)-1) (as represented by N)
p print
* multiply the next 2 items
+Q_+1N input + -1*(1+N)
K "V"
*+3*3N">" 3N+3 many ">"'s
; ends for statement
InQ2 if input is not 2
VJ For all the numbers 0-((input/2)-1) (as represented by N)
p print
*JK input/2 many ">"'s
*+s*2aaNc-J 1 2c-J 1 2+3*Q3">" int(abs(abs(N-((input/2)-1)/2)-((input/2)-1)/2)))+(input*3)+3 many ">"'s
; end of for statement
IqQ2 if input is 2
pK*6"> print "V" and 6 ">"'s
```
[You can try it here!](http://pyth.herokuapp.com/?code=J%2FQ2K%22V%22P%2a.E%2aQ1.5%2B%2aQKbVJp%2a%2BQ_%2B1NK%2a%2B3%2a3N%22%3E%22%3BInQ2VJp%2aJK%2a%2B.E%2a2aaNc-J+1+2c-J+1+2%2B3.E%2aQ3%22%3E%22%3BIqQ2pK%2a6%22%3E&input=286%0A%0A287&test_suite=1&test_suite_input=2%0A4%0A6%0A12&debug=0)
[Answer]
# Mathematica, 104 bytes
```
""<>{t=Table;c=t[{"v"~t~#,">"~t~#2,"
"},#3]&;h=#/2;c[#,0,3h],c[#-i,3i,z={i,h}],c[h,6h+2Min[i-1,h-i],z]}&
```
Unnamed function taking a positive even integer as input and returning a string (with a trailing newline). Note that the newline between the two lines of code above is part of the code. The main work is done by the function `c`, whose ungolfed definition
```
c[#1, #2, #3] = Table[{Table["v", #1], Table[">", #2], "\n"}, #3]
```
creates a table of lists, each one consisting of several `"v"`s in a row followed by several `">"`s followed by a newline. Fortunately, the range `#3` for the outer `Table` can have a variable name, which can be referred to in the expressions `#1` and `#2`; this allows the function `c` to be called with both constant and variable arguments. The rest is just computation, and the string-joining operator `""<>` flattens the nested lists that arise for free.
[Answer]
## Python, 3.5 ~~183~~ 177 bytes
```
n=int(input())
h=n//2
z=h%2
l=['v'*h+'>'*(2*n-h+3*h+i*2)for i in range(1*z+n//4)]
*map(print,['v'*n]*(3*h)+['v'*i+'>'*(3*(n-i))for i in range(h,n)][::-1]+[l,l[:-1]][z]+l[::-1]),
```
*Explanation incoming.*
[Try it Online!](https://tio.run/nexus/python3#XYwxDoMwEAR7v4Im8t3ZCGGokJyPWC4okvgk54IskoLPEwe6dDsrzeziWVZgWd4rIKrkpeuc2ny6OJV90B9NyeirJnAkbTJDRSaH91dpuGFpyiyPG/S0mWqOGBU95wWWUrP20CUSVAvNQXzGBgJpGf8zyQrGME1tH03INoffimGLJp8v2n0fvw)
[Answer]
## Groovy, 168 bytes
```
{n->h=n/2;z=(int)h%2;l=(0..<1*z+n/4).collect{'v'*h+'>'*(2*n-h+3*h+it*2)};(['v'*n]*(3*h)+(n-1..h).collect{'v'*it+'>'*(3*(n-it))}+(z==0?l:l[0..<-1])+l[-1..0]).join('\n')}
```
This is an unnamed closure. The approach is completely similar to my [Python 3.5](https://codegolf.stackexchange.com/a/108089/47650) answer.
[Try it Online!](https://tio.run/#gb9Vt)
[Answer]
## Batch, 279 bytes
```
@echo off
set i=for /l %%i in (2,2,%1)do
set v=
%i%call set v=v%%v%%v
%i%echo %v%&echo %v%&echo %v%
%i%call:a
%i%call set v=%%v%%]]]
%i:,2,=,4,%call:c&if %%i lss %1 call set v=%%v%%]]
%i:2,=4,%call:b
exit/b
:a
set v=%v:~1%]]]]]
:b
set v=%v:~0,-2%
:c
echo %v:]=^>%
```
Note: the second line ends in a space. Batch has problems with echoing `>`s in variables so I have to a) use a substitute b) call a subroutine to echo the corrected string. In fact I have three subroutines:
* `a` is used for the heel. One `v` is removed each time and three `>`s are added. Two extra `>`s are added so that the subroutine can fall through into the `b` subroutine.
* `b` is used for the bottom of the foot. Two `>`s are removed each time. The subroutine then falls through into the `c` subroutine.
* `c` prints the current row of the sock, replacing the placeholder character so that the `>`s print properly.
The fourth line handles the width of the leg while the fifth line handles its length. The seventh line handles the length of the foot while the eighth line handles the top half of the foot height by adding two `>>` to each line after printing it. This works for sock sizes that are multiples of 4, and an adjustment is made for other sock sizes so that the longest line does not get repeated.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 269 bytes
```
1k?d1.5*sadsdsb[[[v]nlb1-dsb0<f]dsfx[]pldsbla1-dsa0<c]dscxldd1-sisb2su[[[v]nlb1-dsbldli-<g]dsgx[[>]nlb1-dsblu+0<t]dstx[]plu2+suli1-dsilddsb2/!>m]dsmxld3*dsdsolidswst[[[v]nlw1-dsw0!>x]dsxx[2-]sa[2+]sy[[>]nlo1-dso0<g]dsgxldltli1+2/<yltli1+2/>adsdsolisw[]plt1-dst0!>f]dsfx
```
All right, well...this is *massive*. It wasn't easy, I'll tell you that much, what with all the register references, comparisons, macros, lack of string manipulation abilities, etc. Nonetheless, I had fun putting this together, and that's all that really matters, right? ;)
[Try It Online!](https://tio.run/nexus/dc#VY/RDsIgDEW/Za8jOMCY@EDwQwgPbGQLkTmTgrCvn8XNGN/a29vT243fb46fLi1YBw56rfXLPELPKTZMjsbBWLR5BmyDraplckB1KME5TsFDLyD9rQUXPJUTmqaitfrpiTAZUY4fYhIEUvB15JGFnK5RM45nRJ/bGmcJ3kGGeOBz9WbWqIKuUrSgBqwWxMC631mqYWHHbcwRkU9EJ9dvpezBhVwzxLoQkbg/um3XNw "dc – TIO Nexus")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 185 bytes
```
#define L for(i=0;i<h;i++,p(10,1))
p(c,n){n&&putchar(--n?p(c,n):c);}
f(n,i,k,h){h=n/2;for(k=3;k--;)L p(118,n);L{p(118,n-i-1);p(62,3*i+3);}L{p(118,h);p(62,3*n);p(62,2*(4*i/n?h-i-1:i));}}
```
[Try it online!](https://tio.run/##TY1NboNADIX3cworVSMPzCgwVG2Fg3IBjtBNNIGMheoiRFaIs9MhJVG98M/z52dvr94vy8ulaVkaqKH9GZCrjPgYiNPU9JhnJtda9eiN6En2@/42@nAe0Fo5/aml1zSrFsWw6UzQU6jk4Gj16qqCOmtJ1xCt8s9IUz1trWWba@rx3Zki4bSILo9deOqydS7Bt4QPcgrrWck60vPCMsL3mQU1TEpBjPgVcJUZKsgpliN8EKQprwhs0Q8RaXEnEXq9lF@yM@AgAdb0ZFp0yf/5cRPhTZ3v@Z6GZrwNAhkpNS@/ "C (gcc) – Try It Online")
Mostly boring, except I use a recursive function to print repeated characters.
[Answer]
# PHP, 229 bytes
a quite lazy approach
```
for($m=$n=$p=$argv[1];$i++<$q=$n*1.5;)echo($d=str_pad)("
",$n+1,v);for(;$p-->$n/2;)echo$s="
".$d($d("",$p,v),$m+=2,">");$r=[$s.=$d("",$q,">")];for($k=$n>>2;--$k;)$r[]=$s.=">>";echo join($r),$n&2?"$s>>":"",join(array_reverse($r));
```
prints a leading newline. Run with `-nr`.
**breakdown**
```
// print first part + preparing some variables for later
for($m=$n=$p=$argv[1];$i++<$q=$n*1.5;)echo str_pad("\n",$n+1,v);
// print second part + prepare $s for third part
for(;$p-->$n/2;)echo$s="\n".str_pad(str_pad("",$p,v),$m+=2,">");
// third part: create an array of strings ...
$r=[$s.=str_pad("",$q,">")];
for($k=$n>>2;--$k;)$r[]=$s.=">>";
// ... then print it and its reverse
echo join($r),$n&2?"$s>>":"",join(array_reverse($r));
```
] |
[Question]
[
Don't you find that reading simple text isn't appealing enough? Try our
```
##### ### ### ##### ##### ##### ##### # # ##### #
# # # # # # # # # # # # #
##### ### # # # # #### # # #
# # # # # # # # # # # #
# # ### ### ##### ##### # ##### # # # #
```
Much more fancy isn't it? But it's pretty long to write by hand, it would be wonderful if someone did a program that do it for me !
**Your task**, if you volunteer to help me, will be to write a program or a function that takes a string containing `[a-zA-Z\s\n]` only, and output (or return) the ascii writing of it!
You must use the following alphabet to format your output:
```
##### #### ### #### ##### ##### ### # # ##### ##### # # # # #
# # # # # # # # # # # # # # # # # # ## ##
##### #### # # # #### #### # ## ##### # # ### # # # #
# # # # # # # # # # # # # # # # # # # # # #
# # #### ### #### ##### # ### # # ##### ### # # ##### # #
# # ### #### ### #### ### ##### # # # # # # # # # # #####
## # # # # # # # # # # # # # # # # # # # # # #
# # # # # #### # # #### ### # # # # # # # # # # #
# ## # # # # ## ## # # # # # # ## ## # # # #
# # ### # #### # # ### # ### # # # # # # #####
```
The space:
```
|
| it's a 5x5 square of spaces
| but had to pad it with |s to make it appear in this post
|
|
```
As this is a fixed-width font, the space character is also surrounded by spaces, resulting in a 7-width space between the two letters.
```
a b
1234567 -- these numbers are just for the example, you don't have to output them
##### ####
# # # #
##### ####
# # # #
# # ####
a b
1234567890123
##### ####
# # # #
##### ####
# # # #
# # ####
```
When you encounter a newline, as in the input
```
ascii
text
```
Just make sure to separate the two blocks of text by at least one empty line
```
##### ### ### ##### #####
# # # # # # #
##### ### # # #
# # # # # # #
# # ### ### ##### #####
##### ##### # # #####
# # # # #
# #### # #
# # # # #
# ##### # # #
```
Also, you are allowed to replace the `#`s with any other character as long as it is in the printable ASCII range, and is not spaces. You could for instance use `A`s for the letter A, `B` for the letter B and so on.
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") (and moreover [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'")) the winning submission will be the one that solve this challenge in the least byte possible, have fun!
[Answer]
## Python 3, 375 bytes
```
f=lambda i:"\n\n".join("\n".join(map(" ".join,zip(*[[x.replace("0"," ")[a*5:a*5+5]for a in range(5)]for x in[["{:025b}".format(int(c,36))for c in'0 JPCFL J2UKE 92Y3Y J2KAM JOMCF JOMC0 92B72 AYP81 JFM3J JFMHO AZC7M AB6ZJ B5I5T B43N5 92YWE J2UJ4 92YY7 J2UQC 926UM JFM2S AYE5Q AY8G4 AYHKH AT6Q9 AT6KK AWU7'.split()][x!=" "and ord(x)-64]for x in j.upper()]])))for j in i.split("\n"))
```
[See this code running on ideone.com.](http://ideone.com/woZHjC)
The same code, but somehow nicely indented, formatted and commented:
```
f = lambda i: \
# join multiline strings together using an empty line as separator:
"\n\n".join(
# join the string lines of one big output line together:
"\n".join(
# join the corresponding rows of the letters together using " ":
map(" ".join, zip(*
# make a list (output line) of list (output characters)
# of strings (single character's rows):
[
# replace 0s with spaces and split the bit strings into
# chunks of 5 characters - the rows of each letter:
[x.replace("0", " ")[a*5 : a*5+5] for a in range(5)]
for x in [
# split the space separated character codes and
# convert them from base 36 to
# base 2 strings of length 25:
["{:025b}".format(int(c, 36)) for c in
# the encoded font data (reformatted):
'0 JPCFL J2UKE 92Y3Y J2KAM JOMCF JOMC0 92B72 '
'AYP81 JFM3J JFMHO AZC7M AB6ZJ B5I5T B43N5 92YWE '
'J2UJ4 92YY7 J2UQC 926UM JFM2S AYE5Q AY8G4 AYHKH '
'AT6Q9 AT6KK AWU7'.split()]
# select element 0 if we want a space, else find
# out the index from the ASCII code of the letter:
[x != " " and ord(x) - 64]
# repeat for every character in the input line:
for x in j.upper()
]
]
))
# repeat for every line in the input
) for j in i.split("\n")
)
```
I also decided to go for **base 36** encoding as that's the highest base Python's built-in `int()` natively supports. Here is a short Python 3 script I wrote (ungolfed) that converts font definitions like in the question into base 36 codes: [My converter on ideone.com](http://ideone.com/FX6KSl)
The result consists of the character `1` as enabled pixel and a space as disabled pixel. Here's a single example run:
Input (line break as `\n`):
```
Hello World
Python rocks
```
Output:
```
1 1 11111 1 1 111 1 1 111 1111 1 1111
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
11111 1111 1 1 1 1 1 1 1 1 1 1111 1 1 1
1 1 1 1 1 1 1 11 11 1 1 11 1 1 1
1 1 11111 11111 11111 111 1 1 111 1 1 11111 1111
1111 1 1 11111 1 1 111 1 1 1111 111 111 1 1 111
1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1
1111 1 1 11111 1 1 1 1 1 1111 1 1 1 111 111
1 1 1 1 1 1 1 1 11 11 1 1 1 1 1 1 1
1 1 1 1 1 111 1 1 1 1 111 111 1 1 111
```
[Answer]
# Clojure, 552 bytes
```
(defn t[s](print(reduce #(str %1"\n"%2)(map #(apply str %)(let[a[:jpcfl :j2uke :92y3y :j2kam :jomcf :jomc0 :92b72 :ayp81 :jfm3j :jfmho :azc7m :ab6zj :b5i5t :b43n5 :92ywe :j2uj4 :92yy7 :j2uqc :926um :jfm2s :aye5q :ay8g4 :ayhkh :at6q9 :at6kk :je7mn :0]](map(fn[o](map #(str(.replace %"0"" ")"\n")(map(fn[w](reduce #(str %1(.substring %2 w(+ w 5))"0")""(map #(str(apply str(repeat(- 25(count %))"0"))%)(map #(Integer/toString(Integer/valueOf(name %)36)2)(map a(map #(if(= % \space)26(-(int %)97))(.toLowerCase o)))))))(range 0 25 5))))(.split s"\n")))))))
```
Each letter in ascii is represented as a binary string with # - 1, space - 0. Then it's converted to base 36 so that it only takes 5 chars to store + ":" to let Clojure know that it should be treated as symbol.
Then the input is split by newline symbol and for each line we convert a letter in 36 base back to binary base and get first [0:5] symbols add newline symbols, get next [5:10] symbols and so on.
You can see it running here - <https://ideone.com/y99ST5>
[Answer]
# Powershell, ~~261~~ 253 bytes
```
$args-split'
'|%{$s=$_
0..5|%{$l=$_
-join($s|% *per|% t*y|%{$c='_ONO__NQ__QAQQNONON_QQQQQ?QQQQAAAQDDIA[SQQQQADQQQJJ(_OAQOOY_DDGAUUQOQONDQJUDD$QQQQAAQQDEEAQYQAYCPDQJ[JD"QONO_ANQ_GI_QQNA^ENDNDQQD?'[$l*26+$_-65+222*!($_-32)]
0..5|%{' #'[(+$c-shr$_)%2]}})}}
```
Test script:
```
$f = {
$args-split'
'|%{$s=$_
0..5|%{$l=$_
-join($s|% *per|% t*y|%{$c='_ONO__NQ__QAQQNONON_QQQQQ?QQQQAAAQDDIA[SQQQQADQQQJJ(_OAQOOY_DDGAUUQOQONDQJUDD$QQQQAAQQDEEAQYQAYCPDQJ[JD"QONO_ANQ_GI_QQNA^ENDNDQQD?'[$l*26+$_-65+222*!($_-32)]
0..5|%{' #'[(+$c-shr$_)%2]}})}}
}
&$f "ascii art
text"
```
Output:
```
##### ### ### ##### ##### ##### #### #####
# # # # # # # # # # # #
##### ### # # # ##### #### #
# # # # # # # # # ## #
# # ### ### ##### ##### # # # # #
##### ##### # # #####
# # # # #
# #### # #
# # # # #
# ##### # # #
```
## Note:
`$s|% *per|% t*y` [is shortcut](https://codegolf.stackexchange.com/a/111526/80745) for `$s|% toUpper|% toCharArray`
## About space:
For each character of the source string, the script takes a symbol (bit mask) from the magic string `'_ONO__NQ...'`. However, the index goes beyond the magic string for a space. In this case, the bit mask `$c` becomes empty. It means zero for all bits.
## About blank line:
The script displays 6 rows for each symbol instead of 5. The index goes beyond the magic string for a blank line too. So, the row 6 contains spaces only.
It is best seen if you print another character instead of a space. For example `·`.
```
#####··###···###··#####·#####·······#####·####··#####·
#···#·#·····#···#···#·····#·········#···#·#···#···#···
#####··###··#·······#·····#·········#####·####····#···
#···#·····#·#···#···#·····#·········#···#·##······#···
#···#··###···###··#####·#####·······#···#·#·#·····#···
······················································
#####·#####·#···#·#####·
··#···#······#·#····#···
··#···####····#·····#···
··#···#······#·#····#···
··#···#####·#···#···#···
························
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~326~~ ~~322~~ ~~321~~ 317 bytes
-8 bytes thanks to ceilingcat
```
#define X!!putchar
char*p,*q;i,j;f(int*s){for(;p=strtok(p?0:strdup(s),"\n");X(10))for(i=0;i<5;i+=X(10))for(q=p;*q;q+=X(32))for(j=0;j<5;)X((*q-32?"OAOAA?A?A?>A1A>?AAA?O1?1OO1?11>1IA>AAOAAO444OO4457A97591111OAKEAAACCIA>AAA>?A?11>AAIN?A?35>1>@>O4444AAAA>AA::4AAEKAA:4:AA:444O842O"[(*q&~32)*5-325+i]-48:0)>>j++&1?35:32);}
```
[Try it online!](https://tio.run/##RVDLbsIwEDyTrwiphOwEpBgSAXHj1EIcEFJ9RSo9pIGAA@RpCi2iv56uy6G2tJrZnVmtJhnskqRtnzbbVOZbc9XtlmeV7OPa0MUu@3ZFZT@jKZK5sht8S4sa0TJsVK2KAyojNwC4OZeowX1rnVuYrhBxMdY6GbpUPvtUOuF/swpLCksr3RsNH70MhBkI8QohuxqMhpEluOA80p9xwlnEgQkSEaELYWTBGdcS4XmegOKP@XTsTwk8wZdzkM9mfxrt1Q7OF6@ARj4j7IVpm8f1lPMgADRfAvACXWDhxBsK6w1u6f3AjbYPJ/mOfB94k8DFjGWO0yOwKoAhvbcQjXmKZY6wcTM6KbLiJpHSVNurWudFbqpLYR4h3gbS0XOjY8UfCUS@g8CA7GV2OJ7yBynKqm7U@UE@L9evb@26t78 "C (gcc) – Try It Online")
[Answer]
# [SOGL](https://github.com/dzaima/SOGL), 137 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
°f`7-π⅛χ%sΤ↕ņLRΕ⅓9׀b∫rr(¶æKGTΧ3;■ΦΤg¼⁰¡Νg‽}○eΧ²Y∫Οαν⌡l′}¾(8╔ <%╤∙i.d↔ū∫Æo┌jyŗ▲δ⁶=╗$↑yōΛ3h¼╔◄┼)‘’«n.{5{ø}¹,uR{8+:Ahwha’#=?X’«@*}┼L@*┼}pøO
```
Explanation:
```
...‘’«n.{5{ø}¹,uR{8+:Ahwha’#=?X’«@*}┼L@*┼}pøO
...‘ push a string with the letter data ["..."]
’«n split in lengths of 25 [[".", ".", ".",...]]
.{ repeat input times [[".", ".", ".",...]]
5{ø} push 5 empty strings [[".", ".", ".",...], "", "", "", "", ""]
¹ wrap those in an array [[".", ".", ".",...], ["", "", "", "", ""]]
, get a string input [[".", ".", ".",...], ["", "", "", "", ""], "Hello World"]
u lowercase it [[".", ".", ".",...], ["", "", "", "", ""], "hello world"]
R{ } itirate over the ordinals of the string [[".", ".", ".",...], ["", "", "", "", ""], 104]
8+ add 8 to the ordinal [[".", ".", ".",...], ["", "", "", "", ""], 112]
:A save on variable A [[".", ".", ".",...], ["", "", "", "", ""], 112]
h swap 2 items one below the stack [["", "", "", "", ""], [".", ".", ".",...], 112]
w get the ord+8th item of the letter data array (modulo length) [["", "", "", "", ""], [".", ".", ".",...], "----- - - - -----"]
h swap 2 items one below the stack [[".", ".", ".",...], ["", "", "", "", ""], "----- - - - -----"]
a load the variable A [[".", ".", ".",...], ["", "", "", "", ""], "----- - - - -----", 112]
’#=? } if equals to 40 then [[".", ".", ".",...], ["", "", "", "", ""], "----- - - - -----"] (temporalily switching to space case; it incorrectly picks "N" for space)
X delete the string [[".", ".", ".",...], ["", "", "", "", ""]]
’«@* push a string with 25 spaces [[".", ".", ".",...], ["", "", "", "", ""], " "]
┼ add the string vertically-then-horizontally to the array [[".", ".", ".",...], ["", "", "", "", ""], ["- -", "- -", "-----", "- -", "- -"]] (back to "H")
L@* push a string with 10 spaces [[".", ".", ".",...], ["", "", "", "", ""], ["- -", "- -", "-----", "- -", "- -"], " "]
┼ add the string vertically-then-horizontally to the array [[".", ".", ".",...], ["", "", "", "", ""], ["- - ", "- - ", "----- ", "- - ", "- - "]]
p output the resulted line [[".", ".", ".",...], ["", "", "", "", ""]]
øO append to output an empty line
```
note: currently this language can't really accept multiline input string so I've made it ask for a number and read the next x lines as the input.
The first string is
```
"------ - - - - - ----------- - -- - -- - - - - --- - -- -- - - - ------ -- -- - --- ------ - -- - -- - -- ------- - - - - - - --- - -- -- - - -- ----- - - - ------ -- ------- -- -- --- ------- - ----- - -- - -- ----- - - - ------ - - - ---------- - - - ----- --- - -- -- - --- ------ - - - - - - --- - -- -- -- ---------- -- - - -- - - - - - -- - -- - - - - - ------ - ---- - - ----- -- -- - -- -- ----- - - - ------ - - - - - - - -- - --- - - - -- --- - --- -- -"
```
compressed using a custom dictionary that uses " " and "-" (the compression has a special mode with "\n -|/\_" available so even more compression!)
It contains 25 chars per ascii char in the order of the alphabet. they are ordered top-down then right.
the chars go like
```
16b
27c
38d . . .
49e
5af
```
and that's the same way that `┼` adds them to an array.
[Answer]
# JavaScript (ES6), ~~292~~ ~~287~~ 278 bytes
```
s=>s.split`
`.map(s=>`vfefvvehvvh1hhefefevhhhhhv
hhhh111h4491rjhhhh14hhhaa8
vf1hffpv4471llhfhfe4hal444
hhhh11hh4551hph1p3g4hara42
hfefv1ehv79vhhe1u5e4e4hh4v`.replace(/.{26}/g,S=>s.replace(/./g,c=>'012345'.replace(/./g,x=>' #'[(P=parseInt)(S[P(c,36)-10]||0,36)>>x&1])))).join`
`
```
### Demo
```
let f =
s=>s.split`
`.map(s=>`vfefvvehvvh1hhefefevhhhhhv
hhhh111h4491rjhhhh14hhhaa8
vf1hffpv4471llhfhfe4hal444
hhhh11hh4551hph1p3g4hara42
hfefv1ehv79vhhe1u5e4e4hh4v`.replace(/.{26}/g,S=>s.replace(/./g,c=>'012345'.replace(/./g,x=>' #'[(P=parseInt)(S[P(c,36)-10]||0,36)>>x&1])))).join`
`
O.innerText = f('HELLO WORLD\nTHIS IS A TEST')
```
```
<pre id=O></pre>
```
] |
[Question]
[
Your challenge is to format a list of words across multiple lines that are no longer than a given number of characters, so that each line contains as many words as possible and no words are unnecessarily cut off.
## Input
The input will be a space-separated list of words and then a number that is at least 4.
## Output
The output should be the input words grouped into lines so that none of the lines contains more characters than the input number. The words should be output in the order they were input. The words should be separated by a comma and then a space, except at the end of each line, where the space isn't needed. If a word is too long to fit on a line, it should be cut off as little as possible while following the other rules, and "..." should be added to the end.
## Test cases
```
Input:
foo bar baz qux 12
Output:
foo, bar,
baz, qux
Input:
foo bar baz qux 5
Output:
foo,
bar,
baz,
qux
Input:
strength dexterity constitution intelligence wisdom charisma 10
Output:
strength,
dexterity,
consti...,
intell...,
wisdom,
charisma
Input:
quas wex exort 4
Output:
...,
wex,
e...
```
[Answer]
# [Unreadable](https://esolangs.org/wiki/Unreadable), 2559 bytes
This challenge is eerily suited for Unreadable.
**The first version of this was 3379 bytes,** just to give you an idea of how much I golfed this.
The program accepts the input exactly as described in the challenge: a space-separated list of words (which may contain digits and punctuation marks, too), followed by a space and an integer that is at least 4 (lower numbers generate infinite loops).
>
> '""""""'""""""""'"""'""'""'""'""'""'""'"""'"""""'""'""""""'""'"""'""""""""""'""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'""'"""'"""""'"""""""'""""""'""""""""'"""'""""""""'"""""""'""""""""'"""'"""'"""""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'""""'""""'""""""'""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""'"""""'""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""""""'""'"""'""'""'""'""'""'""'""'""'""'""'"""""""'""'"""'""""""'""'""'"""'"""""'""""""'"""""""'""""""""'"""'""""""""'"""""""'"""""""'""""""""'"""'""""""'""'"""'""'"""""""'""'"""'"""""'""""""'""'"""'""""""""'"""""""'""'"""'""""""'""""""'"""'""""""""'"""""""'"""'"""'""""""'""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""""""'""'""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""""""'""'""'"""'""'""'""'""""""'""""""""'"""'""'""'""'""'""'""'""""""'"""'"""'"""""'"""""""'""'"""""""'""""""""'"""'""""'""""'""""'"""""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'""""""'"""'""""""""'"""""""'"""'"""""""""'""""""'""'"""'"""""""'""'"""""""'""""""""'"""'""""""'"""'""""""""'"""""""'"""'"""'"""""'"""""""'""""""'""""""""'"""'""""""""'"""""""'""""""""'"""'"""'""""""'""'""'""'"""'"""""""""'"""""""'"""""""""'"""""""'""'""'""'"""'""""""'"""'""""""""'"""""""'"""'"""""""'"""'""""'""""'"""""""""'"""""""'""'""'""'"""'"'"""""""'""'""'""'""'""'"""'"""'"""""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'"""""""'""""""""'"""'"""""""""'"""""""'""'"""'"'"""""""'""'""'""'""'"""'"""'""""'""""'"""""""""'"""""""'""'""'""'"""'"""'""""'""""'""""'""""'"""""'""""""""'"""""""'""""""'"""'""'"""""""'"""'"""'"""""""""'"""""""'""'"""'""""""'"""'""'"""""""'"""'"""'"""""'""'""""""'"""'""'"""""""'"""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'"'"'"'"""""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'""'""'"""""""'""'""'""'""'"""'"""""""""'"""""""'""'"""'"'"""""""'""'""'""'""'"""'"""'"'"""""""'""'""'"""'""""""""'""""""'"""'"""
>
>
>
## Explanation
I’m going to walk you through how the program processes the input `thyme horseradish peppermint 10`. The expected output is `thyme,\nhorser...,\npeppermint`.
First we start at cell #7 and read the entire input, but subtract 32 from every character so that spaces become zeros.
[](https://i.stack.imgur.com/te1db.png)
For obvious reasons, this leaves the running pointer (named *p* here, stored in cell #0) at the end. We use one while loop to find the last gap, which is the beginning of the number that defines the width of the output (cell #36 in this example).
We now want to decode the number (i.e. convert from decimal). The final result will be in both cells *t* and *r*. We rely on the fact that they start out at zero.
For every digit in the number, do the following:
* Set *t* to −15.
* In a while loop, decrement *r* (which contains the result so far) to −1 (because we need exactly *r* iterations, but since the decrement happens before it is checked as the while loop’s condition, decrementing to 0 would give one fewer iterations) and for each iteration, add 10 to *t*. Now *t* contains 10 times the previous result minus 15.
* Again in a while loop, decrement *\*p* to 0 and for each iteration, add 1 to *t*. After this *t* contains the correct intermediate result so far: the characters `'0'` to `'9'` have ASCII codes 48–57, so after the earlier subtraction of 32 they are 16–25, so we actually add 15–24 to *t*, which cancels with the −15 we set it to earlier. It is also important that this zeroes the cells that used to contain the digit characters so that the subsequent code can recognize the end of the list of words.
* Set *r* to the new intermediate result so that the next iteration finds it in *r*. (Note we do not need to read from *t* again, we can just use the last value from the previous while loop because we know that *\*p* can’t be zero, so it has run at least once.)
Finally, we use another simple while loop (decrementing *t* as the counter) to convert the number we just calculated into unary. We store a string of 1s going leftwards from cell #0. This relies on the fact that cell #1, our running pointer for this (*q*), starts out at 0. We get one fewer 1s because while loops in Unreadable are like that:
[](https://i.stack.imgur.com/tjdr2.png)
After this, we no longer need the value in *r*, so we re-use that cell for something else. We reset the pointers *p* and *q* and initialize some cells with ASCII codes of characters we need later. I’ve also labeled *c* and *s* which we will use later, and we will rely on the fact that *s* starts out at zero:
[](https://i.stack.imgur.com/E6rOa.png)
Hey, wait a minute. Why is cell #0 colored red?... Well, this is to highlight a sneaky trick. Remember we output one 1 too few? The trick is that we use the cell #0 as an “extension” to correct for that. This works because we know that *p* will never be 0. This way, the red block is now 10 cells wide, exactly the number we want. It also saves 9 characters to be able to initialize *q* to 1 instead of 0.
Now we enter the while loop that goes through the words and outputs them all.
Step 1: Find out whether the next word will fit into the current line. We do this by simply moving *p* to the right and *q* left with a while loop until *p* hits the next gap:
[](https://i.stack.imgur.com/X1yA7.png)
Now that *p* is on the *right* of the word, we can check whether this is the last word in the list by checking if *\*(p+1)* is zero. We also store that value (which in our example is 72 because it’s the “h” from “horseradish” minus 32) in *c* because we’ll need it again later. In this case, it isn’t zero, so we will need to output a comma along with the word, so the word is one character longer. Take account of this by decrementing *q* one more time. Finally, use another while loop to move *p* back to the beginning of the word.
[](https://i.stack.imgur.com/2BfHZ.png)
We now know that the word will fit into the current line because *q* is pointing at a non-zero value, so all we have to do is:
* Move *p* forward through the word again, printing each character (plus 32, because all the ASCII codes are off by 32).
* If *c* is non-zero, print a comma (using the value in cell #5).
* Set *s* to a non-zero value to indicate to the next iteration that we are no longer at the beginning of a line and therefore need to output a space character before the next word. (We re-use the return value of the above print statement for this, which is 44 for the comma.)
Output so far: `thyme,`
Then the next iteration of the big loop starts. As before, we check whether the next word fits into the rest of the line by decrementing *q* as we go through the word from left to right. Note that *q* is still −5 from the previous iteration, keeping track of how many characters we’ve already printed in the current line. After counting the characters in “horseradish”, plus one for the comma, plus one because *s* is non-zero indicating that we need to output a space as well, *q* will have overshot the end of the block of 1s:
[](https://i.stack.imgur.com/aquc2.png)
Now *q* points at a zero cell, which means that “horseradish” will not fit into the current line. What we do now depends on whether *s* is non-zero. In our case it is, which means we need to wrap to the next line. All we have to do for that is:
* Print a newline (using cell #3)
* Set *q* back to 1
* Set *s* to 0
Output so far: `thyme,\n`
[](https://i.stack.imgur.com/IveAr.png)
For the next iteration, *p* is in the same place as before, so we will be looking at the same word again. As before, we count the characters in “horseradish”, set *c* to 80 again when we notice there’s another word after this one, decrement *q* for the comma, and rewind *p* back to the beginning of the word:
[](https://i.stack.imgur.com/g9og4.png)
As in the previous iteration, we find that “horseradish” still doesn’t fit because *q* ends up on a cell that is zero. However, this time *s* is zero, which means we do something different than last time. We need to output some of the word, three dots and a comma. Our width is 10, so we need to output 6 characters of the word. Let’s see where we end up if we:
* Find the beginning of the red block of 1s. We can do this by going right because we know that *q* must be left of it.
* Increment *q* once more if we also need to output a comma (*c* ≠ 0).
The tape now looks like this:
[](https://i.stack.imgur.com/r4Pu1.png)
I’ve marked a span of 6 cells here. As you can see, we need to output characters until *q* = −1. This is very code-efficient to check (basically, `while ((++q)+1) { ... }`). So:
* Print those characters (plus 32, because all the ASCII codes are off by 32) until *q* reaches −1. *p* will then be at cell 19, in the middle of the word “horseradish”.
* Print three dots. Since the print command returns its own argument, we can code-efficiently nest it (essentially, `print(print(print('.')))`). We take the ASCII value from cell #5 and add 2 to it to get the ASCII code of the dot.
* Move *p* to the end of the word. Since we know we can’t have already reached the end of the word (because the word was too long, and we had to remove at least 3 characters from it to fit the dots), this loop definitely has at least one iteration, so it’s shorter in code to have the body of the while loop calculate the ASCII value for the dot and then pass the return value of the while loop to the print functions.
* Print a comma if *c* is non-zero.
After all of this, we also print a newline (using cell #3) and set *q* back to 1. We can also set *s* to 0 even though it’s already 0, which makes this the same that we did previously when we wrapped to the next line (when *s* was non-zero), so to avoid repeating the code, we do it after the conditional that checks *s*.
Output so far: `thyme,\nhorser...,\n`
There is only one iteration left. This time, after counting the letters of the word, we get this:
[](https://i.stack.imgur.com/JscpB.png)
This time, there is nothing after *p*, so we set *c* to 0 to indicate “no comma”, and accordingly we do not decrement *q* a further time. Since *q* now points at a non-zero cell, we know the word will fit, so the same code is executed as in the first iteration, except that this time *c* is zero, so it will simply not print the comma.
Output: `thyme,\nhorser...,\npeppermint`
In this walkthrough I did not include a case where the code would actually print a space, but I think it should be fairly clear now. If the code finds that the word fits (*\*q* ≠ 0) and *s* is non-zero, it will simply output a space before the word.
[Answer]
# JavaScript (ES6), 171
As an anonymous function returning the output as an array
(as this is generally allowed unless explicitly forbidden: [meta](http://meta.codegolf.stackexchange.com/a/2422/21348) [meta](http://meta.codegolf.stackexchange.com/a/2456/21348))
```
s=>(s=s.split` `,n=s.pop()-1,t='',o=[],s.map((w,i)=>(w=w[n+=!s[i+1]]?w.slice(0,n-3)+'...':w,(t+w)[n-2]&&(t&&o.push(t.slice(1)),t=''),t+=` ${w},`)),o.push(t.slice(1,-1)),o)
```
```
f=s=>(s=s.split` `,n=s.pop()-1,t='',o=[],s.map((w,i)=>(w=w[n+=!s[i+1]]?w.slice(0,n-3)+'...':w,(t+w)[n-2]&&(t&&o.push(t.slice(1)),t=''),t+=` ${w},`)),o.push(t.slice(1,-1)),o)
// Less golfed
U=s=>(
s=s.split` `,
n=s.pop()-1,
t='', // current line
o=[], // output
s.map( (w,i)=>(
w=w[
n+=!s[i+1] // space for 1 more char on the last line
]?w.slice(0,n-3)+'...':w, // change w if it is too long
(t+w)[n-2]&& ( // if current line + w is too long, ouput t and reset current line
t&&o.push(t.slice(1)),t=''
),
t+=` ${w},`
)),
o.push(t.slice(1,-1)), // remove tailing comma on last line
o
)
console.log=x=>O.textContent+=x+'\n\n';
console.log(f("foo bar baz qux 12").join`\n`)
console.log(f("foo bar baz qux 5").join`\n`)
console.log(f("strength dexterity constitution intelligence wisdom charisma 10").join`\n`)
console.log(f("quas wex exort 4").join`\n`)
```
```
<pre id=O></pre>
```
[Answer]
## Python 2, 206 bytes
```
i=input().split()
l=int(i.pop())
i=[[w[:l-4]+'...',w][len(w)<l]+','for w in i][:-1]+[[w,w[:l-3]+'...'][len(w)>l]]
r=[i.pop(0)]
for w in i:
if len(r[-1])+len(w)<l:r[-1]+=' '+w
else:r+=[w]
print'\n'.join(r)
```
] |
[Question]
[
In this code golf, you will have to determine the direction of the shortest shot that hits exactly **n** cushions before falling into a pocket.
The billiard table is a 6 pocket pool table with the following characteristics:
* Dimensions are variable (**a** x **b**)
* No friction : the ball will roll forever until it falls into a pocket
* Pockets and ball sizes are almost zero. This means that the ball will fall in the pocket only if they have same position.
* The ball is placed at the bottom left hole at the beginning (but doesn't fall in it)

Create a full program or function that takes the dimensions (**a**,**b**) of the table and a the number of cushions to hit **n** as input and returns the angle in degrees of the shortest path hitting exactly **n** cushions before falling into a pocket.
* ***a*** > 0
* ***b*** > 0
* 0 <= ***n*** < 10000000
* 0 < ***alpha*** < 90 (in degrees) precision : at least 10^-6
## examples :
with **a** = 2, **b** = 1, **n** = 1
there are three possible paths : (1) (2) (3) on the following figure.
the number (1) is the shortest so the output should be atan(2) = 63.43494882292201 degrees
[](https://i.stack.imgur.com/VCRHZ.png)
The solution for **a** = 2, **b** = 1, **n** = 4 is atan(4/3) = 53.13010235415598 degrees
[](https://i.stack.imgur.com/uAWAk.png)
## test samples :
```
a = 2, b = 1, n = 1, -> alpha = 63.43494882292201
a = 2, b = 1, n = 2, -> alpha = 71.56505117707799
a = 2, b = 1, n = 3, -> alpha = 75.96375653207353
a = 2, b = 1, n = 4, -> alpha = 53.13010235415598
a = 2, b = 1, n = 5, -> alpha = 59.03624346792648
a = 2, b = 1, n = 6, -> alpha = 81.86989764584403
a = 4.76, b = 3.64, n = 27, -> alpha = 48.503531644784466
a = 2, b = 1, n = 6, -> alpha = 81.86989764584403
a = 8, b = 3, n = 33, -> alpha = 73.24425107080101
a = 43, b = 21, n = 10005, -> alpha = 63.97789961246943
```
This is code/billiard golf : shortest code wins!
[Answer]
## Python 2.7, ~~352~~ ~~344~~ 281 bytes
```
from math import*
def l(a,b,n):
a*=1.;b*=1.
r=set()
for i in range(1,n+3):
t=[]
for k in range(1,i):
for h in[0,.5]:
x=(i-k-h)
if 1-(x/k in r):r.add(x/k);t+=(x*a,k*b),
d=(a*n+1)**2+(b*n+1)**2
for x,y in t:
if x*x+y*y<d:d=x*x+y*y;o=degrees(atan(y/x))
return o
```
* **-16 bytes** thanks to @Dschoni
Explanation: instead calculating the cushions hits, I'm adding n tables and taking the new holes as valid :
[](https://i.stack.imgur.com/IXoMN.png)
Black border/holes is the original, green border/holes is the valid for n=1, red border/holes is the valid for n=2 and so on.
Then I remove the invalid holes (e.g. the blue arrow for n=1). I'll have a list of valid holes and their coordinates, then I calculate their distance from initial point, and then the angle of the smaller distance.
Notes:
~~a=4.76, b=3.64, n=27 - give 52.66286, trying to figure out why~~ fixed, and saved 8 bytes in the process =D
a=43, b=21, n=10005 - takes ~80 seconds (but gives the right angle)
readable version:
```
from math import *
def bill(a,b,n):
a=float(a)
b=float(b)
ratios = set()
for i in range(0,n+2): # Create the new boards
outter = []
j=i+1
for k in range(1,j): # Calculate the new holes for each board
#y=k
for hole_offset in [0,0.5]:
x=(j-k-hole_offset)
if (x/k) not in ratios:
ratios.add(x/k)
outter.append((x*a,k*b))
min_dist = (a*n+1)**2+(b*n+1)**2
for x,y in outter:
if x*x+y*y<min_dist:
min_dist = x*x+y*y
min_alpha=degrees(atan(y/x))
return min_alpha
```
[Answer]
## Haskell, ~~133~~ 117 bytes
This is my implementation:
With a 2x1 table, a path will hit exactly n cushions before going into a pocket if:
(x-1)/2 + (y-1) == n and x,y are mutually primes.
where x,y are the distance of the ball over horizontal/vertical axes.
Paths are the same with arbitrary table size, so we just have to update lengths and angles with (a,b) and keep the shortest.
Path length is sqrt((x\*a/2)^2+(y\*b)^2) and angle is atan((y\*b)/(x\*a/2))
```
z=toEnum
f a b n=minimum[[z x^2+r^2,180/pi*atan(r/z x)]|x<-[1..2*n+2],y<-[n+1-div(x-1)2],r<-[2*b/a*z y],gcd x y<2]!!1
```
] |
[Question]
[
### Background
One-hundred and thirteen years ago, amateur cryptographer Félix Delastelle published his work on the [four-square cipher](https://en.wikipedia.org/wiki/Four-square_cipher), a digraphic substitution cipher that accepts two permutations of a 25-letter alphabet as keys and encodes messages consisting of those letters.
Like most pen-and-paper ciphers, the four-square cipher does not have any cryptographic value today, but at the time of its invention, it had a significant advantage over its monographic counterparts.
One-hundred and thirteen years later, Alice Delastelle decides to improve the four-square cipher by increasing the alphabet's size and the number of keys.[citation needed]
### Key setup
The alphabet contains the following characters (starting with space):
```
!"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ
```
Given a pass phrase, we construct a permutation of this alphabet as follows:
1. Keep only the first occurrence of each character.
2. Append the unused characters from the alphabet, in their natural order.
After turning four pass phrases into four keys, we split each key into a square of side length 7 and arrange the four resulting squares so that they form one big square.
For example, if the pass phrases were
```
PROGRAMMING PUZZLES & CODE GOLF
POPULARITY CONTESTS & CODE BOWLING
CORRECT HORSE BATTERY STAPLE
DON'T TELL EVE!!!
```
the keys would be constructed and arranged like this:
```
PROGAMI POULARI
N UZLES TY CNES
&CDF!"# &DBWG!"
$%'()*+ #$%'()*
,-./:;< +,-./:;
=>?@BHJ <=>?@FH
KQTVWXY JKMQVXZ
CORET H DON'T E
SBAYPL! LV!"#$%
"#$%&'( &()*+,-
)*+,-./ ./:;<=>
:;<=>?@ ?@ABCFG
DFGIJKM HIJKMPQ
NQUVWXZ RSUWXYZ
```
### Encryption
Given a plaintext message such as
```
ALICE LOVES BOB.
```
we append 0 or 1 spaces to make its length even and split it into character pairs:
```
["AL" "IC" "E " "LO" "VE" "S " "BO" "B."]
```
For each character pair, we locate the the first character in the first square (reading order) and the second in the fourth.
Then, we choose the characters in the remaining squares such that the four selected characters form a rectangle whose sides are parallel to the sides of the squares.
Finally, we replace the character pair by the selected characters of the second and third square.
For our example string, this yields
```
["PP" "A@" "E " "YT" "ZE" "EH" "=T" "<-"]
```
resulting in the following ciphertext:
```
PPA@E YTZEEH=T<-
```
### Task
Write a program or function that accepts four pass phrases and a plaintext, uses the above variant of the four-square cipher to encrypt it and returns the resulting ciphertext.
Details:
* The five input strings will consist solely of characters of the mentioned alphabet.
* The five input strings can be read in any order, as such, a single string delimited by newlines or as an array of five strings.
* You may assume that none of the strings is empty.
* The output must be a single string.
If you choose to print the output to STDOUT, you may print only the characters of the ciphertext and (optionally) a trailing newline.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
### Test cases
In all test cases, the first four strings correspond to the key squares in reading order and the last input string to the plaintext.
**Input**
```
PROGRAMMING PUZZLES & CODE GOLF
POPULARITY CONTESTS & CODE BOWLING
CORRECT HORSE BATTERY STAPLE
DON'T TELL EVE!!!
ALICE LOVES BOB.
```
**Output**
```
PPA@E YTZEEH=T<-
```
**Input**
```
!"#$%&'()*+,-./:;<=>
!"#$%&'()*+,-./:;<=>?@ABCDE
!"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKL
!"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRS
HELLO, WORLD!
```
**Output**
```
LALLR)#TROKE !
```
**Input**
```
,'K AB-Q=?@("W$>XM).C#<I:G!OLP*+;SZJTU%NED/&VFHRY
:,-D$C<SU=IYHFVA;! JG/M&L+WT%#.Q@(N*R")EZOBKX?'>P
L()JX,BND?Z<>P*FU%=O@&KIC+A!Y:;$SWHR.EMG'/T"QV #-
<->CI")AP Q:+U;O/F(KH&ER!MW?X'VJLZ#.$,BSGN@TD%*Y=
SPIN THE PPCG WHEEL OF BLAME!
```
**Output**
```
#>TE,VK+,ZQ(&<[[email protected]](/cdn-cgi/l/email-protection)@DM%NAC&>
```
**Input**
```
& %(,-#)$@?/=>'*"<:;!.+
=/$- ?;',@#!(&<")%.:>+*
&%-/<?.;$'#:=!( ,>"+*)@
=,<-*?#.'@/;>%!+:(& ")$
HNRA#JX$H %JAV+"GTS,
```
**Output**
```
GOOD LUCK, HAVE FUN.
```
[Answer]
# Pyth, 74 71 bytes
```
L+%eb7*7/hb7Jcms+oxdN{d--CMr33 91`MTd.z2ssm@VeJ,ydy_dCmxLhdedC,hJ.tcz2d
```
Could probably be optimized a lot. I use a **lot** of zipping.
Takes input in the following order:
```
ALICE LOVES BOB.
PROGRAMMING PUZZLES & CODE GOLF
DON'T TELL EVE!!!
POPULARITY CONTESTS & CODE BOWLING
CORRECT HORSE BATTERY STAPLE
```
[Answer]
# CJam, ~~52~~ ~~50~~ ~~49~~ ~~47~~ ~~46~~ 44 bytes
```
l2/qN/'[,32>A,s-f|2/f{~@S+2<.#_7f%_W%.m.m.=}
```
The input order is lines `5, 2, 3, 1, 4`. [Try it online](http://cjam.aditsu.net/#code=l2%2FqN%2F'%5B%2C32%3EA%2Cs-f%7C2%2Ff%7B~%40S%2B2%3C.%23_7f%25_W%25.m.m.%3D%7D&input=HNRA%23JX%24H%20%25JAV%2B%22GTS%2C%0A%3D%2F%24-%20%3F%3B'%2C%40%23!(%26%3C%22)%25.%3A%3E%2B*%0A%26%25-%2F%3C%3F.%3B%24'%23%3A%3D!(%20%2C%3E%22%2B*)%40%0A%26%20%25(%2C-%23)%24%40%3F%2F%3D%3E'*%22%3C%3A%3B!.%2B%0A%3D%2C%3C-*%3F%23.'%40%2F%3B%3E%25!%2B%3A(%26%20%22)%24).
*(-1 byte thanks to @MartinBüttner, -2 bytes thanks to @Dennis)*
## Explanation
```
l2/ Read the message and split into chunks of 2
qN/ Read rest of input and split by newlines (pass phrases)
'[,32> Generate " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"
A,s- Remove digits 0123456789
f| Setwise OR with each pass phrase to remove duplicates, giving keys
2/ Split keys into two pairs
f{ ... } For each message chunk...
~ Unwrap key pairs
@S+2< Add a space to the message chunk then cap to length 2
.# Find the two chars in keys 1, 4
_7f% Copy indices and perform modulo 7 on both
_W% Copy and reverse
.m.m Vectorised subtraction twice
.= Apply both indices to keys 2, 3
```
For the indices, we want to swap the least significant digits, base 7. For instance, for the first example `AL` are indices `4` and `7` in keys 1 and 4 respectively. In base 7, this is `[0 4]` and `[1 0]`. Swapping the least significant digits gives `[0 0]` and `[1 4]`, i.e. `0` and `11`, and this corresponds to `P` and `P` in keys 2 and 3 respectively.
However, instead of base converting, the code does the following:
```
[4 7] A: Initial indices
[4 0] B: Indices mod 7
[0 4] C: Reverse of B
[4 -4] B-C
[0 11] A-(B-C)
```
[Answer]
# Pyth - 88 86 83 ~~78~~ ~~76~~ ~~75~~ 72 bytes
*8 bytes saved thanks to @orlp*.
Waaay too long, I'm pretty unhappy with this, but just posting it while I look for a better way to handle the squares.
```
Jm+oxdN{d-+d-CMr33 91`MTd.zsms@VtPJ,+*7hKs.DR7xV,hJeJdeK+*7@[[email protected]](/cdn-cgi/l/email-protection)
```
[Try it online here](http://pyth.herokuapp.com/?code=Jm%2BoxdN%7Bd-%2Bd-CMr33+91%60MTd.zsms%40VtPJ%2C%2B*7hKs.DR7xV%2ChJeJdeK%2B*7%40K2%40K1C.tcz2d&input=ALICE+LOVES+BOB.%0APROGRAMMING+PUZZLES+%26+CODE+GOLF%0APOPULARITY+CONTESTS+%26+CODE+BOWLING%0ACORRECT+HORSE+BATTERY+STAPLE%0ADON%27T+TELL+EVE!!!&debug=0).
] |
[Question]
[
### Background
MIDI files are quite different from WAV or MP3 audio files. MP3 and WAV files contain bytes representing a "recording" of the audio, while MIDI files have a series of MIDI messages stored in MIDI events informing a MIDI synthesizer which virtual instrument to play or a MIDI sequencer the playback tempo that should be used. These messages are stored in tracks, and a collection of tracks makes up a MIDI sequence, whose events can be analyzed by a sequencer and have its messages transmitted from the sequencer to a synthesizer's receiver.
Most of the time the MIDI messages stored in MIDI events are Note On messages which tell the synthesizer to play a particular note, or Note Off messages which tell the synthesizer to stop playing the note. These messages contain two data bytes, the first of which informs the synthesizer of the velocity of the note (higher velocity results in a louder note), and the second of which tells the synthesizer the note to play (i.e. Middle C). The events themselves also contain ticks which serve the purpose of telling the sequencer when to send the messages.
### The Challenge
The challenge is to write a full program or a function that analyzes a series of Note On and Note Off MIDI messages in a single-track MIDI sequence and outputs to STDOUT a chart showing when particular notes are on, when they are off, and the velocity of these notes. The vertical axis of the chart represents the note value and should be labeled as described below, and the horizontal axis represents time in MIDI ticks (though it should remain unlabeled to reduce complexity and spacing issues).
Your input may be four separate arrays or lists, each containing a series of integer values; a two-dimensional array or list containing four sub-arrays/sub-lists with a series of integer values; or any other convenient means; this represents the collection MIDI events with Note On and Note Off messages in the track. The values in the first of these arrays specifies the note, the second the velocity, the third the note on event tick, and the fourth the note off event tick. For instance, given four arrays such as these:
```
{60, 62, 64, 65, 67}
{20, 40, 60, 80, 100}
{ 0, 4, 8, 12, 16}
{ 2, 6, 10, 14, 18}
```
Analyzing the first element of each array gives two events: an event at tick 0 with a message that has a Note On command, note 60 (Middle C), and note velocity of 20; and an event at tick 2 with a message that has a Note Off command with the same note and velocity.
### Rules
The chart should feature the numbers 0 through 127 displayed in decreasing order on the left side (representing the note value), when the note starts, the duration of each note (Note Off tick minus Note On tick), and the note's velocity. The symbols representing the notes are dependent on their velocity:
* 0-15: `O`
* 16-31: `=`
* 32-47: `#`
* 48-63: `-`
* 64-79: `@`
* 80-95: `+`
* 96-111: `0`
* 112-127: `*`
You can assume the following:
* The values for note and velocity will be within the range [0, 127].
* The lengths of each of the four arrays will always equal each other.
Here are a few examples:
```
{60, 62, 64, 65, 67}
{20, 40, 60, 80, 100}
{ 0, 4, 8, 12, 16}
{ 2, 6, 10, 14, 18}
127|
126|
125|
...
67 | 00
66 |
65 | ++
64 | --
63 |
62 | ##
61 |
60 |==
59 |
...
2 |
1 |
0 |
{60, 48, 62, 47, 64, 45, 65, 43, 67, 41, 65, 43, 64, 45, 62, 47, 60, 48}
{63, 31, 75, 90, 12, 23, 122, 104, 33, 19, 57, 42, 5, 82, 109, 86, 95, 71}
{0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14, 16, 16}
{2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14, 16, 16, 18, 18}
127|
126|
...
68 |
67 | ##
66 |
65 | ** --
64 | OO OO
63 |
62 | @@ 00
61 |
60 |-- ++
59 |
...
49 |
48 |== @@
47 | ++ ++
46 |
45 | == ++
44 |
43 | 00 ##
42 |
41 | ==
40 |
...
1 |
0 |
```
Here's an example that displays the first few notes of Ode to Joy:
```
{48, 55, 64, 64, 65, 67, 55, 67, 65, 64, 62, 52, 55, 60, 60, 62, 64, 55, 64, 62, 62}
{45, 45, 63, 63, 63, 63, 89, 66, 66, 66, 66, 30, 30, 103, 103, 103, 103, 127, 55, 55, 55}
{ 0, 0, 0, 4, 8, 12, 16, 16, 20, 24, 28, 32, 32, 32, 36, 40, 44, 48, 48, 54, 56}
{16, 16, 2, 6, 10, 14, 32, 18, 22, 26, 30, 48, 48, 34, 38, 42, 46, 64, 50, 55, 64}
127|
...
67 | -- @@
66 |
65 | -- @@
64 |-- -- @@ 00 --
63 |
62 | @@ 00 - --------
61 |
60 | 00 00
59 |
58 |
57 |
56 |
55 |################++++++++++++++++================****************
54 |
53 |
52 | ================
51 |
50 |
49 |
48 |################
...
0 |
```
You can **reduce your score by 25%** if your submission takes an actual MIDI sequence as input, analyzes the Note On and Note Off messages of any track of your choosing provided it contains at least four events with Note On and Note Off messages, and outputs a chart as described above.
This is code golf, so shortest code wins. Good luck!
[Answer]
# [PHP](https://php.net/), 127 + 571 = 698 total score\*
Okay, I'm claiming the bonus. :) This will take a standard MIDI file and display the output.
I've broken up the score above into the main challenge (analyze note on/off and display as chart) and the bonus challenge (read input from standard MIDI) to make scores more comparable.
## Main: 170 bytes - 25% = 127
For the main, the function `$d()` takes the required array and displays the ASCII output. Included are all tests and output of test MIDI file below.
```
$d=function($a){for($l=max($n=$a[0]);$l>=min($n);){$r=' |';foreach($n as$c=>$e)while($e==$l&$a[2][$c]<$a[3][$c])$r[++$a[2][$c]+1]='O=#-@+0*'[$a[1][$c]/16];echo$l--,$r,"
";}}
```
[Try it online!](https://tio.run/##xVZRj9s2DH5ufoXQCru4l8MkWVZkuO72MmAPA9r3ICiCNG0OSJPAl2IDbvfbbyRFKnLurnsZMCCkJYqiqO@j6Ry3x8d3vxy3R7UZhsPwadgcD8Ppdv91aqpO6c/945fv@/Xp9rCf6lV1/@UwTPWu/7b6a6r3vV4tzLLq9O59/@0WHPZVV93rob9Sf1914LpZrbdgVas7ve7f60315/Z2t5nqTd/r3U@w2y0Xer18B6OaRpUeFtfXeeHaLvurD/2bm1@vzdurBdgt2X@2Ydlt1tuD3t3czPQwez153T08PHYTfdrcne5UrxYTRQI6mJkKDsSDNDOlwnw5S0sOljwug0QQa4wswUzBBhXBCpsVHCmbMAT6gqCHjUtYoNXiRB/TqX6eTvZ0MipfgwWs3qZ8aJ49ZAuFkCMDuNTgPgeX1qSMXI1Ph4nA5hpn7Uw1GBgzBM9Ii2CMkG4Lhrktb6dQORbPgjdLKvLlDYsTIHy6t0UMRqCMAgUWivNcIInDgUDQ6QmWiGPTMHvMIKLX8DPIGoRsXLITeqyILTymKRyDk7wRdBREuJQIsIUwltoksaZ@qhznlETCE8YiRTnJnbEAHdgd2GuXhBWC52kbQRpTSTUwaTLqEkZd1CRGQDixPBxnLhFUjfFqHFGh@MAINUaQfq6eqUJLLgR/4YLtNHZSwGdORm9h4de0/BSf//Kc0la8k3mvP/uPzvPjWE/WwvlsfOHIxxd@5uzfxCL/ol6buohRPt1FnGfukO4qRRDBQjJnabAQUGE5tBCnrdNKSw3Bnt2h342V5Y5RVresYgcRKazzJOxs5VgK4ngd@w8f2RZ7zns9B8BtZLX8dIyYVErDSHOro1eT58GmGiakEXX2D4x0Ewska95jUne0JvLlYoaBZwhg5GfL/TePg1zApAnj7sQke0N54aIJ5x86vtAaLtpDlpC@Xd7PLrrDWXLTFAGfOeydh/S9I@EcKU/HuRbCVHsGKV0uKcrYZBVFUfvB/KynhuSzwlXkyGIJs6L7mqzo00K2KApTtphzUvSlTgqdMXFLpd0SbCYrRA5zToo@moQsKcKXwE0qiqpdVkGUN1nRNF6o/DkhJoXCgtEX2Qxn9kgKRks2L1lEEQZHjL7AZmKx4M49Q@oP@SQCL0mNmUXzQz7jiNR/4dP/j3xi9iNFzIJadpOJ/KVV/DdzdQcjVan7ySv9eapPVTd5hX9L1cffP3767cMfMxl0k4fHfwA "PHP – Try It Online")
## Bonus: 761 bytes - 25% = 571
Function `$m()` will load a standard MIDI file (either locally or by URL) and return an array of tracks, each containing an array in the specified note format for all of the MIDI file tracks.
```
$m=function($f){$a=function($f){do$s=($s<<7)+(($c=unpack(C,fread($f,1))[1])&127);while($c&128);return$s;};$r=function($n){foreach($n as$e){if($e[4]==9&&$e[1]>0)foreach($n as$y=>$f)if($f[0]==$e[0]&&($f[4]==8||($f[4]==9&&$f[1]==0))){$o[0][]=$e[0];$o[1][]=$e[1];$o[2][]=$e[2];$o[3][]=$f[2];$n[$y][4]=0;break;}}return$o;};$m=fopen($f,r);while($b=fread($m,8)){$z=unpack(N2,$b)[2];if($b[3]==d){$k=unpack(n3,fread($m,$z))[3]/4;}else{$t=0;$n=[];$d=ftell($m)+$z;while(ftell($m)<$d){$t+=$a($m);if(($e=unpack(C,fread($m,1))[1])==255){fread($m,1);if($w=$a($m))fread($m,$w);}else{if($e>127)list(,$e,$h)=unpack('C*',fread($m,($y=(240&$e)>>4)==12?1:2));else$h=unpack(C,fread($m,1))[1];if($y==9|$y==8)$n[]=[$e,$h,(int)round($t/$k),0,$y];}}if($n)$u[]=$r($n);}}fclose($m);return$u;};
```
[See it online!](https://tio.run/##dVPbbtpAEH3PV6B0hD2xiS@QhmZZUinv7QdYFjJmLbvYu5ZtSgn42@ns1kBaqS@wZzyXM@fs1nl9XrzWeT2ChGc7mXaFkjYkeMxUY0PJq@SXDZJDEvkxMiiXvCooQSLDIzTcGp0sRqkiSXOKjpIWUr4EgUVmg@AcStznRSmoZRTGEaTxgk5Tc0JoIse5fnCCmFvf@afJV8d/sCKKBybuBZ9jJtJcQTmZuNC493f3rO/Z3R1U/HzjnBGhjzsQ3ihouQ3tYvGMjm0TtZ2sk3Rrv7kZUd5Qkhsg0iAcB@EzsoFrSmiOrBHdrpHQsp7RqrfO0qjzYWWBR7NvNIs5/zIe0ymIlz7@nXUgYTIjTEZikjaC/sZjDXXd/HS6HHWLjFpw7iPSWooSo/hPASMUDCgwKBxQaNDUoMwgGcEh1h19tiYmW5Jt2EnpnSqeqVpoqdzmuvuaD9JU7lzPfr9o9i10YY26r15hTYM431DC9pIgp@61FN5J1mnszVgvylYcoSMOdI8iYrXhWSfKktLQgfdh7jW0AN20c@jKaaiH6Zv0r3HVxTjOw6cnMuQWNvz2Qz3eKO1xIGO8WmrDy6LtbBeECzleRlhvD9Ztik222eHMJ09xuZzRuCB8DV5CRKZ7Qf5fZobGgcw86d85khsxj8ws1y5kh43aScrvPNii67tkFfmjiyTCTpvYmHfW91laqlYYNQb7dqw/6weQjPgIKtvKu65uXzxvv98/zqXqRPuYqspr6dWo0quKTeHVRSKVtxaiy9VPIVdqI1adWv1Qh0f6biE7/wY "PHP – Try It Online") *Obviously TIO is sandboxed as to not allow remote requests or local files, so you'll have to run this code locally to see it in action. The first [tests][TIO-jrwa60tu] in the display function includes the array result from the [test MIDI file](https://www.8notes.com/school/midi/piano/beethoven_ode_to_joy.mid).*
### MIDI file load routine ungolfed:
```
$m=fopen($f,'r'); // m = midi file handle
while($b=fread($m,8)){ // read chunk header
$z=unpack('N2',$b)[2]; // z = current chunk size
if($b[3]=='d'){ // is a header chunk?
$k=unpack('n3',fread($m,$z))[3]/4; // k = ticks per quarter note (you can change the 4 to 8 or 16 to "zoom in" so each char represents eights or sixteenth notes)
}else{ // is a track chunk?
$t=0; // track/chunk time offset starts at 0
$d=ftell($m)+$z; // d = end of chunk file pos
while(ftell($m)<$d){ // q = current file pos
$t+=$a($m); // decode var length for event offset and add to current time
if(($e=unpack('C',fread($m,1))[1])==255){ // is a META event
fread($m,1); // read and discard meta event type
if($w=$a($m))
fread($m,$w);
}else{ // is a MIDI event
if($e>127) { // is a new event type
list(,$e,$h)=unpack('C*', // if is a prog change (0x0c), event is 1 byte
fread($m,($y=(240&$e)>>4)==12?1:2)); // otherwise read 2 bytes
} else { // is a MIDI "streaming" event, same type as last
$h=unpack('C',fread($m,1))[1];
}
if($y==9|$y==8) // if is a Note On or Note Off
$n[]=[$e,$h,(int)round($t/$k),0,$y]; // add note to output
}
}
if($n) // if this track has notes,
$u[]=$r($n); // add to array of output tracks ($u)
}
}
fclose($m); // yes, could golf this out and rely on PHP GC to close it
```
A test MIDI file of "Ode to Joy" that can be used [downloaded here](https://www.8notes.com/school/midi/piano/beethoven_ode_to_joy.mid). Example use:
```
$d( $m( 'beethoven_ode_to_joy.mid' )[0] ); // display first track
$d( $m( 'https://www.8notes.com/school/midi/piano/beethoven_ode_to_joy.mid' )[0] );
foreach( $m( 'multi_track_song.mid' ) as $t ) { // display all tracks
$d( $t );
}
```
**"Ode to Joy" [MIDI file](https://www.8notes.com/school/midi/piano/beethoven_ode_to_joy.mid) output**
```
67 | 0000++++ 00000000 00000000
66 |
65 | 0000 ++++ 0000 0000 @@ @@ 0000 ++++
64 |++++++++ ++++ 0000000000 00000000 0000 0000 @@@@ @@ ---- @@ ---- ++++++++++++ ++++ 0000
63 |
62 | ++++ 0000 00++++++++ ++++ 0000 000000 @@@@---- ---- @@@@ ---- ---- ++++ 0000 000000
61 |
60 |++++ ++++0000 0000 ++++0000 ++00000000 ---- ---- ---- 00000000 ++++0000 **** ++00000000
59 | ++++++++
58 | 00000000
57 | ---- ++++++++
56 | --------
55 |++++++++++++++++++++++++00000000000000000000000000000000++++++++00000000000000000000000000000000000000000000000000000000 ---------------------------------------- -------- 0000 ++++++++00000000
54 | ----
53 | ++++++++
52 | 0000000000000000 0000000000000000 ++++0000 00000000
51 |
50 |
49 |
48 |++++++++++++++++ 0000000000000000 0000000000000000 0000000000000000 ++++++++ 00000000
```
**Notes**
In MIDI format, Note On / Note Off events are atomic, meaning that you see a Note On event at a certain time for a given note (say E5), and it's implied that it will play until a Note Off event for another E5 note is seen. As such, it's necessary to analyze the MIDI events and match up a given Note On to it's Note Off, which the code for that is ~~297~~ 184 bytes. Further complicating this, it's fairly common in standard MIDI format to see a subsequent matching Note On with a velocity 0 representing the same thing as a Note Off.
This will now correctly read files that have zero-velocity Note On's instead of Note Off's, so should open most standard files.
**Caveats**
This is by no means a complete implementation of the MIDI format, however I have tested this with a fairly extensive collection of MIDI files and it reads them all nicely.
This submission has not been golfed to an extreme yet, so entirely likely this can be made smaller. I do think it's very unlikely that the 25% score reduction bonus would offset the code needed to read a standard MIDI file. As the (current) smallest submission that just does the ASCII display is ~~106~~ 65 bytes, it would require the MIDI file routines to be implemented in ~~25~~ 21 bytes to beat. I'd challenge anyone to do that (without using a language built-in or module). :)
[Answer]
# Ruby, 106 bytes
This was fun. I'm not sure why no one attempted it.
This function takes input as four array arguments and returns an array of strings, one for each line of the chart.
```
->a,*r{q=(0..z=127).map{|i|"%3d|"%(z-i)+" "*1e4}
a.zip(*r){|n,v,o,f|q[z-n][o+4]="O=#-@+0*"[v/16]*(f-o)}
q}
```
**Note:** This arbitrarily assumes that there will be no more than 10,000 ticks. If you run it in your terminal I suggest piping it to `less` so you can scroll horizontally. You can change `1e4` if you want more ticks, all the way up to `9e9`, but that will take a terabyte or two of RAM.
See it on repl.it: <https://repl.it/Cx4I/1>
[Answer]
# Python 2, ~~163~~ ~~160~~ ~~156~~ 145 bytes
This is not the golfiest way to do it, but it was one of the simplest. If I could figure out how to replace parts of strings without turning them into lists, replacing, and turning them back into strings, that would be very helpful here. Golfing suggestions welcome.
**Edit:** 18 bytes thanks to Leaky Nun. [Try it on Ideone](http://ideone.com/gkQa25)!
```
a=input();z=[" "*max(a[3])]*128
for n,v,b,e in zip(*a):z[n]=z[n][:b]+"O=#-@+0*"[v/16]*(e-b)+z[n][e:]
for i in range(128)[::-1]:print"%3d|"%i+z[i]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 65 bytes
```
®Æ"O=#-@+0*"gXzG
#€Çs ú3 +'|ÃúUmg2 rÔ+5
£VhXÎVgXv)hXÎ+4Xo pXra
Vw
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rsYiTz0jLUArMCoiZ1h6RwojgMdzIPozICsnfMP6VW1nMiBy1Cs1CqNWaFjOVmdYdiloWM4rNFhvIHBYcmEKVnc=&input=W1s2MCwwLDIsMjBdCls2Miw0LDYsNDBdCls2NCw4LDEwLDYwXQpbNjUsMTIsMTQsODBdCls2NywxNiwxOCwxMDBdXQotUg==)
Takes input as a list of notes in the format `[pitch, start_tick, end_tick, velocity]`. If taking input as separate lists is mandatory (i.e. one list containing all the pitches, one containing all the velocities etc.), that can be accomplished at the cost of [1 byte](https://ethproductions.github.io/japt/?v=1.4.6&code=1a7GIk89Iy1AKzAqImdYekcKI4DHcyD6MyArJ3zD+lVtZzIgctQrNQqjVmhYzlZnWHYpaFjOKzRYbyBwWHJhClZ3&input=W1s2MCwgNjIsIDY0LCA2NSwgIDY3XQpbIDAsICA0LCAgOCwgMTIsICAxNl0KWyAyLCAgNiwgMTAsIDE0LCAgMThdClsyMCwgNDAsIDYwLCA4MCwgMTAwXV0KLVI=).
Explanation:
```
®Æ"O=#-@+0*"gXzG #Gets the velocity character to use for each note
® # For each note in the input
Æ # Replace the last item X with:
XzG # Integer divide X by 16
"O=#-@+0*"g # Get the character at that index in the string "O=#-@+0*"
#€Çs ú3 +'|ÃúUmg2 rÔ+5 #Generate the blank chart
#€Ç à # For each number X in the range [0...127]:
s # Turn X into a string
ú3 # Right-pad with spaces until it is 3 characters long
+'| # Add "|" to the end
ú # Right pad each of those with spaces to this length:
Umg2 # Get all the end_tick values
rÔ # Find the largest one
+5 # Add 5
£VhXÎVgXv)hXÎ+4Xo pXra #Put the notes into the chart
£ # For each note:
VgXv) # Get a line from the chart based on the note's pitch
h # Overwrite part of that line:
XÎ+4 # Starting at index start_tick +4
Xo # Overwrite characters with the velocity character
pXra # For the next end_tick - start_tick characters
VhXÎ # Put the modified line back into the chart
Vw #Print the chart
V # Get the chart
w # Reverse it (so 127 is the first line)
# Implicitly print it
```
] |
[Question]
[
Load an image into this stack snippet and move your mouse over it. A black curve that follows the [hue](http://en.wikipedia.org/wiki/Hue) angle, starting at your cursor point, will be drawn:
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><style>canvas{border:1px solid black;}</style>Load an image: <input type='file' onchange='load(this)'><br><br>Max length <input id='length' type='text' value='300'><br><br><div id='coords'></div><br><canvas id='c' width='100' height='100'>Your browser doesn't support the HTML5 canvas tag.</canvas><script>function load(t){if(t.files&&t.files[0]){var e=new FileReader;e.onload=setupImage,e.readAsDataURL(t.files[0])}}function setupImage(t){function e(t){t.attr("width",img.width),t.attr("height",img.height);var e=t[0].getContext("2d");return e.drawImage(img,0,0),e}img=$("<img>").attr("src",t.target.result)[0],ctx=e($("#c")),ctxRead=e($("<canvas>"))}function findPos(t){var e=0,a=0;if(t.offsetParent){do e+=t.offsetLeft,a+=t.offsetTop;while(t=t.offsetParent);return{x:e,y:a}}return void 0}$("#c").mousemove(function(t){function e(t,e){var a=ctxRead.getImageData(t,e,1,1).data,i=a[0]/255,r=a[1]/255,o=a[2]/255;return Math.atan2(Math.sqrt(3)*(r-o),2*i-r-o)}if("undefined"!=typeof img){var a=findPos(this),i=t.pageX-a.x,r=t.pageY-a.y;$("#coords").html("x = "+i.toString()+", y = "+r.toString());var o=parseInt($("#length").val());if(isNaN(o))return void alert("Bad max length!");for(var n=[i],f=[r],h=0;n[h]>=0&&n[h]<this.width&&f[h]>=0&&f[h]<this.height&&o>h;)n.push(n[h]+Math.cos(e(n[h],f[h]))),f.push(f[h]-Math.sin(e(n[h],f[h]))),h++;ctx.clearRect(0,0,this.width,this.height),ctx.drawImage(img,0,0);for(var h=0;h<n.length;h++)ctx.fillRect(Math.floor(n[h]),Math.floor(f[h]),1,1)}});</script>
```
I've only tested this snippet in Google Chrome.
For example, when the cursor is above red, the curve has a 0° slope, but when it's above yellow, it has a 60° slope. The curve continues on for the specified length, continuously changing its slope to match the hue.
Load up this image and when you pan the cursor across it, the line just around the cursor should do a complete counter-clockwise turn:
[](http://en.wikipedia.org/wiki/Hue#/media/File:HueScale.svg)
[This](http://upload.wikimedia.org/wikipedia/commons/7/72/Color_map_fs.png) and [this](http://upload.wikimedia.org/wikipedia/commons/d/d3/Color_complex_plot.jpg) are other neat images to try. (You'll need to save them and then load them with the snippet. They can't be directly linked due to cross-origin constraints.)
Here is a non-minified version of the snippet:
```
function load(i) { //thanks http://jsfiddle.net/vacidesign/ja0tyj0f/
if (i.files && i.files[0]) {
var r = new FileReader()
r.onload = setupImage
r.readAsDataURL(i.files[0])
}
}
function setupImage(e) {
img = $('<img>').attr('src', e.target.result)[0]
function setup(c) {
c.attr('width', img.width)
c.attr('height', img.height)
var ctx = c[0].getContext('2d')
ctx.drawImage(img, 0, 0)
return ctx
}
ctx = setup($('#c'))
ctxRead = setup($('<canvas>'))
}
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
$('#c').mousemove(function(e) { //thanks http://stackoverflow.com/a/6736135/3823976
if (typeof img === 'undefined') return
var pos = findPos(this)
var x = e.pageX - pos.x
var y = e.pageY - pos.y
$('#coords').html('x = ' + x.toString() + ', y = ' + y.toString())
var maxLength = parseInt($('#length').val())
if (isNaN(maxLength)) {
alert('Bad max length!')
return
}
function hue(x, y) {
var rgb = ctxRead.getImageData(x, y, 1, 1).data
var r = rgb[0] / 255, g = rgb[1] / 255, b = rgb[2] / 255
return Math.atan2(Math.sqrt(3) * (g - b), 2 * r - g - b)
}
//gather points
var xs = [x], ys = [y]
var i = 0
while (xs[i] >= 0 && xs[i] < this.width && ys[i] >= 0 && ys[i] < this.height && i < maxLength) {
xs.push(xs[i] + Math.cos(hue(xs[i], ys[i])))
ys.push(ys[i] - Math.sin(hue(xs[i], ys[i])))
i++
}
//draw stuff
ctx.clearRect(0, 0, this.width, this.height)
ctx.drawImage(img, 0, 0)
for (var i = 0; i < xs.length; i++)
ctx.fillRect(Math.floor(xs[i]), Math.floor(ys[i]), 1, 1) //not using strokes because they may be anti-aliased
})
```
```
canvas {
border:1px solid black;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Load an image: <input type='file' onchange='load(this)'>
<br><br>
Max length <input id='length' type='text' value='300'>
<br><br>
<div id='coords'></div>
<br>
<canvas id='c' width='100' height='100'>Your browser doesn't support the HTML5 canvas tag.</canvas>
```
# Challenge
Write a program that does what the snippet is doing, just not interactively. Take an image and an (x, y) coordinate in the bounds of image, and a maximum curve length. Output the same image with the added black curve that follows the hue angles starting at (x, y) and ends when it reached the maximum length or hits an image boundary.
Specifically, start the curve at (x, y) and measure the hue angle there. Go one unit (one pixel's width) in that direction, **noting that your new position is most likely not an integer coordinate**. Mark another point on the curve and move again, using the hue from the closest pixel (using something like `floor` or `round`, I won't be checking this precisely). Continue on like this until the curve goes out of bounds or it exceeds the maximum length. To finish, plot all the curve points as single black pixels (again, use nearest pixels) overlayed on the image, and output this new image.
The "hue angle" is just the [hue](http://en.wikipedia.org/wiki/Hue):
```
hue = atan2(sqrt(3) * (G - B), 2 * R - G - B)
```
Note that for grayscale values that don't technically have a hue, this returns 0, but that's fine.
(This formula uses [`atan2`](http://en.wikipedia.org/wiki/Atan2) which most built-in math libraries have. R, G, B are from 0 to 1, not 0 to 255.)
* You can use any common lossless image file format as well as any image libraries.
* Take input from stdin or the command line, or write a function with arguments for the image file name, x and y, and the max length.
* The max length and x and y are always nonnegative integers. You can assume x and y are in range.
* Save the output image with a name of your choice or simply display it.
* Your implementation does not have to exactly match the snippet. A few pixels in slightly different places due to a slightly different rounding/calculation method is fine. (In chaotic cases this could lead to curves that end up majorly different, but as long as they look correct visually, it's fine.)
# Scoring
The smallest submission [in bytes](https://mothereff.in/byte-counter) wins.
[Answer]
# C with SDL, ~~549~~ 516 bytes
I'll start this party! For some reason, I felt like trying my hand at golf tonight. What you guys do is hard... If there's one thing I don't see any of on this site, it's SDL. I may have just found out why. This particular snippet complies with both SDL2 and SDL1.2, but is atrocious. Called like `f("imagename.bmp", xcoord, ycoord, max_length);`. It saves a file with the same name as given in the arguments. Output seems to be very similar to the OP's code snippet, but "fuzzier." I may try to fix this up a bit later.
```
#include"SDL.h"
f(char*C,x,y,m){SDL_Surface*P=SDL_LoadBMP(C);int p=P->pitch,i=P->format->BytesPerPixel,q=0;double X=x,Y=y,f=255,R,G,B,h;Uint8*Q,d=1,r,g,b,k;while(d){Q=P->pixels+y*p+i*x;SDL_GetRGB(i==4?*(Uint32*)Q:i==3?SDL_BYTEORDER==4321?*Q<<16|Q[1]<<8|Q[2]:*Q|Q[1]<<8|Q[2]<<16:i==2?*(Uint16*)Q:*Q,P->format,&r,&g,&b);R=r/f;G=g/f;B=b/f;h=atan2(sqrt(3)*(G-B),2*R-G-B);for(k=0;k<i;k++)Q[k]=0;X+=cos(h);Y-=sin(h);if((int)X-x|(int)Y-y)q++;x=X;y=Y;d=x<0|x>=P->w|y<0|y>=P->h|q>=m?0:1;}SDL_SaveBMP(P,C);SDL_FreeSurface(P);}
```
Here it is all unraveled:
```
#include"SDL.h"
f(char*C,x,y,m){
SDL_Surface*P=SDL_LoadBMP(C);
int p=P->pitch,i=P->format->BytesPerPixel,q=0;
double X=x,Y=y,f=255,R,G,B,h;
Uint8*Q,d=1,r,g,b,k;
while(d){
Q=P->pixels+y*p+i*x;
SDL_GetRGB(i==4?*(Uint32*)Q:i==3?SDL_BYTEORDER==4321?*Q<<16|Q[1]<<8|Q[2]:*Q|Q[1]<<8|Q[2]<<16:i==2?*(Uint16*)Q:*Q,P->format,&r,&g,&b);
R=r/f;
G=g/f;
B=b/f;
h=atan2(sqrt(3)*(G-B),2*R-G-B);
for(k=0;k<i;k++)Q[k]=0;
X+=cos(h);
Y-=sin(h);
if((int)X-x|(int)Y-y)q++;
x=X;y=Y;
d=x<0|x>=P->w|y<0|y>=P->h|q>=m?0:1;
}
SDL_SaveBMP(P,C);
SDL_FreeSurface(P);
}
```
I should note that care was taken to make it cross platform--in the interest of honesty, it didn't feel good to hardcode it for my machine, even if it cut off a substantial number of bytes. Still, I feel like a couple things are superfluous here, and I'll look at it again later.
EDIT-------
This IS Graphical Output, after all...
I'll update with images that I find interesting periodically.
`f("HueTest1.bmp", 270, 40, 200);`

`f("HueTest2.bmp", 50, 50, 200);`

`f("HueTest3.bmp", 400, 400, 300);`

[Answer]
## Python, ~~203~~ 172
```
from scipy.misc import*
def f(i,x,y,l):
a=imread(i);Y,X,_=a.shape;o=a.copy()
while(X>x>0<y<Y<[]>l>0):r,g,b=a[y,x]/255.;o[y,x]=0;l-=1;x+=2*r-g-b;y-=3**.5*(g-b);imsave(i,o)
```
Sample output:

Call with `f("image.jpg", 400, 400, 300)`
I've wasted a lot of characters for the import, if anyone has suggestions to improve it. May not work in 3.0
[Answer]
# MATLAB, ~~186~~ 172
The game is **on**! Call as `t('YourImage.ext',123,456,100')`, for an image of any type MATLAB supports, starting at (x,y)=(123,456) and maximum length 100. Initial positions cannot be *exactly* at the right and bottom edges (that would cost me two bytes), so to start on the edge, use something like `x=799.99` to start at `x=800`. Indexing starts at 1, not 0.
Code:
```
function t(g,x,y,l)
m=imread(g);[Y,X,~]=size(m);h=2*pi*rgb2hsv(m);while(x>0&x<X&y>0&y<Y&l)
p=ceil(x);q=ceil(y);m(q,p,:)=0;a=h(q,p);x=x+cos(a);y=y-sin(a);l=l-1;end
imshow(m)
```
Revisions:
* Changed from line from previous to next pixel to just putting a dot at a pixel, since the line will never be longer than a pixel! ~~Still using `line` since that is the shortest code I know to produce a pixel.~~
* Changed the color from black to blue, using `Co` to expand to `Color` (which MATLAB does automatically)
* Changed order of calculating next position and drawing a point, since I realized thanks to @grovesNL that I was actually drawing out of bounds since I was checking bounds *after* changing the position.
* Changed from drawing lines to setting rgb matrix to 0 and displaying after.

[Answer]
# MATLAB, 136
```
function t(g,x,y,l)
m=imread(g);imshow(m); h=2*pi*rgb2hsv(m);h=h(:,:,1);s=streamline(cos(h),-sin(h),x,y,[1,l]);set(s,'LineW',1,'Co','k');
```
Copied most of the setup and such from @sanchises, but I instead use `streamline` to compute and draw the path. It does antialias the line though, and uses bilinear interpolation, rather than nearest-neighbor as specified.
[Answer]
## Processing, 323 characters
```
void h(String f,float x,float y,float m){PImage i=loadImage(f);PImage i2=loadImage(f);while(m>0){color c=i.get((int)x,(int)y);float r=red(c)/255;float g=green(c)/255;float b=blue(c)/255;float h=atan2(sqrt(3)*(g-b),2*r-g-b);float dx=cos(h);float dy=-sin(h);m-=1;x+=dx;y+=dy;i2.set((int)x,(int)y,color(0));}i2.save("o.png");}
```
With whitespace:
```
void h(String f, float x, float y, float m) {
PImage i = loadImage(f);
PImage i2 = loadImage(f);
while (m > 0) {
color c = i.get((int)x, (int)y);
float r = red(c)/255;
float g = green(c)/255;
float b = blue(c)/255;
float h = atan2(sqrt(3) * (g - b), 2 * r - g - b);
float dx = cos(h);
float dy = -sin(h);
m-= 1;
x += dx;
y += dy;
i2.set((int)x, (int)y, color(0));
}
i2.save("o.png");
}
```

I'm sure I could shorten this further, but it works for now.
[Answer]
# JavaScript 414
```
function P(G,x,y,l){
I=new Image()
I.onload=function(){d=document,M=Math,C=d.createElement('canvas')
d.body.appendChild(C)
w=C.width=I.width,h=C.height=I.height,X=C.getContext('2d')
X.drawImage(I,0,0)
D=X.getImageData(0,0,w,h),d=D.data,m=255,i=0
for(;l--;i=(w*~~y+~~x)*4,r=d[i]/m,g=d[i+1]/m,b=d[i+2]/m,H=M.atan2(M.sqrt(3)*(g-b),2*r-g-b),d[i]=d[i+1]=d[i+2]=0,x+=M.cos(H),y-=M.sin(H))
X.putImageData(D,0,0)}
I.src=G}
```
] |
[Question]
[
Prior to the discovery of fingerprints and DNA testing, the British police used an anthropometric system to identify repeat offenders. Certain parts of the bodies of criminals were measured and stored in records -- these parts of the body were assumed to not change in size after adulthood. This system was known as *bertillonnage*.
The diagram below shows a filing system used by the police to access these records quickly.

*Diagram 1: A filing system with numbered drawers.*
Note: if you cannot see the image, try the [imgur mirror](https://i.stack.imgur.com/sbWEf.png) or [compile it yourself](http://pastebin.com/qwEUzJkv).
The filing cabinet consists of 81 numbered drawers. Each drawer contains cards, and each card has measurements of particular parts of a criminal's body:
* The length of their head (`H`)
* The breadth of their head (`B`)
* The width of their right ear (`E`)
* The length of their index finger (`F`)
Each measurement is classified as either small, medium or large.
For example, drawer 56 contains cards with the following characteristics: small H, large B, medium E, and small F. This can be notated using the letters `S`, `M`, and `L` in place of small, medium, and large:
```
SH,LB,ME,SF
```
Note that the size letter goes first, then what the measurement is. In addition, an exclamation point `!` may be placed in front to cause a negative:
```
!SH,LB,!ME,SF
```
This indicates cards that have the following characteristics: *not* small H, large B, *not* medium E, and small F. There are four drawers that contain cards with these characteristics -- 58, 60, 61, and 63.
Your task is to write a program, that, when given a string notating some characteristics, outputs all of the drawers that contain cards with those characteristics. If there are no drawers that contain cards with the given characteristics, output `0`.
Here are some sample inputs and outputs.
1. Input: `SH,LB,ME,SF`
Output: `56`
2. Input: `!SH,LB,!ME,SF`
Output: `58,60,61,63`
3. Input: `SB,!MF,!LF`
Output: `1,2,3,4,5,6,7,8,9`
4. Input: `MH,!MH`
Output: `0`
This is code golf, so the shortest entry wins. Ask questions in the comments if the specification is not clear.
[Answer]
## Ruby 1.9.3 - ~~173 157~~ 143
```
x=(1..81).select{|j|$*[0].split(?,).all?{|y|i=j-1
z='SML'
[z[i%9/3]+?H,z[i%3]+?E,z[i/27]+?B,z[i/9%3]+?F].member?(y[-2,2])^y[?!]}}
p x==[]?[0]:x
```
Edit:
* applied [Three If By Whiskey](https://codegolf.stackexchange.com/users/30851/three-if-by-whiskey)'s tips.
* taken parameters from the command line to save some more chars
Online demo: <http://ideone.com/lodTLt>
[Answer]
# Scala - 951
Definitely won't win this one, mainly due to the names of built in functions I think.
```
def m(a: List[Int]) = 0 to 8 flatMap (x => a map (_ + 9*x)) toSet
var SH = m(List(1,2,3))
var MH = m(List(4,5,6))
var LH = m(List(7,8,9))
var SE = m(List(1,4,7))
var ME = m(List(2,5,8))
var LE = m(List(3,6,9))
var SB = 1 to 27 toSet
var MB = 28 to 54 toSet
var LB = 55 to 81 toSet
def l(a: List[Int]) = 0 to 2 flatMap (x => a map (_+27*x)) toSet
var SF = l(1 to 9 toList)
var MF = l(10 to 18 toList)
var LF = l(19 to 27 toList)
var j = Map(("LH",LH),("MH",MH),("SH",SH),("LB",LB),("MB",MB),("SB",SB),("LF",LF),("MF",MF),("SF",SF),("LE",LE),("ME",ME),("SE",SE))
def f(x : String) = {
def h(i : List[String], k : Set[Int]) : Set[Int] = {
if(i isEmpty) k
else if(i.head.startsWith("!")) h(i.tail, k filterNot (j(i.head.replace("!","")) contains _))
else h(i.tail, k intersect j(i.head))
}
h(x split "," toList, 1 to 81 toSet) mkString ","
}
```
Argument is passed into the function `f`
`f("SH,LB,ME,SF")` = `56`
[Answer]
# T-SQL - ~~547~~ 544
Not a winning entry, but suited to this type of problem.
## Grid Table Setup - 254
```
SELECT ROW_NUMBER()OVER(ORDER BY (SELECT $))I,LEFT(Z,1)E,RIGHT(Z,1)H,LEFT(Y,1)F,RIGHT(Y,1)B INTO G FROM(VALUES('SS'),('MS'),('LS'),('SM'),('MM'),('LM'),('SL'),('ML'),('LL'))FB(Y),(VALUES('SS'),('MS'),('LS'),('SM'),('MM'),('LM'),('SL'),('ML'),('LL'))EH(Z)
```
## Query - ~~293~~ 290
```
DECLARE @S CHAR(400)='SELECT ISNULL(SUBSTRING(O,2,99),0)FROM (SELECT CONCAT('','',I)FROM G WHERE '+REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REVERSE(@i),',',' AND '),'S!','!S'),'M!','!M'),'L!','!L'),'S','=''S'''),'M','=''M'''),'L','=''L''')+' FOR XML PATH(''''))O(O)';EXEC(@S)
```
Input is done by declaring @i before the query
```
DECLARE @I VARCHAR(50) = 'SB,!MF,!LF';
```
I could save a further 89 characters if the output doesn't have to be comma delimited row
```
DECLARE @S CHAR(400)='SELECT I FROM G WHERE '+REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REVERSE(@i),',',' AND '),'S!','!S'),'M!','!M'),'L!','!L'),'S','=''S'''),'M','=''M'''),'L','=''L''')
```
[Answer]
## GolfScript 95 ([DEMO](http://golfscript.apphb.com/?c=OychU0gsTEIsIU1FLFNGJwoKJywnLzpyOzgxLHtyezEkW1suOSUzL1wuMyVcLjI3L1w5LzMlXXsnU01MJz19JSdIRUJGJ116aXB7JycrfSVcLiwzPVwxJHsoO30qQD8pISE9fSwhXDt9LHspfSUwb3JgCg%3D%3D&run=true))
```
','/:r;81,{r{1$[[.9%3/\.3%\.27/\9/3%]{'SML'=}%'HEBF']zip{''+}%\.,3=\1${(;}*@?)!!=},!\;},{)}%0or
```
[Answer]
# Mathematica ~~191~~ 235
Represents each cell number in base 3. Each digit position represents a bodily feature. The value of the digit, {0,1,2}, represents "Small","Medium","Large", respectively.
The features correspond to the digits as follows:
>
> {"breadthOfHead", "IndexFingerLength", "LengthOfHead", "WidthOfRightEar"}
>
>
>
For example, the input,
```
{"SH","LB","ME","SF"}
```
signifies:
>
> "LB" implies breadthOfHead = 2 (large)
>
>
> "SF" implies IndexFingerLength = 0 (small)
>
>
> "SH" implies LengthOfHead = 0 (small)
>
>
> "ME" implies WidthOfRightEar = 1 (medium)
>
>
>
`2001`in base 3 is 55 in base 10.
We need to add one because we are counting cells from 1, not zero.
---
## Code
```
c=Characters;t=Table[IntegerDigits[k,3,4],{k,0,80}];
f@i_:=1+FromDigits[#,3]&/@Intersection@@(Cases[t,#]&/@(ReplacePart[{_,_,_,_},{#}]&/@(c/@i
/.Thread[c@"BFHESML"-> {1,2,3,4,0,1,2}]/.{{"!",v_,n_}:> (n-> Except[v]),{v_Integer,n_}:> n-> v})))
/.{}:>0
```
---
## Test Cases
```
f[{"SH","LB","ME","SF"}]
```
>
> {56}
>
>
>
---
```
f[{"!SH","LB","!ME","SF"}]
```
>
> {58, 60, 61, 63}
>
>
>
---
```
f[{"SB","!MF","!LF"}]
```
>
> {1, 2, 3, 4, 5, 6, 7, 8, 9}
>
>
>
---
```
f[{"MH","!MH"}]
```
>
> 0
>
>
>
[Answer]
# Python 3 - 192 - [Try it!](http://ideone.com/aILs8y)
```
from itertools import*
S=input().split(',')
print([i+1for i in range(81)if eval('*'.join('(list(product(*["SML"]*4))[i][%d]%s="%s")'%('BFHE'.find(s[-1]),'!='[s[0]>'!'],s[-2])for s in S))]or 0)
```
[Answer]
# Python 2 - 194
```
from itertools import*
n=map(set,['012']*4)
for x in raw_input().split(','):n['BFHE'.find(x[-1])]&=set(`'SML'.find(x[-2])`)^set('012'*(x<'"'))
print[1+int(''.join(x),3)for x in product(*n)]or[0]
```
Output has brackets, and don't care about order of output
Some suggestions from Falko, and a couple from myself to take off 10 chars.
] |
[Question]
[
As you may know, hackers are everywhere and they want to hack everything. You were asked to make [password requirements which will stop any hacker](http://thedailywtf.com/Articles/Security-by-PostIt.aspx). The problem is, that your boss has heard that paying for LOC is evil and he pays you $1800 - $0.03 \* characters inserted per month to make you write simplest thing which possibly could work. So, you have to use small number of characters (hopefully very small), or otherwise forget about cash. Also, your boss doesn't care what language you will use.
The requirements for good passwords are similar to those in mentioned article, except the dictionary based requirements were removed to avoid making solution depend on external files, you don't have to check for letters being rearranged (Hard to understand what it actually means), last rule is removed (What is 3/4?) and it doesn't check old passwords.
The exact requirements after removing certain requirements from linked article are:
* have at least 8 character(s)!
* not be longer than 12 characters!
* have upper and lower case characters!
* have no more than 8 upper-case letter(s)!
* have no more than 8 lower-case letter(s)!
* have at least 2 letter(s)!
* have a leading letter!
* have at least 1 digit(s)!
* not be your username!
* not be your username backwards!
* not contain your username!
* not contain your username backwards!
* have no more than 1 pair(s) of repeating characters!
* not have 3 *occurences* of the same character!
* not contain *carat* (^)
* not contain space
* not contain =
* not *conatain* &
* not contain #
* not contain ,
* not *conatain* ;
* not contain "
* not contain >
* not contain <
* not contain [
* not contain |
* not contain )
All misspellings on this list were left as is.
```
$ ./checkpass
Username: John
Password: L!]E2m69
OK.
$ ./checkpass
Username: John
Password: JohnnhoJ12
Nope.
$ ./checkpass
Username: JOE.smith
Password: JOE!smith123
OK.
```
The shortest code wins money (sent as JPG file). It has to show "Username: " and "Password: " prompts and reply with exact message.
[Answer]
## Perl, 203 194 189 193 chars
Here's my Perl take on the problem:
```
print"Username: ";chop($u=<>);$n=reverse$u;print"Password: ";$_=<>;
say/^\pL.{7,11}$/*/\d/*/[A-Z]/*9>y/A-Z//&y/a-z//<9*/[a-z]/*
!/[" #,;->^&[|)]|(.)(.*\1.*\1|\1.*(.)\3)|\Q$u\E|\Q$n/?"OK.":"Nope."
```
The regexes check, in order, that the password:
* starts with a letter, has eight to twelve characters
* contains a digit
* contains an uppercase letter
* has eight or fewer uppercase letters
* has eight or fewer lowercase letters
* contains a lowercase letter
* does not contain any of the forbidden punctuation marks, three occurrences of any character, more than one occurrence of a doubled character, the username, or the username reversed.
(Thanks to Peter Taylor for pointing out a bug in the 189-char version.)
[Answer]
### Ruby, 270 characters
```
$><<"Username: ";u=gets.chop
$><<"Password: ";gets
puts ('^.{8,12}$+\p{Lower}+\p{Upper}+^(\p{Alpha}.*){2}+\d+(\p{Lower}.*){9}+(\p{Upper}.*){9}+(.)\1.*(.)\2+(.).*\1.*\1+[ ^=&#,;"<>\[|)]+'+u+?++u.reverse).split(?+).map{|r|/#{r}/=~$_??A:?B}*""=="AAAAABBBBBBB"?"OK.":"Nope."
```
A ruby implementation build on twelve regular expressions. Each expression is either a positive match (first five) or a negative one (latter seven). As a restriction the username may only contain letters or digits.
Positive regular expression matches:
* `/^.{8,12}$/`: have at least 8 character(s)!, not be longer than 12 characters!
* `/\p{Lower}/` and `/\p{Upper}/`: have upper and lower case characters!
* `/^(\p{Alpha}.*){2}/`: have at least 2 letter(s)!, have a leading letter!
* `/\d/`: have at least 1 digit(s)!
Negative regular expression matches:
* `/(\p{Lower}.*){9}/`: have no more than 8 lower-case letter(s)!
* `/(\p{Upper}.*){9}/`: have no more than 8 upper-case letter(s)!
* `/(.)\1.*(.)\2/`: have no more than 1 pair(s) of repeating characters!
* `/(.).*\1.*\1/`: not have 3 occurences of the same character!
* `/[ ^=&#,;"<>\[|)]/`: not contain caret, space, =, &, #, ,, ;, ", >, <, [, |, )
* `/#{u}/`: not be your username!, not contain your username!
* `/#{u.reverse}/`: not be your username backwards!, not contain your username backwards!
[Answer]
## Python 3, 291 bytes/characters
```
from re import*
n,p=map(input,["Username: ","Password: "])
c,U,L=lambda x:len(split("[%s]"%x,p)),"A-Z","a-z"
print(["OK.","Nope."][any([8>len(p)>12,2>c(U)>9,2>c(L)>9,3>c(U+L),match(U+L,p),2>c("0-9"),n in p,n[::-1]in p,any(c(x)>3 for x in p),len(findall("(.)\\1",p))>1,c(' ^=&#,;"><[|)')>1])])
```
More nicely formatted and commented:
```
# import all elements from the regular expression module
from re import *
# Get the two lines of user input (username `n`, password `p`):
n, p = map(input, ["Username: ","Password: "])
# Assign some internally useful shortcuts (uppercase letters `U`, lowercase letters `L`):
# `c(x)` counts the occurrences of pattern `x` in the password `p` plus 1
c, U, L = lambda x: len(split("[%s]" % x, p)), "A-Z", "a-z"
# Print the test result: `"OK."` if the `any(...)` function returned `False`, else `"Nope."`.
# The `any(...)` combines the result of all enclosed checks and returns `True` if at least
# one of the checks failed (returned `True`).
print(["OK.", "Nope."][any([ # vvv--- CHECKS: ---vvv
8>len(p)>12, # password length 8-12
2>c(U)>9, # 1-8 uppercase letters
2>c(L)>9, # 1-8 lowercase letters
3>c(U+L), # at least 2 letters
match(U+L,p), # starts with a letter
2>c("0-9"), # at least 1 digit
n in p, # username is not (in) the pw.
n[::-1]in p, # reversed name not (in) the pw.
any(c(x)>3 for x in p), # at most 3 same characters
len(findall("(.)\\1",p))>1, # at most 1 pair (e.g. "AA")
c(' ^=&#,;"><[|)')>1]) # does not contain special char.
])
```
You can find [this solution on ideone.com](http://ideone.com/2oSeu1), but the output looks a bit ugly because it does not show the predefined input or even line breaks there. Also, the username-password combination `"JOE.smith"`-`"JOE!smith123"` is currently entered as fixed input data.
I added a breakdown of all the checks as debug output though.
] |
[Question]
[
[Carcassonne](https://en.wikipedia.org/wiki/Carcassonne_(board_game)) is a tile-based game, where the objective is to construct Roads, Cities and Monasteries, in order to score points. The game works by players taking turns to draw and place tiles to construct a landscape, then claiming roads, cities and monasteries. An example landscape is:
[](https://i.stack.imgur.com/jcVxG.jpg)
There are \$19\$ distinct tiles (ignoring rotations), each of which contains at least one feature (Road, City or Monastery):
[](https://i.stack.imgur.com/QMtF8.jpg)
Also, notice that the landscape must be consistent. This means that roads must connect to other roads, city edges must connect to other city edges and fields must connect to fields. Therefore, these tiles are inconsistent:
[](https://i.stack.imgur.com/e2Vt3.jpg)
To avoid this challenge being about image processing, we can translate each tile into a list containing \$5\$ values, according to this legend:
```
[North edge, East edge, South edge, West Edge, # of cities]
0: Field
1: Road
2: City
```
For instance, [this](https://i.stack.imgur.com/ygJCI.jpg) tile can be described as `[2, 0, 1, 1, 1]`. Using this legend, we can describe each tile uniquely, and it's rotations are rotations of the first four elements. The entire grid can be described as a rectangular matrix, with a \$20^\text{th}\$ distinct value for an empty square. Translating the first landscape into this format, we get:
```
[
[ [], [], [1, 1, 0, 0, 0], [1, 1, 2, 1, 1], [0, 1, 0, 1, 0], [], []],
[[1, 0, 1, 0, 0], [], [0, 0, 0, 0, 0], [2, 0, 2, 0, 2], [], [0, 2, 2, 2, 1], [0, 0, 0, 2, 1]],
[[1, 1, 0, 1, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0], [2, 2, 0, 0, 1], [2, 2, 0, 2, 1], [2, 0, 0, 2, 1], []]
]
```
using `[]` to represent an empty square. The complete list of tiles (ignoring rotations) in the same grid as the second image is
```
[1, 0, 1, 0, 0] [0, 0, 1, 1, 0] [2, 1, 1, 1, 1] [0, 1, 1, 1, 0] [2, 0, 0, 0, 1]
[2, 2, 0, 2, 1] [0, 0, 0, 0, 0] [2, 2, 2, 2, 1] [2, 2, 0, 0, 1] [2, 1, 1, 2, 1]
[2, 2, 0, 0, 2] [0, 0, 1, 0, 0] [2, 0, 1, 1, 1] [2, 1, 1, 0, 1] [0, 2, 0, 2, 1]
[1, 1, 1, 1, 0] [2, 1, 0, 1, 1] [2, 2, 1, 2, 1] [2, 0, 2, 0, 2]
```
---
Your task is to take in a rectangular matrix where every element save one is one of the 19 tiles given above or one of their rotations. Tiles can appear more than once, and not every tile will appear in every input. This landscape will be consistent, as defined above. You should take in this input and output the tile that could fill the empty space in the array, keeping the landscape consistent, as defined above. You may output the tile in any rotation.
As the number of cities on a tile is redundant for this task, you may choose instead to only work with 17 tiles (as 2 tiles are duplicated when ignoring cities) and take input as lists in the form `[N, E, S, W]` instead, giving this list of tiles
```
[1, 0, 1, 0] [0, 0, 1, 1] [2, 1, 1, 1] [0, 1, 1, 1] [2, 0, 0, 0] [2, 2, 0, 2]
[0, 0, 0, 0] [2, 2, 2, 2] [2, 2, 0, 0] [2, 1, 1, 2] [0, 0, 1, 0] [2, 0, 1, 1]
[2, 1, 1, 0] [0, 2, 0, 2] [1, 1, 1, 1] [2, 1, 0, 1] [2, 2, 1, 2]
```
If there are multiple tiles that would work, you may output any number of valid tiles. If no such tile exists, you may produce any output/result that could not be construed as a tile (i.e. it's not in the 19 tiles specified above, nor in any of their rotations). The representation of the "empty space" in the input may be your choice, so long as its consistent, and (although I'm not sure why you would) it isn't one of the 19 tiles above or their rotations, and there will only ever be a single empty space.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
Landscape -> Potential tiles
[[[]]] -> Any tile
[[[0, 0, 0, 0, 0], []]] -> [1, 0, 1, 0, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [2, 0, 0, 0, 1], [2, 2, 0, 2, 1], [0, 0, 0, 0, 0], [2, 2, 0, 0, 1], [2, 2, 0, 0, 2], [0, 0, 1, 0, 0], [2, 0, 1, 1, 1], [2, 1, 1, 0, 1], [0, 2, 0, 2, 1], [2, 1, 0, 1, 1], [2, 0, 2, 0, 2]
[[[], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]] -> [0, 0, 1, 1, 0], [1, 0, 1, 0, 0], [2, 1, 1, 2, 1], [2, 1, 0, 1, 1], [0, 1, 1, 1, 0], [2, 0, 1, 1, 1], [2, 1, 1, 1, 1], [2, 1, 1, 0, 1], [2, 2, 1, 2, 1], [0, 0, 1, 0, 0], [1, 1, 1, 1, 0]
[[0, 1, 0, 1, 0], [], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] -> [1, 0, 1, 0, 0], [2, 1, 0, 1, 1], [0, 1, 1, 1, 0], [2, 1, 1, 1, 1], [1, 1, 1, 1, 0]
[[[0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 1, 0]], [[1, 1, 0, 0, 0], [0, 1, 0, 1, 0], []]] -> [0, 0, 1, 1, 0], [2, 1, 1, 2, 1], [0, 1, 1, 1, 0], [2, 0, 1, 1, 1], [2, 1, 1, 1, 1], [2, 1, 1, 0, 1], [1, 1, 1, 1, 0]
[[[2, 0, 0, 0, 1], [0, 2, 2, 0, 2], [0, 2, 0, 2, 1], [0, 0, 0, 2, 1]], [[0, 2, 2, 0, 1], [2, 1, 2, 2, 1], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0]], [[2, 1, 1, 2, 1], [], [1, 1, 2, 0, 1], [0, 0, 0, 1, 0]]] -> [2, 0, 1, 1, 1]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 87 bytes
```
Fθ⊞ι⟦⁷⟧⊞θ⟦⟦⁷⟧⟧≔⊟Φθ№ιυηIΦE⁸¹E⁴X²﹪÷ιX³λ³∧∧⊖↔⁻Σιχ⊙Φιμ⊖↔⁻λ§ιμ⬤ι&λ§§§θ⁺⌕θη⁻⁼첬μ⁺⌕ηυ∧μ⁻²μ⁺²μ
```
[Try it online!](https://tio.run/##fVHLasMwELz3K3SUwIXKMbSQU5o0kEOKoceQg2urtUCP2JKS9uvdXUtuHocskpcZzYwertuqr22lhuHL9oR2jJTBtVRmZPe8Z/OHEXWAACJeOCe/DS3tga6l8qLHxaUNxqMnMMYy0qKvl0AtK@cn3bY60BeeEexFRkp7AjIHbJugLN0Yv5JH2QjMiYuzjCjMm42pC9NQnCtR90IL4wXgT2dV8IJupQmOfgRNJUj5U3L8TptDpgbmjleB3m9MI36ieCzglEL8Kv1JOoH7XwhvOzxFqSBrLUHX4UPA9cb0ty5UylGdkRy4d@upjvlnfYvPF6@pJ1ueTpJ0@f/BGJsPww4KqCKOPfwk6Pk4LhB@EyoSQnijhc4jcdYCwa@cRXRGLU9anHxyF1d6vocaHo/qDw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a nested array of `[N, E, S, W]` values where `4` represents a field and outputs a double-spaced list of sets of four values representing all valid rotations of all valid tiles. Explanation:
```
Fθ⊞ι⟦⁷⟧⊞θ⟦⟦⁷⟧⟧
```
Add borders to the input allowing any edge.
```
≔⊟Φθ№ιυη
```
Find the row of the tile to be placed.
```
IΦE⁸¹E⁴X²﹪÷ιX³λ³
```
Output all rotations of all tiles, except...
```
∧∧⊖↔⁻Σιχ⊙Φιμ⊖↔⁻λ§ιμ⬤ι
```
... non-existent\* tiles, and...
```
&λ§§§θ⁺⌕θη⁻⁼첬μ⁺⌕ηυ∧μ⁻²μ⁺²μ
```
... tiles that don't fit.
\*There are two categories of non-existent tiles:
* A tile that features all three features must have two roads and one each of the other two features. Conveniently with this input format illegal tiles would have a feature sum of either `9` or `11` and no other tiles have this sum.
* A tile that features two roads and two city edges cannot have them alternating. Conveniently with this input format illegal tiles alternate between `1` and `2` thus their cyclic consecutive absolute differences are all `1`. (Note that by comparison it's possible for tiles to feature two fields and two other features and still have them be alternating.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 40 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
(39 if we may output each tile as many times as it will fit up to rotational symmetry - remove `Q`)
```
3ṗ4o@U,ZƊṙ2=ḢʋƝ€€ȦʋƇ⁸ṙJṂƊ€Qḟ“[^go{~Ẉ‘b4¤
```
A monadic Link that accepts a list of lists of tiles as lists using the no-cities format of `[N,E,S,W]` with `Field=1`, `Road=2`, and `City=3`. Yields a list of tiles that can fit.
The outputted tiles are provided rotated such that their representation is the smallest it can be lexicographical (e.g. if `[3,2,2,1]` fits in any orientation(s) it would be given (once) as `[1,3,2,2]`)
**[Try it online!](https://tio.run/##y0rNyan8/9/44c7pJvkOoTpRx7oe7pxpZPtwx6JT3cfmPmpaA0QnlgHZ7Y8adwClvB7ubDrWBRQMfLhj/qOGOdFx6fnVdQ93dTxqmJFkcmjJ/8PtRyc93Dnj///o6GhjHQVDCIrVUYgG0sZghMQDkVCeIZQH4qKpBdJGEAGEWqCAEYpOQ4hOiFojqFoQNoLpNkRRbxQbGwsA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/44c7pJvkOoTpRx7oe7pxpZPtwx6JT3cfmPmpaA0QnlgHZ7Y8adwClvB7ubDrWBRQMfLhj/qOGOdFx6fnVdQ93dTxqmJFkcmjJfyB9uP1Rw8yjkx7unKGZ9ahx36Fth7b9/x8NBLGxsTpcCkCGgY4CFMXqKCCEQRygoCFYyhAvD8kkJAUkaDGEWo6hHCodC@JGG8JksaiFG2iE4hsgbQRGSDwQiTAezAMbj6rWCGy8EYpaQxSHge0A6zSCecII5m9DmG4DFPUQf8cCAA "Jelly – Try It Online") (with the IO tweaked to use `0`, `1`, and `2`, as in the question).
### How?
There are \$17\$ available tiles out of \$24\$ possible tiles (up to rotational symmetry), so we find all possible tiles that could fit in any rotation, rotate each of them to their lexicographically minimum and then filter out the \$7\$ unavailable tiles.
```
3ṗ4o@U,ZƊṙ2=ḢʋƝ€€ȦʋƇ⁸... - Link: Board
3ṗ4 - {implict range 3 = [1,2,3]} Cartesian power 4
-> All Tiles including unavailable ones like [1,2,3,3]
with all of their uniquely identifiable rotations
⁸ - chain's left argument -> Board
Ƈ - filter {All Tiles} keeping those for which:
ʋ - last four links as a dyad - f(Potential Tile, Board):
o@ - {Board} logical OR (vectorising) {Potential Tile}
-> Board with Potential Tile inserted
U,ZƊ - reverse all the tiles and pair with transpose
(allows same logic for both E-W and S-N checks)
€ - for each of these two:
€ - for each row:
Ɲ - for neighboring pairs of tiles:
ʋ - last four links as a dyad - f(L, R):
ṙ2 - rotate {L} left two
= - {that} equals (vectorising) {R}
Ḣ - head -> relevant comparison
Ȧ - any an all? (0 if any comparison was falsey)
-> all rotations of all tiles that fit
(including the unavailable ones)
...ṙJṂƊ€Qḟ“[^go{~Ẉ‘b4¤ - ...continued:
€ - for each found tile:
Ɗ - last three links as a monad - f(T=rotated tile):
J - range of length {T} -> [1,2,3,4]
ṙ - {T} rotate left (vectorised) {[1,2,3,4]}
Ṃ - minimum -> lexicographically minimal rotation
Q - deduplicate -> Found Tiles (in their minimal rotation)
¤ - nilad followed by link(s) as a nilad:
“[^go{~Ẉ‘ - code-page indices -> [91,94,103,111,123,126,187]
b4 - to base four
-> Unavailable Tiles (in their minimal rotation) = [[1,1,2,3],[1,1,3,2],[1,2,1,3],[1,2,3,3],[1,3,2,3],[1,3,3,2],[2,3,2,3]]
ḟ - {Found Tiles} filter discard {Unavailable Tiles}
```
[Answer]
# Python3, 301 bytes:
```
E=enumerate
def f(b):
for x,r in E(b):
for y,P in E(r):
if[]==P:return[i for i in[[v//d%3for d in(1,3,9,27)]for v in b"[$)'S>QPYDZ&_<( G"]if any(all(X in(Y,[])for X,Y in zip([c and b[x+~q%(2-2//q*4)][y+q%(2-q//5*4)][q%4]for q,c in E((b*x,r[y+1:],b[x+1:],b*y),2)],i[j:]+i[:j]))for j in range(4))]
```
[Try it online!](https://tio.run/##nZBRT8IwFIXf@RUNEW2hZrRg1EV8kviK8YV505iNbVqCY2sGYT7412fbMYaAMTFpt95v59xz17TI35fJ4CZVZTkeRcnqI1J@HrXCKEYxDojbQvFSoQ1VSCZoXBGLCjqpkLIIyRjEaDRxVZSvVALSiqSWAKwdJ@wMTB3qGjM6oLeUXxNh0Np0CdpwRi6e758m3sPL@esdRo9tIWPkJwX2Fws8NT6PgiDGMqWeMX3KFMNMa0IUwKb3lXUwv@SOk3WHREDRs3XmOFe2zjpDm5fRWTU3Drr6t7SOuYKaBvbdLQjlRFAJc1f0JLhzQWzo3LiUn7xFeEiIKFMlkxzHGACE0JrWHuhT1CxB0bHCQP2RWQnbqv4AJ1J@yv/dgzWTnvI3ImEINI7fTEc5fO9G2NbC7TKHBlRP1gTXwAbvm6yG20h@aGKH49ez2i68FtQms3ekfxi/u7fyGw)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 193 bytes
Expects a matrix of strings in `"NESW"` format (or an empty string for the missing tile).
Returns a list of strings in the same format. Only one rotation per tile is included.
```
m=>m.map((r,y)=>r.map((s,x)=>s||0xDB5ECDAAE7E20755344F4D6A4CEn.toString(3).replace(/..../g,s=>[...s].every((_,i,a)=>a.some((_,d)=>m[y+~-d%2]?.[x-(d-2)%2]?.[d^2]-s[d+i&3]))||o.push(s))),o=[])&&o
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVLRatswFIU-uj8hDEslKiuykrSD4Qwndn5gj0ItJnZSj9gKVjoSCP2RvoSxfcg-Y_uaXUkODaUC-957zj1Hx-DXX60uq9PPVfL7ebeKPv_90yTThjXFFuOOHkgy7fxg6B4GczzyfTab5PMsTfP7XPD7yWQ0Hi_G2V06nuct2-lvu65u13hEWFdtN8WywkMGZ7imJplK6Ixi1Y-qO2D8SGtagG3BjG4qO5cwNfJw-xKVn4T6yuQ-wmUkiB_KB6EiI8vbejBShByPmm2fzRM2hBCqE6nIYKD9h_y7uk5RgqQMQ6W-BDPfczgh9dC8p2nIYx6_K3Yh6zUe_mAhPy_E_IKFMVRUhoBewE6w8ALhU3AhfOHC6aBYXQ-LWIizHfXBLSviWPg00HDP-DSBDBBKKRoOUdoe0K7eVADMHAAZOLVWFJ6Y2gAUrhGU951jobMrcAWMlhWgA4-583ByZ2QzOO7s5kW9UkBy7waQlWdvES5E9tUv5G_-zvoj1351geyq5QIVsJXu8mL5hAuUTNFSt0ZvKrbRa7zCBWHfdd3iG3QDP4f_J04nX_8D)
### Commented
```
m => // m[] = input matrix
m.map((r, y) => // for each row r[] at index y in m[]:
r.map((s, x) => // for each string s at index x in r[]:
s || // abort if this is not the missing tile
0xDB5E..A4CEn // lookup BigInt encoding the 17 tiles
.toString(3) // convert it to base 3
.replace( // -> "2222222122202211..0000"
/..../g, // split into groups of 4 characters
s => // for each string s:
[...s] // split s
.every((_, i, a) => // for i = 0 to i = 3:
a.some((_, d) => // for d = 0 to d = 3:
m[ // extract the cell located at
y + ~-d % 2 // row y + dy
]?.[ // and
x - (d - 2) % 2 // column x + dx
]?.[ // take the character corresponding
d ^ 2 // to the opposite direction
] - // and test whether it's defined
s[d + i & 3] // and different from the character
// in s at index (d + i) mod 4
) // end of some()
) // end of every()
|| o.push(s) // if falsy, add s to o
) // end of replace()
), // end of map()
o = [] // initialize o to an empty array
) && o // end of map(); return o
```
] |
[Question]
[
## Goal
Write a function or a program that when given a string, for example `"The quick brown fox jumps over the lazy dog"`, outputs:
```
T h e q u
i
e r t h e c
v k
o l
a b
s z r
p y o
m g o d w
u n
j x o f
```
## Rules
1. You may not truncate the input!
2. The output must be text and formatted as above.
3. The hexagons must have the shortest possible side length. This is wrong for example:
```
T h e q u i
c
l a z y d k
e o
h g b
t r
o
r w
e n
v
o f
o
s p m u j x
```
The outer hexagon above has a side of 7 characters, but clearly it is not optimal. A spiral with an outer hexagon with a side of 6 characters would be able to store all the characters of the string too (as shown previously).
4. The spiral must look *like* an [Archimedean spiral](https://en.wikipedia.org/wiki/Archimedean_spiral):

* This is **not** correct:
```
T h e q u
i
e r t h e c
v k
o l
g a b
s o d y z r
p o
m w
u n
j x o f
```
5. You may start the spiral at any point you like and even go anti-clockwise. Any of these would be valid:
```
. . . . . . . . . . . . u q e h T
. . . . i
x j u m p . j u m p s . c e h t r e
o s . o T k v
f a z y . x y d o v h l . . . . o
l d o T o z g e e b a . .
n g o v h f a . . r r z . . . s
w e e e l q o y . p
o h t r n e h t u w d o g m
r q w i n u
b k c i u o r b k c f o x j
```
The dots (`'.'`) indicate "cells" that weren't used. You **don't** have to include them.
6. It does not matter if the string is not long enough to form a complete spiral, but the rules above must still hold.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") (no loopholes!), so the shortest answer in terms of bytes wins!
---
## More examples
Note that there are more than one valid outputs due to rule 5.
`ABCDE` \$\rightarrow\$
```
A B
C
E D
```
`#####################################################` \$\rightarrow\$
```
# # # # # #
#
# # # # # # #
# # #
# # # # # # #
# # # # #
# # # # # #
# # # #
# # # # # #
# #
# # # # # #
```
`0123456789ABCDEF` \$\rightarrow\$
```
0 1 2 3
4
5
F 6
E 7
D 8
C B A 9
```
`-\\\|///-----\\\|/-----\|/---\---` \$\rightarrow\$
```
-
\
- - - - - \
/ \ \
| - - - | |
\ \ / /
\ - - - /
\ /
- - - - -
```
`Racecar, racecar!` \$\rightarrow\$
```
c e c a
R a r
a r !
c ,
e c a r
```
`0123456789AB` \$\rightarrow\$
```
0 1 2
3
A B 4
9 5
8 7 6
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
Wφ«⎚≔⪪⮌θ¹φ⊞υLυF⁺⭆Φ⮌υ﹪λ²⮌⭆⭆134570×μκ⎇›ν¹μ∧⁼κ¹ω0¿φ«P⊟φM⊕№04κ✳Iκ
```
[Try it online!](https://tio.run/##RU/basMwDH1OvsLLkwwetFvHHvZUsguDBUrbHzCOkpi6dirbLWP02zObrqtAcHSkcySpQZJy0kzTadAGGXSc/ZRFbVAS8JeyWHqvewub0egAazwieYQDF2yesssTq@gHiIJ9oe1DQjyTnSMGKxM9bAJp2zdyhHdtAtK/SUwGjWujcWAEe@CpvLZumhuq5o@Lp@dZJdhW79HDXrBd1myRrKRv@CCU2d5eTkvtpW3h7RCl8bC7kCeeQ7BqVnHOdHd9t2iiCXpMqwKs3JjY/EPRuCPCp1WEe7QBW6hdTBPVbFH9LX/VhCpoZ6GWPkDisvBcnqdpLRUqSYLRBdyV0/3R/AI "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Wφ«
```
Repeat until the string is successfully turned into a spiral. (`φ` is actually a predefined variable here, which is why the loop succeeds at least once.)
```
⎚
```
Start by clearing any output from the previous loop.
```
≔⪪⮌θ¹φ
```
Reset the variable to the input, split into characters and reversed to that its characters can be consumed more easily.
```
⊞υLυ
```
Build up a list of integers for each pass. (The zero entry is useless and serves only to save bytes.)
```
F⁺⭆Φ⮌υ﹪λ²⮌⭆⭆134570×μκ⎇›ν¹μ∧⁼κ¹ω0«
```
Loop over a list of directions for the spiral. This starts with the list of integers, which is reversed and then alternating elements are picked out (again in a byte-saving manner, requiring a further pass through the loop). For each integer, the characters `075431` (representing the directions) are each repeated that many times, except that the last two `11` are replaced with `00` unless they are `31` in which case they are deleted. (This is actually done on the reverse of the strings as that's golfier.) A final `0` is appended before the list is looped over.
```
¿φ«
```
If there are still more characters to print, then:
```
P⊟φ
```
Output the next character without moving the cursor.
```
M⊕№04κ✳Iκ
```
Move two steps horizontally or one step diagonally.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 63 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JḂḤØ-;+2ÄÄ<LS‘RṚm2x6IŻN+Ɗ+Ɗ’Jx$Żị“¬½®‘d4¤’;C¤+\_«/$‘ŒṬ€ṁa"⁸o/o⁶
```
A monadic Link that accepts a list of characters and yields a list of lines.
Starts at the top-left of the smallest outer hexagon and spirals inwards, clockwise.
**[Try it online!](https://tio.run/##y0rNyan8/9/r4Y6mhzuWHJ6ha61tdLjlcIuNT/CjhhlBD3fOyjWqMPM8uttP@1gXED1qmOlVoXJ098Pd3Y8a5hxac2jvoXVAhSkmh5YApaydDy3Rjok/tFpfBSh4dNLDnWseNa15uLMxUelR4458/fxHjdv@H26P/P@/SEkXCPRiYmJq9PX19eBsEAtKKwEA "Jelly – Try It Online")** Or see a [test series](https://tio.run/##AcMAPP9qZWxsef//SuG4guG4pMOYLTsrMsOEw4Q8TFPigJhS4bmabTJ4NknFu04rxoorxorigJlKeCTFu@G7i@KAnMKswr3CruKAmGQ0wqTigJk7Q8KkK1xfwqsvJOKAmMWS4bms4oKs4bmBYSLigbhvL2/igbb/w4dZJMakauKBvsK2wrb//ycwMTIzNDU2Nzg5QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eic "Jelly – Try It Online").
### How?
Split into two parts, for ease of reading...
```
JḂḤØ-;+2ÄÄ<LS‘RṚm2x6IŻN+Ɗ+Ɗ’Jx$Ż - Link: list of characters, "Chars"
J - 1-indexed indices -> [1,2,...,len(Chars)]
Ḃ - mod two -> [1,0,1,0,1,0,...]
Ḥ - double -> [2,0,2,0,2,0,...]
Ø-; - prefix with [-1,1] -> [-1,1,2,0,2,0,2,0,...]
+2 - add two -> [1,3,4,2,4,2,4,2,...]
Ä - cumulative sums -> [1,4,8,10,14,16,20,24,...]
Ä - cumulative sums -> [1,5,13,23,37,53,73,95,...]
<L - less than length(Chars)?
e.g. L=9 -> [1,1,0,0,0,0,0,0,0,0,0]
S - sum -> outer hexagon side length
‘ - increment
R - range -> [1,2,3,...,side-1,side,side+1]
Ṛ - reverse -> [side+1,side,side-1,...,3,2,1]
m2 - modulo-2 slice -> [side+1,side-1,side-3,...]
x6 - repeat each element six times
Ɗ - last three links as a monad - f(X):
I - deltas of X
Ɗ - last three links as a monad - f(Y):
Ż - prepend a zero to Y
N - negate
+ - add Y (vectorises)
+ - add X
’ - decrement (vectorises)
-> number of steps to take in each direction
- has excess such instructions
$ - last two links as a monad f(Z):
J - 1-indexed indices
x - repeat (vectorises)
-> 1, 7, 13, ... represent East
2, 8, 14, ... represent South-East
etc...
Ż - prefix a zero (to have a starting point)
-> "Instructions"
```
```
ị“¬½®‘d4¤’;C¤+\_«/$‘ŒṬ€ṁa"⁸o/o⁶ - ...continued...
¤ - nilad followed by links as a nilad:
¤ - nilad followed by links as a nilad:
“¬½®‘ - code-page indices -> [7, 10, 8]
d4 - div-mod four -> X = [[1,3],[2,2],[2,0]]
’ - decrement X -> [[0,2],[1,1],[1,-1]]
C - complement X -> [[0,-2],[-1,-1],[-1,1]]
; - concatenate -> [[0,2],[1,1],[1,-1],[0,-2],[-1,-1],[-1,1]]
-> "Directions"
ị - {Instructions} index into {Directions}
\ - cumulative reduce by:
+ - addition (vectorises)
$ - last two links as a monad:
/ - reduce by:
« - minimum (vectorises)
_ - subtract -> normalises the minimal values to 0
‘ - increment -> make them 1-indexed
ŒṬ€ - for each: 2d array of zeros with a one
at the given 2d index
ṁ - mould like Chars (keep first length(Chars))
a"⁸ - zipped logical AND (vectorises) Chars
/ - reduce by:
o - logical OR (i.e. layer these together)
o⁶ - logical OR (vectorise) with a space character
(replaces remaining zeros with spaces)
```
[Answer]
# [Haskell](https://www.haskell.org/), 360 bytes
```
import Data.Array
t(a,b)(c,d)=(a+c,b+d)
s i=[[a!(r,c)|c<-[b..d]]|((p,b),(q,d))<-[b],r<-[p..q]]where
d=zip(scanl t(0,0)$concat$zipWith replicate(concat$iterate(map(2+))[1,1,1,3,1,3])$cycle[(0,2),(-1,1),(-1,-1),(0,-2),(1,-1),(1,1)])$reverse i
b=foldl(\((p,b),(q,d))((r,c),e)->((min p r,min b c),(max q r,max d c)))((0,0),(0,0))d
a=accumArray(flip const)' 'b d
```
[Try it online!](https://tio.run/##VZBNSwMxEIbv@yumpdAJzS61Xl1B8CLoyYOHdZF81YZms2mSqpX@93VSvUhIXuaZmWTe7ETaG@emyQ5hjBnuRRbNXYziVGUUXDJUXLMWxUpxudKsSmDbrhMzjFyxs7qpO9k0uu/PiIHKOR6onhXc80gSmubQ9587E00Fuv22AZMS3kHGNV@zhRq9EnlB/MXmHUQTnCVg8C9hs4klHETAzYqx7oqXdV12T@0n5UxHV23o6Zoyv1IXXfO60L@o5Kghmg8TkwFbgWy3o9MOX/@Njhdn3LD6FnGwHgJEXlQCYZrjCw6FkGoipaEY4ZeT6QpEK5Q6DpdPxK2zAchKymwJSwl6GoT1Lbl5eoNwzM85PvpFmj8sB0jBem/9O8Tx6DU4uzcg6EfUGDUHKeRpNp9@AA "Haskell – Try It Online")
```
o u n d l
r i
, b a k
g d b e
n r ! y
i o a
n c e r
n I
i p s m '
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 127 119 115 bytes
```
{(0N,w)#@[""@!4*s*w;(#x)#+\(2*s),(|2,,/--:\(-1 1+w:-2+8*s),2)7!&-2_,/+|2,(-2*|&5 1)+6#,|-1+2*1+!s:-_-%-6!1+#x;:;x]}
```
-8 : squeezed
-4 : and again
[Attempt This Online!](https://ato.pxeger.com/run?1=nZLLUtVAEIarfJI-OSUkJ8mBRK7JBhWwVEBFvGPhMOkcWjIzYS5wqsQnccOGh8Knccbowq3ZZCbd_ff_f5Uft-cnciZv7jaPqmi5KB-srK6tb2w-fPR4e3f3ydNnz_f29w9evHx1-Prozdt37z98ZKe8wXZ2Rl_POyFVr6NbZ9t848611bd4-SC7SsZbn6Joa7QyMZOrOh7Pk3F6HJcTk2TxdZllS3leHcd5AUV6VeVluhEqZbI-WsjLk2wp9T1xXk6uF1ahSNK1cXadF2k5KdKRqfKT_H6-NirS8byu6vnn78Pyn_c2vyxXi-1iHAXnO1Edjf_n8XP_MtjZjeo4hFlNsuiQceRMZ6CHwyiqj-poT2kUQL1xAhrVKQ2GLDCBNgOupEFu0ToNrKGeDCc5A-zIFw02fgCQnBGqAYui98MkOTXUOGnBWejYqZcHtIM0gmAzyYB1dOHYFN5YQEnCa4OgcLj0VyYyuHBkQCpjtWsA56g5WWZJSXBdxwRXg3JoIkNh029J6n0zIPPGhfekhgB-lZ3CdpBkziKQdt7JkJUkaOw1nqFsUPvg_sOl6lzv16G345MCGoPAqev-EvKBHLRuRsyCDIagZ9pfnJ7Czpxjb9EFjJ6B4px51ha466lhNkz4FL1W1KAMFAMpv5S7rmchN6i2JU4MGjSoQ1WoLthgARB5HOYPVyemUVIPf9DNzfD-BQ)
[Answer]
## Javascript, 365 bytes
```
f=s=>(b=Math.abs,m=Math.max,w=h=3,x=-2,y=0,l=[...s].reverse().map(n=>(c=y>0?b(x)<y||-x==y?[x+=2,y]:x>0?[++x,--y]:[++x,++y]:y<0?b(x)<-y||(x<0&&x>y-4)||x==-y?[x-=2,y]:x<0?[--x,++y]:[--x,--y]:x>0?[--x,--y]:[++x,++y],w=m(w,b(x)),h=m(h,b(y)),c.push(n),c)),d=Array.from(Array(2*h+1),r=>Array(2*w).fill(' ')),l.map(([x,y,n])=>d[y+h][x+w]=n),d.map(r=>r.join('')).join(`
`))
```
Depending on the length of the string, there might be some extra whitespace surrounding the spiral on each side.
### Ungolfed
From an (empty) start position of `(-2, 0)` a two-dimensional array gets filled by assigning each consecutive letter to a new position computed from the last. It is not optimal to condense this to six conditions for six directions, for my solution I used eight.
As the spiral is constructed inward-out, its final size is only apparent after completing the assignment.
```
f = s => {
b = Math.abs, m = Math.max
w = h = 3, x = -2, y = 0
l=[...s].reverse().map(n => { // map letter n to [x, y, n]
if(y > 0) { // lower half
if(b(x) < y || -x == y) { // between the lower corners, left included
c = [x+=2,y] // go right
} else if(x > 0) { // right lower quadrant
c = [++x,--y] // go right and up
} else { // left lower quadrant
c=[++x,++y] // go right and down
}
} else if(y < 0) { // upper half
if(b(x) < -y || (x < 0 && x > y - 4) || x == -y) {
// between the upper corners, right included,
// on the left going two steps further out
c = [x-=2,y] // go left
} else if(x < 0) { // upper left quadrant
c = [--x,++y] // go left and down
} else { // upper right quadrant
c = [--x,--y] // go left and up
}
} else if(x > 0) { // right corner
c = [--x,--y] // go left and up
} else { // left corner
c = [++x,++y] // go right and down
}
w=m(w,b(x)),h=m(h,b(y))
c.push(n)
return c
})
d=Array.from(Array(2*h + 1),r => Array(2*w).fill(' '))
l.map(([x,y,n]) => {
d[y+h][x+w] = n // place letters in array, origin in the middle
})
return d.map(r => r.join('')).join('\n')
}
```
] |
[Question]
[
## Intro
Help! I'm stuck on a snow-covered mountain and I need to get down as fast as possible, preferably without dying. I have a map showing how high each part of the mountain is above the normal ground.
I am a novice skier, which means I like to stick to slopes that aren't too steep. I'm willing to go down just two moderately steep sections, however - but not back to back!
## Rules
Your program's job is to, given a *n* x *m* matrix of height values, navigate from the skier's current position (the top left corner) to the base (the bottom right corner). Height values will be given as integers between 0 and 25, with 25 being the highest possible point and 0 being the base of the mountain. It should be noted the mountain does not have to start at 25 units high, but will always finish at the 0 in the bottom right corner.
There are a few constraints:
* The skier can move up, down, left, or right on the map. No diagonals.
* The skier is usually only comfortable on slopes that bring him down 2 units or less.
* The only exception to the above rule is that the skier can go down a maximum of two sections that will bring him down 3 or 4 units.
* The skier can move upwards if necessary, but only one unit at a time. **The skier also cannot go upwards or flat then immediately thereafter go down a steep slope of 3 or 4 units, he must already be headed downwards before taking a steep slope. Also, his first move cannot be to go down a steep slope, and he cannot do two steep slopes back to back**.
* It is possible for the skier to visit a location twice (as seen in the fourth example - this is due to the fact that the skier cannot go down two steep slopes in a row)
## Input
As mentioned above, the map will be given by a matrix containing integer values from 0 to 25, with a 0 in the bottom left corner (there could be zeroes in other places on the map). These maps will always have at lease one best solution but could have several worse solutions. These matrices will always have spaces and line breaks as separators - double spaces will be used if the integer is just one character (see examples below)
## Output
Your program is to output a sequence of moves (the format of this sequence does not matter so long as it is coherent) that shows the best way down the mountain - meaning fewest moves on the map. These moves can be represented by any strings, numbers, or characters you like, so long as they are distinct and are described in your solution. A sample output might look like `RRDDRRRURRDDDDRR`, where `R` means right, `D` means down, `U` means up, and `L` means left.
## Test cases
Input 1:
```
10 13 13 13 13
8 9 11 13 25
0 7 11 12 23
6 5 2 2 0
```
Sample output 1:
```
DRDDRRR
```
Input 2:
```
16 12 12 10 8 6
14 12 6 8 0 4
10 20 4 2 1 2
8 20 10 8 4 0
9 8 9 25 2 0
```
Sample output 2:
`DDDDRRURRDR` or `DRURRRRDDDD`
Input 3:
```
20 19 15 11 0 9 15 6
18 20 13 12 11 9 18 12
16 25 9 7 6 2 1 1
12 20 10 4 4 4 3 2
13 12 13 0 0 0 0 0
```
Sample output 3:
```
RRDDRRDRRRD
```
Input 4:
```
20 18 10 11 12 0
19 11 1 4 5 0
18 16 3 3 3 3
19 8 7 17 19 3
18 20 11 12 13 3
17 17 16 16 14 2
20 21 11 14 11 0
```
Sample output 4:
```
DDDDDRRRRULLULRURRRDDDD
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer wins - get creative!
[Answer]
# JavaScript (ES6), ~~223 ... 205~~ 199 bytes
```
f=(m,x=o=0,y=0,n=2,V,s,p='',r=m[y]||0,v=r[x],h=V%32-v%32|0)=>63>>h+1&v<64&!p[o.length-1]?h<3||s*n--?1+r[x+!m[y+1]]?[...'LURD'].map((c,d)=>r[f(m,x+--d%2,y+~-d%2,n,r[x]+=32,6>>h&1,p+c),x]=v)&&o:o=p:0:0
```
[Try it online!](https://tio.run/##bVJNj6JAEL37K2omGZGlId0Ngx87rRf2ZrIJiXNhORhlxt0oEGGMJmb/ulvVDcjs7qEkXa/qvVdV/lqf1tXm@LOs3bzYZrfbmxod2FkVirMLRq4ke2UVK5VlsaM6JJf0euXspI7JOWU79frkS/eEP1duq3noz@c7RwxPL2EwfCiTwttn@Xu9c0W62L3412v1JXfdhXCw23lAMkek6SLxPM9aruLISr3DuhyNNmyLZMfkjaw4rrt9kuzi/NbfnJGyo3zJQhQbClY6G5udU3Wyh8NiVqhyxmf8VmdVDQqQASob1Bw2RV4V@8zbF@8j6/tHXX7UADADCxxAIRs/1o/827nMNnW2bYDKZC3762BAjKMBQAKJ4AyE34@UIYLYhAFMMYQwiHxuEWyBcYtIRLqeELPPGLIJDilo7DGKoyiO48eB/Uk9NAw6kBY1w5ZLBCZPnOQF4aDD8CEp0eigEdn3TVjDRzU8ZWDAaUNGX4lOJYGtxYgsruI4@tumpsMWgR00NG9Xg@8QOlMTY0qvUZpKXTWhd1cVMq08bZYY3kcAceeSrBsiMEPo8Kn6XtUq@cbTp@hWH@vV0/aj/801MSrtMXlHPm2SjTTdlfdnpUn8xpOOfuek/Y@Mzer8f7Yk7t7vIFWPDbWOoHdY6pKi6QyaS/SPRyPGq@VytaQrxpTBgW9/AA "JavaScript (Node.js) – Try It Online")
## Commented
The 5 least significant bits of the cells are left unchanged. The upper bits are used to count the number of times a cell has been visited in a given path.
We need quite a lot of variables to fully describe the skier status at any given time, notably the possibility to do a big steep slope.
### Header
```
f = ( // a recursive function taking:
m, // m[] = input matrix
x = // (x, y) = current position, starting at (0, 0)
o = 0, // o = output string, initialized to a numerical value
y = 0, //
n = 2, // n = remaining number of big steep slopes
V, // V = value of the previous cell
s, // s = a flag that is set if a big steep slope is allowed
// for this turn
p = '', // p = current path string
r = m[y] || 0, // r[] = current row (using 0 as a fallback)
v = r[x], // v = value of the current cell (or undefined)
h = V % 32 - v % 32 | 0 // h = height between the previous and the current cell
) => // (0 if V is undefined)
(...) //
```
### Tests
```
63 >> h + 1 & // if the height is greater than or equal to -1 and less
// than or equal to 4 and
v < 64 & // v is defined and less than 64 and
!p[o.length - 1] ? // the current path is shorter than the best solution or
// we don't have a solution yet (in which case o.length - 1
// is NaN):
h < 3 || // if the height is less than 3 or
s * n-- ? // a big steep slope is allowed and we can still do one:
1 + r[x + !m[y + 1]] ? // if we haven't reached the bottom-right cell,
// i.e. m[y + 1] is defined or 1 + r[x + 1] is not NaN:
(...) // process the recursive calls
: // else:
o = p // update the solution to this path
: // else:
0 // do nothing
: // else:
0 // do nothing
```
### Recursive calls
```
[...'LURD'].map((c, d) => // for each direction character c at index d:
r[ // we will eventually restore r[x]
f( // recursive call:
m, // m[] is unchanged
x + --d % 2, // add dx to x
y + ~-d % 2, // add dy to y
n, // n is unchanged
r[x] += 32, // add 32 to the current cell
6 >> h & 1, // set s if h is either 1 or 2
p + c // append c to the path
), // end of recursive call
x // restore r[x] to ...
] = v // ... v
) && o // end of map(); yield o
```
[Answer]
# [J](http://jsoftware.com/), 185 bytes
Far from perfect, but it's something. Could theoretically save 17 bytes by omitting the check for revisiting places, but then the last example ran out of memory on my machine and I couldn't truthfully say all examples were verified. :-)
Takes in the map and outputs a list of offset coordinates `1 0,0 1,_1 0,0 _1` that I've mapped to `DRUL` in TIO for easier comparison.
```
}.@{.@(((](\:+/"2)@#~[*/@((4((1>=&3-_1|.2=])*>&0*3>[:+/\3=])@:|(+:<:i.4)I.0,2-/\({~ ::_"_ 0<"1))*3>[:+/[:="1/~<"1@])0 2+/\@|:])[:,/((,-)=i.2),~"1 2/])^:(0=<:@$@[-:+/@{.@])^:_&(1 1 2$0))
```
[Try it online!](https://tio.run/##fZFPb6MwEMXv/hRPtErsBIz/ACFuiJB2tdJKPVXqiVBOW6l7bW9N89XTmQnbvbSVBoSfHzO/Z/89Z3b5iC5hiRwOiZ7C4sfd7a/zm@1fba@1HvUhrcssmP7qNKxKkiqt/b5bxGLyRxu60az2C7eK@4F8h0jrPh31Ou3Sk63Mb@vyUJQH/XpCSlM2we0yb8zsH1KX@fJEUj8ah0Ad@mMazZDyUuu8MN2TDSY/ZR6hHM1D0q7bpf66Hwr6mxFZnBbagxzXzpizOb/8eX7xHMstMntjpwAt4YzyDj5@lGqBLeA9L0OtHLC5LANCVA1QA0HKKaOW97e4@7kEJQlY48riETJK8Tt8PrDhZlwOLRooX/GKWtNshwqMFPiDp1AEMBQJ4ifZQW3FTO9Q0z4JX6MEQYmfonDTLXzNAd0leC1ErcyLQulFb@mb0WngVs6kmfGoFB@O8FWYK/KumjtEbv6/voGNAlt9CdvykMttUGhm50vmgTVEIUPDw/8Ve9rLHW44a/wI52c0Vjay20hVDE6G4MVTydl8g1ypdw "J – Try It Online")
### How it works
```
(1 1 2$0)
```
We keep the routes as a list of offsets, starting with `0 0`.
```
(…)^:(0 = <:@$@[ -: +/@{.@])^:_
```
Do until the head of the list – which is nearest the bottom right – equals the dimensions of the map - 1.
```
[: ,/ ((,-)=i.2) ,~"1 2/ ]
```
Each route gets the 4 offsets added, so we have 4 times as many routes: `(0 0,1 0),(0 0,0 1),(0 0,_1 0),(0 0, 0 _1)`. Then we have to filter these routes based on several checks.
```
0 2 +/\@|: ]
```
List of offsets -> List of absolute coordinates, transposed so each routes' first points are in one list, then each routes' second points are in one list, etc:
```
0 0,0 0, 0 0,0 0
1 0,0 1,_1 0,0 _1
```
This format seems more suitable for the checks, but maybe a `(…)"2` would have been enough. However, now each check can build up a matrix saying which coordinate is ok and which not and in the end we can easily reduce it.
```
3 > [: +/ [: ="1/~ <"1@]
```
No place should be visited 3 times. This check is just to keep the number of routes from exploding.
```
0, 2 -/\ ({~ ::_"_ 0<"1)
```
Gets the height values from the map at the absolute coordinates. If something is out of range, it will be replaced with infinity. Then we'll get the diff between neighboring heights and prepend 0 so the matrix will align with the previous one. Now we have (given the first map):
```
0 0 0 0
2 _3 _ _
```
With
```
4 …@| (+:<:i.4) I.
```
we sort the height diffs into 4 categories: 0 = not reachable, 1 = climb up, 2 = gentle slope, 3 = steep slope.
```
3 > [: +/\ 3=]
```
Less then 3 steep slopes.
```
>&0
```
Point must be reachable
```
1 > =&3 - _1 |. 2 = ]
```
3 is only allowed if 2 was in front of it.
```
] …@ #~ [ */
```
A route is only taken if all of its coordinates passed all tests.
```
(\:+/"2)
```
Sort the routes based on their last, absolute coordinate.
```
}.@{.
```
Finally the loop has ended and the first route contains the best route written in offsets, with only a `0 0` at the top that gets dropped.
] |
[Question]
[
I have a [combinatorics problem](https://math.stackexchange.com/q/2465571/121988) that I'd like to put on the [OEIS](https://oeis.org/)—the problem is that I don't have enough terms. This code challenge is to help me compute more terms, and the winner will be the user with the submission containing the greatest number of terms.
---
# The Problem
Suppose I give you a triangular array of light bulbs with side length \$n\$:
```
o
o o
o o o
o o o o
o o o o o
o o o o o o
1 2 ... n
```
I'm going to turn on three lightbulbs that form an "upright" equilateral triangle as in the following example:
```
o
o x
o o o
o o o o
o x o o x
o o o o o o
```
Before I turn on the lights, your job is to remove as many lightbulbs as possible from the array—without losing the ability to deduce the triangle of bulbs that has been turned on. To be clear, if a lightbulb has been removed, it is not lit up when its position is turned on.
For example, if you removed the following bulbs (marked by `.`) you would only see the following two lights turn on (marked by `x`), which is enough uniquely deduce the third (unlit) position:
```
. .
. o . x
. . o . . o
o o o . => o o o .
o o o o . o x o o . <- the third unlit position
o . . . o o o . . . o o
```
Let `a(n)` be the maximum number of bulbs that can be removed without introducing any ambiguities.
---
# Example
With a naive algorithm, I have checked values up to a triangle with side length 7, as seen below:
```
.
. . o
. . o o . o
. . . . . o . o o .
. . . . o o o o o . o o . o .
. . . . o o o o . o o o o o . o . o . o o
. . . o o . o o o o . . o o o . . . o o o . o . o o o
a(2) = 3 a(3) = 4 a(4) = 5 a(5) = 7 a(6) = 9 a(7) = 11
```
---
# Scoring
The submission that computes the sequence `[a(2), a(3), ..., a(n)]` for the largest n wins. If two submissions have identical sequences, then the one that was posted earlier wins.
Although not necessary for the submission, it would be instructive to me if you post a construction of the resulting triangluar arrays, as in the example above.
[Answer]
# [Python 3](https://docs.python.org/3/), `n=8`
```
import itertools
from ortools.sat.python import cp_model
def solve(n):
model = cp_model.CpModel()
solver = cp_model.CpSolver()
cells = {
(y, x): model.NewBoolVar(str((y, x)))
for y in range(n) for x in range(y + 1)}
triangles = [
{cells[v] for v in ((y1, x1), (y2, x1), (y2, x1 + y2 - y1))}
for (y1, x1) in cells.keys() for y2 in range(y1 + 1, n)]
for t1, t2 in itertools.combinations(triangles, 2):
model.AddBoolOr(t1.symmetric_difference(t2))
model.Minimize(sum(cells.values()))
solver.Solve(model)
return len(cells) - round(solver.ObjectiveValue())
for n in itertools.count(2):
print('a(%d) = %d' % (n, solve(n)))
```
Uses [Google OR-Tools](https://developers.google.com/optimization/)' CP-SAT solver.
After running for ~30 seconds, it outputs the following:
```
a(2) = 3
a(3) = 4
a(4) = 5
a(5) = 7
a(6) = 9
a(7) = 11
a(8) = 13
```
~~I didn't event try to wait for `n=9` as it would probably take hours (the number of constraints grows like \$n^6\$)~~. After less than 30 minutes of computation I found out that `a(9)=15`. I'm leaving my score as `n=8` because at the moment the time constraints are unclear, but half an hour is probably too long.
## How it works
Take two distinct equilateral triangles \$T\_1\$ and \$T\_2\$. To avoid ambiguity, there should be at least one bulb on a vertex belonging to *exactly* one of \$T\_1\$ and \$T\_2\$.
Thus the question may be rephrased as a SAT problem, with one constraint for every pair of triangles.
**PS:**
I would very much like to include an example for `n=8`, but I'm having issues with the SAT solver which apparently wants to keep the solutions all for itself.
[Answer]
### Getting the solutions from @Delfad0r's program
I extended @Delfad0r's program to output solutions.
It also gives intermediate results, so you get output like this:
```
Solving n = 8:
a(8) >= 9
a(8) >= 10
a(8) >= 11
a(8) >= 12
a(8) >= 13
o
. o
. o o
. o o .
o o . o o
o o o o . .
o . . o o o .
o . . o . o o o
a(8) = 13
Solving n = 9:
a(9) >= 10
a(9) >= 13
a(9) >= 14
a(9) >= 15
o
o o
o . .
o . o o
. o . o o
. o o o o o
o o o . o . .
o o o . . . o o
. o o o o o o . .
a(9) = 15
```
This computation took several hours.
If you get impatient and press `Ctrl-C` after some possibly non-optimal solution was found, the program will show that solution. So it doesn't take long to get this:
```
.
o o
. o o
. o o o
o o . o o
o . o o o .
o . o . o o o
. o o o o o . o
o . . o o o o o o
o o o o o o o o o .
o o . o o o o . o o o
o o o o o o . o . o o o
o . o o . o o o o o o o o
o o o . o o o o o . o o o o
o o o . o o o o o o o o . . o
o o o o o o o o o o o . o . . o
o o o o . o o o o . o o o o o . o
o o o o o o o o . o o . . o o o o .
o o o o . o o . o . o o o o o o . o o
o o . o o . o o o o . o o o . o o o o o
a(20) >= 42
```
Here is the extended program:
```
import itertools
from ortools.sat.python import cp_model
class ReportPrinter(cp_model.CpSolverSolutionCallback):
def __init__(self, n, total):
cp_model.CpSolverSolutionCallback.__init__(self)
self.__n = n
self.__total = total
def on_solution_callback(self):
print('a(%d) >= %d' %
(self.__n, self.__total-self.ObjectiveValue()) )
def solve(n):
model = cp_model.CpModel()
solver = cp_model.CpSolver()
cells = {
(y, x): model.NewBoolVar(str((y, x)))
for y in range(n) for x in range(y + 1)}
triangles = [
{cells[v] for v in ((y1, x1), (y2, x1), (y2, x1 + y2 - y1))}
for (y1, x1) in cells.keys() for y2 in range(y1 + 1, n)]
for t1, t2 in itertools.combinations(triangles, 2):
model.AddBoolOr(t1.symmetric_difference(t2))
model.Minimize(sum(cells.values()))
print('Solving n = %d:' % n)
status = solver.SolveWithSolutionCallback(model, ReportPrinter(n,len(cells)))
if status == cp_model.OPTIMAL:
rel = '='
elif status == cp_model.FEASIBLE:
rel = '>='
else:
print('No result for a(%d)\n' % n)
return
for y in range(n):
print(' '*(n-y-1), end='')
for x in range(y+1):
print('.o'[solver.Value(cells[(y,x)])],end=' ')
print()
print('a(%d) %s %d' % (n, rel, len(cells) - solver.ObjectiveValue()))
print()
for n in itertools.count(2):
solve(n)
```
[Answer]
# [Python 3](https://docs.python.org/3/)
Based strongly on [Delfad0r's answer](https://codegolf.stackexchange.com/users/82619/delfad0r), mostly follows the same logic progression by checking triangle pairs and validating the configuration if it contains no triangle pairs that fail this validation. Since I didn't use any libraries besides itertools and copy, I have full control over saving the examples encountered throughout the program.
```
examples = dict() # stores examples by key pair of n to a tuple with the triangle and number of lights turned off
for n in range(3, 8):
tri = [] # model of the triangle, to be filled with booleans representing lights
tri_points = [] # list of tuples representing points of the triangle
for i in range(n):
tri.append([True]*(i + 1))
for j in range(i+1):
tri_points.append((i, j))
t_set = [] # list of all possible triangles from tri, represented by lists of points
for i in range(n):
for j in range(len(tri[i])):
for k in range(1, n - i):
t_set.append([(i, j), (i + k, j), (i + k, j + k)])
from itertools import combinations
import copy
# validates whether or not a triangle of n lights can have i lights turned off, and saves an example to examples if validated
def tri_validate(x):
candidate_list = list(combinations(tri_points, x))
tri_pairs = list(combinations(t_set, 2))
for candidate in candidate_list:
temp_tri = copy.deepcopy(tri)
valid = False
for point in candidate:
(row, col) = point
temp_tri[row][col] = False
for pair in tri_pairs:
valid = False
(tri1, tri2) = pair
for point in tri1:
if not valid:
if point not in tri2:
(row, col) = point
if temp_tri[row][col]:
valid = True
for point in tri2:
if not valid:
if point not in tri1:
(row, col) = point
if temp_tri[row][col]:
valid = True
if not valid:
break
if valid:
examples[n] = (temp_tri, x)
return True
return False
# iterates up to the point that validation fails, then moves on to the next n
for i in range(len(tri_points)):
if tri_validate(i + 1):
continue
break
```
Problem is, it's not very efficient. It runs really fast up to `n=5`, but starts to slow down significantly past that point. At `n=6`, it takes around a minute to run, and it's much slower at `n=7`. I imagine there are a lot of efficiency fixes that can be made with this program, but it's a quickly made rough draft of a good solution with a lot more flexibility to check out the inner workings of this method. I'll be incrementally working on this over time.
] |
[Question]
[
## Background
I saw this very interesting Venn Diagram on wikipedia: <https://simple.wikipedia.org/wiki/Alphabet#/media/File:Venn_diagram_gr_la_ru.svg>
It shows the letters (physical shapes) in different alphabets that are common between Russian, Greek and Latin alphabets.
## The Challenge
Given an input string of characters from any of the three scripts shown (i.e capitalised Greek, Cyrillic or Latin letters), output a percentage of the string that matches each language. Repeated letters count every time.
For example, `FFLURS` is all latin-only characters, so the output is `FFLURS is 100% Latin, 0% Cyrillic and 0% Greek`.
By contrast, `TOX BEAM PHP` is formed completely of characters that appear in all three languages, so the output is `TOX BEAM PHP is 100% Cyrillic, 100% Greek and 100% Latin`.
# Lookup Tables
The Venn diagram is the source of the letters below:
**Latin Only:**
```
J,G,S,D,Q,U,V,W,F,L,R
```
**Latin and Cyrillic:**
```
C, С
```
**Latin and Greek:**
```
I,Ι, N,Ν, Z,Ζ
```
**Greek and Cyrillic**
```
Φ,Ф, Π,П, Γ,Г, Λ,Л
```
**All three:**
```
A,B,E,O,M,K,T,X,Y,H,P (and equivalents in greek and cyrillic), (space)
```
**The rest**
...are Greek-only or Cyrillic-only.
**IMPORTANT NOTE**
Unicode defines (for example) "A" in (at least) three separate ways - one for each language. **Whichever is used in the input (Ƈ, ƚ or )), the program should understand it as matching all three languages.**
So, `A` (Latin), `Α` (Greek Alpha) and `А` (Cyrillic) should all give `100% Cyrillic, 100% Greek and 100% Latin` as the answer.
## Input Format
Any string containing exclusively `А-Я`, `Α-Ω`, `A-Z` and (space). These characters can be repeated multiple times within the string.
## Output Format
The output can be in any format, provided the function produces consistent results. I would *like* to see output in the format I show in my examples (`FFLURS is 100% Latin, 0% Cyrillic and 0% Greek`), but in order to make the challenge more open to anyone I'm happy to accept arrays/strings of percentages/ratios:
`[100,0,0]`,
`100 0 0`
`[1.0 0.0 0.0]`
as long as it's always clear which number is which language - so the output should be consistent.
## Some more test cases
`CINEMATICS` -> `CINEMATICS is 100% Latin, 70% Greek and 60% Cyrillic`
`ЩJЩFЩLΞRΞVΞW` -> `ЩJЩFЩLΞRΞVΞW is 50% Latin, 25% Cyrillic and 25% Greek`
-> `is 100% Cyrillic, 100% Greek and 100% Latin`
`ΨΩTESTINGЯЮ` -> `ΨΩTESTINGЯЮ is 63.6% Greek, 63.6% Latin and 45.5% Cyrillic`
## Winning Criteria
Usual rules and exclusions apply; shortest answer (bytes) wins.
(sandbox link: <https://codegolf.meta.stackexchange.com/a/14984/62289>)
For the avoidance of doubt, the only Unicode characters valid in the input are:
* 0020, 0041-005A (Latin alphabet)
* 0020, 0391-03A9 (Greek alphabet)
* 0020, 0401, 0410-042F (Cyrillic alphabet)
But as shown in the lookup tables, characters may be cross-alphabetic.
Adding Jonathan Allan's table from the comments:
```
Latin Greek Cyrillic
U+0020 Space 1 1 1
U+0041 A Latin capital letter A 1 1 1
U+0042 B Latin capital letter B 1 1 1
U+0043 C Latin capital letter C 1 0 1
U+0044 D Latin capital letter D 1 0 0
U+0045 E Latin capital letter E 1 1 1
U+0046 F Latin capital letter F 1 0 0
U+0047 G Latin capital letter G 1 0 0
U+0048 H Latin capital letter H 1 1 1
U+0049 I Latin capital letter I 1 1 0
U+004A J Latin capital letter J 1 0 0
U+004B K Latin capital letter K 1 1 1
U+004C L Latin capital letter L 1 0 0
U+004D M Latin capital letter M 1 1 1
U+004E N Latin capital letter N 1 1 0
U+004F O Latin capital letter O 1 1 1
U+0050 P Latin capital letter P 1 1 1
U+0051 Q Latin capital letter Q 1 0 0
U+0052 R Latin capital letter R 1 0 0
U+0053 S Latin capital letter S 1 0 0
U+0054 T Latin capital letter T 1 1 1
U+0055 U Latin capital letter U 1 0 0
U+0056 V Latin capital letter V 1 0 0
U+0057 W Latin capital letter W 1 0 0
U+0058 X Latin capital letter X 1 1 1
U+0059 Y Latin capital letter Y 1 1 1
U+005A Z Latin capital letter Z 1 1 0
U+0391 Α Greek capital letter Alpha 1 1 1
U+0392 Β Greek capital letter Beta 1 1 1
U+0393 Γ Greek capital letter Gamma 0 1 1
U+0394 Δ Greek capital letter Delta 0 1 0
U+0395 Ε Greek capital letter Epsilon 1 1 1
U+0396 Ζ Greek capital letter Zeta 1 1 0
U+0397 Η Greek capital letter Eta 1 1 1
U+0398 Θ Greek capital letter Theta 0 1 0
U+0399 Ι Greek capital letter Iota 1 1 0
U+039A Κ Greek capital letter Kappa 1 1 1
U+039B Λ Greek capital letter Lambda 0 1 1
U+039C Μ Greek capital letter Mu 1 1 1
U+039D Ν Greek capital letter Nu 1 1 0
U+039E Ξ Greek capital letter Xi 0 1 0
U+039F Ο Greek capital letter Omicron 1 1 1
U+03A0 Π Greek capital letter Pi 0 1 1
U+03A1 Ρ Greek capital letter Rho 1 1 1
U+03A3 Σ Greek capital letter Sigma 0 1 0
U+03A4 Τ Greek capital letter Tau 1 1 1
U+03A5 Υ Greek capital letter Upsilon 1 1 1
U+03A6 Φ Greek capital letter Phi 0 1 1
U+03A7 Χ Greek capital letter Chi 1 1 1
U+03A8 Ψ Greek capital letter Psi 0 1 0
U+03A9 Ω Greek capital letter Omega 0 1 0
U+0401 Ё Cyrillic capital letter Io 0 0 1
U+0410 А Cyrillic capital letter A 1 1 1
U+0411 Б Cyrillic capital letter Be 0 0 1
U+0412 В Cyrillic capital letter Ve 1 1 1
U+0413 Г Cyrillic capital letter Ghe 0 1 1
U+0414 Д Cyrillic capital letter De 0 0 1
U+0415 Е Cyrillic capital letter Ie 1 1 1
U+0416 Ж Cyrillic capital letter Zhe 0 0 1
U+0417 З Cyrillic capital letter Ze 0 0 1
U+0418 И Cyrillic capital letter I 0 0 1
U+0419 Й Cyrillic capital letter Short I 0 0 1
U+041A К Cyrillic capital letter Ka 1 1 1
U+041B Л Cyrillic capital letter El 0 1 1
U+041C М Cyrillic capital letter Em 1 1 1
U+041D Н Cyrillic capital letter En 1 1 1
U+041E О Cyrillic capital letter O 1 1 1
U+041F П Cyrillic capital letter Pe 0 1 1
U+0420 Р Cyrillic capital letter Er 1 1 1
U+0421 С Cyrillic capital letter Es 1 0 1
U+0422 Т Cyrillic capital letter Te 1 1 1
U+0423 У Cyrillic capital letter U 1 1 1
U+0424 Ф Cyrillic capital letter Ef 0 1 1
U+0425 Х Cyrillic capital letter Ha 1 1 1
U+0426 Ц Cyrillic capital letter Tse 0 0 1
U+0427 Ч Cyrillic capital letter Che 0 0 1
U+0428 Ш Cyrillic capital letter Sha 0 0 1
U+0429 Щ Cyrillic capital letter Shcha 0 0 1
U+042A Ъ Cyrillic capital letter hard sign 0 0 1
U+042B Ы Cyrillic capital letter Yeru 0 0 1
U+042C Ь Cyrillic capital letter soft sign 0 0 1
U+042D Э Cyrillic capital letter E 0 0 1
U+042E Ю Cyrillic capital letter Yu 0 0 1
U+042F Я Cyrillic capital letter Ya 0 0 1
```
[Answer]
# JavaScript (ES6), ~~197~~ 179 bytes
Returns an array of 3 ratios in [0..1].
```
s=>[...s].map(_=>(x='b;C6cC6%c>b^[<$]_3--_c_acC-----$+aKHbKK[`H`H]'[(p=s[a='charCodeAt'](l++)%202%116%89)>>1][a]()-36,x/=p&1||8,L+=x/4&1,G+=x/2&1,C+=x&1),l=L=G=C=0)&&[L/l,G/l,C/l]
```
[Try it online!](https://tio.run/##fY7PboJAEIfvPgUHgd3yd7UhNu2SmI2ClXqopj1striu2tqgECENB5/Fc7m0b0J4IwrttXGSmXzJfDP5vfMPnorjLsmMQ7ze1Ftcp9ilpmmmzNzzBITYBTlWV7fEEcSRhbt6oXddFvYNIxQhF8Roq6vxqb@aTunSX/pMpSDBKeVYFW/8SJq/w0xlINI0KPfsnoyQIw9uoOsiRjkD0Og7em7hREGn00APNJxb1wrSvRZ6DZAGFAT1CAfYwwTbUFFoYEW61zSxIlZv4@OeZxKWuIRdif8mP7TYzCsJ2TY0s3i8yzdrgCDsdER8SONoY0bxK/i7BVugksls9DBcTMhchY31v1QV91UxroqgPD@W56fy/HxBli7sys@yWIzmi8nMq76rr9asfwA "JavaScript (Node.js) – Try It Online")
### How?
We use the (rather inefficient) hash function `% 202 % 116 % 89` to transform each character code into an index in [0..88]. The corresponding lookup table consists of 3-bit entries where bit #2 = Latin, bit #1 = Greek and bit #0 = Cyrillic. Using decimal digits, this gives:
```
76273722773722017732767267300071731711117377737577371111111111000775474476474767744474447
```
We append an extra `1` to get en even number of entries and encode this bit stream with printable ASCII characters in the range [37..99] (`%` to `c`), with 6 bits of payload data per character.
This leads to the following string:
```
b;C6cC6%c>b^[<$]_3--_c_acC-----$+aKHbKK[`H`H]
```
The offset was chosen to avoid characters such as `\` that would have required escaping.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 56 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
A hash may well be shorter.
```
O:⁹:2;ON©œị“ŒḂI4ƥƒⱮıtɱN¦“¤COṙṚ¹`“ÑṂḄẈɼ]ġÐ’b4¤+4Bṙ®Ḣµ€S÷L
```
A monadic link returning a list of ratio amounts in the order English, Greek, Russian.
**[Try it online!](https://tio.run/##AYYAef9qZWxsef//Tzrigbk6MjtPTsKpxZPhu4vigJzFkuG4gkk0xqXGkuKxrsSxdMmxTsKm4oCcwqRDT@G5meG5msK5YOKAnMOR4bmC4biE4bqIybxdxKHDkOKAmWI0wqQrNELhuZnCruG4osK14oKsU8O3TP///9CpStCpRtCpTM6eUs6eVs6eVw "Jelly – Try It Online")**
...or see a [fully formatted output](https://tio.run/##AbgAR/9qZWxsef//Tzrigbk6MjtPTsKpxZPhu4vigJzFkuG4gkk0xqXGkuKxrsSxdMmxTsKm4oCcwqRDT@G5meG5msK5YOKAnMOR4bmC4biE4bqIybxdxKHDkOKAmWI0wqQrNELhuZnCruG4osK14oKsU8O3TP/Dh8OXyLcyw6ZyMTvigqzigJ0lxbzigJw@yovCocOwTHHhupLCu@G4ssKkS@KCrGrigb4sIP//zqjOqVRFU1RJTkfQr9Cu "Jelly – Try It Online") (including the implied rounding to one decimal place)
### How?
We wish to have code which translates each possible character to a triple of ones and zeros representing whether they belong to each of the alphabets (much like the table in the question where `C` is `1 0 1`). Once that is done we can sum across these and divide by the length to yield the ratios (between zero and one inclusive) - this is just `S÷L` (seen at the right of the code).
For any given character We know that if the ordinal is less than 256 it counts as English, if it is greater than 1024 it counts as Russian, and that if it is in-between 256 and 1024 it counts as Greek. As such taking the ordinal and integer dividing by 256 and then integer dividing the result by two yields `0` for the space and Latin characters (count as English), `1` for Hellenic (count as Greek), and `2` for Cyrillic (count as Russian). This is just `O:⁹:2` in Jelly (seen at the left of the code).
If we rotate the triples of bits such that the natural alphabet bit\* is the most significant then we can encode the lower two bits (as values between zero and three inclusive) in a look-up table with three rows and then rotate right by the numbers found above.
When we do this there are two things worthy of note - 1. Jelly has a rotate-left-by atom not a rotate-right-by one; 2. the Hellenic row of the look-up table would start with a zero (since `Ξ` is only Greek), thwarting a simple base-4 encoding (since leading zeros are not encodable). To alleviate (1) we can rotate-left by the negated value and to alleviate (2) we can encode our rows in reverse and index into them with the negative amount. This way we can negate both the row and column index with a single byte (`N`) as such our row and column indices may be calculated with `O:⁹:2;ON`.
Note that Jelly now has a multi-dimensional indexing atom, `œị`.
The table is formed from three large numbers which, once converted to base four, give the lower bits required for Cyrillic, Greek and Latin(+Space) respectively. They are of minimal length such that modular indexing by the negated ordinal values is possible - 47, 25, and 30 respectively (the `.`s are at unused indexes):
```
1: 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 1 3 3 2 3 1 3 3 3 1 3 0 0 0 0 3 0 1 3 0 3 0 0 0 0 0 0
. . . . . . . . . Я Ю Э Ь Ы Ъ Щ Ш Ч Ц Х Ф У Т С Р П О Н М Л К Й И З Ж Е Д Г В Б А Ё . . . . .
2: 3 2 3 1 0 3 1 3 0 2 3 3 0 0 3 2 3 3 0 0 3 2 3 0 1
Μ Λ Κ Ι Θ Η Ζ Ε Δ Γ Β Α Ω Ψ Χ Φ Υ Τ Σ . Ρ Π Ο Ξ Ν
3: 3 3 0 0 0 3 0 0 0 3 3 2 3 0 3 0 2 3 0 0 3 0 1 3 3 0 0 3 0 2
Y X W V U T S R Q P O N M L K J I H G F E D C B A . . . Z
```
As an example consider the character Φ at Unicode point U+03A6 (which should yield `[0,1,1]`) it has an ordinal value of (3×16²+10×16+6 =) 934. (`O:⁹:2` means 934//256//2 =) 1 identifying it as part of the Hellenic block. The `;O` concatenates the ordinal giving us `[1,934]` and the `N` then negates both values giving us `[-1,-934]`. Since Jelly indexing is both 1-based and modular and there are three rows the `-1` references the second of the three rows (row 2 in the above code-block), since the middle row has a length of 25 the `-934` references the (-934%25 =) 16th entry in that row, which is `2`. The code then adds four (the most significant bit) giving us `6` which converted to binary is `[1,1,0]`. The code then rotates this left by each of `[-1,-934]` and takes the head (i.e. the rotation left by -1, a rotation right by 1) yielding `[0,1,1]` as required.
\* English for space since it's grouped with the Latin characters
---
**Commented code**
```
O:⁹:2;ON©œị“...“...“...’b4¤+4Bṙ®Ḣµ€S÷L - Link: list of characters e.g.: "СЯ"
µ€ - for €ach character: С Я
O - cast to ordinal 1057 1071
⁹ - literal 256
: - integer division 4 4
:2 - integer divide by 2 2 2
O - cast to ordinal 1057 1071
; - concatenate [2,1057] [2,1071]
N - negate [-2,-1057] [-2,-1071]
© - copy to register for later
¤ - nilad followed by link(s) as a nilad:
“...“...“...’ - list of integers encoded in base 250 = [4951760157204492290900832256, 1043285073970097, 1081712651052809266]
b4 - convert to base 4 = [[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,1,3,3,2,3,1,3,3,3,1,3,0,0,0,0,3,0,1,3,0,3,0,0,0,0,0,0],[3,2,3,1,0,3,1,3,0,2,3,3,0,0,3,2,3,3,0,0,3,2,3,0,1],[3,3,0,0,0,3,0,0,0,3,3,2,3,0,3,0,2,3,0,0,3,0,1,3,3,0,0,3,0,2]]
œị - index into 2 0 ^--[-2,-1071] [-2,-1057]--^
+4 - add four 6 4
B - convert to binary [1,1,0] [1,0,0]
® - recall from register [-2,-1057] [-2,-1071]
ṙ - rotate left [[1,0,1],[0,1,1]] [[0,0,1],[1,0,0]]
Ḣ - head [1,0,1] [0,0,1]
S - sum [1,0,2]
L - length 2
÷ - divide [0.5,0,1]
- i.e.: 50.0% Latin, 0% Greek, 100% Russian
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 165 bytes
```
->s{(0..2).map{|x|s.chars.map{|c|o=c.ord;(o<33?7:"ĝ]ē¯]÷W59WUė½ñĝĕ×ßoĝėÏė55#{?!*15}"[o-[913,1040,65][y=o>>7<=>7]].ord+226>>3*-~y)[x]*1.0}.sum/s.size}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WsNAT89IUy83saC6pqKmWC85I7GoGMJNrsm3TdbLL0qx1si3MTa2N7dSOjI39sjkQ@tjD28PN7UMDz0y/dDewxuPzD0y9fD0w/PzgYzph/uPTDc1Va62V9QyNK1Vis7XjbY0NNYxNDAx0DEzjY2utM23szO3sbUzj40Fma1tZGRmZ2espVtXqRldEatlqGdQq1dcmqtfrFecWZVaW/u/QCEtWsnNzSc0KFgplgvMC/GPUHBydfRVCPAIgIk5e/q5@jqGeDrDVV1Y6XVhpduFlT7n5gWdmxd2bl44TObcinMrQ1yDQzz93C@sv7AOrqERxlJQiv0PAA "Ruby – Try It Online")
**Edit:** Significantly golfed the code, and most importantly, squeezed 3 translation sequences into one UTF-8 string. The original longer code is kept below for better readability and explanation of the logic.
### Ruby, 211 bytes
```
->s{(0..2).map{|x|s.chars.map{|x|o=x.ord;o<33?7:o<91?"77517117317173771117111773"[o-65]:o<938?"7762737237673276702776722"[o-913]:"74764744444767776757767#{?4*15}"[o-1040]}.inject(0.0){|y,z|y+=z.to_i[x]}/s.size}}
```
[Try it online!](https://tio.run/##PY7dToNAEIXvfQqCN1btyu4CY2uR1AYU09amxZ@EEFNrGzFRGqgJv6/CtdzomxDeCHeb4CRzMuec72KCr5e42WhN9zJMjySESAd9LLdpFmUhWr0tg7C1vhYhP3i98AeU6tD3Bz2siwAKBoyBMgUK7MT7BSo6fldVXM7Rcw6qhAGEggqUMJEIi4AQzvUwdfsiyKDKIPNhDW8VLoepLh9jJecglmTJzZH3@b5e7di3UifN4tMki0@0BO38Z8@J3PwsRKGXrPO82QobRzTN8f18IboHe2ffPQlXxnAizG5mbTaypsZkaFujf6oub@vSrMtxVcyr4qEqHtum@q5K21jY1vS6/q1/2lgQ3eYP "Ruby – Try It Online")
May not be the most efficient approach, but does the job. Uses a translation table for each alphabet with character occurrence in different scripts encoded by the bits of the number (in the order: Latin, Greek, Russian). The output is an array of percentages in the same order.
To fix the outlier `Ё` case I extended the Russian-only block of 4-s from 10 positions at the end of the alphabet to 15. This way, `Ё` gets picked correctly with negative index (and we are not required to handle lowercase letters than correspond to these extra indices).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 230 bytes
```
.+
$&¶$&¶$&¶$&
T`ΓΔΘΛΞΠΣΦΨΩЁБГДЖ-ЙЛПФЦ-Я`_`.+(?=¶.+¶.+$)
T`CDFGJ\LQRSUVWЁБДЖ-ЙС-Я`_`.+(?=¶.+$)
T`DFGIJ\LNQRSUVWZΔΖΘΙΝΞΣΨΩ`_`.+$
¶(.*)
¶$.1$*
1
100$*
.
1
(1+)¶(\1)*1*¶(\1)*1*¶(\1)*1*
$#2 $#3 $#4
```
[Try it online!](https://tio.run/##ZY5PSsNgEMX3c4pAPyV/6Ec/dStSYxJT0liTtBUpGBcu3LgQL@ARpKVYirFSKWZjdzlADjDMjeIkCoIuHm9g3pvf3N883N5dVzu6l1bSArFbFr@CJMUpzvAZl5jhCte4wQ/M6ZGeaEozmrdpQUt6pXfatGmbXqXS0o8Oy0JatYTBB@wT1@tNgvMoHo7GTfOn9/an0aQ57HM6/I5fMnvO9AW@MH9ds5uGgLLQpWmwCamECQpUp8MuedKVZfB6ogxTmf8HEK09TbT2WQdV5brBMIohObvQjp1uXxucDsD2Q6ffTXw7Bsp7lLuUB5hFmI0wG0P9ROLEiR96tKVP0L4A "Retina 0.8.2 – Try It Online") Link includes test cases. Note: Output is in % truncated down to an integer, because increasing the precision made the script too slow and it timed out on TIO.
] |
[Question]
[
Last time you made [a square of text](https://codegolf.stackexchange.com/questions/88926/a-square-of-text), but now, can you make a **cube** of text?
## The Challenge
Given a string, output the string in the form of a cube.
You can assume the string will always have 2 chars or more, and will only have printable ascii characters.
## How to Make a Text Cube

## Test Cases
```
Input:
Test
Output:
Test
e ss
s e e
tseT T
s e e
e ss
Test
Input:
Hello, world!
Output:
Hello, world!
e dd
l l l
l r r
o o o
, w w
w , ,
o o o
r l l
l l l
d e e
!dlrow ,olleH H
d e e
l l l
r l l
o o o
w , ,
, w w
o o o
l r r
l l l
e dd
Hello, world!
Input:
Hi
Output:
Hi
iHH
Hi
```
## Reference Implementation in Python
```
text = raw_input("Enter a string: ")
print " " * (len(text) - 1) + text
spaces = len(text) - 2
_spaces = spaces
for i in range(1, len(text) - 2 + 1):
print " " * spaces + text[i] + " " * _spaces + text[(i + 1) * -1] + " " * (_spaces - spaces) + text[(i + 1) * -1]
spaces -= 1
print text[::-1] + " " * _spaces + text[0]
spaces = _spaces - 1
for i in range(1, len(text) - 2 + 1):
print text[(i + 1) * -1] + " " * _spaces + text[i] + " " * spaces + text[i]
spaces -= 1
print text
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! Tiebreaker is most upvoted.
* Standard loopholes are disallowed.
* Trailing newline and trailing spaces are allowed.
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 92410; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# Python 2, ~~228~~ ~~223~~ ~~221~~ ~~203~~ ~~199~~ ~~195~~ 189
```
t=input()
x=" "
l=len(t)-1
q=l-1
f=range(q,0,-1)
print x*l+t
for i in f:print x*i+t[l-i]+x*q+t[i]+x*(q-i)+t[i]
print t[::-1]+x*q+t[0]
for i in f:print t[i]+x*q+t[l-i]+x*(i-1)+t[l-i]
print t
```
# Python 3, ~~192~~ ~~188~~ 182
```
t=input()
x=" "
l=len(t)-1
q=l-1
p=print
f=range(q,0,-1)
p(x*l+t)
for i in f:p(x*i+t[l-i]+x*q+t[i]+x*(q-i)+t[i])
p(t[::-1]+x*q+t[0])
for i in f:p(t[i]+x*q+t[l-i]+x*(i-1)+t[l-i])
p(t)
```
[Answer]
# x86 (IA-32) machine code, 126 bytes
Hexdump:
```
60 8b f9 57 33 c0 f2 ae 5e 2b fe 4f 87 fa 8d 1c
12 8b c3 48 f6 e3 c6 04 07 00 48 c6 04 07 20 75
f9 8b ea 4d 53 8d 04 2a 50 53 8b c5 f6 e3 8d 44
68 01 50 53 2b c2 8b c8 50 4b 53 55 53 03 c5 50
f7 d3 53 50 53 95 f6 e2 6b c0 04 50 43 53 51 6a
01 4a 52 6a 01 50 6a ff 51 b0 0a 6a 0b 8b dc 59
8b 6c cb fc 88 04 2f 03 2c cb 89 6c cb fc 83 f9
0a 75 01 ac e2 ea 4a 79 e0 83 c4 58 61 c3
```
This is a bit long, so to explain it I'll give C code first:
```
void doit(const char* s, char out[])
{
int n = strlen(s);
int w = 2 * n;
int h = w - 1;
int m = n - 1;
memset(out, ' ', h * w);
out[h * w] = 0;
int offset1 = n + m;
int offset2 = w * m + 2 * m + 1; // 2 * n * n - 1
int offset3 = offset2 - n; // 2 * n * n - n - 1
int offset4 = 4 * n * m; // 4 * n * n - 4 * n
int offsets[] = {
offset3, -1,
offset4, 1,
m, 1,
offset3, 1 - w,
offset4, -w,
offset2 - 1, -w,
offset2 - 1, w - 1,
m, w - 1,
offset3, w,
offset2, w,
offset1, w,
};
do
{
char c = *s++;
for (int i = 0; i < 11; ++i)
{
if (i == 9)
c = '\n';
int offset = offsets[i * 2];
assert(offset > 0 && offset < w * h);
out[offset] = c;
offsets[i * 2] += offsets[i * 2 + 1];
}
} while (--n);
}
```
Here `n` is the length of the input string.
The dimensions of the output area are `2n` (width) by `2n-1` (height). First, it fills everything with spaces (and adds a terminating null byte). Then, it travels along 11 straight lines in the output area, and fills them with text:
* 2 lines are filled with end-of-line bytes (=10)
* 9 lines are filled with the consecutive bytes of the input string
Each line is represented by two numbers, a start offset and a stride. I stuffed them both into the array `offsets`, to make access "easy".
The interesting part is filling the array. There is little importance for the order of the entries in the array; I tried to rearrange them to minimize the number of register conflicts. In addition, quadratic formulas have some freedom in choosing the way of calculation; I tried to minimize the number of subtractions (because additions can be implemented by the flexible `LEA` instruction).
Assembly source:
```
pushad;
; // Calculate the length of the input string
mov edi, ecx;
push edi;
xor eax, eax;
repne scasb;
pop esi; // esi = input string
sub edi, esi;
dec edi;
; // Calculate the size of the output area
xchg edi, edx; // edx = n
// edi = output string
lea ebx, [edx + edx]; // ebx = w
mov eax, ebx;
dec eax; // eax = h
mul bl; // eax = w * h
; // Fill the output string with spaces and zero terminate it
mov byte ptr [edi + eax], 0;
myfill:
dec eax;
mov byte ptr [edi + eax], ' ';
jnz myfill;
mov ebp, edx;
dec ebp; // ebp = m
; // Fill the array of offsets
push ebx; // w
lea eax, [edx + ebp];
push eax; // offset1
push ebx; // w
mov eax, ebp;
mul bl;
lea eax, [eax + 2 * ebp + 1];
push eax; // offset2
push ebx; // w
sub eax, edx;
mov ecx, eax; // ecx = offset3
push eax; // offset3
dec ebx;
push ebx; // w - 1
push ebp; // m
push ebx; // w - 1
add eax, ebp;
push eax; // offset2 - 1
not ebx;
push ebx; // -w
push eax; // offset2 - 1
push ebx; // -w
xchg eax, ebp; // eax = m
mul dl;
imul eax, eax, 4;
push eax; // offset4
inc ebx;
push ebx; // 1 - w
push ecx; // offset3
push 1;
dec edx; // edx = n - 1
push edx;
push 1;
push eax;
push -1;
push ecx;
; // Use the array of offsets to write stuff to output
myout:
mov al, '\n';
push 11;
mov ebx, esp;
pop ecx;
myloop:
mov ebp, [ebx + ecx * 8 - 4];
mov [edi + ebp], al;
add ebp, [ebx + ecx * 8];
mov [ebx + ecx * 8 - 4], ebp;
cmp ecx, 10;
jne skip_read;
lodsb;
skip_read:
loop myloop;
dec edx;
jns myout;
add esp, 11 * 8;
popad;
ret;
```
I used byte multiplications here, limiting the length of the input string to 127. This avoids clobbering the register `edx` - the product is calculated in `ax` instead.
A minor glitch: when filling the array, the length of the string gets decreased by 1. So I adjusted the loop exit condition:
```
jns myout
```
It counts down to -1.
[Answer]
# Ruby, ~~148~~ 144 bytes
+1 byte from the `n` flag. Shows newlines instead of semicolons for readability (same functionality).
```
S=" "
X=S*s=$_.size-2
puts X+S+I=$_,(r=1..s).map{|i|c=I[~i];S*(s-i+1)+I[i]+X+c+S*~-i+c},I.reverse+X+I[0],r.map{|i|c=I[i];I[~i]+X+c+S*(s-i)+c},I
```
Run like so. Input is a line of STDIN, with no trailing newline, so it likely needs to be piped from file.
```
ruby -ne 'S=" ";X=S*s=$_.size-2;puts X+S+I=$_,(r=1..s).map{|i|c=I[~i];S*(s-i+1)+I[i]+X+c+S*~-i+c},I.reverse+X+I[0],r.map{|i|c=I[i];I[~i]+X+c+S*(s-i)+c},I'
```
[Answer]
# Pyth, 78 bytes
```
AtBtlQJ_SH
+*dGQVJs[*Nd@Q-GN*dHK@QN*d-HNK;
++_Q*dHhQVJs[@QN*dH@Q-GN*dtN@Q-GN;
```
With trailing newline. Inspired by Joshua de Haan's Python 3 answer.
[Try it online here!](http://pyth.herokuapp.com/?code=AtBtlQJ_SH%0A%2B%2adGQVJs%5B%2aNd%40Q-GN%2adHK%40QN%2ad-HNK%3B%0A%2B%2B_Q%2adHhQVJs%5B%40QN%2adH%40Q-GN%2adtN%40Q-GN%3B%0A&input=%22head%22&debug=0)
[Answer]
## Javascript, ~~225~~ 198 bytes
Saved 27 bytes thanks to @Neil
```
f=(s,l=s.length-2,d=' ',r='repeat',t=d[r](l))=>[d+t+s,...a=[...Array(l)].map((_,i)=>d[r](l-i)+s[i+1]+t+(p=s[l-i])+d[r](i)+p),[...s].reverse().join``+t+s[0],...a.map(v=>v.trim()).reverse(),s].join`
`
```
* [...] instead of .concat
* [...]+map instead of *for* loop
* only one statement by moving variables as function parameters
* better initialization for *l* and *t*
**Original answer:**
```
f=s=>{l=s.length,d=' ',r='repeat',a=[],t=d[r](l-2)+s;for(i=1;i++<l-1;)a.push(d[r](l-i)+s[i-1]+d[r](l-2)+(p=s[l-i])+d[r](i-2)+p);console.log(d+[t].concat(a,[...t].reverse().join``+s[0],a.map(v=>v.trim()).reverse(),s).join`
`)}
```
[Answer]
# Java 7, 283 bytes
```
void a(String s){int h=s.length(),n=h*2-1,t=n-h,u=n-1;char[][]c=new char[n][n];for(int i=0;i<h;i++){c[0][t+i]=c[i][t-i]=c[t][t-i]=c[t+i][t]=c[t+i][u-i]=c[t-i][t+i]=c[t-i][u]=c[u][i]=c[u-i][0]=s.charAt(i);}for(int y=0;y<n;y++){System.out.println(new String(c[y]).replace('\0',' '));}}
```
[**Try it here!**](https://ideone.com/si1aKH)
**Ungolfed:**
```
void a(String s) {
int length=s.length(),
n=length*2-1,
mid=n-length,
doubleMid=n-1;
char[][]c=new char[n][n];
for(int i=0;i<length;i++) {
c[0][mid+i]=
c[i][mid-i]=
c[mid][mid-i]=
c[mid+i][mid]=
c[mid+i][doubleMid-i]=
c[mid-i][mid+i]=
c[mid-i][doubleMid]=
c[doubleMid][i]=
c[doubleMid-i][0]=s.charAt(i);
}
for(int y=0;y<n;y++){
System.out.println(new String(c[y]).replace('\0',' '));
}
}
```
] |
[Question]
[
The internet has failed. DDoS attacks are now rampant and widespread. It is up to you to take control and repair the internet.
Each bot will control 20 nodes in this network. Every node is either *active* or *safe*, has an owner, and has a strength, which starts at 2. Every active node is connected to all other active nodes.
Each turn, you will receive a list of all active nodes with their strength. For each of the active nodes that you own, you either:
1. Designate an *active* node you want to transfer your *entire* strength to, or
2. Save and increase its strength
Then the following happens *in order*:
1. A Node choosing to save its strength will increase its strength by 1.
2. All nodes choosing to transfer their strength will simultaneously transfer their entire strength to the new node.
3. If a node was transferred strength from an enemy node, an attack will ensue. If an enemy *owner* collectively transfers more strength than the original owner (and all other attackers), then that enemy becomes the new owner. The strength of that node then becomes the strength of the attacker. If there is a tie for strength, then the owner will be chosen randomly.
4. All nodes left without any strength will be considered *safe*, and gives 1 point to the owner.
After 100 games of 100 turns, the owner with the most safe nodes across all games wins. **EDIT: I changed it from 2000 to 100 turns, as it ended up that the last 1900 turns were useless**
# IO
You will be passed the list of active nodes (via command line args) like the following:
```
F20 F4 E7 E2 E20 F2
```
`F` designates that the node is a friendly node, and `E` designates that the node is an enemy.
For each of your friendly nodes, you should return an action (via STDOUT) like the following:
```
0,0 1,3 5,0
```
The above would mean that you want to increase your strength of the first node, use your second node to attack the fourth node, and your last node will transfer its strength the first node (and if nobody attacks it, it will become a safe node).
After returning, your program should quit.
# Scoreboard
>
> accumulator got 3240 points
>
>
> classy got 2370 points
>
>
> dumbot got 2262 points
>
>
> random\_bot got 1603 points
>
>
> smarter\_random\_bot got 1319 points
>
>
> steady\_bot got 1097 points
>
>
>
The controller can be found here: <https://github.com/nathanmerrill/NetAttack>
[Answer]
# Accumulator, Python
Let's get this party started! My submission should work both on Python 2 and Python 3.
```
import sys
inputs = [(i, x[0], int(x[1:])) for (i, x) in enumerate(sys.argv[1].split())]
own_nodes = sorted([(s,i) for (i,o,s) in inputs if o == 'F'])
targets = sorted([(s,i) for (i,o,s) in inputs if o == 'E'])
if targets:
t_copy = targets[:]
out = ""
total_str = 0
attackers = []
for (s,i) in own_nodes:
attackers += [i]
if t_copy:
total_str += s
if t_copy[0][0] < total_str - 1:
j = max([j for j in range(len(t_copy)) if t_copy[j][0] < total_str - 1])
out += " ".join([str(k) + "," + str(t_copy[j][1]) for k in attackers]) + " "
attackers = []
total_str = 0
t_copy = t_copy[:j] + t_copy[j+1:]
if attackers:
if t_copy:
out += " ".join([str(k) + "," + str(t_copy[0][1]) for k in attackers])
else:
out += " ".join([str(k) + "," + str(attackers[0]) for k in attackers])
else:
out = " ".join([str(i) + "," + str(own_nodes[0][1]) for (s,i) in own_nodes])
print(out.rstrip())
sys.stdout.flush()
```
The idea is really simple.
I start enumerating my nodes in ascending order of strength, keeping a running sum of the strengths.
When the sum exceeds the strength of the weakest enemy node (+1 for a possible increase), I attack that node and remove it from the pool, reset the sum, and continue.
At the end, if the strongest nodes can't find anyone to attack, they'll collect more strength.
*EDIT:* Accumulator is now a bit smarter.
Instead of always attacking the weakest enemy node, it accumulates the strength until it could do so, and then attacks the strongest free node it can with that strength.
Also, if there are still enemies left at the end, any unassigned nodes will attack the weakest remaining enemy, just in case it decides to transfer its strength away.
[Answer]
# Classy, Python3
```
import random, sys
f,e,p=[],[],[]
for si,s in enumerate(sys.argv[1].split()):
if s[0]=='F': f+=[(int(s[1:]),si)]
else: e+=[(int(s[1:]),si)]
f=sorted(f,key=lambda t:t[0]);r=4
f1,f2,f3=f[:len(f)//r],f[len(f)//r:len(f)//r*2],f[len(f)//r*2:]
for fa in f3:
ea=[t for t in e if t[0]<fa[0]]
p+=[(fa[1],random.choice(ea)[1])] if ea else [(fa[1],fa[1])]
for fd,fs in zip(f1,reversed(f2)):
p+=[(fs[1],fd[1])]
p+=[(fd[1],fd[1])]
if len(e)==0: p=[(fe[1],0) for fe in f]
for t in p: print(t[0],',',t[1],' ',sep='',end='')
sys.stdout.flush()
```
The bot splits its own nodes into 3 categories based on strength and each node acts according to its category.
* Each strong node attacks a random enemy node which it can beat.
* Each middle node supports it's weak node pair.
* Each weak node supports itself.
Result against Accumulator and the two sample bots:
```
smarter_random_bot got 1301 points
random_bot got 1841 points
Accumulator got 2178 points
Classy got 2580 points
```
[Answer]
# Dumbot, Nodejs
```
var input = process.argv.splice(2);
var regexp = new RegExp(" ", "gm");
input = String(input).split(regexp);
var nodes = [];
var targets = [];
for(var i = 0; i < input.length; i++){
if(input[i].charAt(0) == "F")
nodes.push(i);
else
targets.push(i);
}
var result = "";
var length = nodes.length;
for(var i = 0; i < length; i++){
if(targets.length>0)
result += nodes.shift() + "," + targets.shift() + " ";
else
result += nodes.shift() + ",0 ";
}
console.log(result);
```
The bot will attack without any thinking or strategy. The main goal is to ensure a lot of safe node right at the beginning. Be aware that this bot make an infinite loop with accumulator.
[Answer]
# SteadyBot, Node.js
```
(new Promise(function(resolve, reject) {
var input = process.argv[2];
if(input) {
resolve(input);
} else {
process.stdin.once('data', function(data){
resolve(data.toString());
});
}
})).then(function(input) {
return input.trim().split(' ');
}).then(function(nodes) {
var friends = [], enemies = [];
nodes.forEach(function(value, index) {
var data = { index: index, strength: parseInt(value.substring(1)) };
if(value[0] === 'F') {
friends.push(data);
} else {
enemies.push(data);
}
});
function weaknessCompare(a, b) {
return (a.strength > b.strength) ? -1 : ((a.strength < b.strength) ? 1 : 0);
}
friends.sort(weaknessCompare);
enemies.sort(weaknessCompare);
if(enemies.length === 0) {
friends.forEach(function(friend) {
friend.target = 0;
});
} else {
if(friends.length > 0) {
var strongest = friends[0];
for(var i = 0; i < enemies.length; i++) {
var enemy = enemies[i];
if(enemy.strength + 1 < strongest.strength) {
strongest.target = enemy.index;
break;
}
};
}
if(friends.length > 1) {
friends[1].target = friends[friends.length - 1].index;
}
}
console.log(friends.map(function(friend) {
return friend.index + ',' +
(typeof friend.target === 'number' ? friend.target : friend.index);
}).join(' '));
});
```
* Assumes enemies won't reinforce large nodes: Largest friendly node attacks strongest enemy it can beat under this assumption.
* Assumes that weakest target will be attacked: Second largest friendly node moves to weakest friendly node each round.
* Wants lots of free strength: Other nodes wait.
] |
[Question]
[
On December 4, 2017, the Google Doodle was a [graphical programming game featuring a bunny](https://www.google.com/doodles/celebrating-50-years-of-kids-coding). The later levels were nicely non-trivial and they seemed like a great candidate for an [atomic-golf](/questions/tagged/atomic-golf "show questions tagged 'atomic-golf'") challenge.
## Details
### Game
* **There are four available moves: hop forward, turn left, turn right, and loop. Each of these moves is one token**, corresponding to the fact that they are each one tile in the game.
* The bunny can face four orthogonal directions (i.e. north, south, east, west).
* The bunny can hop forward (move one square in the direction it's facing) and turn left or right.
* Loops may have any number of other moves inside them, including other loops, and their iteration count is any positive integer (though the game technically allows an iteration count of 0).
* The board is a set of grid-aligned squares and the bunny can hop between adjacent squares.
* **The bunny cannot hop into the void.** Meaning that an attempt to hop off the board does nothing. *(This was apparently a surprise for some people and a disappointment for others.)*
* Squares are either marked or unmarked. When the bunny is on a square, it becomes marked.
* The level is complete when all squares are marked.
* You may assume a solution exists.
### Your code
* **Objective: given a board, find one or more shortest solutions.**
* Input is a list of square locations forming the board (distinguishing marked and unmarked squares) and output is a list of moves. Input and output *format* does not matter at all, so long as they are human-readable and understandable.
* **Winning criterion:** sum of number of moves of shortest solutions found within one minute for each board. If your program does not find a solution for any particular board, your score for that board is (5 \* number of squares).
* **Please do not hardcode solutions in any manner.** Your code should be able to take any board as input, not just the ones given as examples below.
## Examples
**Solutions are hidden in spoilers to give you a chance to play the game first and attempt some of these yourself.** Also, only one solution is provided below for each.
`S` is the bunny's starting square (facing east), `#` is an unmarked square, and `O` is a marked square. For moves, my notation is `F` = hop forward, `L` = turn left, `R` = turn right, and `LOOP(<num>){<moves>}` denotes a loop that iterates `<num>` times and does `<moves>` each time. If the loop can run any number of times beyond some minimum number, `<num>` may be omitted (i.e. infinity works).
**Level 1:**
```
S##
```
>
> F F
>
>
>
**Level 2:**
```
S##
#
#
```
>
> LOOP(2){F F R}
>
>
>
**Level 3:**
```
S##
# #
###
```
>
> LOOP{F F R}
>
>
>
**Level 4:**
```
###
# #
##S##
# #
###
```
>
> LOOP{ F LOOP(7){F L} } (found by DJMcMayhem)
>
>
>
**Level 5:**
```
#####
# # #
##S##
# # #
#####
```
>
> LOOP(18){ LOOP(10){F R} L}
>
> Source: [Reddit](https://www.reddit.com/r/ProgrammerHumor/comments/7hrikj/valid_shortest_solution_that_requires_40_hours_to/)
>
>
>
**Level 6:**
```
###
#OOO#
#OSO#
#OOO#
###
```
>
> LOOP{ LOOP(3){F} L }
>
>
>
**Huge boards:** (shortest solutions currently unknown)
12x12:
```
S###########
############
############
############
############
############
############
############
############
############
############
############
```
Level 5 but way bigger:
```
#############
# # # # # # #
#############
# # # # # # #
#############
# # # # # # #
######S######
# # # # # # #
#############
# # # # # # #
#############
# # # # # # #
#############
```
More holey boards:
```
S##########
###########
## ## ## ##
###########
###########
## ## ## ##
###########
###########
## ## ## ##
###########
###########
```
and
```
S#########
##########
## ## ##
## ## ##
##########
##########
## ## ##
## ## ##
##########
##########
```
Finally, asymmetry can be a real pain in the butt:
```
#######
# ## #
#######
###S###
# ## #
# ## #
#######
```
and
```
#########
# ## ###
###S ###
# #######
### ##
##### #
#### ###
#########
#########
```
[Answer]
# Python 3, 67 tokens
```
import sys
import time
class Bunny():
def __init__(self):
self.direction = [0, 1]
self.coords = [-1, -1]
def setCoords(self, x, y):
self.coords = [x, y]
def rotate(self, dir):
directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
if dir == 'L':
self.direction = directions[(directions.index(self.direction) + 1) % 4]
if dir == 'R':
self.direction = directions[(directions.index(self.direction) - 1) % 4]
def hop(self):
self.coords = self.nextTile()
# Returns where the bunny is about to jump to
def nextTile(self):
return [self.coords[0] + self.direction[0], self.coords[1] + self.direction[1]]
class BoardState():
def __init__(self, map):
self.unvisited = 0
self.map = []
self.bunny = Bunny()
self.hopsLeft = 0
for x, row in enumerate(map):
newRow = []
for y, char in enumerate(row):
if char == '#':
newRow.append(1)
self.unvisited += 1
elif char == 'S':
newRow.append(2)
if -1 in self.bunny.coords:
self.bunny.setCoords(x, y)
else:
print("Multiple starting points found", file=sys.stderr)
sys.exit(1)
elif char == ' ':
newRow.append(0)
elif char == 'O':
newRow.append(2)
else:
print("Invalid char in input", file=sys.stderr)
sys.exit(1)
self.map.append(newRow)
if -1 in self.bunny.coords:
print("No starting point defined", file=sys.stderr)
sys.exit(1)
def finished(self):
return self.unvisited == 0
def validCoords(self, x, y):
return -1 < x < len(self.map) and -1 < y < len(self.map[0])
def runCom(self, com):
if self.finished():
return
if self.hopsLeft < self.unvisited:
return
if com == 'F':
x, y = self.bunny.nextTile()
if self.validCoords(x, y) and self.map[x][y] != 0:
self.bunny.hop()
self.hopsLeft -= 1
if (self.map[x][y] == 1):
self.unvisited -= 1
self.map[x][y] = 2
else:
self.bunny.rotate(com)
class loop():
def __init__(self, loops, commands):
self.loops = loops
self.commands = [*commands]
def __str__(self):
return "loop({}, {})".format(self.loops, list(self.commands))
def __repr__(self):
return str(self)
def rejectRedundantCode(code):
if isSnippetRedundant(code):
return False
if type(code[-1]) is str:
if code[-1] in "LR":
return False
else:
if len(code[-1].commands) == 1:
print(code)
if code[-1].commands[-1] in "LR":
return False
return True
def isSnippetRedundant(code):
joined = "".join(str(com) for com in code)
if any(redCode in joined for redCode in ["FFF", "RL", "LR", "RRR", "LLL"]):
return True
for com in code:
if type(com) is not str:
if len(com.commands) == 1:
if com.loops == 2:
return True
if type(com.commands[0]) is not str:
return True
if com.commands[0] in "LR":
return True
if len(com.commands) > 1 and len(set(com.commands)) == 1:
return True
if isSnippetRedundant(com.commands):
return True
for i in range(len(code)):
if type(code[i]) is not str and len(code[i].commands) == 1:
if i > 0 and code[i].commands[0] == code[i-1]:
return True
if i < len(code) - 1 and code[i].commands[0] == code[i+1]:
return True
if type(code[i]) is not str:
if i > 0 and type(code[i-1]) is not str and code[i].commands == code[i-1].commands:
return True
if i < len(code) - 1 and type(code[i+1]) is not str and code[i].commands == code[i+1].commands:
return True
if len(code[i].commands) > 3 and all(type(com) is str for com in code[i].commands):
return True
return False
def flatten(code):
flat = ""
for com in code:
if type(com) is str:
flat += com
else:
flat += flatten(com.commands) * com.loops
return flat
def newGen(n, topLevel = True):
maxLoops = 9
minLoops = 2
if n < 1:
yield []
if n == 1:
yield from [["F"], ["L"], ["R"]]
elif n == 2:
yield from [["F", "F"], ["F", "L"], ["F", "R"], ["L", "F"], ["R", "F"]]
elif n == 3:
for innerCode in newGen(n - 1, False):
for loops in range(minLoops, maxLoops):
if len(innerCode) != 1 and 0 < innerCode.count('F') < 2:
yield [loop(loops, innerCode)]
for com in "FLR":
for suffix in newGen(n - 2, False):
for loops in range(minLoops, maxLoops):
if com not in suffix:
yield [loop(loops, [com])] + suffix
else:
for innerCode in newGen(n - 1, False):
if topLevel:
yield [loop(17, innerCode)]
else:
for loops in range(minLoops, maxLoops):
if len(innerCode) > 1:
yield [loop(loops, innerCode)]
for com in "FLR":
for innerCode in newGen(n - 2, False):
for loops in range(minLoops, maxLoops):
yield [loop(loops, innerCode)] + [com]
yield [com] + [loop(loops, innerCode)]
def codeLen(code):
l = 0
for com in code:
l += 1
if type(com) is not str:
l += codeLen(com.commands)
return l
def test(code, board):
state = BoardState(board)
state.hopsLeft = flatten(code).count('F')
for com in code:
state.runCom(com)
return state.finished()
def testAll():
score = 0
for i, board in enumerate(boards):
print("\n\nTesting board {}:".format(i + 1))
#print('\n'.join(board),'\n')
start = time.time()
found = False
tested = set()
for maxLen in range(1, 12):
lenCount = 0
for code in filter(rejectRedundantCode, newGen(maxLen)):
testCode = flatten(code)
if testCode in tested:
continue
tested.add(testCode)
lenCount += 1
if test(testCode, board):
found = True
stop = time.time()
print("{} token solution found in {} seconds".format(maxLen, stop - start))
print(code)
score += maxLen
break
if found:
break
print("Final Score: {}".format(score))
def testOne(board):
start = time.time()
found = False
tested = set()
dupes = 0
for maxLen in range(1, 12):
lenCount = 0
for code in filter(rejectRedundantCode, newGen(maxLen)):
testCode = flatten(code)
if testCode in tested:
dupes += 1
continue
tested.add(testCode)
lenCount += 1
if test(testCode, board):
found = True
print(code)
print("{} dupes found".format(dupes))
break
if found:
break
print("Length:\t{}\t\tCombinations:\t{}".format(maxLen, lenCount))
stop = time.time()
print(stop - start)
#testAll()
testOne(input().split('\n'))
```
This program will test a single input board, but I find **[this test driver more useful](https://tio.run/##zRltb9pG@Lt/xc1oit0YBOmkaVFTaauUaRJbJOg3iiInPprrzBnZpgVF@e3Z89yb7@wz0KaVRguYe95f77nLZl8/FPz18zNbb4qyJtW@CtRjzdY0CO7ztKrIH1vO91F8GRB4ZXRFbm8ZZ/XtbVTRfKXW8YU/Rxkr6X3NCk6uyGKckMnShd8XRZlVCBxOEjIEsOFb0fqdgArGCdklZN9m35Aj1CIuizqtqaIEJSxCo5KgW4DY8TJRyiVSD70A@jT6shWSkqsrcjY9a9h5TW1kLKLmecR4RneRix2TczKJyc/kF6@o2XcVNTSijKceio03csa14henu/o9y2kUS8oBmdF6W4IPvzzQkpL6gZI7zAzCKpLeFVtImoJ82q438G1kGS4tgaXgRRaW4MV4CY5x9V9gXGyciQcHQ6ZTtUjLbC4SoS9fE7JON23Tt/wzq1hNM7B@7IIAG7NG@c8sS9OvdHG4QPBwNaWrWnAzoFVRYkqXxRfCOKF8u6Ylaurqgy9Ov8wAS4i115HDPiH3D2npsgCeLRYqqQQqZtXgrAtvRI3SzYbyLJrEXqSWj86vyCToINLcljc/Sd5FHHixgNNwgiY2vlYZ4OfqhmXUNBLRQrwkNK9oP7NNyXgdhX9v85ptckqqOi1rxj@STQGACiKx5VmYkBXk9hX0zVFVZ7Qs437tAIfuWI0uPuI6cpLrxkf53HxzCPp9o/zyF/@c5iwzmcj4Zluf6o5eV@h606pJRS2kU9NCaflP0YobdgPG6dHAdTTELgKUrHqgWU8ra/cRU/pIK7x1aG9TTMC6N2QH75zySLsjJinPJGjfAkF/tDQst/xdsVYC7ou1xZ@tpILGiFa7kPKDDr7pZG9aBh4lB/kiC69bWYiG6z1GRtDaaVo9QCDZvhNeE@4wHtgtF/sl@Qnc3c1YSwhuerEfwdg49PY10CNqSQO7JvHlKa1SsPTiWNzIRSO1W3qWEWrGwdDqHS8v0LDevQ7BlUiGNXitau97AgwKiO/2NCBJcBd6pX9YU8TtbVWX3RlQJXIo9Hp8SsjjUxyOYONap3XUyATNWKUWjHKxzb2km372IFpCgiAQmU8/wTAwoxl05ZRD88/QSxlVlBBCVs05g7bSINkIFuvrFCIQaLJ6v5GcYEpcxjjqgOhLN88lENtSOJ2FvsJQTLvxBXosZ82jcYVIMV9TE0q366RD36@Q31K18r7cUuXRw/76VGAbhdQIwxE@RxgQTEsxomDpg3CpqvZkCmNSSTMMDQIVB0S3Vhfh9fU1dOdwNsVP0B6fZ@JrOp2Gy268pM56OrJEO15WcVyLEPKidsPohGJ9MApNd9PFA@XrbwUdBVs8tE5N1MbLfv1O5dpi2J8FB5l5vfGWTETvlTtQ7UL7nHVIhDfJLJ4ncMOgMzSyTPlHGulqimNf@KFKmONiY46CHQw9Kgw@GAuiNgG6GkjkMlTfYdU7bN8YLcSR7biI82MiTjH/gH0Wie58ts/aujm2m9Xv4ARLj/Ov0uP8ZD38id/Oh7fktZCY5nnkdBNUpdV6HMoThLsNWQybeVrX2hmSAy6Jjvt1za4TZsHnHN20PjB1aKxGEbsTvGoaoGMBYksDYHb/E8h4QupiM6WfaQ66o8XKmnW6m6rh4ze5wLheuNB7BoeUsIpwz2iemaO4gLtVKhFWJfhlAVtJiJc64VR@zcKlIhSnJN5q3G1S2HAUvXieWs8zzbfBmannjoTXl87xn3FOS73ZaRdhricy@K1kQRK5y5gGp92UGA/6D/6YxEZajPOxrKcxuNSsQ0S30HNhRo9huWcbU14XA52a3RrGS/d6Q2VkeN3ZcRBabVcrtmuZfuE3/SXmWycQ7BV4XhSS@4/7HhsXQL6MxXWTIA4849s3hBTLUxVEVx1bjcmvrp@Pn89f6K5Wxrz1bebfPyf63PeD0uKw4hBsEfZDpAhHvF7bsfthS5667Ts3V4u9rTuXN2tfNbbmspVrcVaTdhpzrsb6mlZykE/IHd6VKuUqPFfibWZzfyrBDdS@1HR2J6uJHJnDJR91SyEPsYFzqENwc0PRaPw77Lla0/uipI4rmTLFvREVS3YWqDuhD/wDfw8s8U5Ikj0@XZoDKhNX8835aiCpzj7wM3nOkV5JcCG27SrRLfhHkxF@RLFdAjDZArA5AuILrRIHKJyjY7dgMIUpb5IbOsnkopXPUKzv0O3OfXXjfFlOK5bXtIw8h@NEl5qUFXuqBTUUddkKt/cko3FBqLTMX333BQfH@w4ukmqUZlmkmXnuJY3V575rFaWIYeCmeLeLyLj4D1IyrMWmFdUDV6KPT9DY/4W4VUW@FX@pkRLAJQCqKNieVSbRpN8TKWMoMyg@xN/v@6YiwCOSpxfnrqTpv51BVyjY9Y6FrGy7ZjzNyRwFXYI1zX0OruC1zbMsN7xJwmsd8WtUbXImaydeTC7xRgKT09RqCJPsfDAIhsOh@IZqE2/9ewDPAwWHb0JwBT8HClviNxiSRlDNrWeNgahAfXNzA6s3c/GJz3JdSTWvYPD/@mFsbMDE@vdC2PwH8LQ1n/vNgmei/weDH4zj6hG41ES@3ceX4loxCwYSNbDQ5s56C@7EW0MVnXoiFi@xWSlqovkYirZqAdSeKs8QBIVYwoHZaJ//Aw)**. It will test every single board at the same time and print how long it took to find that solution. When I run that code on my machine (Intel i7-7700K quad core CPU @ 4.20 GHz, 16.0 GB RAM), I get the following output:
```
Testing board 1:
2 token solution found in 0.0 seconds
['F', 'F']
Testing board 2:
4 token solution found in 0.0025103092193603516 seconds
[loop(17, [loop(3, ['F']), 'R'])]
Testing board 3:
4 token solution found in 0.0010025501251220703 seconds
[loop(17, [loop(3, ['F']), 'L'])]
Testing board 4:
5 token solution found in 0.012532949447631836 seconds
[loop(17, ['F', loop(7, ['F', 'L'])])]
Testing board 5:
5 token solution found in 0.011022329330444336 seconds
[loop(17, ['F', loop(5, ['F', 'L'])])]
Testing board 6:
4 token solution found in 0.0015044212341308594 seconds
[loop(17, [loop(3, ['F']), 'L'])]
Testing board 7:
8 token solution found in 29.32585096359253 seconds
[loop(17, [loop(4, [loop(5, [loop(6, ['F']), 'L']), 'L']), 'F'])]
Testing board 8:
8 token solution found in 17.202533721923828 seconds
[loop(17, ['F', loop(7, [loop(5, [loop(4, ['F']), 'L']), 'F'])])]
Testing board 9:
6 token solution found in 0.10585856437683105 seconds
[loop(17, [loop(7, [loop(4, ['F']), 'L']), 'F'])]
Testing board 10:
6 token solution found in 0.12129759788513184 seconds
[loop(17, [loop(7, [loop(5, ['F']), 'L']), 'F'])]
Testing board 11:
7 token solution found in 4.331984758377075 seconds
[loop(17, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])]
Testing board 12:
8 token solution found in 58.620323181152344 seconds
[loop(17, [loop(3, ['F', loop(4, [loop(3, ['F']), 'R'])]), 'L'])]
Final Score: 67
```
This last test just barely squeaks in under the minute restriction.
### Background
This was one of the most fun challenges I've ever answered! I had a blast pattern hunting and looking for heuristics to cut down on things.
Generally, here on PPCG I tend to answer relatively easy questions. I'm especially fond of the [string](/questions/tagged/string "show questions tagged 'string'") tag because it's generally pretty well suited for my languages. One day, about two weeks ago, I was looking through my badges and I realized that I had never gotten the [revival](https://codegolf.stackexchange.com/help/badges/59/revival) badge. So I looked through the *unanswered* tab to see if anything caught my eye, and I found this question. I decided that I would answer it no matter the cost. It ended up being a bit harder than I thought it would, but I finally got a brute-force answer that I can say I'm proud of. But this challenge is totally out of the norm for me since I don't usually spend more than an hour or so on a single answer. This answer took me a little over 2 weeks and at least 10+ of work to finally get to this stage, though I wasn't keeping careful track.
The first iteration was a pure brute force solution. I used the following code to generate all snippets up to length **N**:
```
def generateCodeLenN(n, maxLoopComs, maxLoops, allowRedundant = False):
if n < 1:
return []
if n == 1:
return [["F"], ["L"], ["R"]]
results = []
if 1:
for com in "FLR":
for suffix in generateCodeLenN(n - 1, maxLoopComs, maxLoops, allowRedundant):
if allowRedundant or not isSnippetRedundant([com] + suffix):
results.append([com] + suffix)
for loopCount in range(2, maxLoopComs):
for loopComs in range(1, n):
for innerCode in generateCodeLenN(loopComs, maxLoopComs, maxLoops - 1, allowRedundant):
if not allowRedundant and isSnippetRedundant([loop(loopCount, innerCode)]):
continue
for suffix in generateCodeLenN(n - loopComs - 1, maxLoopComs, maxLoops - 1, allowRedundant):
if not allowRedundant and isSnippetRedundant([loop(loopCount, innerCode)] + suffix):
continue
results.append([loop(loopCount, innerCode)] + suffix)
if loopComs == n - 1:
results.append([loop(loopCount, innerCode)])
return results
```
At this point, I was sure that testing every single possible answer would be way too slow, so I used `isSnippetRedundant` to filter out snippets that could be written with a shorter snippet. For example, I would refuse to yield the snippet `["F", "F", "F"]` because the exact same effects could be achieved with `[Loop(3, ["F"])`, so if it we get to the point where we test length-3 snippets, we know that no length-3 snippet could solve the current board. This used a lot of good mnemonics, but ultimately was *waaaay* too slow. Testcase 12 took just over 3,000 seconds using this approach. This is clearly significantly too slow. But using this information and a bunch of computer cycles to brute force short solutions to every board, I could find a new pattern. I noticed that almost every solution found would generally look like something like the following:
```
[<com> loop(n, []) <com>]
```
nested several layers deep, with the single coms on each side being optional. This means that solutions like:
```
["F", "F", "R", "F", "F", "L", "R", "F", "L"]
```
would never appear. In fact, there was never a sequence of more than 3 non-loop tokens. One way to utilize this would be to filter out all of these and not bother to test them. But generating them was still taking a non-negligible amount of time, and filtering through the millions of snippets like this would barely cut time off. Instead I drastically rewrote the code-generator to only generate snippets following this pattern. In pseudo code, the new generator follows this general pattern:
```
def codeGen(n):
if n == 1:
yield each [<com>]
if n == 2:
yield each [<com>, <com>]
if n == 3:
yield each [loop(n, <com length 2>]
yield each [loop(n, <com>), <com>]
else:
yield each [loop(n, <com length n-1>)]
yield each [loop(n, <com length n-2>), <com>]
yield each [<com>, loop(n, <com length n-2>)]
# Removed later
# yield each [<com>, loop(n, <com length n-3>), <com>]
# yield each [<com>, <com>, loop(n, <com length n-3>)]
# yield each [loop(n, <com length n-3>), <com>, <com>]
```
This cut the longest test case down to 140 seconds, which is a ridiculous improvement. But from here, there were still some things I needed to improve. I started more aggressively filtering out redundant/worthless code and checking to see if code has been tested before. This cut it down further, but it wasn't enough. In the end, the final piece that was missing was the loop counter. Through my highly advanced algorithm (read: *random trial and error*) I determined that the optimal range to allow loops to run in is [3-8]. But there's a huge improvement in there: If we know that `[loop(8, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])]` can't solve our board, then there's absolutely no way that `[loop(3, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])]` or any loop count from 3-7 could solve it. So rather than iterating through all the loop sizes from 3-8, we set the loop count on the outer loop to the max. This ends up cutting the search space down by a factor of `maxLoop - minLoop`, or 6 in this case.
This helped a lot, but ended up inflating the score. Certain solutions I had found earlier by brute force require larger loop numbers to run (for example, boards 4 and 6). So rather than setting the outer loop count to 8, we set the outer loop count to 17, a magical number also calculated by my highly advanced algorithm. We know we can do this because increasing the loop count of the outermost loop has no effect on the solution's validity. This step actually reduced our final score by 13. So not a trivial step.
] |
[Question]
[
## Introduction:
I'm a twisty puzzles collector. [Here you can see my current collection of ± 300 puzzles.](http://twistypuzzles.com/forum/viewtopic.php?f=14&t=26889)
I think everyone knows the regular Rubik's Cube (3x3x3 Cube), which is a *NxNxN* Cube. There are also Cuboids (block-shaped puzzles), which come in different forms, [perhaps better explained by SuperAntionioVivaldi here](https://www.youtube.com/watch?v=ZGCdgtnW9Tc):
* **Regular Domino Cuboids** (like the [2x2x3](http://s16.postimg.org/r6o488i05/DSC_0052.jpg); [2x3x3](http://s13.postimg.org/4dl182odj/DSC_0053.jpg); [3x3x4](http://s11.postimg.org/nje0t6mlv/DSCN0396.jpg); etc.) - They come in the form of *NxNx(N+O)* or *Nx(N+O)x(N+O)*, which have either two odd dimensions and an even, or two even and an odd.
* **Shapeshifter Cuboids** (like the [2x2x4](https://s32.postimg.org/c47lh9r1h/DSCN1045.jpg); 3x3x5; [3x3x9](http://s9.postimg.org/5i83zwoxr/DSC_0059.jpg); [4x4x6](http://s18.postimg.org/frxuis4kp/DSC_0054.jpg); etc.) - They come in the form of *NxNx(N+P)*, which as the name suggests, shapeshifts (in all directions). All three dimensions are either odd or even.
* **Floppy Cuboids** (like the [1x3x3](http://s21.postimg.org/ugezl12qf/DSC_0055.jpg); [2x4x4](https://s32.postimg.org/c47lh9r1h/DSCN1045.jpg); etc.) - They come in the form of *Nx(N+P)x(N+P)*, which are almost the same as the Shapeshifters, but with so-called Floppy Parities.
* **Brick Cuboids** (like the [2x3x4](http://s32.postimg.org/nqpgtfs3p/DSCN0941.jpg); [3x4x5](http://s8.postimg.org/lme9d7af9/DSC_0177.jpg); 2x3x5; etc.) - They come in the form of Nx(N+O)x(N+P), which just like the Regular Domino Cuboids have either two odd dimensions and an even, or two even and an odd; but don't have any of the same dimensions.
* **Ultimate Shapeshifters** (like the [2x4x6](http://s24.postimg.org/5z7kb4ddh/DSC_0204.jpg); 3x5x7; 2x4x10; etc.) - They come in the form of *Nx(N+O)x(N+R)*, and shapeshift in any direction. All three dimensions are either odd or even; but don't have any of the same dimensions.
## Challenge:
### Input:
A positive integer ***n*** with the following restriction: 8 <= ***n*** <= 125.
***n*** can be uniquely decoded as the product of three values (the dimensions), of which each is between 2 and 5 inclusive.
The reason I've restricted it to 2-5 is to prevent duplicated inputs (like `1x2x4 = 8` and `2x2x2 = 8`), even though [there are many lower/higher order Cuboids](http://twistypuzzles.com/cgi-bin/pdb-search.cgi?ckey=&act=adv&all=&phr=&any=&non=&sec=35&mec=&inv=&pro=&dat=) out there. This also means there are no test cases for Ultimate Shapeshifters.
### Output / Test cases:
These are all the cases your program/function should support, ranging from edge lengths 2 through 5 in every possible three-dimensional configuration:
```
Input Cuboid/Cube Type/Output
8 2x2x2 Cube
12 2x2x3 Regular Domino Cuboid
16 2x2x4 Shapeshifter Cuboid
20 2x2x5 Regular Domino Cuboid
18 2x3x3 Regular Domino Cuboid
24 2x3x4 Brick Cuboid
30 2x3x5 Brick Cuboid
32 2x4x4 Floppy Cuboid
40 2x4x5 Brick Cuboid
50 2x5x5 Regular Domino Cuboid
27 3x3x3 Cube
36 3x3x4 Regular Domino Cuboid
45 3x3x5 Shapeshifter Cuboid
48 3x4x4 Regular Domino Cuboid
60 3x4x5 Brick Cuboid
75 3x5x5 Floppy Cuboid
64 4x4x4 Cube
80 4x4x5 Regular Domino Cuboid
100 4x5x5 Regular Domino Cuboid
125 5x5x5 Cube
```
### Challenge rules:
* Any non-Cube/non-Cuboid input within the 8-125 range should result in 'none' as output.
* The output format is your own choice. I think the most reasonable is integers, like `0` = 'none'; `1` = Cube; `2` = Regular Domino Cuboid; `3` = Shapeshifter Cuboid; `4` = Floppy Cuboid; `5` = Brick Cuboid. Any other output format is also fine, as long as you specify which one you've used.
### General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* [Default Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. (*NOTE: Since I don't know if there is a smart formula for the input-to-output conversion, it is allowed to hardcode the answers based on the input.*)
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ 21 bytes
`None: 0
Cube: 1
Regular Domino Cuboid: 2
Shapeshifter Cuboid: 3
Brick Cuboid: 4
Floppy Cuboid: 5`
```
•S3X@I¨%÷'•5L¦3ãPÙIkè
```
[Try it online!](https://tio.run/nexus/05ab1e#@/@oYVGwcYSD56EVqoe3qwN5pj6HlhkfXhxweKZn9uEV//8bWgAA)
or as a [Test suite](https://tio.run/nexus/05ab1e#s1AwNDI9uqOs8v@jhkXBxhEOnodWqB7erg7kmfocWmZ8eHHA4ZmV2YdX/K9UOrzfSuHwfiWd/wA)
**Explanation**
```
•S3X@I¨%÷'• # push base-214 compression of the number 123224454212324512210
5L¦ # push the list [2,3,4,5]
3ã # cartesian product with repetion of size 3
P # product of each sublist
Ù # remove duplicates
Ik # get the index of input in that list (-1 if non-existant)
è # get the element at this index in the above number
```
The only place I see that we could save bytes here is find a better way of generating the number **123224454212324512210**.
It is only 1-off from a prime, so one possible save would be to find the index of that prime and generate the index in less than 9 bytes.
I don't know how well the pi-function works for 21-digit primes but that could be a possibility.
[Answer]
## JavaScript (ES6), ~~97~~ ~~92~~ 86 bytes
This function first checks the validity of the input, then picks the correct value from a lookup table.
Surprisingly, the longest part is the validity check (is **n** of the form **x\*y\*z** with **x**, **y** and **z** in **[2,3,4,5]**?). There must be a shorter way of doing it, but I couldn't figure it out so far.
```
n=>'NBBF..CRCC.BRR..SFRRRRR.B..C'[[34707324,0x80000800,4240,262208][n&3]>>n/4&1&&n%29]
```
Returns a character:
* **N**: None
* **C**: Cube
* **R**: Regular Domino Cuboid
* **S**: Shapeshifter Cuboid
* **B**: Brick Cuboid
* **F**: Floppy Cuboid
### Test
```
let f =
n=>'NBBF..CRCC.BRR..SFRRRRR.B..C'[[34707324,0x80000800,4240,262208][n&3]>>n/4&1&&n%29]
// invalid
;[9,13,99].map(
n => { console.log(n, f(n)) }
)
// valid
;[8,12,16,20,18,24,30,32,40,50,27,36,45,48,60,75,64,80,100,125].map(
n => { console.log(n, f(n)) }
)
```
[Answer]
## Ruby, ~~106 98~~ 96 bytes
```
->n{[[x=25,2421],[15,53],[9,21],[4,1232504350200510002]].any?{|a,b|n%a<1&&x="00#{b}"[n/a]}?x:?0}
```
Because, why not, hardcoding.
As specified, 0 = 'none'; 1 = Cube; 2 = Regular Domino Cuboid; 3 = Shapeshifter Cuboid; 4 = Floppy Cuboid; 5 = Brick Cuboid
[Answer]
# [Perl 6](http://perl6.org/), ~~69~~ 58 bytes
```
{%(unique([X*] (2..5)xx 3)Z=>:32<AM0K21IHN61H5>.comb){$_}}
```
Uses the integer output format suggested in the task description, except that it returns the uninitialized value `(Any)` instead of `0` in case of inputs that don't form a valid cube/cuboid.
### How it works
1. ```
unique([X*] (2..5)xx 3)
```
Generates the list `8 12 16 20 18 24 30 32 40 50 27 36 45 48 60 75 64 80 100 125`.
2. ```
:32<AM0K21IHN61H5>.comb
```
Generates the list `1 2 3 2 2 5 5 4 5 2 1 2 3 2 5 4 1 2 2 1` (from a base-32 literal).
3. ```
%( Z=> )
```
Generates a Hash (associative map) with the first list as the keys, and the second list as the values.
4. ```
{$_}
```
Indexes the Hash with the input number..
[Answer]
## Batch, 163 bytes
```
@set/as=0,c=29948521
@for /l %%i in (2,1,5)do @for /l %%j in (%%i,1,5)do @for /l %%k in (%%j,1,5)do @set/as+=c%%6*!(%%i*%%j*%%k-%1),c/=6,c+=14081593*!c
@echo %s%
```
Uses the suggested output format. Explanation: The basic idea is to loop over the list of cubes as defined in the question. For each cube, we calculate to see if its volume is the input integer, and if so, calculate the type of cube from a lookup table.
The original lookup table was a string of letters, but doing string manipulation in a `for` loop is tricky, so I switched to digits which can be extracted arithmetically. Sadly Batch is limited to 32-bit integers so I couldn't fit all of the digits into a single variable (even in base 5 you can only get 13 digits) so instead I split the variable up into two parts, encoded in base 6 for convenience. `29948521` is `2545522321` in base 6 which encodes the 10 smallest cuboids in reverse order; when it runs out of digits we add `14081593` which is `1221452321` in base 6 encoding the 10 biggest cuboids.
] |
[Question]
[
Palindromes are fun, but some of the other strings are starting to feel left out. We can turn those strings into *chunky palindromes* by splitting them up into palindromic arrays of chunks.
For example, the string `"abcabca"` isn't a palindrome if we read it character by character, but we have three different ways of making it a *chunky* palindrome:
```
["abcabca"]
["a" "bcabc" "a"]
["a" "bc" "a" "bc" "a"]
```
As you can see, chunky palindromicness is a very inclusive concept; every string can be turned into a chunky palindrome in at least one way.
### Task
Write a program or a function that receives a string as input and returns its *palindromic chunkiness*, i.e., the number of its partitions that are palindromic arrays.
### Test cases
```
OUTPUT | INPUT
--------+---------------------------------------------
1 | ""
1 | "a"
1 | "ab"
2 | "aa"
2 | "aaa"
3 | "abcabca"
4 | "abababab"
28 | "abcabcaabababababcabca"
1 | "bbbbabababbbbababbbaaaaa"
20 | "ababbaaaabababbbaaabbbaa"
5 | "baaabaabababaababaaabbaab"
62 | "bbaaababbabbabbbabaabaabb"
2 | "a man a plan a canal panama"
25 | "ama nap lan aca nal pan ama"
93 | "SATOR AREPO TENET OPERA ROTAS"
976 | "abcabcaabcabcaabcabcaabcabcaabcabcaabcabca"
28657 | "ababababababababababaababababababababababa"
2097152 | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
```
### Additional rules
* You may assume that the input will consist of 42 or less printable ASCII characters, optionally surrounded by your language's string delimiters and/or followed by a newline.
* For each valid input string, **your code must finish in less than one minute on my machine** (Intel Core i7-3770, 16 GiB RAM, Fedora 21).
With an adequate algorithm, it should be easy to comply with this time limit. However, you will most likely not be able to iterate over all partitions of the input string.
* If you choose to print the output to STDOUT, it may be followed by a single newline.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
# Pyth, ~~40~~ ~~34~~ ~~27~~ 22 bytes
```
Lhsmy:bd_df!xb>TbS/lb2
```
[Try it in the online interpreter](http://pyth.herokuapp.com/?code=Lhsmy%3Abd_df%21xb%3ETbS%2Flb2%0AyM.z&input=a%0Aab%0Aaa%0Aaaa%0Aabcabca%0Aabababab%0Aabcabcaabababababcabca%0Abbbbabababbbbababbbaaaaa%0Aababbaaaabababbbaaabbbaa%0Abaaabaabababaababaaabbaab%0Abbaaababbabbabbbabaabaabb%0Aa+man+a+plan+a+canal+panama%0Aama+nap+lan+aca+nal+pan+ama%0ASATOR+++AREPO+++TENET+++OPERA+++ROTAS%0Aabcabcaabcabcaabcabcaabcabcaabcabcaabcabca%0Aababababababababababaababababababababababa%0Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&debug=0).
Heavily golfed down from initial 40 byte version. Thanks to FryAmTheEggman for pointing out a couple of useful operators (docs are hard to search!) that have saved me 6 bytes total. Thanks to Dennis for a clever single byte saving by interpreting the result of `x` as a truthy/falsy value rather than an index - `!xb>Tb` rather than `q<bT>Tb`.
---
How it works:
We define a function `y` which determines the chunkiness of a string `b` by recursively calling itself on substrings of `b`. Functions are automatically memoized in Pyth, so recursion has very little overhead in terms of time.
```
L def y(b): return ___
S/lb2 The range [1,2,...,len(b)/2]
f!xb>Tb Filter n for which b[:n] == b[-n:]
m Map each n in the list to...
y:bd_d y(b[d:-d])
hs Take the sum and add one (implicit return)
```
[Answer]
# Pip, ~~98~~ 66 bytes
*-32 thanks to @DLosc!*
```
k:{[[z:a]]AL$AL({b:zc:b@<aAL_M(kb@>a)z:bc}M@>(,#a))}#(_QRV_FI(ka))
```
My first Pip answer!
[Answer]
## CJam (41 39 bytes)
```
qM{_,2/,\f{\~_2$>@2$<@~)/(@=\M*j*}1b)}j
```
[Online demo](http://cjam.aditsu.net/#code=qM%7B_%2C2%2F%2C%5Cf%7B%5C~_2%24%3E%402%24%3C%40~)%2F(%40%3D%5CM*j*%7D1b)%7Dj&input=ababababababababababaababababababababababa)
This is "eager" in the sense that it finds the number of chunky palindromes for each "central" string (i.e. the result of removing the same number of characters from both ends of the original string), but because it uses the auto-memoising `j` operator each is calculated once only, giving a very fast program (and saving a few characters over a non-memoised implementation).
Thanks to Dennis for a one byte saving.
[Answer]
# Mathematica, ~~77~~ ~~72~~ 57 bytes
```
1+Tr[#0/@ReplaceList[#,{a__,b___,a__}:>{b}]]&@*Characters
```
[Answer]
# Perl, 86 bytes
84 bytes code + 2 switches
There HAS to be a shorter method, but here goes:
```
perl -lpe 'sub c{my($x,$i)=@_;$x=~/^(.{$i})(.*)\1$/&&c($2,0*++$s)while++$i<length$x}c$_;$_=++$s'
```
Takes input from STDIN, one string per line.
Explanation: For values `1<=$i<length(input string)`, uses the regex `/^(.{$i})(.*)\1$/` to get the left and right chunks and increments the count. Then recursively does the same for the center part of the string.
] |
[Question]
[
*This challenge is loosely inspired by the unimplemented esolang [Pada](https://esolangs.org/wiki/Pada).*
Consider an array of 8 bits, all initialised to zero. We'll introduce a very minimalistic instruction set to print arbitrary strings. There are two instructions, both of which take a parameter `N` which is the index of a bit:
* `t N` for **t**oggle: This changes the value of bit `N`.
* `p N` for **p**rint: This interprets all 8 bits as a byte, *starting from bit `N` and wrapping around the end*. The character corresponding to this byte is printed to STDOUT.
Let's look an example. We want to print `:=`. Naively we achieve this as follows (0-based bit indices):
```
t 2 [0 0 1 0 0 0 0 0]
t 3 [0 0 1 1 0 0 0 0]
t 4 [0 0 1 1 1 0 0 0]
t 6 [0 0 1 1 1 0 1 0]
p 0 [0 0 1 1 1 0 1 0] == 58 == ':'
t 5 [0 0 1 1 1 1 1 0]
t 6 [0 0 1 1 1 1 0 0]
t 7 [0 0 1 1 1 1 0 1]
p 0 [0 0 1 1 1 1 0 1] == 61 == '='
```
But instead, we can make use of the cyclic feature of `p` and save two instructions:
```
t 2 [0 0 1 0 0 0 0 0]
t 3 [0 0 1 1 0 0 0 0]
t 4 [0 0 1 1 1 0 0 0]
t 6 [0 0 1 1 1 0 1 0]
p 0 [0 0 1 1 1 0 1 0] == 58 == ':'
t 1 [0 1 1 1 1 0 1 0]
p 7 [0 1 1 1 1 0 1 0] == [0 0 1 1 1 1 0 1] == 61 == '='
^
```
So `p 7` simply starts reading the byte value from the last bit instead of the first.
## The Challenge
Given a non-empty string of printable ASCII characters (0x20 to 0x7E, inclusive), produce an optimal list of instructions (one line per instruction) to print that string with the above system. If there are multiple optimal solutions (which will almost always be the case), generate only one of them.
You may choose between 0-based and 1-based indexing for the bits, but please state your choice.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. If you don't print the result to STDOUT, it should still be a single newline-separated string.
This is code golf, so the shortest answer (in bytes) wins.
## Test Cases
Each test case is a single line containing the input string, followed by the optimal number of instructions, followed by one possible solution.
You should *not* output the instruction count in your solution - this is only included here so you can check the correctness of your code if it prints a different instruction list.
```
?
7 instructions
t 2
t 3
t 4
t 5
t 6
t 7
p 0
:=
7 instructions
t 2
t 3
t 4
t 6
p 0
t 1
p 7
0123456789
26 instructions
t 2
t 3
p 0
t 7
p 0
t 6
t 7
p 0
t 7
p 0
t 5
t 6
t 7
p 0
t 7
p 0
t 6
t 7
p 0
t 7
p 0
t 2
t 3
p 3
t 2
p 3
9876543210
28 instructions
t 2
t 3
t 4
t 7
p 0
t 7
p 0
t 0
t 7
p 5
t 4
p 5
t 0
t 5
p 0
t 7
p 0
t 5
t 6
t 7
p 0
t 7
p 0
t 6
t 7
p 0
t 7
p 0
Hello, World!
39 instructions
t 1
t 4
p 0
t 3
t 7
p 2
t 1
t 6
p 2
p 2
t 0
t 1
p 2
t 0
t 1
t 3
p 2
t 6
t 7
p 2
t 0
t 2
t 6
t 7
p 1
t 0
t 1
t 5
p 0
t 2
t 7
p 3
t 2
t 6
p 0
t 4
p 0
t 1
p 3
The quick brown fox jumps over the lazy dog.
150 instructions
t 1
t 3
t 5
p 0
t 1
t 2
p 1
t 1
t 3
t 7
p 0
t 1
t 5
t 7
p 0
t 1
t 3
t 7
p 0
t 5
p 0
t 3
t 4
t 5
p 0
t 4
t 6
p 0
t 4
p 0
t 1
t 4
t 6
t 7
p 0
t 1
t 6
p 0
t 3
p 0
t 0
t 5
p 4
t 0
t 7
p 0
t 1
p 1
t 3
t 5
t 6
t 7
p 0
t 1
t 5
t 6
p 0
t 4
t 7
p 0
t 1
t 2
p 3
t 5
t 6
t 7
p 2
t 1
t 2
t 6
p 0
t 0
p 7
t 0
t 7
p 5
t 3
t 4
t 6
t 7
p 0
t 6
t 7
p 0
t 1
t 3
t 6
t 7
p 0
t 1
t 4
t 5
t 6
t 7
p 0
t 4
p 4
t 6
p 0
t 1
t 6
p 4
t 5
t 6
t 7
p 0
t 1
t 3
t 5
p 0
t 1
p 1
t 1
t 3
t 7
p 0
t 1
t 5
t 7
p 0
t 1
t 4
t 5
p 0
t 1
p 3
t 3
t 7
p 1
t 1
t 5
p 0
t 1
t 3
t 4
t 7
p 0
t 1
t 5
p 0
t 4
t 6
t 7
p 0
t 4
p 0
t 1
t 4
t 7
p 0
```
The test cases were generated with this [CJam reference implementation](http://cjam.aditsu.net/#code=0a8*%3ABq%7Bi2b8Ue%5B8%2C%5Cfm%3E_ee%5C2%24f.%5E%3A%3A%2B.%5C2%2F%240%3D1%3D~%401%24.%5Eee%7BW%3D%7D%2C0f%3D%7B%22t%20%22ooNoT)%3AT%3B%7D%2F%5C%22p%20%22ooNoT)%3AT%3B%7D%2F%3BT%22%20instructions%22&input=The%20quick%20brown%20fox%20jumps%20over%20the%20lazy%20dog.).
[Answer]
# Ruby, 171
```
->w{s=[0]*8
w.chars.flat_map{|c|z=0..7
*m,i=z.map{|j|z.select{|k|s[k]!=z.map{|i|c.ord[i]}.rotate(j)[k]}<<j}.min_by &:size
m.map{|m|s[m]=1-s[m];"t #{7-m}"}+["p #{i}"]}*?\n}
```
A Ruby function that's *only* double the size of the reference implementation. :)
Try it online: <http://ideone.com/ysYyFP>
The program is pretty straighforward: it starts off with the 8 bits set to 0 and iterates through the characters. At each step, it takes the shortest route from the current state to a state that would allow printing the character. It returns a string in the specified format.
The initial (less golfed) version of the program is available [here](http://ideone.com/oVm0Et).
[Answer]
# CJam, ~~81~~ 76 bytes
Still a lot to golf.
```
0]8*q{i2b8Te[8,\fm>:X\_@\f.=::+_$W=#:YX=_@.{=M['tSUN]?U):U;}o0:U;['pSYN]o}/;
```
[Try it online](http://cjam.aditsu.net/#code=0%5D8*q%7Bi2b8Te%5B8%2C%5Cfm%3E%3AX%5C_%40%5Cf.%3D%3A%3A%2B_%24W%3D%23%3AYX%3D_%40.%7B%3DM%5B'tSUN%5D%3FU)%3AU%3B%7Do0%3AU%3B%5B'pSYN%5Do%7D%2F%3B&input=The%20quick%20brown%20fox%20jumps%20over%20the%20lazy%20dog.).
[Answer]
# CJam, 67 bytes
```
U]8*l{i2b8Ue[8,{1$m>2$.^:+}$0=_@m>@1$.^ee{~{"t "op}{;}?}/"p "o\p}/;
```
[Try it online](http://cjam.aditsu.net/#code=U%5D8*l%7Bi2b8Ue%5B8%2C%7B1%24m%3E2%24.%5E%3A%2B%7D%240%3D_%40m%3E%401%24.%5Eee%7B~%7B%22t%20%22op%7D%7B%3B%7D%3F%7D%2F%22p%20%22o%5Cp%7D%2F%3B&input=The%20quick%20brown%20fox%20jumps%20over%20the%20lazy%20dog.)
Explanation:
```
U]8* Build start bit array [0 0 0 0 0 0 0 0].
l Get input.
{ Start loop over input characters.
i Convert character to integer.
2b Convert to binary array.
8Ue[ Pad to 8 entries with leading 0.
8, Generate list of possible rotation amounts.
{ Start of sort function block.
1$ Get bit array of character.
m> Rotate by rotation amount.
2$ Get previous bit array.
.^ Element-wise xor to get different bits.
:+ Add elements in result to get count of different bits.
}$ Sort possible rotations by count of different bits.
0= Get first rotation amount in sorted list, which is the one with the
one that results in the smallest count of different bits.
_ Copy count. Will use original for "p" output later.
@ Get the character bit array to top of stack.
m> Rotate it, to get optimal rotated bit array.
@ Get previous bit array to top of stack.
1$ Copy rotated bit array, will need the original as starting point
for next character.
.^ Element-wise xor to get different bits.
ee Enumerate array to get pairs of index and bit value.
{ Loop over bits.
~ Unpack index bit pair.
{ Start of if block for bit value.
"t "o Output "t ".
p Output index and newline.
} End of if block.
{ Start of else block.
; Pop the index value.
}? End of ternary if.
}/ End loop over bits.
"p "o Output "p ".
\ Swap rotation amount to top.
p Print rotation amount and newline.
}/ End loop over input characters.
; Ppp current bit array off stack to prevent extra output.
```
] |
[Question]
[
Write a program or function that takes in a positive integer and prints or returns an ASCII art depiction of an [archery arrow](https://en.wikipedia.org/wiki/Arrow), scaled according to the input.
If the input is `1` the output is
```
/\
/ \
\__/
||
||
||
||
||
||
||
||
/||\
/ || \
/ || \
// \\
/ \
```
If the input is `2` the output is
```
/\
/ \
/ \
/ \
\ /
\____/
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
/| |\
/ | | \
/ | | \
/ | | \
/ | | \
/ |__| \
/ / \ \
/ / \ \
// \\
/ \
```
If the input is `3` the output is
```
/\
/ \
/ \
/ \
/ \
/ \
\ /
\ /
\______/
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
/| |\
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ |____| \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
// \\
/ \
```
If the input is `4` the output is
```
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
\ /
\ /
\ /
\________/
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
/| |\
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ | | \
/ |______| \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
// \\
/ \
```
The pattern continues on for larger input numbers - the arrow is scaled up accordingly.
Notice that for any input N:
* The arrowhead is a pentagon with 2×N underscores at the base, N slashes on each of the sides extending from the base, and 2×N slashes on the two sides that form the arrow tip.
* The shaft (including the part within the fletching) consists of 11×N lines of two vertical bars separated by 2×(N-1) spaces. The very last line has underscores instead of spaces.
* The fletching surrounds the lower 3×N lines of the shaft. Two lines of 2×N slashes extend diagonally downward from either side of the shaft and are joined with vertical columns of slashes.
* The complete arrow is 16×N lines high and 6×N characters wide.
In your output there should be no empty lines before the arrow tip and only up to one trailing newline.
None of the output lines should have unnecessary leading spaces (the left edge of the fletching should be as leftmost as possible) but any of the lines may have any number of trailing spaces.
**The shortest submission in bytes wins.**
[Answer]
# Perl, 298 bytes
```
for$y(0..($w=<>)*16-1){$r=$w*3;for$x(0..$w*6-1){$z=$x<$r?$x:$w*6-$x-1,$_.=$z==$r-$y-1&&$y<$w*2||!$z&&$y>=$w*13-1||($z==$w*16-1-$y||$z==$w*13-1-$y)&&$z<$w*2?$x<$r?'/':'\\':$z==$y-$w&&$y>=$w*2&&$y<$r?$x<$r?'\\':'/':$z==$r-$w&&$y>=$r&&$y<$w*14?'|':$z>=$r-$w&&($y==$r-1||$y==$w*14-1)?_:$"}$_.=$/}print
```
Multi-line:
```
for$y(0..($w=<>)*16-1){$r=$w*3; # read input and loop over rows
for$x(0..$w*6-1){ # loop over columns
# flip x on right side of arrow:
$z=$x<$r?$x:$w*6-$x-1;
# slashes on fletching and tip of arrowhead:
$_.=$z==$r-$y-1&&$y<$w*2||!$z&&$y>=$w*13-1||($z==$w*16-1-$y||$z==$w*13-1-$y)&&$z<$w*2?$x<$r?'/':'\\':
# slashes on underside of arrowhead:
$z==$y-$w&&$y>=$w*2&&$y<$r?$x<$r?'\\':'/':
# vertical bars on side of shaft:
$z==$r-$w&&$y>=$r&&$y<$w*14?'|':
# underscores on base of arrowhead and shaft:
$z>=$r-$w&&($y==$r-1||$y==$w*14-1)?_:$"
}
$_.=$/ # add newline at end of each row
}
print # print out string
```
Output:
```
2
/\
/ \
/ \
/ \
\ /
\____/
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
/| |\
/ | | \
/ | | \
/ | | \
/ | | \
/ |__| \
/ / \ \
/ / \ \
// \\
/ \
```
Thanks to Dom Hastings for helping me save 5 (and counting) bytes
[Answer]
# Pyth, ~~149~~ ~~147~~ ~~146~~ ~~144~~ 146
*Edit 2015-9-23: had a bug, fixed for 2 bytes. Might be possible to make shorter, I have no time now.*
Still seems too long for a Pyth answer.
```
M*tGHK*11Q=Y*3QA" /"jbC+R*yQG+_Js[ms[*dGHgt-YdG\_gKG\_)tQs[gQGHgyQG\_*K\|)ms[*+QdGH*y-tQdG\\*+*8QydGHgYGH)Qms[*++KQdGHgYGH)tQ+g*13QG*hYH)mXd"\/")J
```
## Explanation (almost up to date)
I basically generate the transpose of the arrow, since its line format is much simpler. Also, I only generate one half and then reverse it to save a lot of bytes.
```
M*tGH g(a,b) = (a - 1) * b
A" /" G = " ", H = "/"
ms[...)tQ N-1 lines inside body
s[...) 1 line of edge of body
ms[...)Q N lines of tip + fin
m...Q N-1 lines of fin
+... 1 line of edge of fin
s[ ) flatten the maps to it
J save to J
_ reverse
J another copy (unreversed)
mXd"\/") swap "\" and "/" on each line
+ add to other half
+R*yQG add 2*N spaces to each line
C transpose
jb join by newline
m tQ map d over 0...N-2
s[ ) concatenate
*dG d spaces
H "/"
=Y*3Q save 3*N to Y
gt- dG 3*N-d-2 spaces
\_ "_"
K*11Q save 11*N to K
g G 11*N-1 spaces
\_ "_"
s[ ) concatenate
gQG N-1 spaces
H "/"
gyQG 2*N-1 spaces
\_ "_"
*K\| 11*N pipes
m Q map d over 0...N-1
s[ ) concatenate
*+QdG N+d spaces
H "/"
*y-tQdG 2*(N-d-1) spaces
\\ "\"
*+*8QydG 8*N+2*d spaces
H "/"
gYG 3*N-1 spaces
H "/"
m tQ map d over 0...N-2
+++ concatenate
*++KQdG 12*N+d spaces
H "/"
gYG 3*N-1 spaces
H "/"
+ concatenate
g*13QG 13*N-1 spaces
*hYH 3*N+1 slashes
```
[Answer]
# Julia, 452 bytes
This answer isn't very inspired, and I haven't golfed it beyond the glaringly obvious. I intend for this to be a score for other people to beat.
```
function R(c,x,y,e,f,n)
for i=1:n
a[y,x]=c
x+=e
y+=f
end
end
function f(n::Int)
global a=fill(' ',16n,6n)
F='/'
B='\\'
q=3n+1
r=2n+1
R(F,3n,1,-1,1,2n)
R(B,q,1,1,1,2n)
R(B,n+1,r,1,1,n)
R(F,5n,r,-1,1,n)
R('_',r,3n,1,0,2n)
R('|',r,q,0,1,11n)
R('|',4n,q,0,1,11n)
R('_',r+1,14n,1,0,r-3)
R(F,2n,11n+1,-1,1,2n)
R(B,4n+1,11n+1,1,1,2n)
R(F,1,13n,0,1,3n)
R(B,6n,13n,0,1,3n)
R(F,2n,14n+1,-1,1,2n)
R(B,4n+1,14n+1,1,1,2n)
for b = 1:16n
println(join(a[b,:]))
end
end
```
Try it out:
```
julia> f(1)
/\
/ \
\__/
||
||
||
||
||
||
||
||
/||\
/ || \
/ || \
// \\
/ \
```
ungolfed:
```
# Repeat a character through array a from (x,y) -> (x+n*dx,y+n*dy)
function R(a::Array{Char,2},c::Char, x::Int, y::Int, dx::Int, dy::Int, n::Int)
for i = 1:n
a[y,x] = c
x += dx
y += dy
end
end
function arrow(n::Int)
a = fill(' ',16n,6n)
# upper left of head
R(a,'/',3n,1,-1,1,2n)
# upper right of head
R(a,'\\',3n+1,1,1,1,2n)
# lower left of head
R(a,'\\',n+1,2n+1,1,1,n)
# lower right of head
R(a,'/',5n,2n+1,-1,1,n)
# bottom of head
R(a,'_',2n+1,3n,1,0,2n)
# shaft
R(a,'|',2n+1,3n+1,0,1,11n)
R(a,'|',4n,3n+1,0,1,11n)
R(a,'_',2n+2,14n,1,0,2n-2)
# upper fletching edges
R(a,'/',2n,11n + 1,-1,1,2n)
R(a,'\\',4n+1,11n+1,1,1,2n)
# fletching sides
R(a,'/',1,13n,0,1,3n)
R(a,'\\',6n,13n,0,1,3n)
# lower fletching edges
R(a,'/',2n,14n + 1,-1,1,2n)
R(a,'\\',4n+1,14n+1,1,1,2n)
for r = 1:16n
println(join(a[r,:]))
end
end
```
[Answer]
# Ruby, 233
```
->n{(16*n).times{|i|j=i/n
m=n*3
e=' '*6*n
i%(11*n)==m-1&&e[2*n..4*n-1]=?_*2*n
j%14>2&&e[m+n-1]=e[m-n]=?|
k=(i-n)%m
k<n||j<11||(e[m+k]=?\\;e[m-1-k]=?/)
j>12&&(e[-1]=?\\;e[0]=?/)
j<3&&(e[n+l=(i-n*2)%(n*4)]=?\\;e[5*n-l-1]=?/)
puts e}}
```
I am particularly pleased with the wraparound technique I used to draw all `\` in the head with a single expression (and likewise for `/`)
**Ungolfed in test program**
```
f=->n{
#loop line by line, 0..16*n-1
(16*n).times{|i|
#convenience variables
j=i/n
m=n*3
#setup a string of spaces
e=' '*6*n
#draw the ___ at top and bottom of shaft
i%(11*n)==m-1&&e[2*n..4*n-1]=?_*2*n
#draw the |, overwriting the _ in the bottom corners
j%14>2&&e[m+n-1]=e[m-n]=?|
#draw the diagonal fletching
k=(i-n)%m
k<n||j<11||(e[m+k]=?\\;e[m-1-k]=?/)
#draw the ends of the fletching (note index -1, meaning last character in string)
j>12&&(e[-1]=?\\;e[0]=?/)
#draw the arrow head, wrapping round with %(n*4)
j<3&&(e[n+l=(i-n*2)%(n*4)]=?\\;e[5*n-l-1]=?/)
#output the line
puts e}
}
f.call(gets.to_i)
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 128 bytes
```
d(\/n꘍⁰3*↳øṀ,)(⁰n+\\꘍⁰d‹n- n⁰‹=[\_|ð]*+øṀ,)8*(⁰d\|꘍⁰‹꘍m,)d(\/n꘍⁰d↳\|+⁰‹꘍øṀ,)(\/⁰d↲\|+n⁰‹=[\_|ð]⁰‹*+øṀ,)d(\/n꘍⁰d‹↳:L⁰d≠[\/p]⁰꘍øṀ,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=d%28%5C%2Fn%EA%98%8D%E2%81%B03*%E2%86%B3%C3%B8%E1%B9%80%2C%29%28%E2%81%B0n%2B%5C%5C%EA%98%8D%E2%81%B0d%E2%80%B9n-%20n%E2%81%B0%E2%80%B9%3D%5B%5C_%7C%C3%B0%5D*%2B%C3%B8%E1%B9%80%2C%298*%28%E2%81%B0d%5C%7C%EA%98%8D%E2%81%B0%E2%80%B9%EA%98%8Dm%2C%29d%28%5C%2Fn%EA%98%8D%E2%81%B0d%E2%86%B3%5C%7C%2B%E2%81%B0%E2%80%B9%EA%98%8D%C3%B8%E1%B9%80%2C%29%28%5C%2F%E2%81%B0d%E2%86%B2%5C%7C%2Bn%E2%81%B0%E2%80%B9%3D%5B%5C_%7C%C3%B0%5D%E2%81%B0%E2%80%B9*%2B%C3%B8%E1%B9%80%2C%29d%28%5C%2Fn%EA%98%8D%E2%81%B0d%E2%80%B9%E2%86%B3%3AL%E2%81%B0d%E2%89%A0%5B%5C%2Fp%5D%E2%81%B0%EA%98%8D%C3%B8%E1%B9%80%2C&inputs=2&header=&footer=)
Generates the rocket bit by bit.
[Answer]
## Python 3, 336 bytes
```
def f(n):
N=n+n;R=[*range(3*n)]
L = [f'/{i*" "}\\' for i in R[:N]] + [f'\\{2*(N+~i)*"_ "[i+1<n]}/' for i in R[:n]] + [f'|{" "*~-n}|']*8*n + [
f'/{"|"+2*~-n*"_ "[i+1<3*n]+"|":^{2*min(i,N-1)+N}}\\' for i in R
] + ["/"*(i+1<N)+f'/{" "*(n+i)}\\'.center(6*n-2)+"\\"*(i+1<N) for i in R[:N]]
return "\n".join(u.center(6*n).rstrip() for u in L)
```
] |
[Question]
[
Write a program or function (or set of programs/functions) to encrypt and decrypt data given the following specification:
## Encryption
1. Calculate an XOR hash of the input by XOR-ing every byte with each-other.
2. XOR every byte of the input by this hash.
3. Shift the result four bits left.
4. Pad the left side with the first four bits of the XOR hash.
5. Pad the right side with the last four bits of the XOR hash.
## Example
* Given input: `"G0lf"` (`0x47306C66`)
* Calculate XOR hash: `0x47 ^ 0x30 ^ 0x6C ^ 0x66 = 0x7D`
* XOR every byte by hash: `0x3A4D111B`
* Expected result (after shift and pad): `"s¤Ñ\x11½"` (`0x73A4D111BD`)
## Rules
* Your program/function can input/output of whatever type makes sense in your golfing language of choice *(String, Byte Array, etc)* as long as the input/output are the actual bytes. For example, you may not output a hexidecimal string.
* Encryption and decryption can be separated into separate programs (score will be the their combined size) or a single one. Single methods can take an argument for whether it should encrypt or decrypt.
* Input for encryption can be expected to be at least 1 byte in size.
* Input for decryption can be expected to be at least 2 bytes.
* Non-printable bytes do not need to be escaped in the output.
[Answer]
# CJam, 36 + 34 = 70 bytes
A bit different approach using binary forms
**Encrypter**:
```
q_:^:Hf^H+{i2b8Ue[}%)4/~@\]e_8/2fb:c
```
How it works:
```
q_:^ e# Read input as string, copy and XOR all the chars
:Hf^ e# Store the XOR in H and XOR each char with H
H+ e# Append H to the char array
{ }% e# On each of the elements in the array
i2b e# Convert the ASCII value to binary
8Ue[ e# Pad with 0 so that the length is 8
) e# Pop out the last array element, which is H
4/~@\ e# Put first 4 bits of H before the input array
e# And rest 4 after it
]e_8/ e# Flatten everything into a single array and group
e# into pieces of 8 bits
2fb:c e# Convert each 8 bit part to integer and then to
e# its character form
```
**Decrypter**:
```
q{i2b8Ue[4/~}%)\(@+2b\:+8/2fb\f^:c
```
How it works:
```
q{ }% e# For each character of the input string
i2b e# Convert to ASCII code and then to its binary form
8Ue[ e# Pad with enough 0 so that length is 8 bit
4/~ e# Split into parts of 4 and unwrap
)\(@+ e# Take out the first and last 4 bit group and join
e# them together to get the XOR Hash H
2b\ e# Convert H to decimal form and swap to put the
e# remaining converted input array on top
:+8/ e# Join all bits together and split into groups of 8
2fb e# Convert each 8 but group to decimal form
\f^ e# Swap to put H on top and XOR each number with H
:c e# Get character from each of the ASCII value
```
Try the [encrypter](http://cjam.aditsu.net/#code=q_%3A%5E%3AHf%5EH%2B%7Bi2b8Ue%5B%7D%25)4%2F~%40%5C%5De_8%2F2fb%3Ac&input=G0lf) and [decrypter](http://cjam.aditsu.net/#code=q%7Bi2b8Ue%5B4%2F~%7D%25)%5C(%40%2B2b%5C%3A%2B8%2F2fb%5Cf%5E%3Ac&input=s%C2%A4%C3%91%11%C2%BD) online
[Answer]
# Pyth, 69 bytes
```
Ksm>+0jCd16_2zJ?,hKeKQmxFdCcK2=KsmmxFkC,dJc?tPKQK2smCid16c?KQ++hJKeJ2
```
This combines encryption and decryption, simply add a `0` as argument for encryption or a `1` for decryption. The reason for this is simple. Converting strings into bits (or 4 bit integer) or the reverse is really really long in Pyth. By combining the both functions into one program, I can save a lot of bytes.
Online demonstrations: [Encryption](https://pyth.herokuapp.com/?code=Ksm%3E%2B0jCd16_2zJ%3F%2ChKeKQmxFdCcK2%3DKsmmxFkC%2CdJc%3FtPKQK2smCid16c%3FKQ%2B%2BhJKeJ2&input=G0lf%0A0&debug=0) and [Decryption](https://pyth.herokuapp.com/?code=Ksm%3E%2B0jCd16_2zJ%3F%2ChKeKQmxFdCcK2%3DKsmmxFkC%2CdJc%3FtPKQK2smCid16c%3FKQ%2B%2BhJKeJ2&input=s%C2%A4%C3%91%11%C2%BD%0A1&debug=0).
### Explanation:
The first part converts the input into a list of 4-bit integer (each char get converted into 2 4-bit integer) and stores it in `K`.
```
m z map each character d of input (=z) to:
Cd the ascii-value of d
j 16 convert the result into base 16
>+0 _2 insert a zero to the front and take the last 2 values
(so that each char gets mapped to exactly 2 numbers)
Ks chain all these tuples and assign them to K
```
The second part determines the hash values and stores them in `J`. If `Q==0` it computes them by xor, otherwise it takes the first and last value of `K`.
```
? Q ... if Q (=second input) else ...
,hKeK [K[0], K[-1]]
m CcK2 map each d of zipped(K chopped into pairs) to:
[zipped(...) gives me 2 lists, one with the values of the even indices, and one with the odd indices]
xFd fold the list d by xor
J store the result in J (this is the hash value)
```
The next part does the xor using the hash values. When `Q == 0` it is performed on the complete list `K`, otherwise only on the list `K` without the first and last value.
```
=KsmmxFkC,dJc?tPKQK2
?tPKQK K[1:-1] if Q else K
m c 2 map each d of [... chopped into pairs] to:
m C,dJ map each pair k of zip(d,J) to:
xFk apply xor to the 2 values in k
=Ks chain all these tuples and assign them to K
```
And the last part converts `K` back to chars:
```
smCid16c?KQ++hJKeJ2
?KQ++hJKeJ K if Q else J[0] + K + J[1]
m c 2 map each pair of [... chopped into pairs] to:
id16 convert d into a single integer
C convert to char
s join all chars and print
```
[Answer]
# Javascript (*ES6*) 83 + 73 = 156
Both functions take input as and ouput an array of numbers to represent bytes.
**Encrypt 85 84 83**
```
E=s=>s.concat((h=s.reduce((x,y)=>x^y))<<4&240^h).map(x=>a<<4&240|(a=x^h)>>4,a=h>>4)
```
**Decrypt 75 73**
```
D=s=>s.map(x=>(a<<4&240|(a=x)>>4)^h,h=(a=s.shift())&240|s[~-s.length]&15)
```
**Demonstration (Firefox only)**
```
E=s=>s.concat((h=s.reduce((x,y)=>x^y))<<4&240^h).map(x=>a<<4&240|(a=x^h)>>4,a=h>>4)
D=s=>s.map(x=>(a<<4&240|(a=x)>>4)^h,h=(a=s.shift())&240|s[~-s.length]&15)
toHexString = x=>'0x'+x.map(y=>y.toString(16)).join('')
input = [...'G0lf'].map(x=>x.charCodeAt());
document.write('Input: ' + toHexString(input) + '<br />');
encrypted = E(input);
document.write('Encrypted: ' + toHexString(encrypted) + '<br />');
decrypted = D(encrypted);
document.write('Decrypted: ' + toHexString(decrypted) + '<br />');
```
---
**Using Strings 131 + 129 = 260**
And just for fun... here's some versions which use strings for input/output instead.
```
E=(s,h=0)=>[for(x of s)(h^=y=x.charCodeAt(),y)].concat(h<<4&240^h).map(x=>String.fromCharCode(a<<4&240|(a=x^h)>>4),a=h>>4).join('')
D=s=>(s=[s.charCodeAt(j=i)for(i in s)]).map(x=>String.fromCharCode((a<<4&240|(a=x)>>4)^h),h=(a=s.shift())&240|s[~-j]&15).join('')
E('G0lf') // 's¤Ñ\x11½'
D('s¤Ñ\x11½') // 'G0lf'
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 + 17 = 42 bytes
```
Oµ^^/;^/b⁴Ż€-.ịⱮµṪjFs2ḅ⁴Ọ
```
[Try it online!](https://tio.run/##y0rNyan8/9//0Na4OH3rOP2kR41bju5@1LRGV@/h7u5HG9cd2vpw56ost2KjhztagXIPd/f8P9wOlI/8/1/J3SAnTUlHQSkxKbkktbhECQA "Jelly – Try It Online")
```
Ob⁴FµḢ,Ṫ,s2$ḅ⁴^/Ọ
```
[Try it online!](https://tio.run/##AUQAu/9qZWxsef//T2LigbRGwrXhuKIs4bmqLHMyJOG4heKBtF4v4buM/8OH4oKsWf//InPCpMOREcK9IiwgInFxQVAhMFAmIg "Jelly – Try It Online")
[Full round trip](https://tio.run/##y0rNyan8/9//0Na4OH3rOP2kR41bju5@1LRGV@/h7u5HG9cd2vpw56ost2KjhztagXIPd/dw@YMUuQEldizSAUrqFBupQCTj9IHS/x/ubDk8EUS0//@v5G6Qk6YEAA).
+6 bytes correcting a bug which looks like it also plagues [Martin's CJam answer](https://codegolf.stackexchange.com/a/49200/66833)
## How they work
### Encryption
```
Oµ^^/;^/b⁴Ż€-.ịⱮµṪjFs2ḅ⁴Ọ - Main link. Takes S on the left
O - Convert S to char codes; Call this O
µ - Discard S and use O as the left argument
^/ - Reduce O by XOR to get the hash, X
^ - XOR each element in O by X
^/ - X
; - Concatenate to the end of O
⁴ - 16
b - Convert each to base 16
Ż€ - Prepend a 0 to each
Ɱ - For each:
-.ị - Get the -0.5th index
This returns the last 2 elements of the list
As the ị atom returns [floor(x)ị, ceil(x)ị] for
non-integer x, and uses 1-indexing. Therefore,
-.ị = -0.5ị = [floor(-.)ị, ceil(-.)ị]
= [-ị, 0ị] = last 2 elements
For a integer < 16, b⁴ returns a singleton list
Otherwise, it'll return (here) a pair
We then prepend 0 so each list has either 2 or 3 elements
and ignore the leading 0 if it already had 2 elements
Call this list of nibbles N
Currently, N = [[a, b], [c, d], ..., [x, y]]
where [a, b] are the nibbles of the XOR'ed elements
and [x, y] are the nibbles of X
µ - Discard O and use N as the left argument
Ṫ - Remove [x, y] from N
j - Join [x, y] with N, yielding [x, [a, b], ..., y]
F - Flatten; [x, a, b, c, d, ..., y]
s2 - Split into pairs; [[x, a], [b, c], ...]
ḅ⁴ - Convert each from base 16
Ọ - Convert back to characters
```
### Decryption
```
Ob⁴FµḢ,Ṫ,s2$ḅ⁴^/Ọ - Main link. Takes S on the left
O - Convert to char codes
b⁴ - Convert to hex
F - Flatten; Call this list of hex bytes H = [x, a, b, ..., y]
µ - Discard S and use H as the left argument
Ḣ - Remove the first element of H, x
Ṫ - Remove the final element of H, y
, - Pair; [x, y]
$ - Group the previous two links as a monad f(H):
s2 - Split into pairs
, - Pair with [x, y]; [[x, y], [[a, b], ...]]
ḅ⁴ - Convert each from hex
^/ - Reduce by XOR
Ọ - Convert into chararacters
```
] |
[Question]
[
>
> **EDIT : Recently, my question has been proposed as a duplicate of [2048 Bot Challenge](https://codegolf.stackexchange.com/questions/25226/2048-bot-challenge). I would like to stress that this question is different from that question, and will require answers to be thought of differently than that question. 2048 Bot Challenge asked the user to create a bot, and it would be run for an hour, with the highest score being the user's score. Additionally, it had a limit of 555 bytes. My challenge runs the code much less frequently, only 3 times. Your score is calculated by using the average score of those three times and dividing by the character length of your golfed code. My question encourages entries to be "smarter," and not try and get the highest score by brute force.**
>
>
>
-
>
> EDIT: The get method was changed to getTile, to avoid confliction with the JS keyword get. Additionally, a high score section was added.
>
>
>
Recently, I created a site that allows the popular game 2048 to be controlled using JavaScript. My site is linked here:
<http://thatcoolidea.com/2048>
How:
An Ace Editor is located above the board. You place code in it, which is run once every 250 ms, or 4 times per second. This is called a cycle.
Use the following methods to control the board. You can't use the arrow keys.
```
up(); //move up
down(); //move down
left(); //move left
right(); //move right
move(integer); //integer is a direction. 0:up,1:right,2:down,3:left
getTile(y,x); //gets the value of the tile in position y,x on the board. See diagram
```

The following variables are defined for your convenience:
```
eother //boolean, alternates every cycle
frozen //integer, counts how many cycles the board has remained stationary
lastDir //integer, indicates the last direction that was tried to move in
//uses same format as the move method above.
startup //boolean, will always be true when the game first starts
//you can change it as you wish
a
b //a b and c are all persistant variables, they do not change each cycle
c //any other variables defined in the cycle will be reset every time
```
Rules:
* No Randomness, you must use logic. (Yes, I know the example code uses random.)
* No hooking into the game functions or cheating in other ways
* Generally, try to only call one move method per cycle. It is OK if you use more, but it screws with the animation
* The board must start in a random state, no modification of pre-game state
* You must provide both the uncompressed and golfed version of the code in your post.
* You must provide a link to the site that already loads the uncompressed version of your code, served via PasteBin (For example, ...thatcoolidea.com/2048?i=pH18GWtu loads the example code.)
Scoring:
* Your code will be scored by me.
* Part A of your score is an average of 3 runs of the code, rounded down.
* Part B of your score is the character length of your golfed code.
* Your final score is Part A divided by Part B
The winner will have their code immortalized as the example code on the site, if they choose, and acknowledged in a comment in the code.
Good luck! Hope you enjoy the challenge.
**Current High Score**
225.22 - Freezer - user3217109
[Answer]
# Sinker/Shaker, 65 bytes
[Here's mine](http://thatcoolidea.com/2048?i=ifwusxB8). It's as blind and simple as they come.
```
if(startup){startup=false;a=0}b=(a++)%4;move(frozen>2?0:b==0?2:b)
```
Uncompressed(ish)...
```
if(startup){startup=false;a=0;}
b=(a++)%4;
move(frozen>2?0:b==0?2:b)
```
All it does is repeats down, right, down, left, etc. and hits up once if it gets stuck. It doesn't always do very well, but it'll occasionally get 512s. My high score during testing was 7520.
[Answer]
# Traffic light - 23 21 bytes
```
move(frozen&2|eother)
```
[This is the link.](http://thatcoolidea.com/2048/?i=Je4srQWL)
This will move alternatingly up and right, except when the board has remained stationary for the last two moves, in which case it will move down and left respectively.
My original, functionally equivalent submission was 23 bytes long and scored 182.72:
```
move((frozen&2)+eother)
```
[Answer]
# Whirlpool - 37 21 17 bytes - Score: 211.22
I decided to go with a "less is more" approach. My code is a simple design that tries to go up, right, down, left... I will be working on a learning AI to see a more optimal way to approach the puzzle.
```
a=a|0;move(a++%4)
```
Optimizer helped to shorten `a`'s initialization.
Sam helped to shorten `a`'s initialization, removed `var`.
Ungolfed?
```
var a=a|0;
a++;
move(a%4);
```
My top score with this AI is 5120.
# Freezer - 12 bytes - Score: 225.22
This bot has move priority. It attempts to go up. If it can' go up, it goes right. If it can't go right, it does down. If it can't go down it goes left.
```
move(frozen)
```
## James Bond Explanation
The encrypted code decrypts to say:
```
HTMLActuator.prototype.updateScore=function (score) {score*=9989800000;
this.clearContainer(this.scoreContainer);
var difference = score - this.score;
this.score = score;
this.scoreContainer.textContent = this.score;
if (difference > 0) {
var addition = document.createElement("div");
addition.classList.add("score-addition");
addition.textContent = "+" + difference;
this.scoreContainer.appendChild(addition);
}
}
```
Optimizer should have golfed his decrypted code. This could have been #Optimized.
[Answer]
# Hanger - 20 bytes
### Official score: 224.87 - 2nd place by 0.35 points
This bot uses the down, left, down, right approach, but with the unusual feature that it will never move up. I'm not sure how to score cases where it hangs and does not complete, or whether the fact that that occurs renders it illegal. Here it is, though:
```
b=b|0;move(b++%4||2)
OR
move(startup++%4||2)
```
Initialization pattern thanks to @Optimizer.
In my 3 test runs, it scored 4284, 6352 and 4232, for an average of 4956. I will update when the official test is run.
---
Alternate version which gets out of hangs (27 bytes):
```
b=b|0;move(b++%4||b%997&&2)
```
] |
[Question]
[
## Background
[Lambda calculus](https://en.wikipedia.org/wiki/Lambda_calculus) is a model of computation using *lambda terms*.
* A variable \$x\$ is a lambda term.
* If \$E\$ is a lambda term, the lambda abstraction \$\lambda x. E\$ is a lambda term.
* If \$E\_1, E\_2\$ are lambda terms, the lambda application \$E\_1 E\_2\$ is a lambda term.
The rule of computation is called \$\beta\$-reduction: \$(\lambda x. E\_1) E\_2\$ is reduced to \$E\_1\$ in which every occurrence of \$x\$ is replaced with \$E\_2\$. For example, \$(\lambda x. x x)(\lambda y. y)\$ is reduced to \$(\lambda y. y)(\lambda y. y)\$, then to \$\lambda y. y\$.
[Combinatory logic](https://en.wikipedia.org/wiki/Combinatory_logic) operates on a similar premise, but instead of variables and lambda abstraction, it uses a fixed set of combinators. Each combinator has a fixed arity, and it is \$\beta\$-reduced only when it gets enough number of arguments applied to it.
For example, \$S\$ and \$K\$ have following reduction rules:
$$
\begin{align}
S x y z &\mapsto x z (y z) \\
K x y &\mapsto x
\end{align}
$$
\$S\$ has an arity of 3, so \$SKK\$ is not reducible. But if you apply one more argument to it, it reduces to \$SKKx \mapsto Kx(Kx) \mapsto x\$, which shows that \$SKK\$ is extensionally equal to the identity function \$\lambda x. x\$ in lambda calculus.
[SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) is a well-known *complete* combinatory logic system, i.e. a system where any arbitrary lambda calculus term can be represented. [This section on Wikipedia](https://en.wikipedia.org/wiki/Combinatory_logic#Completeness_of_the_S-K_basis) shows how to transform any given lambda term into a SKI expression.
[BCKW system](https://en.wikipedia.org/wiki/B,_C,_K,_W_system) is a lesser known complete system, discovered by Haskell Curry in 1930. It uses four combinators defined as follows:
$$
\begin{align}
B x y z &\mapsto x (y z) \\
C x y z &\mapsto x z y \\
K x y &\mapsto x \\
W x y &\mapsto x y y
\end{align}
$$
In Haskell terms, \$B\$ equals `(.)`, \$C\$ equals `flip`, and \$K\$ equals `const`. Haskell doesn't have a built-in for \$W\$, but it is equal to `(<*>id)`.
## Challenge
Given a lambda term, convert it to an equivalent term in BCKW system.
The I/O format is flexible. The lambda term and BCKW term can be represented as a string notation ([fully parenthesized](https://codegolf.stackexchange.com/q/205809/78410) or using [prefix notation](https://codegolf.stackexchange.com/q/112115/78410)) or a (pre-parsed) nested structure. It is also allowed to use four distinct values (numbers, chars, strings) in place of BCKW combinators. The lambda term can also use [de Bruijn indexes](https://en.wikipedia.org/wiki/De_Bruijn_index) or other directly equivalent representations.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Examples
There are infinitely many different correct outputs for every input, so these are merely examples of possible conversions.
```
\x. x
=> W K or B C C
\x. x x
=> W (W K)
\x y z. x (y z)
=> B
\x y z. z x y
=> B C (C (W K))
\f g x y. f (g x) (g y)
=> B W (B (B C) (B (B (B B)) B))
\x y z. y (y y) y
=> K (W (W (W (B (B (B (B K))) B))))
\f x. f (f (f x))
=> W (W (C (B B (B B B)) B))
```
[Answer]
# [Haskell](https://www.haskell.org/), 133 bytes
```
data T=T:@T|L T|V Int|B|C|K|W
l(x:@y)=W:@(B:@(C:@l x):@l y)
l(V 0)=W:@K
l(V n)=K:@V(n-1)
l x=K:@x
f(L x)=l$f x
f(x:@y)=f x:@f y
f x=x
```
[Try it online!](https://tio.run/##ZZA7b4MwFIV3fsUZOthDokI3S5aspEsFU4NIVyuYBNVxKqAtSP7tpZdHGpFamPv47jm2fNL1u7G273PdaKQyFSr1CVKf4cU1fuO3Pvb7wLJWqI7LvVBsQ3srlEXLh3/HiWZ4HGE85o7LWKiMuVVIEO1QtUHBEpJI@1BgKCZDyoUq0AWUyLbPTVV@le6I0tWNdgeD3enyjTT4D16Nzgmcdekgqd2YSh8asE9nS2dqrHHWH2D1oF@joF2RglMcOe8TjNcOpgihcC2nL0M0NCmGV0jrxm@qiE8xXPBp5Gn2iP5Glo3RdOkaLo@dJQv7u6G7O/4cCquPdb9629Fb5dpenHmeH/AX "Haskell – Try It Online")
Accepts De Bruijn–indexed lambda terms with \$λ\$ written as `L`, application written as `:@`, and variables written `V 0`, `V 1`, … from innermost to outermost.
This uses the standard unoptimized \$SKI\$ abstraction elimination algorithm, with \$Sxy\$ and \$I\$ replaced by \$W(B(Cx)y)\$ and \$WK\$. As such, it’s very inefficient in terms of output size.
[Answer]
# [Python 3](https://docs.python.org/3/), 451 bytes
```
I='W','K'
F=lambda v,e:v==e[0]or F(v,e[1])if[]==e*0else e!=v if''==e*0else F(v,e[0])and F(v,e[1])
f=lambda x,u:0*x==()and u==x[1]
T=lambda e,v='$':e if''==e*0else(T(e[1][0],v)if f(*e[::-1])and F(e[0],e[1][0])else(('K',T(e[1],v))if F(*e)else(I if e[0]==e[1]else T([e[0],T(*e[::-1])],v))))if[]==e*0else((('W',e[0][0])if f(e,v)else(('C',e[0][0]),e[1]),v)if f(e[0],v)else(((('B',e[0]),e[1][0]),v)if f(e[1],v)else((I,v)if v==e[0]else T(e[0],v),T(e[1],v))))
```
[Try it online!](https://tio.run/##VZFBa4QwEIXv/ooUCpORFJTehFy2IEivQg8hB7sbqaCurKvYX28niWl2L0PMvO/Nmzj93n@u4/u@VxK@QMAnJKXsm@H70rBVmGKV0qhMX2@s5PStco1dqzTdppnpZ8PMi1xZ1wLEK6/MNDbjJWJJG3w3sRRZuknJnWKRciNBUoe@EauEVyjMsy@vuTUiY7FSCNby1KiieMvDIDtTHBJ0BKd9hMeIsVBJkO9V5M4sYjfMtUtec@VM6mjtQHxempMxPZaV2lEuC4UOMz9iy68e8hqf/bDgcPJC/A8dhXkUVv72@BNHzsPqYTnEfV7OZyaZghEE1dbVjSp3Z5poG3RGqhsgaq2T6daNd3pbCyMmU7/MzmNw9Bi5ICF2AHwgLULT/wA "Python 3 – Try It Online")
Previous byte counts: 628, 617, 559, 552, 536, 506, 495, 480, 472, 461, 456
I was working on a term-rewriting procedure for this in my free time anyways, why not golf it? Input/Output format is strings for variables, ~~tuples~~ lists of length two for lambda abstractions, and ~~lists~~ tuples of length two for applications.
(Reduced char count by switching input/output method)
(Reduced to 559 bytes thanks to @ovs)
] |
[Question]
[
Stackylogic is a programming language I made up in a previous challenge: **[Run Stackylogic](https://codegolf.stackexchange.com/questions/84851/run-stackylogic)**. Read that post for full details and examples, but here is how it works paraphrased:
>
> Stackylogic takes `0`'s and `1`'s for input and outputs a single `0`
> or `1` upon completion.
>
>
> A program consists of lines that only contain the characters `01?` as
> well as exactly one `<` at the end of one of the lines. Lines may not
> be empty and the line with the `<` must have at least one `0`, `1`, or
> `?` before it.
>
>
> Here's a sample program that computes the [NAND](https://en.wikipedia.org/wiki/NAND_gate) of two bits:
>
>
>
> ```
> 1
> ?<
> 11
> ?
> 0
>
> ```
>
> Every line in a program is considered a [stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)), with the
> bottom on the left and the top on the right. Implicitly, there is an
> empty stack (i.e. empty line) before the first line in a program and after the last
> line.
>
>
> The `<`, called the cursor, marks the stack to start on
> when a program is run. Execution proceeds as follows:
>
>
> 1. Pop the top character off the stack the cursor is currently pointing to.
>
>
> * If the character is `?`, prompt the user for a `0` or a `1` and act as if that was the character.
> * If the character is `0`, move the cursor one stack up (to the line above the current line).
> * If the character is `1`, move the cursor one stack down (to the line below the current line).
> 2. If the stack the cursor moves to is empty, output the last value that was popped off a stack (always a `0` or `1`), and end the
> program.
> 3. Else, if the stack the cursor moves to is not empty, go back to step 1 and repeat the process.
>
>
>
The key thing to realize for this challenge is that all Stackylogic programs equate to a [truth table](https://en.wikipedia.org/wiki/Truth_table). Some predetermined number of boolean values are input and exactly one boolean is deterministically output.
So your task is to produce a Stackylogic program that satisfies or simulates, i.e. has the same output as any given truth table. But it's not obvious that Stackylogic *can* simulate any truth table, so here's a [proof by induction](https://en.wikipedia.org/wiki/Mathematical_induction):
>
> ### Base Case
>
>
> The two 0-input truth tables are the tables that always output `0` or
> `1`. The Stackylogic equivalents of these tables are `0<` and `1<`
> respectively.
>
>
> ### Inductive Step
>
>
> Assume Stackylogic can simulate any N-input truth table. Let M = N +
> 1.
>
>
> An M-input table, T, can be expressed as two N-input tables,
> T0 and T1, plus the additional input bit B. When
> B is 0, the result of T0 is used. When B is 1, the result
> of T1 is used.
>
>
> For example, the 3-input truth table corresponding to the pseudocode
>
>
>
> ```
> if B:
> result = x OR y
> else:
> result = x NAND y
>
> ```
>
> is
>
>
>
> ```
> B x y | result
> 0 0 0 | 1
> 0 0 1 | 1
> 0 1 0 | 1
> 0 1 1 | 0
> 1 0 0 | 0
> 1 0 1 | 1
> 1 1 0 | 1
> 1 1 1 | 1
>
> ```
>
> which is really the two 2-input truth tables for NAND and OR stacked
> atop each other with the muxing bit B.
>
>
> Let S0 and S1 be the Stackylogic programs that
> satisfy T0 and T1 respectively (we know these exist based on the first assumption). Program S that
> satisfies T can then be constructed as:
>
>
>
> ```
> [lines of S0 excluding the cursor, with 0 appended to all lines below the cursor]
> ?<
> [lines of S1 excluding the cursor, with 1 appended to all lines above the cursor]
> ```
>
> This arrangement effectively muxes between S0 and
> S1 based on the first input bit (from line `?<`). If it is
> `0`, the cursor will ride the appended `0`'s up to the original cursor
> position of S0, which will then be bordered top and bottom by
> empty stacks, and thus run exactly identical to the original
> S0. Likewise, if `1` is input, the cursor will ride the
> `1`'s down to S1's cursor position and proceed to execute
> it as if it were alone.
>
>
> For example, Stackylogic programs for OR and NAND are
>
>
>
> ```
> ?
> ?<
>
> ```
>
> and
>
>
>
> ```
> 1
> ?<
> 11
> ?
> 0
>
> ```
>
> They can be combined to simulate
>
>
>
> ```
> if B:
> result = x OR y
> else:
> result = x NAND y
>
> ```
>
> like so:
>
>
>
> ```
> 1
> ?
> 110
> ?0
> 00
> 0
> ?<
> ?1
> ?
>
> ```
>
> Thus, any truth table can be simulated by a Stackylogic program.
>
>
>
# Challenge
Write a program or function that takes in an N input truth table (N > 0) in the form of a list of 2N boolean values that represent the outputs of the table in ascending binary order.
Any reasonable input format is alright. e.g. for an OR truth table
```
x y | OR
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 1
```
any of these styles of inputs would be fine:
`0111`
`0, 1, 1, 1`
```
0
1
1
1
```
`[False, True, True, True]`
Print or return a Stackylogic program that satisfies the truth table, i.e. has the exact same output given the same input. *Any* finite program that satisfies that table is valid output. You do not need to follow the inductive proof's method of construction. The Stackylogic programs do not need to be optimally short.
For example, if the input were `11100111`, one valid output would be
```
1
?
110
?0
00
0
?<
?1
?
```
but there are many others.
**The shortest code in bytes wins.**
See [the original Stackylogic challenge](https://codegolf.stackexchange.com/questions/84851/run-stackylogic) if you need an interpreter.
[Answer]
# Pyth, 53 bytes
```
L?tb,lehJyMc2bsX0.e.e+W>_Wk-Yhb0ZkebJ\?,0]`hbjXF+yQ\<
```
[Try online](https://pyth.herokuapp.com/?code=L%3Ftb%2ClehJyMc2bsX0.e.e%2BW%3E_Wk-Yhb0ZkebJ%5C%3F%2C0%5D%60hbjXF%2ByQ%5C%3C&input=%5B1%2C+1%2C+1%2C+0%2C+0%2C+1%2C+1%2C+1%5D&debug=0)
This is an exact implementation of the system described in the challenge for how to implement arbitrary truth tables in Stackylogic. We simply cut the truth table in half, implement it recursively, and then append 0 and 1 as appropriate.
This defines a recursive function, whose return value is `[1, ['0', '?', '1']]`, where the first number is the location of the pointer, and the rest is a stackylogic program.
```
L?tb,lehJyMc2bsX0.e.e+W>_Wk-Yhb0ZkebJ\?,0]`hbjXF+yQ\<
Q = eval(input())
L?tb,lehJyMc2bsX0.e.e+W>_Wk-Yhb0ZkebJ\?,0]`hb
L def y(b): return
?tb if b[1:] (base case on false)
,0]`hb else: [0, str([0])]
then:
c2b Cut the input in half
yM Map y over the halves
J Store that in J
,leh The cursor position is the length
of the body of the first function
.e J enum-map, where k is the index
and b is the value, over J
.e eb enum-map, Y is the index and
Z is the value, over body of b
+W Zk Add to Z (line) k (the overall
index, 0 or 1) conditional on
-Yhb Y (line index) - cursor
_Wk Negated if k
> 0 > 0
X0 \? Add '?' to the first element
s Concatenate, giving the body
jXF+yQ\<
yQ Call the above on the input
+ \< Append a '<'
XF Splat the 3 element list into the 'append-at' function,
adding the curson in the right place
j Join on newlines and print.
```
[Answer]
# Python 3, ~~352~~ ~~208~~ 205 bytes
~~This is still very ungolfed, and I will try to add an explanation later.~~ *After some modifications, I managed to remove ~~144~~ 147 bytes.*
```
f=lambda x,l=len,r=range:'\n'.join(*x)if l(x)<2 else f([[x[i][j]+['0',''][j<=l(x[i])//2]for j in r(l(x[i]))]+[['?','?<'][l(x)<3]]+[x[i+1][j]+['1',''][j>=l(x[i])//2]for j in r(l(x[i]))]for i in r(0,l(x),2)])
```
A function `f` that takes input of the truth table values as a list of Booleans of the form `['1','1','1','0','0','1'...]`, where `'1'` is truthy and `'0'` is falsey, and returns a Stackylogic program.
[Try it on Ideone](https://ideone.com/rsEz56)
If you want to test a produced program, you can use [GamrCorps](https://codegolf.stackexchange.com/users/36670/gamrcorps)'s Convex interpreter [here](http://convex.tryitonline.net/#code=Ti9TXCt7cylfJzw9e1I6TTt9e1IpOlI7K30_fSUnPC1NKXsow6Y9KXNfOlE7Ij8xMCAiImwrIE0pOk07IE0oOk07IFc6TTtBfnAiUy_Di35-XyFTKit0TSlROkE7fWg7Ow&input=MQow&args=MQo_PAoxMQo_CjA).
**How it works**
This is a recursive function and uses the inductive method described in the question.
At the zero-indexed recursion level `a`, the function creates `n/2` `a+1`-input Stackylogic programs from the `n` `a`-input programs in the list. This is done by joining all adjacent pairs of two programs in the list with `?`; since the cursor is always at the middle element of each constituent program, the required appending of `0` or `1` can be performed by iterating over each line of the programs being joined, and appending if the index of the current line is less than or equal to/greater than or equal to the middle index as appropriate. If the list contains only two programs, the next recursive call will give the final program; since this requires a cursor, joining instead occurs on `?<`.
When the list has length `1`, the list must contain just one element containing the full program. Hence, all lines in the program are joined on a newline, and then returned.
An example helps to illustrate this:
```
Take the input ['1', '1', '1', '0', '0', '1', '1', '1'].
Level Return value
0 [['1', '?', '1'], ['1', '?', '0'], ['0', '?', '1'], ['1', '?', '1']]
1 [['1', '?', '10', '?', '11', '?', '0'], ['0', '?', '10', '?', '11', '?', '1']]
2 [['1', '?', '10', '?', '110', '?0', '00', '?<', '01', '?1', '101', '?', '11', '?', '1']]
3 '1\n?\n10\n?\n110\n?0\n00\n?<\n01\n?1\n101\n?\n11\n?\n1'
which when printed gives:
1
?
10
?
110
?0
00
?<
01
?1
101
?
11
?
1
```
] |
[Question]
[
# The Challenge
Given a `n x m` matrix with `n > 1` and `m > 1` filled with integers
```
1 2 3
4 5 6
```
and a list of integers with exactly as many values as `2x2` blocks in the matrix (`(n-1)*(m-1)` if you need the exact number)
```
[1, 2]
```
Output the matrix with every `2x2` block rotated by the current value in the list in the given order. The example above would yield
```
4 6 2
5 3 1
```
The first block gets rotated one time to the right and the second block gets rotated two to the right.
## Notes
* A positive integer means you rotate right by that many steps.
* A negative integer means you rotate left by that many steps.
* A zero means that you don't rotate.
* You rotate the blocks row-wise. That means that you start in the first row and go to the right. Once you rotated every block in that row you go to the next one. At the end every block was rotated exactly once.
* Keep in mind that the blocks overlap each other. The first matrix above has the blocks `[[1,2],[4,5]]` and `[[2,3],[5,6]]` for example.
* Each rotation of a block affects the rotation on the adjacent blocks. This is why you have to do the rotations in the pattern described above.
# Rules
* You may take the input in the most convenient format. Please specify in your answer which one you use. This does **not** allow you to read the matrix block-wise though.
* Function or full program allowed.
* [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
# Test cases
Input format here is a list of lists for the matrix and a normal list for the values.
```
[[1,2],[3,4]], [-3] -> [[4,1],[3,2]]
[[1,1,1],[1,1,1]], [-333, 666] -> [[1,1,1],[1,1,1]]
[[1,2,3],[4,5,6]], [1,2] -> [[4,6,2],[5,3,1]]
[[1,2,3],[4,5,6],[7,8,9]], [4,0,12,-20] -> [[1,2,3],[4,5,6],[7,8,9]]
[[1,2,3,4,5],[5,4,3,2,1],[1,2,3,4,5]], [2,-3,4,1,6,24,21,-5] -> [[4,1,5,2,4],[2,1,3,5,5],[3,2,4,3,1]]
```
**Happy Coding!**
[Answer]
## CJam (42 40 bytes)
```
{(\@2$,(/.{@a@a+z(\@.{4,={+2/zW%~}*}z~}}
```
[Online demo](http://cjam.aditsu.net/#code=%5B2%20-3%204%201%206%2024%2021%20-5%5D%20%5B%5B1%202%203%204%205%5D%20%5B5%204%203%202%201%5D%20%5B1%202%203%204%205%5D%5D%0A%0A%7B(%5C%402%24%2C(%2F.%7B%40a%40a%2Bz(%5C%40.%7B4%2C%3D%7B%2B2%2FzW%25~%7D*%7Dz~%7D%7D%0A%0A~p)
Basically this applies the same technique twice in order to fold the block
```
{4,={+2/zW%~}*}
```
which operates on a 2x2 matrix and a number of times to rotate.
```
[first row] [[second row] [third row] ... [last row]] [value_0 value_1 ... value_n]
```
can be processed with
```
.{block}
```
and has the effect of
```
[first row]
[second row] value_0 {block}~
[third row] value_1 {block}~
...
```
because `.` (like `%` in CJam) doesn't gather the results into an array until it's finished.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~37~~ 35 [bytes](https://github.com/abrudz/SBCS)
```
{⌽∘⍉@⍺⊢⍵}/⌽(⊂,{(4|⎕)/,⊢∘⊂⌺2 2⍳⍴⍵})⎕
```
[Try it online!](https://tio.run/##fZC/TsMwEMZ3P8WNtnRRZMfOiJi68gCRh0ioLEVFiAW1LB1KiRIEAxILCxMbA7BUQkh9lHuR8Ln8CwxMvu@7330@uz6aZPun9WR60Et3N7PSvu5Kt5bmXrqXsxxSS7PgmfZzubwxOTuW1S3sHEX7ht7mQbon6Z4Tb8AoWZ2P@xmQBHYX/8elDrBmIe3akfsd1SOqP6xPZHkly2ttyVFhtKdApVHH0@TDU2MFJmml/sAE1uiAo4C0ZuB@zjvaPCbDUknOk7PQYZj48w6N5bCiwcqpq8zeaKSqyuJLisiV58BljEzJiZTtUAWvRM1V4IJtjF80g926HrVDhwd@SnCcJWHTuGdnOQvfiRb3OPaYwSRmwjYr5fiPW94B "APL (Dyalog Unicode) – Try It Online")
Switched to a more straightforward method after I realized `@` also accepts a matrix of coordinates. Then we don't need to fiddle with the coordinate order; we extract the submatrix coordinates with `⊢∘⊂⌺2 2`, and just rotate them directly using `⌽∘⍉`.
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 37 [bytes](https://github.com/abrudz/SBCS)
```
{1⌽@⍺⊢⍵}/⌽(⊂,{(4|⎕)/,2,∘⌽/2,⌿⊂¨⍳⍴⍵})⎕
```
[Try it online!](https://tio.run/##dY@9SgNBFIX7eYrbZQfusszszJYiCGmtZZliYVkRognGRqKNRQwhK1oI1lZ2FmojiJBHuS@yORN/WASrueebc86dqSajtD6vRuPDThbXTTczsvrYlfZdlo/Svl1mkIksr3iWuAu5udcZW5bFA3CGYfWJu/WTtC/Svka/hic2dcfVmcxvZX6XGLKU68SRp0Kr03HkYKpR8ESt1B8zwasTjyOHNLpHv/OW1s8RGCrIOrIG2vcb8Yy9g0HdnEwHqj6aTujfV8eI0vvDoSpLg8/lgUvHnosQmCIJlO5QCVZg5tJzziaEHzfDu6UOs8UN93hssJxGYWLcsTWc@t9Ggz2WHTJIIuO3XbHHfW3ZAA "APL (Dyalog Unicode) – Try It Online")
A full program that takes the matrix, then the vector of rotation amounts. Prints the resulting matrix with a leading space.
`@` can extract the elements at certain positions, manipulate them, and place them back into the original matrix, which is great for 2×2 rotation. In particular, `1⌽@(1 1)(2 1)(2 2)(1 2)` extracts the top left submatrix `[a b][c d]` into a vector `a c d b`, rotates once to the left (`1⌽`) into `c d b a`, then puts the values back so that the submatrix becomes `[c a][d b]`. This achieves rotating the submatrix exactly once.
```
{1⌽@⍺⊢⍵}/⌽(⊂,{(4|⎕)/,2,∘⌽/2,⌿⊂¨⍳⍴⍵})⎕
⍝ Read from right:
⎕ ⍝ Take the matrix from stdin
{...} ⍝ Pass to the dfn as ⍵
⍳⍴⍵ ⍝ Matrix of 2D coordinates of ⍵
2,⌿⊂¨ ⍝ Pair vertically adjacent coordinates
2,∘⌽/ ⍝ Catenate horizontally adjacent coordinate pairs,
⍝ flipping the right one so that it looks like (1 1)(2 1)(2 2)(1 2)
, ⍝ Flatten the matrix of lists of coordinates
(4|⎕)/ ⍝ Copy each (Rotations modulo 4) times
⌽(⊂,...) ⍝ Prepend the original matrix enclosed and reverse the entire array,
⍝ so that it is suitable for RTL reduce
{ }/ ⍝ RTL reduce by...
1⌽@⍺⊢⍵ ⍝ Take the matrix ⍵ and rotate once at coordinates ⍺
```
[Answer]
## CJam, ~~65~~ ~~63~~ ~~60~~ 55 bytes
There *must* be a better way to do this...
```
{_e_\z,:N(@/Ta*ee{~4,=,f{;1$,,\[XTN_)]f+_(+er\f=}~}/N/}
```
This is an unnamed function that expects the instructions and the matrix (in that order) on the stack and leaves the resulting matrix in their place.
[Test it here.](http://cjam.aditsu.net/#code=%5B2%20-3%204%201%206%2024%2021%20-5%5D%20%5B%5B1%202%203%204%205%5D%20%5B5%204%203%202%201%5D%20%5B1%202%203%204%205%5D%5D%0A%0A%7B_e_%5Cz%2C%3AN(%40%2FTa*ee%7B~4%2C%3D%2Cf%7B%3B1%24%2C%2C%5C%5BXTN_)%5Df%2B_(%2Ber%5Cf%3D%7D~%7D%2FN%2F%7D%0A%0A~p)
### Explanation
I don't feel like writing the full breakdown for the code right now, so here is a rough overview:
* 2D array manipulation is a pain in CJam, so I'm instead unrolling the matrix, compute each rotation as a permutation of the elements at specific positions and then split the array into rows again at the end. The width of the matrix is stored in `N`.
* A rotation at position `k` in the unrolled array changes four indices: `k <- k+1`, `k+1 <- k+1+N`, `k+N <- k`, `k+1+N <- k+1`. For each index `k` along the instruction list, I compute a permutation corresponding to this, and apply it to the unrolled input array.
* This leaves the problem, that in the linear array some rotations will be positioned with its top left corner in the last column of the input. To skip these, I riffle zeroes into the instruction list, such that these invalid 2x2 sub-blocks *are* technically processed, but with a no-op.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~166~~ 159 bytes
```
A,R=input();m=~-len(A[0])
for j,r in enumerate(R):exec r%4*"a,b,c,d=A[j/m][j%m:][:2]+A[j/m+1][j%m:][:2];A[j/m][j%m:j%m+2]=c,a;A[j/m+1][j%m:j%m+2]=b,d;"
print A
```
[Try it online!](https://tio.run/##ZY7RaoMwFIbvfYoQKOj8ZZqoaw25EN@gtyEX1mZUqamIZdvNXt1F3UbHCOFwvv87ORk@psvNsrmSlNK5xFG2drhPfiB6@RldjfVLFevAe72NpMNIWkuMvfdmrCfjH4PCvJuGjLv0idY4ocFZlqp77rXqdn2hVcF0uIIweUDiwXE3ZFo2qMUf8ZufcBbUG8bWTqSc3R/FspG@XdqrIdW2vqKzUgmYhuJItQZREdfewtxxdKsb5xwkz/MtZuAuTpEhX@PlkX8B1Av2OKxCihgJQ8TiXw/Ock7mKnf9tu@HLzNOX5oEOVgKliDK9Bc "Python 2 – Try It Online")
] |
[Question]
[
Note: this challenge involves downloading and sifting through HTML webpages. If your language cannot handle this you might not want to participate in this challenge.
# Introduction
There are always discussions over in [The Nineteenth Byte Chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte) about who leads the starboard. So, lets help everyone out and count the total amount of stars per user in the chat.
# Challenge
Given an positive integer `N` which is greater than zero, calculate the leader(s) of the starboard of the last `N` starred messages in the chat. These messages can be viewed [here](http://chat.stackexchange.com/rooms/info/240/the-nineteenth-byte?tab=stars). Hint: each page has 50 starred messages. Output will be a list of the top 5 users *by amount of starred messages*. A bonus of **-15%** off your byte count will be granted if you can display the usernames of those users, but no penalty will be given if you simply display the user id numbers. **Please note that there is profanity in some of the starred messages. If you are sensitive to this type of language, view the page with caution.**
Examples (Image is current starboard as of writing this challenge):
[](https://i.stack.imgur.com/a4tNk.png)
* (RED) Input: `5` Output (With bonus): `[Geobits Sp3000 PhiNotPi Seadrus]`
* (BLUE) Input: `10` Output (Without bonus): `[51024 17335 24697 116494 129255]`
* (GREEN) Input: `14` Output (Without bonus): `[51024 116494 141697 17335 24697]`
**Extra stuff:**
Ties in the top 5 will be sorted by lowest to highest *user id* number. If there is less than five users, just output the leaderboard with *empty slots* at the end. Input and output can be in any format. Output does not need to be capitalized. If input is greater than `50`, you must still count the messages on page 2, page 3, etc. You may assume that input will always be under `2^31`, and will also not be so large that it 1) is larger than the amount of starred messages that there is and 2) will not crash the program (by making arrays to big, running out of memory, etc.).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins!
---
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
---
```
var QUESTION_ID=62182,OVERRIDE_USER=36670;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
* I' m so sorry for being slow but reading starred messages while coding was so hilarious and dilatory, this could have kept my mood up for a month.
---
* **Edit:** Yes, I found it, the tie and duplicate ids issues are both fixed up harmonically. The trick is that the old code sorts the user-ids by descending number of stars, so I twisted some lines of my program in a way that it sorts users according to 99-n°\_stars; since 99 is way bigger than the top hit star-cap (hopefully - I assumed), sorting the result by increasing number of stars kills both birds with one stone, descending stars with ascendant user-ids.
---
## [BrownRecluse](http://brownrecluse.en.uptodown.com/download), ~~without bonus = 536~~ with bonus = 551-15% = 468 b
```
U=New(URL);P=New(Parser);L=New(Stack);t=New(Stack);v='http://chat.stackexchange.com/rooms/info/240/the-nineteenth-byte?tab=stars&page=';j=input();a=0;for i=1to j\50+1do begin U.Location=v+i;U.get;P.Parse(U.Data);x=New(RegEx);x.Data=U.Data;x.Mask='users/(\d*)/(\S*)".*?"times">(\d*?)<';while(x.Match)and(a<j)do begin L.Push(Format('%3d%9s%s',[99-x.Value[3],x.Value[1],x.Value[2]]));a=a+1;end;end;L.sort;i=0;for each L as y do if(not y.empty)and(not t.find(y.right(y.Length-12)))and(i<5)then begin y.delete(1,12);i=i+1;t.push(y);end;output(t.join(' '));
```
## Input
```
60
```
## Output
```
mego rainbolt alex-a lembik v
```
## Input
```
90
```
## Output
```
aditsu mego rainbolt alex-a lembik
```
## NOTES
* This program (including bonus) doesnt support unicode characters - I'm sorry Vɪʜᴀɴ!
* This program works based on the standard feature that each page contains almost 50 starred messages by default.
* See clearly that 60 and 90 messages are contained within the first two pages, whilst the outputs differ.
* [This is](http://brownrecluse.en.uptodown.com/download) the download page of this programming language in case it is not in your possession
* In case needed, this is the bonusless program of **485 b**
```
U=New(URL);P=New(Parser);L=New(Stack);t=New(Stack);v='http://chat.stackexchange.com/rooms/info/240/the-nineteenth-byte?tab=stars&page=';j=input();a=0;for i=1to j\50+1do begin U.Location=v+i;U.get;P.Parse(U.Data);x=New(RegEx);x.Data=U.Data;x.Mask='users/(\d*)/(\S*)".*?"times">(\d*?)<';while(x.Match)and(a<j)do begin L.Push(Format('%3d%9s',[99-x.Value[3],x.Value[1]]));a=a+1;end;end;L.sort;i=0;for each L as y do if(not y.empty)and(not t.find(y.right(y.Length-3)))and(i<5)then begin y.delete(1,3);i=i+1;t.push(y);end;output(t.join(' '));
```
***Input***
```
60
```
***Output***
```
169713 107051 141888 94625 116494
```
***Input***
```
90
```
***Output***
```
50454 169713 107051 141888 94625
```
>
> If there was incoherence between results my code isn't taking the blame!
>
>
>
] |
[Question]
[
**Introduction**
A family of seals are stranded upon an iceberg in the Arctic Circle. There is a radio transmitter located on the iceberg which the seals can use to call for help. However, only the daddy seal knows how to operate the radio transmitter. And worse, the ice is very slippery this time of year, so the seals will slide uncontrollably until they hit another seal or slide off the edge of the iceberg, making it very difficult for the daddy seal to reach the radio transmitter. Luckily, one of the seals is a computer scientist, so she decides to write a program to figure out how to manoeuvre the daddy seal to the radio transmitter. As there is not much space on the ice to write a program, she decides to make the program use as little bytes as possible.
**Input Description**
The seal's program will take input in from STDIN, command line arguments, or user input functions (such as `raw_input()`). It cannot be preinitialised in a variable (e.g. "This program expects the input in a variable `x`").
The first line of the input consists of two comma separated integers in the form
```
A,B
```
Following that is `B` lines consisting of `A` characters each. Each line can only contain characters out of the following:
* `.`: The cold, cold, ocean. The map will always have this as a border.
* `#`: A part of the iceberg.
* `a`...`z`: A seal that is not the daddy seal on the iceberg.
* `D`: The daddy seal on the iceberg.
* `*`: The radio transmitter.
(Note that the daddy seal is always notated with an uppercase `D`. A lowercase `d` is simply a regular seal.)
**Output Description**
According to the following rules regarding how the seals can move, output a list of instructions for the seals on how they should move to get the daddy seal to the radio transmitter.
1. **Rule:** All seals can move up (`U`), down (`D`), left (`L`), and right (`R`). They cannot slide diagonally.
2. **Rule:** Upon moving, a seal will continue to move in the same direction until it collides with another seal or falls into the sea.
1. If a seal collides with another seal, it will stop moving. The seal it collided with will **not** move.
2. If a seal falls into the sea, it will drown and disappear from the map. That is, it does not act as a collider for other seals and it cannot be moved again.
3. **Rule:** Two seals cannot move at the same time, neither can a seal be moved while another one is still moving. The next seal can only be moved once the previous seal has stopped moving.
4. **Rule:** There is no restriction regarding moving a seal multiple times, or the number of seals that drown.
5. **Rule:** A correct solution will have the daddy seal *end* at the radio transmitter. The daddy seal cannot simply *pass* the transmitter while sliding.
The output will consist of several lines, each in the form
```
A,B
```
Where `A` is the seal to move (`D` for the daddy seal, `a`...`z` for others), and `B` is the direction to move the seal (either `U`, `D`, `L`, or `R`). Note that you **do not need to find the shortest route.** Any route that gets the daddy seal to the goal is an acceptable output.
**Example Inputs and Outputs**
Input:
```
25,5
.........................
.#######################.
.####D#############*k###.
.#######################.
.........................
```
Output:
```
D,R
```
Input:
```
9,7
.........
.a#####b.
.#####d#.
.##l*###.
.###m#p#.
.#D#.#c#.
.........
```
Output (one possible output out of many):
```
m,R
b,L
D,U
D,R
D,D
D,L
```
Input:
```
26,5
..........................
.###..................###.
.l*##########v#########D#.
.###..................###.
..........................
```
Output (one possible output out of many):
```
v,D
D,L
```
If you have any other questions, please ask in the comments.
[Answer]
# Python 3, 520 bytes
```
R=range
g=[list(input())for i in R(int(input().split(',')[1]))]
f=set(sum(g,[]))-set(".#*")
L=8
def P(p,g):
if len(p)>L:return
for s in f:
c=sum(y.index(s)for y in g if s in y)
if c<1:continue
r,=[n for n in R(len(g))if s in g[n]]
for d in R(4):
m=p+s+",%s\n"%"LURD"[d];G=[y[:]for y in g];o="#";i,j=I,J=r,c
while"#"==o:G[i][j]="#";G[I][J]=s;i,j=I,J;I,J=i+d%2*(d-2),j+(~d%-2&d-1);o=G[I][J]
if"."==o:G[i][j]="#"
if"D"==s:
if"."==o:continue
if"*"==o:print(m);1/0
P(m,G)
while 1:P("",g);L+=4
```
I may do a more detailed explanation later if people want, but basically this runs a [depth-first search with iterative deepening](http://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search) on the state space of possible moves. If a move causes the daddy seal to fall off, it is immediately rejected. If the daddy ends up next to the transmitter, the sequence of moves is printed, and the program divides by zero to force an exit.
I can make the code run significantly faster by adding `if G!=g:` at the beginning of the second-last line, for 8 extra bytes--this rejects moves that don't change anything, such as `k,L` in the first test case.
The runtime varies noticeably from one run to the next, even with the same input--evidently a result of the fact that I pick the next seal to move by iterating over a `set`, which is an unordered type. I timed the second test case at 5 minutes 30 seconds, though it didn't seem that long the first time I ran it. With the optimization mentioned above, it's more like 40 seconds.
[Answer]
# JavaScript (ES6) 322 ~~334 323~~
**Edit2** Added animation in the snippet
**Edit** Bug fix, remember initial posiiton of '\*', so I find it even when a seal slide over it and erase it.
Implemented as a function with the input string as parameter (probably invalid but waiting for a clarification). Output via popup.
The problem with multiline string input in JavaScript is that `prompt` does not manage it well.
As for the algorithm: a BFS, should find an optimal solution.
I keep a queue of game status in variable `l`, the status beeing the character grid `g` and the sequence of moves so far `s`. Besides, there is a set of grids obtained so far in variable `k`, to avoid exploring the same grid again and again.
The main loop is
* dequeue a game status
* try all possibile moves, enqueue the status after each valid move (IIF the resulting grid is not already present)
* if solution found then exit the loop
```
F=s=>{
o=~s.match(/\d+/),g=[...z=s.replace(/.*/,'')];
for(l=[[g,'']],k=[];[g,s]=l.shift(),!g.some((c,p)=>
c>'A'&&[-1,1,o,-o].some((d,j)=>{
t=s+' '+[c,'LRUD'[j]];
for(q=p;(u=g[q+d])<'.';)q+=d;
return(c<'a'&z[q]=='*')||
c>'D'|u>'.'&&!(
f=[...g],u=='.'?0:f[q]=c,f[p]='#',
k[h=f.map(v=>v>'D'?0:v)]||(k[h]=l.push([f,t]))
)
})
););
alert(t)
}
```
Run Snippet to test in FireFox
```
F=s=>{
o=~s.match(/\d+/),g=[...z=s.replace(/.*/,'')];
for(l=[[g,k=[]]];[g,s]=l.shift(),!g.some((c,p)=>
c>'A'&&[-1,1,o,-o].some((d,j)=>{
t=s+' '+[c,'LRUD'[j]];
for(q=p;(u=g[q+d])<'.';)q+=d;
return(c<'a'&z[q]=='*')||
c>'D'|u>'.'&&!(
f=[...g],u=='.'?0:f[q]=c,f[p]='#',
k[h=f.map(v=>v>'D'?0:v)]||(k[h]=l.push([f,t]))
)
})
););
return t
}
$('.T td').each(function(i,td) { $('.R td').eq(i).text(F($(td).text())) });
$(".R").on('click','td',function(){
var i = $(this).index();
var $td = $('.T td').eq(i);
var t = $td.text().trim();
animate($td, $td.text().trim(), $('.R td').eq(i).text().trim());
});
$('#GO').on('click',function() {
var s = T0.value, h=F(s)
console.log(s)
$('#R0').text(h);
animate($('#A'), s,h);
});
function animate($out, s, h){
o=~s.match(/\d+/),g=[...s.replace(/.*/,'')];
fr=[g.join('')];
h.replace(/.,(.)/g, (c,d)=>{
i = g.indexOf(c=c[0]);
d = [-1,1,o,-o]['LRUD'.search(d)]
for(;g[i+d]<'.';i+=d)
{
g[i]='#',z=[...g],g[i+d]=c,z[i+d]='<b>'+c+'</b>', fr.push(z.join(''))
}
if(g[i+d]=='.')
{
g[i]='#', fr.push(g.join(''))
}
})
var fa = ()=>{
var f=fr.shift();
f ? $out.html(f) : (
clearInterval(i),
$out.text(s),
$out.toggleClass('Anim')
)};
$out.toggleClass('Anim');
fa();
var i=setInterval(fa, 500);
}
```
```
td { vertical-align: top; font-family: monospace; white-space: pre; }
textarea { width: 99%; height:10em;}
pre { margin: 0; }
.R td { background: #fdc; padding: 6px 0; }
.R td:hover { background: #ffc }
.T td { background: #ddf}
B { color: red }
.T td.Anim, td.Anim { background: #ffc; }
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing=5>
<tr>
<th colspan=4>Predefined tests</th>
</tr>
<tr class=T>
<td>25,5
.........................
.#######################.
.####D#############*k###.
.#######################.
.........................</td>
<td>9,7
.........
.a#####b.
.#####d#.
.##l*###.
.###m#p#.
.#D#.#c#.
.........</td>
<td>26,5
..........................
.###..................###.
.l*##########v#########D#.
.###..................###.
..........................</td>
<td>8,5
........
.##c###.
.a#*#D#.
.##b###.
........</td>
</tr>
<tr><td colspan=4>Click on solution text to start animation</td>
</tr>
<tr class=R>
<td></td><td></td><td></td><td></td>
</tr>
<tr><th colspan=2>Your test </th></tr>
<tr><td colspan=2><textarea id=T0></textarea></td>
<td colspan=2 id=A></td>
</tr>
<tr>
<td colspan=2>Find solution and animate <button id=GO>go</button></td>
<td colspan=2 id=R0></td>
</tr>
</table>
```
[Answer]
## C++, 628 bytes
Well, this didn't turn out very short:
```
#include <set>
#include <iostream>
using namespace std;struct R{string b,m;bool operator<(R r)const{return b<r.b;}};int w,h,t,j,k,z=1;char c,f;set<R> p,q;int m(R r,int x,int d,char a){for(j=x,c=r.b[x];(f=r.b[j+=d])==35;);if(c-68||f-46){r.b[x]=35;if(f-46)r.b[j-d]=c;r.m+=c;r.m+=44;r.m+=a;r.m+=10;if(c==68&j-d==t){cout<<r.m;z=0;}if(p.count(r)+q.count(r)==0){q.insert(r);}}}int main(){cin>>w>>c>>h>>c;R r;string l;for(;k++<h;){getline(cin,l);r.b+=l;}t=r.b.find(42);r.b[t]=35;q.insert(r);for(;z;){r=*q.begin();q.erase(q.begin());p.insert(r);for(k=0;z&&k<w*h;++k){if(r.b[k]>64){m(r,k,-1,76);m(r,k,1,82);m(r,k,-w,85);m(r,k,w,68);}}}}
```
I chose C++ because I wanted to use the data structures (`set`, `string`), but it's inherently quite verbose. The solution does reasonably well on performance, solving test 2 in a little over 2 seconds on a MacBook Pro, even though it's not optimized for runtime.
Code before starting to eliminate whitespace and some other length reduction:
```
#include <set>
#include <iostream>
using namespace std;
struct R {
string b, m;
bool operator<(R r) const {return b < r.b; }
};
int w, h, t;
set<R> p, q;
bool z = true;
void m(R r, int k, int d, char a) {
int j = k;
char s = r.b[k], f;
for (; (f = r.b[j += d]) == 35;);
if (s - 68 || f - 46) {
r.b[k] = 35;
if (f - 46) {
r.b[j - d] = s;
}
r.m += s;
r.m += 44;
r.m += a;
r.m += 10;
if (s == 68 && j - d == t) {
cout << r.m;
z = false;
}
if (p.count(r) + q.count(r) == 0) {
q.insert(r);
}
}
}
int main() {
char c;
cin >> w >> c >> h >> c;
string b, l;
int k;
for (k = 0; k < h; ++k) {
getline(cin, l);
b += l;
}
t = b.find(42);
b[t] = 35;
R r;
r.b = b;
q.insert(r);
for ( ; z; ) {
r = *q.begin();
q.erase(q.begin());
p.insert(r);
for (k = 0; z && k < w * h; ++k) {
c = r.b[k];
if (c > 64) {
m(r, k, -1, 76);
m(r, k, 1, 82);
m(r, k, -w, 85);
m(r, k, w, 68);
}
}
}
return 0;
}
```
The core idea behind the algorithm is that two sets are maintained:
* `q` is the set of configurations that are pending processing.
* `p` is the set of configurations that have been processed.
The algorithm starts with the initial configuration in `q`. In every step, a configuration is popped from `q`, added to `p`, all possible seal movements are generated, and the resulting new configurations inserted into `q`.
Test run:
```
bash-3.2$ ./a.out <test1
D,R
bash-3.2$ time ./a.out <test2
p,U
c,U
p,R
c,L
m,L
b,L
a,L
D,U
b,L
D,R
D,D
D,L
real 0m2.267s
user 0m2.262s
sys 0m0.003s
bash-3.2$ ./a.out <test3
v,U
D,L
bash-3.2$
```
] |
[Question]
[
Well the [community](https://codegolf.stackexchange.com/users/-1/community?tab=activity&sort=revisions) is just a bot. But what if it would have been a person?
Your task is to find what community's reputation might have been if it would have been given reputation for the edits it makes.(simply 2\*edits)
This should work for any site, but we would consider PP&CG for this question.
Use any language, even data.stackexchange would work.
As it is code golf, smallest code wins as much reputation I gain+15(via bounty, I will leave 101 for myself :P ).
EDIT: consider all kind of edits that increase reputation.
[Answer]
I know URL shorteners are cheaty but since everyone else is using them I probably should.
# Bash, with `bc` and URL shortener: ~~67 62 60 58~~ 54
```
bc<<<`wget x.co/4Ccg3 -qO-|grep -oP "(?<='>)[0-9]+"`*2
```
Downloads the relevant page to STDOUT, then searches for `'>` followed by a sequence of digits - it misuses the fact that in the page's source code, single quotes are only rarely used; in fact the sequence `'>` occurs twice, and only once followed by a number, which is the number of edits. Using the Perl-style lookbehind, the `'>` isn't actually included in the match.
The `-o` option makes `grep` output only the matched string rather than the entire line containing it (there is a `h1` on the same line and I don't want that).
The resulting number of edits is concatenated with `*2` and sent to `bc`.
**@11684 pointed out that you start out with 1 reputation, but the asker clearly forgot that so it's not mentioned in the question (it would break existing answers if it was). If you want to add that in just put in `+1` at the end of the code, adding 2 chars.**
# [SHELF](https://github.com/professorfish/bash-shelf), 36 - doesn't count as the language was created after the question
```
, `W x.co/4Ccg3|t "(?<='>)[0-9]+"`*2
```
SHELF is a golfed version of Bash, like PYG is for Python.
[Answer]
# Python (~~191~~ ~~181~~ ~~170~~ ~~126~~ 117)
@Henrik: Good idea to use an url shortener. Don't mind if I just borrow yours, do you? Just to kick it off, this will probably get beaten very, very fast ;)
```
i=__import__("urllib2").urlopen("http://x.co/4Ccg3").read();j=i[i.index("<span class='count")+20:];print 2*int(j[:2])
```
Searches for the `<span class='count'>` that contains the amount of reputation the bot has.
[Answer]
# JavaScript (EcmaScript 6 + jQuery) - 80 Characters
```
$.get('/users/-1/?tab=activity&sort=revisions',r=>alert($('.count',r).text()*2))
```
Run it in the JavaScript console on any StackExchange page (although ECMAScript 6 arrow functions are only supported on FireFox at the moment so it will have do be done in that browser until the others catch up) and will get Community's reputation on that domain. So running it on `http://codegolf.stackexchange.com` will get the Code Golf Community's reputation (currently 118) and running it on `http://academia.stackexchange.com/` would get the reputation from that site (currently 162).
Which hopefully answers the
>
> This should work for any site
>
>
>
bit of the question.
[Answer]
## JavaScript (with jQuery) - 141
```
$.get('http://codegolf.stackexchange.com/users/-1/?tab=activity&sort=revisions',function(o){alert($('<a>').html(o).find('.count').html()*2)})
```
**EDIT** : only works if executed from any StackExchange page... or if [same origin policy is disabed](https://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome/6083677#6083677).
If same origin policy is disabled, can be shorten to 96 chars :
```
$.get('http://tinyurl.com/pfmsq8w',function(o){alert($('<a>').html(o).find('.count').html()*2)})
```
[Answer]
***I've included the 1 reputation that you start with!***
# jQuery, 76
```
$a=$("body");$a.load("//x.co/4Ccg3 .count",function(){$a.text($a.text()*2+1)
```
on any page with jQuery and requested by http.
# jQuery, only works on the relevant page - 23
```
$(".count").text()*2+1;
```
The page it runs on is <http://goo.gl/JOqzpF>.
[Answer]
# StackExchange Data 78 chars
[Click here to run the query](http://data.stackexchange.com/codegolf/query/edit/199372)
```
SELECT COUNT(*)*2FROM PostHistory WHERE UserId=-1AND PostHistoryTypeId IN(4,5)
```
[Answer]
# PowerShell (143)
My first ever PowerShell script! Counts the number of revisions and times it by two (very inspired by @Synthetica's Python answer).
```
$s=(New-Object Net.WebClient).DownloadString("http://tinyurl.com/pfmsq8w");(0+($s.Substring($s.IndexOf("s='cou")+10,8) -replace "[^\d]",""))*2
```
] |
[Question]
[
Inspired by [this question from electronics.SE](https://electronics.stackexchange.com/questions/77227/is-simple-voice-synthesis-just-digits-0-9-possible-with-cortex-m0-with-4kb-fl), here's a challenge for you:
**Write a program or subroutine that takes in a sequence of decimal digits (0 to 9) and speaks them aloud, *without* using an existing speech synthesis tool.**
### Input:
You may ask for the input digits to be provided in any reasonable format, e.g. as a string of ASCII digits, an array of integers, a BCD-encoded number, etc. If your solution is an executable program, you may take the input as a command line parameter, read it from standard input, or obtain it in any other reasonable manner.
Your program *must* be able to speak **at least eight digits** per invocation. You *may* assume that the first digit is not zero, unless it is the only digit.
### Output:
Your program may either speak the numbers directly using an audio device, or it may output a playable sound file. The output file, if any, may be in any standard audio format, or it may consist of raw sample data. If you output raw sample data, please note the appropriate parameters for playback (sample rate, bits per sample, endianness, signed/unsigned, # of channels). Formats supported by [aplay](http://linux.die.net/man/1/aplay) are preferred.
You are free to decide the details on how the numbers will be spoken, but your output should consist of English language digits spoken in a manner **understandable to a typical English speaker**, and it should be clear enough for the listener to be able to accurately transcribe a spoken eight-digit random number. No, just beeping *n* times doesn't count. Don't forget to include pauses between the digits.
### Scoring:
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") scoring rules apply: Your score is the length of your code in bytes or, if your code is written in Unicode text, in Unicode characters. Lowest score wins. Any language goes.
As the original question on electronics.SE was about embedded programming, I felt it would be appropriate to toss a bone to authors using low-level languages: if your solution is written in a compiled language, you may choose to count the length of the **compiled executable file** in bytes as your score. (Yes, precompiled bytecode, such as a Java `.class` file, is OK too.) If you choose to make use of this option, please include a copy of the compiled executable in your answer (e.g. as a hex dump) along with your source code and the compiler version and options you used to generate it.
An **honorable mention**, along with a +50 rep bounty, will be granted to the first answer that also meets the criteria of the [original question](https://electronics.stackexchange.com/questions/77227/is-simple-voice-synthesis-just-digits-0-9-possible-with-cortex-m0-with-4kb-fl), i.e. is capable of running on an embedded MCU with 4 kb of flash and 1 kb of SRAM.
### Restrictions:
You may not make use of any **files or network resources** that are not part of your chosen language's standard runtime environment, unless you count the length of said files or resources as part of your score. (This is to disallow e.g. loading audio samples from the web.)
You may also not use any pre-existing **speech synthesis tools or libraries** or compilations of audio data (unless you also count their size as part of your score), *even if* they're included in your chosen language's standard runtime environment.
[Answer]
# ruby - 3710 = 90 characters code + 3620 bytes data
```
require'zlib'
$><<$*[0].chars.map{|x|Zlib::Inflate.inflate File.open(x).read}.join(?0*5e3)
```
input: a single command line argument, the number to read
output: raw sound data, PCM 8bit/8kHz
This can read any input string, as long as
* it only contains characters that are valid file names. for only four chars, you can enlarge that set to all characters.
* you have the neccessary files.
* why oh you space dee oh en apostrophe tee space em i en dee space tee aitch i es period
`5e3` encodes the pause between two words. Here, 5ksamples ~= 0.6s. Tweak as desired.
Now, the tricky part is to get the sample files in 4K and yet be able to decompress them easily and in sufficient quality. Here is how I got them:
* Take a Text-to-speech engine able to produce sound files. [Wikipedia has one](http://en.wikipedia.org/wiki/Wikipedia:Pediaphon).
* Feed it a text containing all digits, ideally close together. I used <http://en.wikipedia.org/wiki/Base_13>
* Downsample.
* Cut out each part in a [sound editor](http://audacity.sourceforge.net/).
* Save as a raw file.
* Decimate each sample (discard low-order bits).
* Deflate.
Now, one has to choose a sample rate and decimation amount. Too much, and the sound won't be understandable. Too little, and you don't fit. I have settled for 8kHz/3b. There they are: <https://github.com/honnza/drops/raw/master/digits.zip>
* 8KHz \* 4b/sample and higher quality - too big
* 8KHz \* 3b/sample - low quality, but it fits into 4K
* 8KHz \* 2b/sample - kch kchhhhhhhhh [not understandable]
* 2KHz \* 8b/sample - too big
* 2KHz \* 3b/sample - kch kchhhhhhhhh
* 1KHz \* 8b/sample - kch kchhhhhhhhh
Here's the decimation script:
```
require'zlib'
Dir.glob "*.raw" do |fname|
File.open fname[/\d/], "wb" do |out|
File.open fname do |input|
bytes = input.bytes.to_a
bytes.map! {|x|x&0xE0}
dfl = Zlib::Deflate.deflate(bytes.pack("C*"),9)
dfl.each_byte do |byte|
out.print byte.chr
end
puts "done #{fname}: #{dfl.size}"
end
end
end
```
As for the original challenge: there are 476 bytes of space for code and the file table. This might be slightly too much depending on how tiny we can get with a DEFLATE library. If neccessary, we can cut a few corners here and there by cropping the audio samples a bit more aggresively. `[fo:r]` or `[o:]` doesn't really matter but it saves bytes. I have been somewhat benevolent when cropping the numbers. Also, a different decimation scheme or sacrificing some decimation for downsampling might help - I'll toy with these later. Also, dropping the DEFLATE headers might save a tiny amount of space.
Concatenating sound samples is quite easy, but 4K is a little cramped. If you are not bound by 4k space, I suggest less decimation. 4 bits per sample actually fares quite well and is only slightly bigger.
] |
[Question]
[
Not to be confused with [Password Bishop Goodness](https://codegolf.stackexchange.com/questions/179841/password-bishop-goodness)!
Given a string, answer (truthy/falsy or two consistent values) if it constitutes a password which is *strong against bishops*.
A password is *strong against bishops* if it is a string consisting of alternating letters (in `a-h`) and digits (in `1-8`) such that each pair of characters can be interpreted as a square on a chessboard, and if you place a white pawn on each square named in the password, then there is no way for a white bishop to travel, in any number of consecutive moves, from any square in the first (`1`) row to any square in the last (`8`) row.
## Examples
### Passwords strong against bishops
* `a1b1c1d1e1f1g1h1`
* `a8b8c8d8e8f8g8h8`
* `a1b2c3d4d5f5f4g3g4h2b5`
* `h4g4f4e4c4b4a4c3e3`
* `a1b1c1d1e1f1g1a8b8c8d8e8f8g8`
* `b4b5d4d5f4f5g3h5`
>
> For example, `a1b1c1d1e1f1g1a8b8c8d8e8f8g8` corresponds to the position [](https://lichess.org/editor/PPPPPPP1/8/8/8/8/8/8/PPPPPPP1_w_-_-) and `b4b5d4d5f4f5g3h5` corresponds to the position [](https://lichess.org/editor/8/8/8/1p1p1p1p/1p1p1p2/6p1/8/8_w_-_-)
>
>
>
### Passwords weak against bishops
* `a4c4e4g4g5d6f6e3d2b2` (well-formed but not strong — thanks Jo King for this example!)
* `b1c1d1e1f1g1h1a8b8c8d8e8f8g8` (well-formed but not strong)
* `h4g4f4e4c4b4a4c3` (well-formed but not strong)
* `d4` (well-formed but not strong)
* `b4b5d4d5f4f5g2h5` (well-formed but not strong)
* `correct horse battery staple` (ill-formed)
* `1a1b1c1d1e1f1g8a8b8c8d8e8f8g` (ill-formed)
* `a` (ill-formed)
* `aa` (ill-formed)
[Answer]
## Ruby, ~~115~~ ~~182~~ 163 bytes
```
->s{z=('00'..'99').map{|x|x=~/[09]/||s[(x[1].ord+48).chr+x[0]]};(11..18).map &g=->x{z[x]||[x-11,x-9,x+z[x]=9,x+11].map(&g)};s=~/^([a-h][1-8])*$/&&(z[81,9]-[9])[8]}
```
[Try it online!](https://tio.run/##XZHdbqMwEIXv/RRWuwqwCU4GTGVU0RexvJL/HakNCKhEA/TVs6Z3dK5mjuZ8Z6TpP9XXwzWP/G2Y702aXC4JIUldJxn5kN28TMvUfJ/5pRbnZRl4OnEQpO3NkbKM6NAfJ34RYn1NAQgB9uPCB9/kb9N855NYFj7lAKcpr0/TcVOarYFIiZvpwWfr6xAT/qVc5kFwyJnI/v45Hw7pnTM41SLntcg4E@sjkaBAgwELDjwEQJIppplhljnmWWAobhS6NNRUrnLUl56GQlUoUE8dtVRTRSXVpS3RnrUHIUVV9QOhrvJlqFA0RbunvjIv7sWWplAF2h/zC/E7Ehm6xxYRq9u@t3rEoe0Hi5UcR9t/4WGU3btFsDuR7fhIIikT8n692YFYqQM2LV62cUE4VtdfbyN@ep4d38T4qfajE@R6G7qYt@LneZPXJ2Rv5vEf)
Returns `1` for strong and `nil` for weak. (The +67 bytes was for taking into account "backtracking.")
```
->s{
z= # this is the board
('00'..'99').map{|x| # coordinates are described as y*10 + x
x=~/[09]/|| # truthy if out of bounds...
s[(x[1].ord+48).chr+x[0]] # ...or impassable
} # now only the passable squares are falsey
(11..18).map # for each x position at y=1,
&g=->x{ # call helper function on that square
z[x]|| # if the square is passable (i.e. falsey),
[x-11,x-9,x+z[x]=9,x+11] # mark it impassable by setting to 9 (truthy)
.map(&g) # call helper recursively for each neighbor
}
s=~/^([a-h][1-8])*$/ # make sure the input was valid,
&&(z[81,9]-[9])[8] # and check that the last row was never reached
}
```
A few tricks that were used:
* Instead of the numerical range `0..99`, we use the *string* range `'00'..'99'` so that the number is automatically left-padded to 2 digits and stringified. This makes out of bounds checking very short -- match with regex `/[09]/`.
* Inside the helper function, while building the list of new coordinates `[x-11, x-9, x+9, x+11]`, we simultaneously assign `z[x]` to `9` in the process, which happens to be a truthy value (marking the square visited).
* In the last line, we want to check that the array `z[81,9]` does not contain `9`. We do this by removing all instances of `9` (`z[81,9]-[9]`), then asking for the 9th element of the resulting array (`[8]`). Since we know the array originally had 9 elements, if any were removed, we'll get `nil`, whereas if they all remained, we'll get the last element of the array (which happens to always be `1`).
[Answer]
# [Python 2](https://docs.python.org/2/), 330 318 313 309 370 bytes
```
import numpy as n
b=n.ones([8,8])
q=r=1
s=input()
l=len(s)
def g(x,y=0,p=0):
if b[y,x]and p<32:
if y<7:
if x<7:
g(x+1,y+1,p+1)
if y:g(x+1,y-1,p+1)
if x:
g(x-1,y+1,p+1)
if y:g(x-1,y-1,p+1)
else:global q;q=0
for i in range(l/2):
x=ord(s[2*i])-97;y=ord(s[2*i+1])-49
if y>8or y<0 or l%2or x>8or x<0:r=0
if r:b[7-y,x]=0
map(g,range(8))
print q&r
```
[Try it online!](https://tio.run/##dZHfbpswFMav66ewInWBBTZsTOPSeC8S5cLGf0Aihhiq4qfPbFqto9MuDEe/c77vO4bRz@1g8b0ZpIIM7na7e3cdBzdD@3odPeQTtEAw@2OwakrONKOXFNyYYwhMrLPj65ykoGe9ssmUAqk0NMmSeVZkIyvSGjx0Goqzz5YLtxKOpxIHFqE/HWMVy@WjfAjSA8p8OOMBpSuKk/UHzz95VP3R5P/R5BuN6idVm34QvIe3lxsrgB4c7GBnoePWqKT/iePCCxucTKYz/t5d0vz5@OI/wQEFRJ7XW/lfNOj9qYDh1T/i8FxWtJyK2gX7OORqcT7m8foBXPmYmOw9jKYpGF1nZ3j75u7hswPw1na9gqhWi2pg/B/3PUcCNUgihTQyqEV7sOdU0IZKqqimhrY0IiRwU0oiK11pYkpDWiyq0GiJIZoo0hBBOGlKVb5P/@W5tQttQUS1WhFdmbKNNkEaTAwxlXzST6qUWOA4uVntH6Ov4QFJ8jUArwHN4JxqZtgOblJQ8HlWzsNp5mOvQhttVqabpLhePHz/Gw)
[Try practical version online!](https://tio.run/##dZHfbpswFMav66ewInWBBTYMpnFpvBeJcmHjPyAR4xiq4qfPbFqto9MuDEe/c77vOwbr52405b0dhYQU7na7e3@1o5uheb1aD9kEDeDU/BiNnJIzycglBTfqKAIT7Y19nZMUDHSQJplSIKSCOlkyT4vM0iJtwEOvID/7bLkwI6A9oSKwCP3pGKtYLh/lQ5AeUObDsQeUrihONh88/@RR9UeT/0eTbzRymGSjh5GzAd5ebrQAanSwh72Bjhktk@FnGRde6OhEMp3L7/0lzZ@PL/4THFBA@Hm9lf9Fgt6fChhew2MZnsuKllPRuGAfh1zDz8c8Xj@AK7OJzt7DSJoC63ozw9s3dw@fHYC3rh8kRI1cZAvj/7jvGeKoRQJJpJBGHdqDPSOctEQQSRTRpCMRIV62lcCiVrXCutK4K3kdGh3WWGGJW8wxw20lq/fpvzy3dqHNMa9XK6xqXXXRJkiDica6Fk/qSVai5GWc3Kz2j9HX8IAE/hpQrgHt6JxsZ9iNbpKQs3mWzsNpZnaQoY02K5NNUlwvHrb/DQ) (original can take 4^32 operations to check completely, I suggest using this one - same number of bytes)
Not a super short solution - I couldn't figure out how to make a lambda function version of g shorter than g itself.
-4 bytes thanks to Quuxplusone
+61 bytes accounting for backtracking (thanks for pointing that out Jo King and for the golfing tips)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~490~~ ~~476~~ 474
```
def f(p):
a=[set(ord(c)-33 for c in s)for s in"* )+ *, +- ,. -/ .0 / \"2 !#13 \"$24 #%35 $&46 %'57 &(68 '7 *: )+9; *,:< +-;= ,.<> -/=? .0>@ /? 2B 13AC 24BD 35CE 46DF 57EG 68FH 7G :J 9;IK :<JL ;=KM <>LN =?MO >@NP ?O BR ACQS BDRT CESU DFTV EGUW FHVX GW JZ IKY[ JLZ\\ KM[] LN\\^ MO]_ NP^` O_ R QS RT SU TV UW VX W".split()];x=set((ord(p[i+1])-49)*8+ord(p[i])-97 for i in range(0,len(p),2))
r=set(range(8))-x
for i in range(99):r=set().union(*[a[c]for c in r])-x
return all(c<56 for c in r)
```
[Try it online!](https://tio.run/##dVHZUqNAFH33K864Adm0oSGEbJpVszquMxJUlgZSpkgKsEq/PtPGsQxW@da37tnu6dVbGi4jeb32mA9fXEnGDl7rCUvFZeyJK3NuSUWqV/J67v@cJ5bkL2PMMY8Q21HAxOPCgkWcWpAlqRpvyB8LXZKKrzv4hJvEylUqxgdCKr1E82Uk5kzz0@1ZKirKBv38Lp5sfBL@3M1ByiNXQL6IQgnFI5SOcYTZroxfe0Thj32ZYu9AUbF/SDUcCGoZh6KmQygjZ3BypcrpRo0LVOtcotbgIvUml2mc4KgJuQWinLYh01YHitrugmqdHtRytw9N752h3IcxQKV6PoRRG4xQrQ/HqDVGE9Sb4ykaJ5MLNKdoXeK0/fsKrc7lNdrdqxt0ete36PZv7tA7u/2D/h0G9zgf/jUxGN3PZhiOTQujyWz2gPHUesTk4uEJ00dcgstwES7BBTidk@92S8lqMefdWaZrvZfjbj7B2rQcs/QljmAvFqJbUzV87aX1Kp5HKYTr@IUlhrDzMfqiYBOHuMQjjPgkICERpK2d7uiu7ulM9/VAD/XMjjiyq3jUU33Vp4ES0FB21G1ESAPqU0Zd6lCbugpTvvG3fLNO2ziHOurGhfpqoIRfDkLPXiTZWxyu5/MbAtXTfI0pnswzZjJlb/3Z9Xv27Z1Hf8wnhxk3dxnHzE0RLuOEwbHTlMVvSFJ7tWDbOJIpQ8/EynSWGfi0/gc)
This works by "flood-fill." First we create a list `a` of which squares are adjacent to which other squares, bishopwise. Then we create a set `x` of exclusions (based on the password). Then we initialize a set `r` of reachable squares, which starts out as just the first row (minus any exclusions), and repeatedly "flood" outward from there, 99 times, which should be more than enough. Finally, we test to see if any of the squares in the last row ended up in our reachable set. If so, we have a weak password! If not, we have a strong password.
Disadvantage, perhaps disqualifying (I don't know the usual rule here): If the password is ill-formed (such as "correct horse battery staple"), then we throw an exception instead of returning `False`. But we do always return `True` iff the password is strong!
Minus 16 bytes thanks to Jo King. We inline `a` in the one place it's used, and constant-fold some math.
```
def f(p):
x=set(ord(p[i])-489+8*ord(p[i+1])for i in range(0,len(p),2));r=set(range(8))-x
for i in[1]*99:r=set().union(*[[set(ord(k)-33for k in s)for s in"* )+ *, +- ,. -/ .0 / \"2 !#13 \"$24 #%35 $&46 %'57 &(68 '7 *: )+9; *,:< +-;= ,.<> -/=? .0>@ /? 2B 13AC 24BD 35CE 46DF 57EG 68FH 7G :J 9;IK :<JL ;=KM <>LN =?MO >@NP ?O BR ACQS BDRT CESU DFTV EGUW FHVX GW JZ IKY[ JLZ\\ KM[] LN\\^ MO]_ NP^` O_ R QS RT SU TV UW VX W".split()][c]for c in r])-x
return all(c<56for c in r)
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 285 bytes
```
import StdEnv,Data.List
$_[_]=1<0
$a[x,y:l]=case[[u,v]\\u<-[0..7],v<-[0..7]|u==toInt x-97&&v==toInt y-49]of[p]= $[p:a]l;_=1<0
$a _=all(\[_,y]=y<7)(iter 64(nub o\e=e++[k\\[u,v]<-e,p<-[-1,1],q<-[-1,1],k<-[[abs(u+p),abs(v+q)]]|all((<>)k)a&&all((>)8)k])(difference[[e,0]\\e<-[0..7]]a))
```
#
```
$[]
```
[Try it online!](https://tio.run/##PZBNb4JAFEX3/goWBpkwGCaxpVrGlV2YuGjicnghTxgsYfgQBiKJv71TtLW7czf3vvMSJbEyZZ32Slol5pXJy6ZutXXU6Uc10B1qXB7yTs/msYiBs9CfzVFc6bhRwBPspBA9HSCK@tAT/nIZAB2edOs51/W@0tbVWwe2PTzj6K3WUGeiAW7NRbNBUO/xX7cVc1TKiURMR@BjGBAn17K1XldO1Z@sOpJcuq4oougxHHqSNtOgxygDevmnYiKBp87p3YbQOwzuhQDc7uVOuCUFQdt@hC15IwUQJ82zTLaySiYnSf3JST5NAAkxR43TY@4Xg1ggO7GEpUyyjJ3ZAsx3kik8d8bbH8xurLDMk9/wqVBndVsa78u8@H75Aw "Clean – Try It Online")
`$[]` is `$ :: [[Int]] [Char] -> Bool` composed with the first argument, giving `\ [Char] -> Bool`.
The function works by consuming the string two characters at a time, immediately returning false if the string is in an invalid format as soon as it sees the invalid part. Once the string has been processed, it places a bishop on every empty square on one side of the board and moves them in every way possible 64 times and checks if any of the end positions is in the target row.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~339~~ ~~316~~ ~~358~~ ~~353~~ 345 bytes
-23 bytes thanks to @Doorknob.
+42 bytes accounting for backtracking.
```
p[m_]:=StringPartition[#,m]&;l=Range@8;f[n_]:=Check[w=(8#2+#1-8)&@@@({LetterNumber@#,FromDigits@#2}&@@@(p@1/@p[UpTo@2]@n));g=Graph[Sort/@UndirectedEdge@@@Position[Outer[EuclideanDistance@##&,#,#,1],N@Sqrt@2]&@GraphEmbedding@GridGraph@{8,8}//Union]~VertexDelete~w;c:=#~Complement~w&;m=0;Do[m+=Length@FindPath[g,i,j],{i,c@l},{j,c[l+56]}];m==0,0>1]
```
[Try it online!](https://tio.run/##dVLRatswFH3vV5gYspa6pHLkIho8BE07tpUuW9btwZghS9eyWltyZYVshOTXMyXbWFxa9KSrc8@59@g0zFXQMKc4227brPmRX6ZzZ5WWM2adcsroLIyafDip0y9MS6BkUmZ6B7uqgD9my/SYhPFpiM7IyZBSery6BefA3i2aAiwNoxtrmqmSynU0jNd7SEvRiLbZffvV0Din@uRkItN3lrVVNjfWjei9FsoCdyCuhZekdGa6P7N8Wnju7HrBayWA6anqHNMcaBgOo9AflEd3dP5knSce0j3ntR9ECL@RvyqxL9EVich6NLrXnjPffAPr4OcUanCwWU74ZRpurkzT1tCAdpvlcNKk55OpyZrT9Ba0dBW9UVrMvHeZjFT0kEcrFXFar6PVQ8Sz@jS5yNe570rPo/O3KN8ezbylLht4a42Wl4P8b6GkA4YKxJFAgEokUYV6b6QgnAgCpCSSVORZX8zHAoukTEosxxJXcZEcIioscYkBc1xghvkYxq/r9pUOcQUukr0KLhM5rnYK/7b5Duyxt0t/k9c5n092@Cbwq@pxT/2DCT76X33TBV0LXLE6WPp5gs7Ui11U@iZ7KfCiMhEX5QWMRVzEB1Tv6/rsxtgGRK@LG7tLYVAZ20FQsF2ufwU@cT4Zg3w0@rxQ4P7DUc9S0ls/eAHPXqodFI@2vwE "Wolfram Language (Mathematica) – Try It Online")
I rewrote most of this to account for backtracking, I think there may be an easier way to define the graph `g`, Mathematica has `GraphData[{"bishop",{8,8}}]` which is the graph of all moves a bishop can make on a chessboard ([Bishop Graph](http://mathworld.wolfram.com/BishopGraph.html)), but this graph includes connections further than nearest diagonal neighbor. If anyone knows a shorter way to do that let me know. Credit for the graph construction goes to [this MathematicaSE answer](https://mathematica.stackexchange.com/a/110850/53487).
Returns `True` for strong passwords, `False` for weak/ill-formed passwords. Note that for most of the ill-formed passwords it will produce a bunch of error messages and then return `False`. If this is not in line with the rules then they can be suppressed by changing `f[n_]:=...` to `f[n_]:=Quiet@...` costing 6 bytes.
Ungolfed:
```
p[m_] := StringPartition[#, m] &;
f[n_] :=
Check[
w = (8 #2 + #1 -
8) & @@@ ({LetterNumber@#, FromDigits@#2} & @@@ (p@1 /@
p[UpTo@2]@n));
r = GridGraph[{8, 8}];
g = Graph[Sort /@ UndirectedEdge @@@
Position[Outer[EuclideanDistance@## &, #, #, 1],N@Sqrt@2] &@
GraphEmbedding@r // Union]~VertexDelete~w;
s = Complement[{1,2,3,4,5,6,7,8},w];
e = Complement[{57,58,59,60,61,62,63,64},w];
m = 0;
Do[m += Length@FindPath[g, i, j], {i, s}, {j, e}];
If[m == 0,True,False]
, False]
```
Breakdown:
```
p[m_]:=StringPartition[#,m]&
```
Takes a string argument and splits it into a list of strings each of length `m`.
```
Check[...,False]
```
Returns `False` if any error messages are produced, which is how we catch the ill-formed strings (i.e. assume they are well-formed, inevitably producing an error down the line).
```
(8*#2 + #1 - 8) & @@@ ({LetterNumber@#, FromDigits@#2} & @@@ (p@1 /@
p[UpTo@2]@n));
```
Takes the string of pawn positions and splits it such that `"a2h5b"` becomes `{{"a","2"},{"h","5"},{"b"}}`, then `LetterNumber` will convert the letter to a number (`a -> 1`, etc) and `FromDigits` converts the numeral into an integer. If the string is not well formed, this step will produce an error which will be caught by `Check`, returning `False`. These two numbers are then converted to an integer corresponding to a square on the board.
```
r = GridGraph[{8, 8}];
g = Graph[
Sort /@ UndirectedEdge @@@
Position[Outer[EuclideanDistance@## &, #, #, 1],
N@Sqrt@2] &@GraphEmbedding@r // Union]~VertexDelete~w;
```
Constructs the graph of all nearest-neighbor diagonal edges with the pawn positions deleted.
```
s = Complement[{1,2,3,4,5,6,7,8},w];
e = Complement[{57,58,59,60,61,62,63,64},w];
```
These are lists of unoccupied starting and ending vertices respectively
```
m=0
Do[m += Length@FindPath[g, i, j], {i, s}, {j, e}];
If[m == 0,True,False]
```
Loops over the starting and ending vertices, for each pair `FindPath` will be a list of paths between them. If there are no paths between them, it will be an empty list, so `Length@` returns `0`. If there are no paths at all, then `m` will be zero, and we return `True`, otherwise return `False`.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 192 bytes
```
import re
s=p=input()
t={0,1}
while s!=t:s=t;t=t|{i for x in s for i in[x-9,x-7,x+7,x+9]if-9<i<72and-2<x%8-i%8<2and"%c%d"%(97+i%8,i/8)not in p}
print(max(s)<64and""==re.sub("[a-h][1-8]","",p))
```
[Try it online!](https://tio.run/##ZVLbjtsgEH3nK6ZIUWwtbouNE5Ka/kiUB262kRLbAlb1Ks23pzbbSs0uEmg4M5w5w8z0FvtxqPjkH3o0FgRgjB/uOo0@grcoiEm4YXqNWY6iuH0n9I5@9e5iIXwR8RhE/BFF/H1z0I4eZnADhGS6xTzNxYHMxZ7ML@s@nF1bHBrX7Es5mKJs5g0v3IY36xVv9GY5ssP@ZYGI@8bzYYwr33RHk3dDzK5yzkLe7NgajoXw9mt4VRk@yaI/n2jBz5hgTKY8fyxFIBRtiGGp6IS2kiqqqaGWtrSjPd2SBeOKa2645S3veM8TRlWpK8NM3dYt66qO9aWqV0/POtYyyzRTTDJd2epv/H@8z4yrXzFVJzbW1l3VJ6bl9cLTsa42u3ZnK1OqMsU@KfzM9VHBihn2KUv5nkWP3lsdoR99sKBkjNa/QYhyutjVT5@k86d0SWU65PaMEPrXT0g/ekSwrPeWOAJY/ARMwA5GYJwnn52tztZxInDDaXrwEbKLvCojj@Dye47Q4w8 "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
A knight fill is a flood fill using the connectivity of the knight chess piece. Specifically:
```
1 1
1 1
0
1 1
1 1
```
(0 is the initial point, 1s show the connected cells)
## Challenge
Given a 2D grid of spaces and walls, and an initial location, perform a knight-fill on the grid. Shortest code wins.
## Rules
* You may take input and produce output in any format you like (image, string, array, whatever). You may take the initial location as part of the input grid or as a separate coordinate. For the purpose of this explanation, the following format will be used:
```
######## # = wall
######## x = initial location
## x ##
## ##
########
## ##
########
########
```
* Output is a copy of the input grid with the knight-fill result added
* Your fill must not be in the same "colour" as the space or walls, but can be the same as the initial location marker. For example given the image above, a valid output would be:
```
######## # = wall
######## @ = fill (could also have been x)
## @ @##
## @ @##
########
##@ @ ##
########
########
```
* You may assume that the input grid will always contain a 2-cell wall on all sides
* You may assume that the initial location will never be inside a wall
* You may assume that the grid will never be larger than 1000x1000
* Builtins are fine
* Shortest code (in bytes) wins
## Test Cases
In all test cases, `#` denotes a wall, denotes empty space, and `x` denotes the initial location of the fill. `@` denotes the output fill.
```
Input 1:
########
########
## x ##
## ##
########
## ##
########
########
Output 1:
########
########
## @ @##
## @ @##
########
##@ @ ##
########
########
Input 2:
############
############
## ## x##
## ## ##
##### ##
## ##
############
############
Output 2:
############
############
## ##@@@@@##
##@##@@@@@##
#####@@@@@##
## @@@@@@@##
############
############
Input 3:
####################
####################
## ## ##
## ## ##
## ## ######## ##
## ## ######## ##
## ## ## ## ##
## ## ## ## ##
## ## ## ## ##
## ## ## ## ##
## ## ######## ##
## ## ######## ##
## ## ## ##
## ## x## ##
## ############ ##
## ############ ##
## ##
## ##
####################
####################
Output 3:
####################
####################
##@@##@@@@@@@@@@@@##
##@@##@@@@@@@@@@@@##
##@@##@@########@@##
##@@##@@########@@##
##@@##@@## ##@@##
##@@##@@## ##@@##
##@@##@@## ##@@##
##@@##@@## ##@@##
##@@##@@########@@##
##@@##@@########@@##
##@@##@@@@@@@@##@@##
##@@##@@@@@@@@##@@##
##@@############@@##
##@@############@@##
##@@@@@@@@@@@@@@@@##
##@@@@@@@@@@@@@@@@##
####################
####################
Input 4:
################
################
## ###
## x ###
## ####### ###
## ####### ###
## ## ## ###
## ## ## ###
## ## ## ###
## ######## ##
## ######## ##
## ## ##
## ## ##
################
################
Output 4:
################
################
## @ @ ###
## @ @ @ ###
## ####### ###
##@ ####### @###
## ## ## ###
## @## ##@ ###
## ## ## ###
##@ ########@ ##
## ######## ##
## @ @ ## @##
## @ @## ##
################
################
Input 5:
##############
##############
## ###
## ###
## ###
## ### ###
## #x# ###
## ### ###
## ###
## ###
## ###
##############
##############
Output 5:
##############
##############
##@@@@@@@@@###
##@@@@@@@@@###
##@@@@@@@@@###
##@@@###@@@###
##@@@#@#@@@###
##@@@###@@@###
##@@@@@@@@@###
##@@@@@@@@@###
##@@@@@@@@@###
##############
##############
```
[Answer]
# Octave, 73 bytes
```
function a=F(s,a)do;b=a;until(a=~s&imdilate(a,de2bi(")0#0)"-31)))==b;a+=s
```
[Online Demo!](http://rextester.com/CIPLE53966)
\*Some changes applied to run in rextester.
A function that takes a 2d array of 0 & 2 as wall and an array of 0 & 1 as initial location and outputs an array of 0 & 1 & 2.
[Answer]
## JavaScript (ES6), 116 bytes
```
f=(s,l=s.search`
`,t=s.replace(eval(`/(x| )([^]{${l-2}}(....)?|[^]{${l+l}}(..)?)(?!\\1)[x ]/`),'x$2x'))=>s==t?s:f(t)
v=(s,l=s.search`
`)=>!/^(#+)\n\1\n[^]*x[^]*\n\1\n\1$/.test(s)|s.split`
`.some(s=>s.length-l|!/^##.+##$/.test(s))&&`Invalid Input`
```
```
textarea{font-family:monospace}
```
```
<textarea rows=11 cols=33 oninput=o.value=v(this.value)||f(this.value)></textarea><textarea rows=11 cols=33 id=o reaodnly></textarea>
```
Based on my answer to [Detect Failing Castles](https://codegolf.stackexchange.com/q/109015). Fills using `x`s.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~394 387 381 356 352 347 319 313 154~~139 bytes
* **154 bytes after only counting the core function and not the function concerning I/O formatting**
* saved 7 bytes: thanks to @Jacoblaw and @Mr.Xcoder: `except:0`
* saved 28 bytes!!!: Thanks to @ovs: got rid of `try: except` block and several other golf
* Thanks to @Dave for the beautiful test module.
* saved 6 bytes: `g[(a,b)]` as just `g[a,b]`
* **@nore saved 15 bytes!!!**:
```
def x(g,a,b,m):
if(a,b)in g and"!">g[a,b]or m:
g[a,b]="@"
for i in 1,2,-1,-2:
for j in 3-abs(i),abs(i)-3:g=x(g,a+i,b+j,0)
return g
```
[Try it online!](https://tio.run/##lZFNTsMwEIX3PoUxi9rqpCLNLsKIe4QsHNUJzo@TuolahDh7GMegAipFeGHPfH6aeR4PL@Nzb5N53umSnngFCgroREqoKTnGwlhaUWV37IY9VBmSvHe0w3saMskeGSYlUkNRHMMWohiirZcsuPY4iVRx4EZAOKIkreTSbm2gWNdwJwh1epwctpuddMpWmnhP3kUlX99AS22nTjs1am/PV25gaam58mRBLdQBmQWhyQbaXNY@NiWb2H2ddmAl0lBj7@WONyIdnLEjX602dW8s9@ZQCLHI9nDMvfQYpK0QghAlGWPk9se6BOh5fQGnb@BDfRXQsP0HnItcBp@ufgN/PQ5HsDkMrcGxPdmVyOI0J/hhYn4H "Python 3 – Try It Online")
[Answer]
## Mathematica, 117 bytes
The usual story: powerful built-ins but long names…
```
HighlightGraph[g,ConnectedComponents[h=Subgraph[g=KnightTourGraph@@Dimensions@#,Flatten@#~Position~1],#2]~Prepend~h]&
```
[Try it at the Wolfram sandbox!](https://sandbox.open.wolframcloud.com/)
It takes two inputs: first is the input grid as an array of `0`s (for the walls) and `1`s (for spaces), then a single integer for the starting position, found by numbering the grid along the rows from top to bottom, e.g.
```
1 2 3 4 5
6 7 8 9 10
11 12 13 14 ...
```
You can call the function like `HighlightGraph[...~Prepend~h]&[{{0,0,...,0}, {0,0,...,0}, ..., {0,0,...,0}}, 20]`.
The `KnightTourGraph` function constructs a graph with vertices corresponding to positions in the grid and edges corresponding to valid knight moves, then we take the `Subgraph` of the vertices that aren't walls, and find the `ConnectedComponents` of the starting vertex. The output is a graph (shown rotated 90º anticlockwise) with the non-wall vertices highlighted red, and the filled vertices highlighted yellow. For example, for the first test case, the output looks like:
[](https://i.stack.imgur.com/BdSTC.png)
] |
[Question]
[
I was watching the world snooker championship and it got me wondering..
**Snooker scoring**
In the game of snooker there are certain rules that you must adhere too:
* When there are red balls on the table, during your turn you must first pot a red ball
* After potting each red ball, you must pot a colored (not red) ball (the potted colored ball is then replaced onto the table)
* After all the red balls are up (there are 15) you can first choose a colored ball and then you start with the lowest scoring ball and work your way up to the highest scoring ball (these are not replaced)
* Not potting at any point ends your turn.
* Points per ball
+ Red ball: 1 point
+ Yellow ball: 2 points
+ Green ball: 3 points
+ Brown ball: 4 points
+ Blue ball: 5 points
+ Pink ball: 6 points
+ Black ball: 7 points
**The question**
You start with a table with all the balls still on it - **15** red and **one** of each of the other coloured balls - and are given the score of a player in snooker after their first turn, what are the ways that they could have achieved this score?
Input will be a score going from 1 to 147. You can choose if it is an integer or a string. Output should be the different combinations of number of times you potted each ball.
Test cases:
```
Input: 4
Output:
1r 1g
2r 1y
Input: 25
Output:
4r 3b
5r 2b 1br 1y
5r 2b 2g
...
9r 8y
```
Rules:
* You can choose whether you output the possibilities divided by a new line or a separator of some sort (/,;|\ or even others I'm missing)
This is codegolf, so the shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~65~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
7Ḋṗ15Ė€F;ɗ€ƊÄċƇ⁸f€RŻ€IṢ€Q
```
A monadic Link that accepts an integer, "score", from \$[1,147]\$ and yields a list of lists - each being a potential selection of ball scores used in reaching the given score disregarding the order in which they were actually potted.
**[Try it with only six reds](https://tio.run/##y0rNyan8/9/84Y6uhzunmx2Z9qhpjZv1yelA6ljX4ZYj3cfaHzXuSAWSTWuCju4Gkp4Pdy4CUoH/D7e7AzUaAwA "Jelly - Try it online!")** (`15` replaced with `6`; again, fifteen reds would take an age).
### How?
```
7Ḋṗ15Ė€F;ɗ€ƊÄċƇ⁸f€RŻ€IṢ€Q - Link integer, S
7 - seven
Ḋ - dequeue -> coloured ball scores, [2..7]
Ɗ - last three links as a monad - f([2..7]):
15 - fifteen
ṗ - ([2..7]) Cartesian power (15) -> all length 15 words
using the coloured ball scores as letters
€ - for each (such Word):
ɗ - last three links as a dyad - f(Word, [2..7])
e.g. Word = [7,...,7]
Ė€ - enumerate each [[1,7],...,[1,7]]
F - flatten [1,7,...,1,7]
; - concatenate ([2..7]) [1,7,...,1,7,2,3,4,5,6,7]
Ä - cumulative sums, i.e. convert each such legal way to
clear the table to a list of the running score
Ƈ - filter keep those for which this is truthy (non-zero):
⁸ - chain's left argument (S)
ċ - count - i.e. count of S in the running score
R - range (input Score) -> [1..S]
f€ - for each (running score list) filter keep ([1..S])
Ż€ - prefix each with a zero
I - forward differences of each (back to ball scores)
Ṣ€ - sort each
Q - deduplicate
```
---
Original \$66\$ byte entry (\$65\$ really, since the trailing `G` is post-formatting):
```
L⁼30µÐfµ7Ḋ;\¤;€Ṣ€µ€;/
ċ1<⁴µÐfµ;Ç
7Ḋœċ⁴Ḷ¤;/L€;$€;@þ2B¤;/ḟ€0ÇS⁼¥Ðf⁸G
```
Well, it's too slow for TIO now!
...so [here](https://pastebin.com/gZ1NthvR) is a paste of the 2636 ways to make exactly **100** produced offline.
...and **[here](https://tio.run/nexus/jelly#@@/zqHGPodGhrYcnpB3aav5wR5d1zKEl1o@a1jzcuQhIHtoKJKz1uY50G9qYQ1VZH27nAqk8OvlIN5DeBlSv7wNSpgIiHA7vM3ICCT3cMR/INzjcHgy04tBSoNZHjTvc////b24KAA)** is a version that will run there with just **SIX reds** (maximum break = 75)
Prints a grid of numbers each line being a space separated list of ball values (e.g. three red and two green would be on a line reading `1 1 1 3 3`).
---
For a value-grouped version that prints lines of counts along with the full names of the balls, at 102 bytes:
```
ŒrÑ€
Ṫ;ị“¡^³ṗ⁼¬wḌ⁼ø÷OẏK¦ẆP»Ḳ¤$K
L⁼30µÐfµ7Ḋ;\¤;€Ṣ€µ€;/
ċ1<⁴µÐfµ;Ç
7Ḋœċ⁴Ḷ¤;/L€;$€;@þ2B¤;/ḟ€0ÇS⁼¥Ðf⁸Ñ€K€Y
```
---
### How?
```
L⁼30µÐfµ7Ḋ;\¤;€Ṣ€µ€;/ - Link 1, create post-red-ball games: list of all pre-yellow-ball-games
µÐf - filter keep if:
L⁼30 - length equals 30 (games that get on to the yellow)
µ µ€ - for €ach sequence leading to the yellow:
¤ - nilad followed by link(s) as a nilad:
7Ḋ - 7 dequeued = [2,3,4,5,6,7]
;\ - ;\ cumulative reduce with concatenation = [[2],[2,3],[2,3,4],...]
;€ - concatenate the sequence with €ach of those
Ṣ€ - sort each one
;/ - reduce with concatenation (flatten by one)
ċ1<⁴µÐfµ;Ç - Link 2, filter bogus entries created and append post-yellow-ball games: list of pre-yellow-ball games (along with the bogus ones with 16 reds potted)
µÐf - filter keep if:
ċ1 - count ones
⁴ - literal 16
< - less than?
µ - monadic chain separation
Ç - call the last link (1) as a monad
; - concatenate
7Ḋœċ⁴Ḷ¤;/L€;$€;@þ2B¤;/ḟ€0ÇS⁼¥Ðf⁸G - Main link: score
7Ḋ - 7 dequeued = [2,3,4,5,6,7]
¤ - nilad followed by link(s) as a nilad:
⁴ - literal 16
Ḷ - lowered range = [0,1,2,...,15]
œċ - combinations with replacement (every possible colour-ball selection that goes with the red pots)
;/ - reduce with concatenation (flatten by one)
$€ - last two links as a monad for €ach:
L€ - length of €ach (number of coloured balls potted)
; - concatenate
¤ - nilad followed by link(s) as a nilad:
2B - 2 in binary = [1,0]
þ - outer product with:
;@ - concatenation with reversed @rguments
;/ - reduce with concatenation (flatten by one)
ḟ€0 - filter discard zeros from €ach
Ç - call the last link (2) as a monad
Ðf - filter keep:
¥ ⁸ - last two links as a dyad, with score on the right
S⁼ - sum(ball values) is equal to score?
G - format as a grid
- implicit print
```
[Answer]
## JavaScript (ES7), ~~188~~ ~~180~~ 178 bytes
Returns an array of arrays (sorted from red to black).
```
n=>[...Array(17**6)].map((_,x)=>[2,3,4,5,6,p=7].map(v=>(k=a[++j]=x%17|0,x/=17,t+=k,p+=!!(y=y&&k),s-=k*v),y=s=n,a=[j=t=0])&&(s==15|s>=t)&s<16&s<t+2&t<9+p&&(a[0]=s,a)).filter(a=>a)
```
### Commented
**Note**: This version doesn't include the last optimization on `p` (now initialized to 7) which makes the logic harder to understand.
```
n => // given a target score n:
[...Array(17**6)].map((_, x) => // for each x in [0 .. 17^6 - 1]:
[2, 3, 4, 5, 6, 7].map(v => // for each v in [2 .. 7] (yellow to black):
( k = a[++j] = x % 17 | 0, // k = a[j] = number of colored balls of value v
x /= 17, // update x to extract the next value
t += k, // update t = total number of colored balls
p += !!( // update p = number of consecutive colors that were
y = y && k // potted at least once, using y = flag that is zeroed
), // as soon as a color is not potted at all
s -= k * v ), // subtract k * v from the current score s
y = s = n, // initialize y and s
a = [j = t = p = 0] // initialize a, j (pointer in a), t and p
) // at this point, s is the alleged number of red balls
&& // this combination is valid if we have:
(s == 15 | s >= t) & // - 15 red balls or more red balls than colored ones
s < 16 & // - no more than 15 red balls
s < t + 2 & // - at most one more red ball than colored ones
t < 16 + p // - no more than 15 + p colored balls
&& // if valid:
(a[0] = s, a) // update the combination with red balls and return it
).filter(a => a) // end of outer map(): filter out invalid entries
```
### Example output
Below is the output for n = 140:
```
// R Y G Br Bl P Bk
[ [ 15, 1, 1, 1, 1, 8, 9 ],
[ 15, 1, 1, 1, 2, 6, 10 ],
[ 15, 1, 1, 1, 3, 4, 11 ],
[ 15, 1, 1, 2, 1, 5, 11 ],
[ 15, 1, 1, 1, 4, 2, 12 ],
[ 15, 1, 1, 2, 2, 3, 12 ],
[ 15, 1, 2, 1, 1, 4, 12 ],
[ 15, 1, 1, 2, 3, 1, 13 ],
[ 15, 1, 1, 3, 1, 2, 13 ],
[ 15, 1, 2, 1, 2, 2, 13 ],
[ 15, 2, 1, 1, 1, 3, 13 ],
[ 15, 1, 2, 2, 1, 1, 14 ],
[ 15, 2, 1, 1, 2, 1, 14 ],
[ 15, 1, 1, 1, 1, 1, 15 ] ]
```
### Demo
This is too slow for a snippet. You can **[try it here](https://repl.it/HZ2m/3)** instead. (You may get one or two *unresponsive script* alerts, but it should eventually complete.)
] |
[Question]
[
## Introduction
[Dobble/SpotIt](https://boardgamegeek.com/boardgame/63268/spot-it) is a card game, where people have to spot same symbol on pair of cards in shortest time, indicate it and move to next pair. Each card has multiple symbols (8 in normal version), but exactly one is common between each pair of cards.
Example from physical copy of game:
[](https://i.stack.imgur.com/K7yaR.jpg)
## Challenge
Write a program, which given set of symbols (single ascii characters) and number of symbols on single card will produce output listing cards with symbols for each card. There are obviously many equivalent combinations, your program just has to write any of combinations which produces largest amount of cards for given input.
It is a code-golf, so shorter the code, better.
It would be also great if computation will finish before heat death of universe for most complicated case.
## Input
Two arguments to function/stdin (your choice)
* First of them being collection of symbols, something like 'ABCDE" or ['A','B','C','D','E'] - your choice of format, be it string, set, list, stream, or whatever is idiomatic for language of choice. Characters will be given from set of [A-Za-z0-9], no duplicates (so maximum size of input symbol set is 62). They won't be neccesarily ordered in (so you can get "yX4i9A" as well for 6-symbol case).
* Second argument is integer, indicating amount of symbols on single card. It will be <= than size of symbol set.
## Output
Print multiple lines separated by newlines, each one of them containing symbols for single card.
## Examples
```
ABC
2
>>>>
AB
BC
AC
```
Or
```
ABCDEFG
3
>>>>
ABC
BDE
CEF
BFG
AEG
CDG
ADF
```
Or
```
ABCDE
4
>>>>
ABCD
```
## Hints
* Number of cards produced cannot be larger than amount of distinct symbols and in many combinations it will be considerably smaller
* You might want to read up [Some math background](https://math.stackexchange.com/questions/442043/covering-with-most-possible-equal-size-subsets-having-pairwise-singleton-interse) if you need help with math side of the problem
This is my first code golf challenge, so please forgive possible issues with formatting/style - I'll try to correct errors if you point them in comments.
Edit:
There is a very nice youtube video explaining the math behind the Dobble setup [here](https://www.youtube.com/watch?v=VTDKqW_GLkw):
[Answer]
# [Python 2](https://docs.python.org/2/), ~~192~~ 162 bytes
I have an argument that this produces the maximum set of cards for every scenario and it does handle the 3 test cases.
```
from itertools import*
def m(a,s):
C=["".join(x)for x in combinations(a,s)]
while len(C):
print C[0]
C=list(set(A for A in C if len(set(A)&set(C[0]))==1<s))
```
[Try it online!](https://tio.run/##JY7BCsIwDIbve4rgQVoZooIXcYfRxxhD6uw00jajCTifvq7zFMj/f18yfeVF8ZQxTJQEWBLGZx4TBUBxSYg8wz/cVQ83QlC2Zn2pwDTdZrN/E0Y165ESzIARBgp3jFaQIq/NvoLPC70D76IyBYRpuSFgusOSLRqPLIqdqBaKpi0aAziuxLrX2zIKoHXTHK@sdQ7q/@ve8oB48/RxabDsusvp2NdnnX8 "Python 2 – Try It Online")
### Algorithm
Given an alphabet `a` and a card size `s`, take all combinations of `s` elements in `a` and call it `C`, then:
* Take the first element of `C`, call it `C0`
* Save `C0`
* Remove all elements from`C` that have a union with `C0` not equal to `1`
* Repeat with second element of `C`
* Continue until `C` is empty
Then print the saved elements.
### Argument
Some non-empty subset of `C` is our maximal solution, `K`. Since it contains at least one element and any two elements are indistinguishable, choose an arbitrary element, `C0`, of `C` to be in `K`. For any element `e` in the `K`, the cardinality of `e` union `x` is 1 for `x != e` in `K`; so eliminate all elements in `C` whose union with `C0` does not have cardinallity 1. By the same reasoning, choose a new arbitrary element in `C`, add it to `K`, and reduce `C`. Eventually `C` is the empty set and `K` will be the maximal solution because at no point did we choose an element that was distinguishable from any other element.
---
## Test Cases
These test cases were written before I realized that the printing was a requirement.
```
a=["a","b","c"]
b=2
c=3
d=m(a,b)
print d,len(d)==c
>> ['bc', 'ab', 'ac'] True
a=["a","b","c","d","e","f","g"]
b=3
c=7
d=m(a,b)
print d,len(d)==c
>> ['aef', 'abc', 'bde', 'ceg', 'adg', 'cdf', 'bfg'] True
a=["a","b","c","d","e"]
b=4
c=1
d=m(a,b)
print d,len(d)==c
>> ['abcd'] True
```
**Update**
* **+9** [16-12-07] Fit the print requirement
* **-11** [16-12-07] Golfed out my `R` variable
* **-30** [16-12-09] Golfed out my `K` variable, Thanks to [*@Leo*](https://codegolf.stackexchange.com/users/62393/leo)!
[Answer]
# Haskell, ~~175~~ 156 bytes
My first take at golfing, let me know if I've messed something up.
```
import Data.List
f 0_=[[]]
f n a=g$c n a
c n a=[a!!i:x|i<-[0..(length a)-1],x<-f(n-1)(drop(i+1)a)]
g[]=[]
g(x:t)=x:g(filter(\z->length(z`intersect`x)<= 1)t)
```
[Try it online!](https://tio.run/##JYxBDoIwFET3nOJLWLTREog7Ql259Aa1kS@0pREKgS4a4t0r6mbe5E0yPa4vNQwx2nGeFg9X9Jjf7OoTDcWDCyHl3hwgN1n7ZfJLLvBwsFV425qJIs/JoJzxPSBlpTyFmmniWElJt0wzsceSIpWJEZKLHSRUnvJQGaLt4NVC7hu7/A/I1li3q1W1vgm05lBST@OI1gGHedlHyEDDGVJ8tp3SJo0f "Haskell – Try It Online")
Thank to [@Paul Mutser](https://codegolf.stackexchange.com/users/86374/paul-mutser) for improvement and -19 bytes
---
[Original version](https://tio.run/##TYyxCsIwGIR3n@IUhwRNsbiVxsnRN4hBf2uSBttY0oBBfPdacPG2u@/uWhofpusm3w/PmHCkRMXJj2my2OEildJ6YRFA0qFZAK/WRINGKloufZU/vhZqVxSsM8GlFsRFqbe5FpYFUXJ2j8@B@U3Jiet5/ZNTWqo/y3KVRy5z5Zj1XTKRnd/i8Htk76sPczSaJl0zryVKPpennnyAxBBnijUs9ljRrbkb61bTFw "Haskell – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~88~~ 77 bytes
```
{+(combinations($^a,$^n),{my \d=.[0];say d.join;grep *∩d==1,.[1..*]}...!*)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WlsjOT83KTMvsSQzP69YQyUuUUclLk9TpxqoIibFVi/aINa6OLFSIUUvKz8zzzq9KLVAQetRx8oUW1tDHb1oQz09rdhaPT09RS3N2v/WXGn5RQo2jk7OCkYKQNLF1c1dwRjCUjCxU9C1U1Ap1lFQyVOo5uIEmapkCwNACaC4kjUXZ5qGSrEeyFE6CtoqeZrWXLX/AQ "Perl 6 – Try It Online")
] |
[Question]
[
In an effort to level the playing field between languages with built-in date libraries and those without, let's work with a fictional calendar. The Forgotten Realms are a (*the?*) campaign setting for Dungeons & Dragons. Of course, each have their own calendar.
## The Calendar of Harptos
Conveniently, a year in the Forgotten Realms also has 365 days. Furthermore, the calendar also has 12 months. However, this is where it gets interesting. Each month is exactly 30 days long. The remaining 5 days are holidays which fall *between* the months. Here are the months and holidays in order (with holidays indented):
```
1 Deepwinter
Midwinter
2 The Claw of Winter
3 The Claw of the Sunsets
4 The Claw of the Storms
Greengrass
5 The Melting
6 The Time of Flowers
7 Summertide
Midsummer
[Shieldmeet]
8 Highsun
9 The Fading
Highharvestide
10 Leaffall
11 The Rotting
The Feast of the Moon
12 The Drawing Down
```
Notice that I've inserted a sixth holiday in brackets. This is the leap day which only occurs every four years (yes, that's it — there are no additional shenanigans with the centuries).
Side note about month names: each month has a formal and a common name. The above are the common names. I've picked those because I think they allow for more interesting compression.
There are several numberings of the years, but the most widespread one is *Dalereckoning*, shortened to *DR*. (Also, every year [has one or more names](http://www.editthis.info/wiki/Year_Names_in_Dalereckoning), but we're not going to bother with that.)
The components of a date should be separated by a comma and a space. All in all, a valid date might look like:
```
4, The Melting, 1491 DR
```
or
```
Shieldmeet, 1464 DR
```
Note that there is no day number for the holidays. (I suppose `4th of The Melting` would be nicer for the days of the months, but I don't want to drag ordinal numbers into this.)
Footnote: I came up with this when xnor complained that every single date challenge needs the leap year computation. I've failed in eliminating it completely, but at least it's only a single modulo in this calendar.
## The Challenge
Given a valid date of the Calendar of Harptos, as well as an integer `D`, output the date `D` days later. Note that `D` may be negative, in which case you should return the date `D` days earlier.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
You may assume that the year is positive and less than 2000.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test Cases
The first dozen or so test cases should test all the edge cases surrounding holidays and leap years. The next set are to test that ranges across multiple years work and all months and holidays have been implemented. The second half is all the same test cases again but with negative offsets.
```
"30, Summertide, 1491 DR" 1 => "Midsummer, 1491 DR"
"30, Summertide, 1491 DR" 2 => "1, Highsun, 1491 DR"
"Midsummer, 1491 DR" 1 => "1, Highsun, 1491 DR"
"30, Summertide, 1492 DR" 1 => "Midsummer, 1492 DR"
"30, Summertide, 1492 DR" 2 => "Shieldmeet, 1492 DR"
"30, Summertide, 1492 DR" 3 => "1, Highsun, 1492 DR"
"Midsummer, 1492 DR" 1 => "Shieldmeet, 1492 DR"
"Midsummer, 1492 DR" 2 => "1, Highsun, 1492 DR"
"Shieldmeet, 1492 DR" 1 => "1, Highsun, 1492 DR"
"1, Highsun, 1490 DR" 365 => "1, Highsun, 1491 DR"
"1, Highsun, 1491 DR" 365 => "Shieldmeet, 1492 DR"
"Shieldmeet, 1492 DR" 365 => "Midsummer, 1493 DR"
"Midsummer, 1493 DR" 365 => "Midsummer, 1494 DR"
"Shieldmeet, 1500 DR" 365 => "Midsummer, 1501 DR"
"14, Deepwinter, 654 DR" 5069 => "The Feast of the Moon, 667 DR"
"Midwinter, 17 DR" 7897 => "15, The Fading, 38 DR"
"3, The Claw of Winter, 1000 DR" 813 => "25, The Claw of the Storms, 1002 DR"
"Greengrass, 5 DR" 26246 => "9, The Claw of the Sunsets, 77 DR"
"30, The Melting, 321 DR" 394 => "29, The Time of Flowers, 322 DR"
"17, The Time of Flowers, 867 DR" 13579 => "20, Highsun, 904 DR"
"Highharvestide, 1814 DR" 456 => "30, The Drawing Down, 1815 DR"
"23, The Rotting, 1814 DR" 3616 => "16, Leaffall, 1824 DR"
"1, Deepwinter, 1 DR" 730499 => "30, The Drawing Down, 2000 DR"
"Midsummer, 1491 DR" -1 => "30, Summertide, 1491 DR"
"1, Highsun, 1491 DR" -2 => "30, Summertide, 1491 DR"
"1, Highsun, 1491 DR" -1 => "Midsummer, 1491 DR"
"Midsummer, 1492 DR" -1 => "30, Summertide, 1492 DR"
"Shieldmeet, 1492 DR" -2 => "30, Summertide, 1492 DR"
"1, Highsun, 1492 DR" -3 => "30, Summertide, 1492 DR"
"Shieldmeet, 1492 DR" -1 => "Midsummer, 1492 DR"
"1, Highsun, 1492 DR" -2 => "Midsummer, 1492 DR"
"1, Highsun, 1492 DR" -1 => "Shieldmeet, 1492 DR"
"1, Highsun, 1491 DR" -365 => "1, Highsun, 1490 DR"
"Shieldmeet, 1492 DR" -365 => "1, Highsun, 1491 DR"
"Midsummer, 1493 DR" -365 => "Shieldmeet, 1492 DR"
"Midsummer, 1494 DR" -365 => "Midsummer, 1493 DR"
"Midsummer, 1501 DR" -365 => "Shieldmeet, 1500 DR"
"The Feast of the Moon, 667 DR" -5069 => "14, Deepwinter, 654 DR"
"15, The Fading, 38 DR" -7897 => "Midwinter, 17 DR"
"25, The Claw of the Storms, 1002 DR" -813 => "3, The Claw of Winter, 1000 DR"
"9, The Claw of the Sunsets, 77 DR" -26246 => "Greengrass, 5 DR"
"29, The Time of Flowers, 322 DR" -394 => "30, The Melting, 321 DR"
"20, Highsun, 904 DR" -13579 => "17, The Time of Flowers, 867 DR"
"30, The Drawing Down, 1815 DR" -456 => "Highharvestide, 1814 DR"
"16, Leaffall, 1824 DR" -3616 => "23, The Rotting, 1814 DR"
"30, The Drawing Down, 2000 DR" -730499 => "1, Deepwinter, 1 DR"
```
[Answer]
# Ruby, ~~543~~ ~~523~~ ~~521~~ ~~498~~ ~~511~~ 509 bytes
To encourage more answers to this question, I'm going to post a Ruby version of my Python answer, since I figured it would be shorter. This answer *is* shorter but not by much. Can *you* do better?
**Edit:** With thanks to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) and his suggestion [here](http://chat.stackexchange.com/transcript/message/26689055#26689055).
**Edit:** I golfed the "number of days in a month" list down considerably.
**Edit:** While golfing down how I handled `d[10]=r%4<1?1:0` to `d[10]=0**(r%4)` for a byte, I noticed I'd introduced a bug while golfing down `d`, the number of days list, so that Shieldmeet had 30 days by accident. And so, the byte count has come back up. I will also edit the Python answer to fix this bug there.
**Edit:** I forgot that functions don't need to be named in this question.
```
->s,n{x=s[0..-4].split(", ");x=x[2]?x:[1,*x];t=(["Deepwinter,Midwinter","Winter","Sunsets","the Storms,Greengrass,The Melting,The Time of Flowers,Summertide,Midsummer,Shieldmeet,Highsun,The Fading,Highharvestide,Leaffall,The Rotting,The Feast of the Moon,The Drawing Down"]*',The Claw of ').split(?,);p,q,r=x[0].to_i+n,t.index(x[1]),x[2].to_i;d=[30,1,30,30]*4+[1,30];d[10]=0**(r%4);(a=p<1?1:-1;q=(q-a)%18;p+=a*d[a<0?q-1:q];r-=a*0**q;d[10]=0**(r%4))until(1..d[q])===p;z=d[q]<2?[t[q],r]:[p,t[q],r];z*", "+" DR"}
```
Ungolfed:
```
def h(s,n)
x=s[0..-4].split(", ")
x=x[2]?x:[1,*x]
t=["Deepwinter,Midwinter","Winter","Sunsets","the Storms,Greengrass,The Melting,The Time of Flowers,Summertide,Midsummer,Shieldmeet,Highsun,The Fading,Highharvestide,Leaffall,The Rotting,The Feast of the Moon,The Drawing Down"]
t=t*',The Claw of ' # turns the above array into a string with "Claw"s inserted
t=t.split(?,) # then splits that string back up again by ","
p=x[0].to_i+n
q=t.index(x[1])
r=x[2].to_i
d=[30,1,30,30]*4+[1,30]
d[10]=0**(r%4)
until(1..d[q])===p
a=p<1?1:-1
q=(q-a)%18
p+=a*d[a<0?q-1:q]
r-=a*0**q
d[10]=0**(r%4)
end
z=d[q]<2?[t[q],r]:[p,t[q],r] # putting z=[t[q],r] on another line saved me no bytes
z*", "+" DR"
end
```
[Answer]
# Python 3, ~~712~~ ~~652~~ ~~636~~ ~~567~~ ~~563~~ ~~552~~ ~~550~~ ~~548~~ ~~529~~ 540 bytes
At last, I found time to write an answer for this excellent question. It isn't very golfed yet (the month names list ~~and the number of days list are~~ is particularly egregious in this case~~, and the fact that handling negative `D` requires a separate while loop~~) but at least it's an answer.
**Edit:** Fixing a bug
```
def h(s,n):
x=s[:-3].split(", ");x=[1]*(len(x)<3)+x;t="Deepwinter,Midwinter,The Claw of Winter,The Claw of the Sunsets,The Claw of the Storms,Greengrass,The Melting,The Time of Flowers,Summertide,Midsummer,Shieldmeet,Highsun,The Fading,Highharvestide,Leaffall,The Rotting,The Feast of the Moon,The Drawing Down".split(",");p,q,r=int(x[0])+n,t.index(x[1]),int(x[2]);d=[30,1,30,30]*4+[1,30];d[10]=r%4<1
while p>d[q]or p<1:a=[-1,1][p<1];q=(q-a)%18;p+=a*d[q-(a<0)];r-=a*0**q;d[10]=r%4<1
return', '.join([str(p)]*(d[q]>2)+[t[q],str(r)])+" DR"
```
Ungolfed:
```
def harptos(date, num):
t = "Deepwinter,Midwinter,The Claw of Winter,The Claw of the Sunsets,The Claw of the Storms,Greengrass,The Melting,The Time of Flowers,Summertide,Midsummer,Shieldmeet,Highsun,The Fading,Highharvestide,Leaffall,The Rotting,The Feast of the Moon,The Drawing Down"
t = t.split(",") # split up the names of the months
x = date[:-3] # removes " DR"
x = x.split(", ")
if len(x) < 3:
x = [1] + x # if we have two items (holiday), append a "day of the month"
p = int(x[0]) + num # initialize the "date" by adding num to it
q = t.index(x[1])
r = int(x[2])
d=[30,1,30,30]*4+[1,30] # all the month lengths
d[10] = r%4 < 1 # leap year toggle
while p > d[q]: # while the "date" > the number of days in the current month
p -= d[q] # decrement by number of days in current month
q = (q+1)%18 # increment month
r += 0**q # increment year if the incremented month == the first month
d[10] = r%4 < 1 # leap year toggle
while p < 1: # while the "date" is negative
q = (q-1)%18 # decrement month first
p += d[q] # add the number of days in the decremented month
r -= 0**q # decrement year if the decremented month == the first month
d[10] = r%4 < 1 # leap year toggle
m = [t[q],str(r)] # start the result array
if d[q] > 2:
m = [str(p)] + m # if the month is NOT a holiday, add the day
return ", ".join(m) + " DR"
```
] |
[Question]
[
A man has two devices.
* **A time machine** - He can control this machine by thinking. It allows him to travel from any point in time to another point in time in the past or future (or even the present point in time) in no time at all. Note that if he travels to the past from B to A, then all normal events (time machines, alternators excluded) from A to B must repeat in the exact same way. Then from point B, he is taken back to point A. Thus, a single time travel creates an infinite loop.
* **Alternator** - Realising this problem, he creates another machine. He notices that, even though all physical events get repeated in a loop, his thoughts may be different. Hence this machine was designed to be controllable by thought as well. The machine can be used at any time to provide an alternate future (but not past) with respect to the time he used it.
**Example**
I'll explain all the details using a lengthy example.
```
1000 T+250 250 T+0 500 T-200 100 T-50 125 A 225 T-400 500 A 100 T-200 150 T-25 100 T+100 50 A 25
```
* 1000 years pass. It is year 1000 now.
* He travels from 1000 to 1250.
* 250 years pass. It is year 1500 now.
* He travels from 1500 to 1500. This has no effect (and can be ignored).
* 500 years pass. It is now year 2000
* He travels from 2000 to 1800.
* 100 years pass. It is year 1900 now.
* He travels from 1900 to 1850.
* 125 years pass: However, this time, as he is in a loop, things are different. 50 years pass from 1850 to 1900. He loops back to 1850. Another 50 years pass from 1850 to 1900. He loops back again. 25 years pass and it is 1875, thus completing 125 years.
* He uses the alternator. Now there exists an alternate future to the year 1875, which he is now in. The past has not changed.
* 225 years pass. It is now year 2100.
* He travels from 2100 to 1700.
* 500 years pass: 175 years from 1700 to 1875 pass normally. No he encounters the alternator again, which means that now a *3rd* future has been created post-1875. 325 years pass normally, making it year 2200.
* Using an alternator now has no effect (and can be ignored) since there exists only one future to 2200 which has not yet been defined.
* 100 years pass. It is now 2300.
* He travels from 2300 to 2100.
* 150 years pass: 100 years from 2100 to 2200 pass normally. A second future gets created from 2200. 50 years pass and it is now year 2250.
* He is supposed to go from 2250 to 2225. However, there now exist two 2225s in two different timelines. Hence this leads to a paradox, since we cannot determine which point in time he will reach. (We will not assume that he goes to the more recent timeline) Hence this terminates our simulation.
* Anything further `100 T+100 50 A 25` is completely ignored since a paradox has occured and our simulation has stopped running.
*Hint:* If you are struggling to understand the example, imagine time to be like a path you are digging in the earth. If you are time travelling, you are creating a teleporter. If you are using the alternator, you are digging a new path into the wall of an existing path.
**Paradox**
Assume A, B and C are three points in time (one after another). A paradox is said to have occurred iff:
* you are at a point C, there exists an alternator at a point B, there exists more than one future to point B (and you are in one of them), and you attempt to access any point between B and C via time travel.
* you are at a point A, there exists an alternator at a point B, there exists more than one future to point B, and you try to access a point C (after B) via time travel.
**Input**
A series of events, similar to the example. (Format is flexible.)
**Output**
A truthy/falsey value, indicating whether a paradox has occured.
**Challenge**
Shortest code (in bytes) wins.
[Answer]
# Ruby, ~~510~~ 460 bytes
```
p=[0];w=[n=x=0]
i=gets.split.map{|s|
if x!=1
if s[0]=="A"
w<<n
else
if s[0..1]=="T+"
t=n
q=s[2..-1].to_i
if w[-1]==t||(w[-1]>t&&w[-1]<n+q)
w<<w[-1]
n+=q
else
n+=(t<p[-1]&&n+q>p[-1])?q%(p[-1]-n):q
end
elsif s[0..1]=="T-"
t=n
p<<n
n-=s[2..-1].to_i
x=(x==0&&w[-1]>0&&t>w[-1]&&n>w[-1])?1:0
else
t=n
q=s.to_i
if w[-1]==t||(w[-1]>t&&w[-1]<n+q)
w<<w[-1]
n+=q
else
n+=(t<p[-1]&&n+q>p[-1])?q%(p[-1]-n):q
end
end
end
else
break
end}
p x
```
**Input**
As per example
**Output**
0 = No Paradox, 1 = Paradox
**Sample**
The sample input provided: `1000 T+250 250 T+0 500 T-200 100 T-50 125 A 225 T-400 500 A 100 T-200 150 T-25 100 T+100 50 A 25`
returns `1`, indicating a paradox occurred.
**Notes**
This is not only the first [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'") exercise I attempt, but it is also the first Ruby program I have written. Hence, it could probably be even shorter.
**Brief Explanation**
```
p: Infinite loops
w: Alternate timelines
n: Now (regardless of timeline)
x: Paradox
```
Infinite loops will only occur while traveling forward in time. I am happy for any feedback - especially if it is pointing out a better way to solve this.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~93~~ ~~92~~ ~~86~~ 82 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ðU0V#vyAQiYˆðUëy.ïiYy+DX˜såàiXD€нY@Ïн©θ-®¥OÄ%®θY-YOVëVëYy¦+©¯@àXðʘà*i1q}XY®Ÿª{U®V
```
Input is in the same format as in the challenge description, except that alternator `A` is `abcdefghijklmnopqrstuvwxyz` instead to save a byte.
Outputs `1` if a paradox occurred, or the input itself if not (only `1` is truthy in 05AB1E, everything else is falsey).
Loosely based on [my Java 10 answer](https://codegolf.stackexchange.com/a/186274/52210).
[Try it online.](https://tio.run/##yy9OTMpM/f//8IZQgzDlskrHwMzI021A3uHVlXqH12dGVmq7RJyeU3x46eEFmREuj5rWXNgb6XC4/8LeQyvP7dA9tO7QUv/DLaqH1p3bEakb6R92eDUQRVYeWqZ9aOWh9Q6HF0Qc3nC46/Scwwu0Mg0LayMiD607uuPQqurQQ@vC/v83NDAwUAjRNjI1UADhEG0DBVOQiK4RkDQEs4DChkamColJySmpaekZmVnZObl5@QWFRcUlpWXlFZVVCkZA6RBdEwOIXjwKDRFGm4JZphAhbUOwXrx2mAIA)
Or try it online with added debug-lines (*TODO: Create proper test suite with all test cases at once..*):
- Test case with backward time-travel paradox: [Try it online.](https://tio.run/##fY8xT8JAFMf3fopnjYul5NrYxUVMmCUm0PQGhwNOqQKFa6lU42KMg4tfgIEFE8QURhaWuziRED6DX6S2B@LGcO/e@733/788zydVlyaJmFUUZCuHoQKg1nqM0XYAESXsFNQznMsoaQaUtUngMT@DfCpp4LaoHjAS0qbEjqSqjDRMXTIYZWV0fummHwBevmbrAMQkyovpFkZa0VkOfDESww0BcIo/z1/rBS6I9/WCj1dzncd8VBIvRzxezbGOS7acFJOtwFZ2BY74h8bHfFoQQ0fMxNtyIIbHf85qhzBS9/rg1eSx9QM1Z3SfZNfBPP6e88/Hiix5bCtX6oUHWwn1oZFeu1Pm1VySGAghKGumhSB7ZQ2BlRHdTKMhsxQbpgWkWqvT65uGe3vXbLW9Tpf5QS@870cPYKbtsn6CNto9g8a/tSUza4M0Q2r37rB@AQ)
- Test case with forward time-travel paradox: [Try it online.](https://tio.run/##PY@xTgJBEIb7e4pxjY1wZDHS2IgJtcQELreFxQKrnAIHe8fJamyMsbDxBSiugQQxByUNzW6sSAjP4Iuc7IoUM5P/m/lnMn5Aax5LUzWvWtixDiMLANX7nLNOCIJRfgbonGQ1pa2Q8Q4NfR5oKGeGhl6b2SGnEWsZ7BqKTGbRdouGQktxceVtCwBZvelzAGoqcmq2gyJTclfDQI1U/EcA3NLPy9dmSYrqY7OUk/XClokcldXrkUzWC2KTsmMm1XRncKy9IEKOM3IiZ0UVu2qu3ldDFR//b0ZdymnDH4BfN882DlA233s2XZfI5HshP5@qRsrEsa7RpQ87Cwuguf1278yhbJrmTwoYaK3eYDe3Te/uvtXu@N0eD8J@9DAQj6DbFbuAMeio2Kc6Z/IY418)
- Test case without time-travel paradox: [Try it online.](https://tio.run/##fY8xT8JAFMf3fopnjYul5Frt4iImzBITaNrB4YBTqkDhWirVuBjj4OIXYGDBBDGFkYXlLk4khM/gF6m9AxkZ7t39f@//f5fnB7jqkTTls4qCbOUwUgDUWo9S0g4hJpiegXru5gTFzZDQNg59GgjIppKGXovoIcURaUrsSKrKSqJsioCxkPHFlZddAO7yTXwHwCdxnk@3MNaKznIQ8BEfbgiAU/x9@V4v3AL/WC/YeDXXWcJGJf56xJLV3NXdki2dfLIN2MpOuDH71NiYTQt86PAZf18O@PD4f7LawRTX/T74Nbls/UDNGd1n2XVclvzM2ddTRUqW2Mq1eunDNkICaGTb7pJ5NZemBkIIypppIRCnrCGwBNHNrBrylWHDtABXa3Vyc9vw7u6brbbf6dIg7EUP/fgRzKxd1k/RJrvHaOxGn@w3mtYf)
**Explanation:**
```
ðU # Set variable `X` (time-travels) to a space character " "
0V # Set variable `Y` (current year) to 0
# # Split the (implicit) input by spaces
v # And loop over each event `y`:
yAQi # If the current event `y` is an alternator ("abcdefghijklmnopqrstuvwxyz"):
Yˆ # Add the current year `Y` to alternators-list `GB`
ðU # And reset variable `X` to " "
ëy.ïi # Else-if the current event `y` is an integer:
Yy+ # Calculate the current year `Y` plus the integer `y`
D # Duplicate `Y+y`
X˜såài # If this `Y+y` is within any of the time-travel ranges:
X €н # Get the starting positions of each time-travel
Y@ # Check for each starting position if the current year `Y` is >= it
D Ï # And only leave the time-travel ranges for which this is truthy
н # Then pop and push the first one
© # Store this time-travel range in variable `r` (without popping)
θ # Pop and only leave the time-travel destination
- # Subtract it from the `Y+y` we duplicated
% # And modulo it with:
®¥OÄ # The absolute distance of the time-travel `r`
®θ # Then push the time-travel destination again
Y- # And subtract the current year `Y`
YO # Then sum these two and the current year `Y` together
V # And pop and store it as new year `Y`
ë # Else (`Y+y` is not within any time-travel ranges)
V # Simply pop and store the duplicated `Y+y` as new year `Y`
ë # Else (the current event `y` is a time-travel)
y¦ # Remove the leading "T"
Y + # And add the value to the current year `Y`
© # Store this value in variable `r`
¯@à # Check if any alternator in list `GB` is >= this value
Xðʘà # Check if there are any time-travels
*i } # And if both are truhy:
1 # Push a 1
q # Stop the program
# (after which the top of the stack is output implicitly)
Y®Ÿ # Create a list in the range [current year `Y`, new year `r`]
X ª # Append it to the time-travels `X`
{ # And then sort these time-travels
U # After which we pop and store it as updated `X`
®V # And then set `Y` to the new year `r`
# (if we haven't reached `q`, the (implicit) input is output instead)
```
[Answer]
# Java 10, ~~498~~ ~~485~~ 478 bytes
```
import java.util.*;s->{var a=new Stack<Long>();var m=new TreeMap<Long,Long>();long p=0,c=0,t,v,k;o:for(var S:s.split(" "))if((t=S.charAt(0))>65){var b=S.charAt(1)>44;v=new Long(S.substring(2));for(var A:a)p=A>c+(b?-v:v)|m.size()<1?p:1;if(v>0)m.put(c,b?c-v:c+v);c+=b?-v:v;}else if(t>64){a.add(c);m.clear();}else{t=new Long(S);e:for(var e:m.entrySet())if((k=e.getKey())>=c){for(v=c;v<=c+t;)if(a.contains(v++))break e;c=(v=e.getValue())+(c+t-v)%(k-v);continue o;}c+=t;}return p>0;}
```
Input is (for now) in the same format as in the challenge description.
-13 bytes thanks to *@BenjaminUrquhart*.
-7 bytes thanks to *@ceilingcat*.
[Try it online](https://tio.run/##rVOxbtswEN3zFQcDBcjKYiTXDlAzUuAOXdpksdGl6EDRTKJYIgXypNR1/e0uRcmtO3TrIIp89@7eHe/4IjoRv2x3p7JujEV48WfWYlmxtxwArq8hSt8DGsBnBcUeVSxNq/FKVsI5uBelPlwBlBqVfRRSwUN/BCiMqZTQIMkabamfwFHuDccrvzgUWEp4AA0ZnFycHzphQWRavcIahdzdfjb6KSeU93gd8I1V6l40wTI9myv/hyZLptJ/OO2mO26Wj8aS3m@9dMw1VYlkAhNKy0dCMFsz@SzsCklCaX6zoEG5@AOnNJ/PeRckexWyZq4tXCiBzCjl5@irpaBNtsplRIq7uFt29GfNXPlDEXqb3jXLlHvBLk9ozZoWiZwWd9LTZNRRLqNs8OFHVTkFnon5zZweBBPbLZGU10z627O@xMA44EVClKvfNaplzZRGu18rJEONu0yxJ4Wf1N4DeSbpIZAzybvbTEbIe5Zg0mj0vXOkiyJKC6vEDhSXmWcG/y@ian0tNCLeJ@7oG7KL@9S9W6lbBYYffRnIj1ZhazU0ecKPJ963t2mLyrd37HJnyi3UXmochK/fQNBhRlA535w0SRLYRLNFAv23iRJY9Eg882sadh5OZwtYwcyvm3ieDJTVaA7ERdgtBihKA6X3WEwo76f4g5@rV2G3DhphxdZ8v0xhNnIHsXMC83OoZIzx0dh/hvgvVbxL/sr5wVwoXT6dcKlBeHxdpfZTNl7reu9Q1cy0yBpvxEqTYI4mS5hEmsnhSMcHeTz9Ag) or [try it online with added debug-lines](https://tio.run/##rVRNb9Q8EL73V4wiIdnkg@yyi8SmSbUc3ssLvaTiQjl4vW5JN4kjexJYoL@9jJ3sRwXciJTIfp75eDyZ8YMYRPyw3T1VTacNwgPtkx6rOnmZAcCrVxDO3gJqwC8KNntUsdR9ixeyFtbCB1G1Py4AqhaVuRNSwbXbAmy0rpVoQbISTdXeg@UZEY8X9LEosJJwDS3k8GTjwrkMwoDIW/UVShRyd/let/cF806Oajx1Y5T6IDpPRmcWNS2hy9NI0ovREO0culWb/p4FVVthEMlIRE3UeXO9utOGubDlyia2qytkAQScj9qrO8YwLxP5RZg1spTz4s1y4kY1mxM748VikR04r9IJY2Vi@431Z2dzzg8WLrFXu14JPmFA0teFDNnmKh5WA//ZJLb6rhi/nF11q9nBlWQNRXpyapKuRyajzZUkNxkOxyQyzMdQ2aNHVG2Vc8fizeJ4DpGI7ZbJo1OTSPpjhk3AyfPggGeHO3qpYynVqklUi2ZfKmT8JNNVc5er5F7h/2pPTJHLo4hDSYZcZsNlLkPM@BnlvUUidYvUaJYNYcif89RpRokdqOwMljkF9Bk/irqnQvKQUeh44C/YLj7VyT1jk5TP@uMYh/JWba9AT4X0pcVp85ung43C3rTQFWn2@JS5bu/6TU3dPjX9oKstNHSYaS4@fQYxVQOVpTacpWkKN@F8mYJ7b8IUlg6J5/Sd@RXBs/kS1jCn7028SEeT9UR7w6VfLUconHkT57EMeOaG@h3N2FdhthY6YcRWfzuXMJ9sx2QHAYtDqHSK8Z82fw3xT07xOn2m@VqfZTq/SXxRfeLpsqlaGo2prOXeomoS3WPSEYl1yzwdBisIwjaR4/Ywon8w/@3m8vmm3z8mLCM/1DJ6X1kEEdElBc2IdX/XEazv6NoENdDc5LdBEJZhcBusblH2xhAGexrIPAhlGGQgarJtBWpjCRIOwqpRMRox0JgS1jhsqhBo6YNsCWfUjXw6xOPTLw).
**Explanation:**
```
import java.util.*; // Required import for the List and TreeMap
s->{ // Method with String parameter and boolean return-type
var a=new Stack<Long>(); // Create a List for the alternators
var m=new TreeMap<Long,Long>();
// Create a sorted Map for the time-travels
long p=0, // Paradox-flag, initially 0
c=0, // Current year, initially 0
t,v,k; // Temp-values, uninitialized
o:for(var S:s.split(" ")) // Loop over the input substrings split by space:
if((t=S.charAt(0))>65){ // If the first character is a 'T':
var b=S.charAt(1)>44; // Check if the second character is a '-'
v=new Long(S.substring(2));
// Convert the String-value to a number
for(long A:a) // Loop over the alternators
p=A> // If an alternator is larger than:
c+ // The current year, plus
(b? // If we travel backwards in time:
-v // Subtract the value
: // Else (we travel forward in time):
v) // Add the value
|m.size()<1? // Or if no previous time-travels occurred:
p // Leave the paradox-flag the same
: // Else:
1; // Set the paradox-flag to 1
if(v>0) // If the value is not 0 (edge-case for "T+0")
m.put(c,b?c-v:c+v); // Add the from-to time-travel to the Map
c+=b?-v:v;} // Increase/decrease the year accordingly
else if(t>64){ // Else-if the character is an 'A':
a.add(c); // Add the current year to the alternators-list
m.clear();} // And empty the time-travel Map
else{ // Else (it's a number)
t=new Long(S); // Convert the String to a number
e:for(var e:m.entrySet())// Loop over the time-travels:
if((k=e.getKey()) // If the time-travel starting point is
>=c){ // larger than or equal to the current year
for(v=c;v<=c+t;) // Loop from the current year to the year+number:
if(a.contains(v++))// If the alternator-list contains any of these years
break e; // Stop the time-travel loop
c= // Set the current year to:
(v=e.getValue()) // The time-travel destination
+ // Plus:
(c+t // The current year plus the number
-v) // minus the time-travel destination
%(k-v); // Modulo the time-travel from-to distance
continue o;} // And then continue the outer input-loop
c+=t;} // Increase the current year by the number
return p>0;} // Return whether the paradox-flag is 1
```
] |
[Question]
[
Given a square of text representing a spiral of characters, rotate it!
The spiral starts at the center and moves *counterclockwise* to the outer edge, starting to the left of center:
```
987
216
345
```
This translates to the string `123456789`. Rotation is done *to the left*, so if you rotate it one position, it will be `234567891`. This is represented by:
```
198
327
456
```
### Input
Input consists of the spiral and the distance to rotate it.
Distance will always be a positive integer or zero, and can be capped at your language's data type limit.
The spiral should be taken as a string, with a line delimiter of your choice (including no delimiter). It will always be a square, not including delimiters, and have an odd side length.
Assume all characters are alphanumeric [A-Za-z0-9].
### Output
Output is the rotated spiral. It should be a square on multiple lines (whether printed or returned).
### Examples
Input
```
3
tne
atd
bin
```
Output
```
bat
nit
den
```
Input
```
18
efilr
naepo
umshf
tootr
butte
```
Output
```
rettu
omseb
oofft
trliu
hpean
```
This is code golf, with score counted in bytes as usual.
[Answer]
# CJam, ~~45~~ 44 bytes
```
]]l~LqN/{(W%@+\zW%}h;m<{1$,/(W%a@W%z+\s}h;N*
```
[Test it here.](http://cjam.aditsu.net/#code=%5D%5Dl~LqN%2F%7B(W%25%40%2B%5CzW%25%7Dh%3Bm%3C%7B1%24%2C%2F(W%25a%40W%25z%2B%5Cs%7Dh%3BN*&input=18%0Aefilr%0Anaepo%0Aumshf%0Atootr%0Abutte)
## Explanation
The lazy solution: unwrap the spiral, use CJam's built-in array rotation, roll the spiral up again.
```
]] e# Push [""]. We'll later use this to roll up the spiral.
l~ e# Read the integer and evaluate it.
L e# Push an empty string: we'll unroll the input into this.
qN/ e# Read the spiral and split it into lines.
{ e# While the top of the stack is truthy...
(W% e# Pull the first line off the spiral and reverse it.
@+ e# Pull up the string we've built so far and prepend the reversed line.
\zW% e# Swap with the remaining spiral, and rotate the spiral.
}h e# This terminates when the centre character has been added to the string and
e# the spiral becomes an empty array.
; e# Discard the empty array.
e# Note that we've unrolled the spiral from outside in, but we've also built up
e# the string in reverse, which gives us the string from inside out.
m< e# Rotate to the left by the given number of characters.
{ e# While the top of the stack is truthy...
1$, e# Copy the spiral so far and get the number of lines.
/ e# Split the string into chunks of that size.
(W%a e# Pull off the first chunk, reverse it and wrap it in an array.
@zW% e# Pull up the spiral so far, rotate it.
+ e# Prepend the chunk to the spiral as a line.
\s e# Swap with the other chunks and flatten them into a string again.
}h e# This terminates when the string has been used up completely.
; e# Discard the empty string.
N* e# Join the lines with linefeed characters.
```
[Answer]
# [Haskell](https://www.haskell.org/), 188 bytes
```
import Data.List;r=reverse;t=transpose;f=take;g=drop
u[[c]]=[c];u(a:b)=a++u(r.t$b)
w k[]=k;w[](a:b)=w[[a]]b;w k l=w((r.f h$l):(t.r$k))$g h l where h=length k
s n=w[].(\s->g n s++f n s).r.u
```
[Try it online!](https://tio.run/##JYuxbsQgEER7f8XqRGFkBSlddIhUKfMHhALn1sYCg7Usx@f7HKWZN9KbCb5GTOk8t/0oxPDl2avvrbImQ/hEqqjZMPlcj3L1xbCPqFfzoHIMzdpf58wVuo3@Pkvjp6mNpFjMcugQrTNRd@v@ZbfWOzfrS0AyfbyGCwSR5H1kRSJKKVYIkKAHJIRgEuaVA8ShQr7eTo0/9e1zhQx1mpY/SEWqnbvfsjloyywqvH@IXuhRb7hsiSB7PAq0vYYFuBQmmBsz3s4X "Haskell – Try It Online")
[Answer]
# Python3, 336 bytes:
```
R=range
def S(N):
x,y=N//2,N//2;r=[(x,y)]
for i in R(2,N,2):
y-=1;F=0;r+=[(x,y)]
for X,Y in[(1,0),(0,1),(-1,0),(0,-1)]:
for _ in R(i):
if F:x+=X;y+=Y;r+=[(x,y)]
F=1
return r
def f(n,s):
s=[[*i]for i in s.split('\n')];T=[s[x][y]for x,y in S(len(s[0]))];T=T[n:]+T[:n]
for x,y in S(len(s[0])):s[x][y]=T.pop(0)
return s
```
[Try it online!](https://tio.run/##bY/NbgIhFIX3PAW7gQ7qoP2xM2Hr0oXOQkNJoxEqiWUIYOI8/RSo2ph0c5N7z3dOzrV9OHZmNrduGFbM7cyXBAep4BotcQ3ghfRsOZlMSRqNYxzFCxYAqs5BDbWBKxRFMk0w7EeMNgtWNa78IzO6IdsIc0RJhQmqCI1zdFtGFItkz@Tnb6jOgRBqBRf1pWSbpi/Z9jEYwgWjADoZzs5Al3srZIhPXs84f9Li3tOPvT3pgIoPU2DRtIx7fhG8z0RMTMwanaRBnlcCZ6TlphZly2tz/fgfrr7GsHZsO4sqfC/kB@u0CUjFr4uieJ@/gSl9BbPnl7hhDG7qLKnBSLALB7DX5lGl8yRLpU8OmJ20HTh/@6MCoeuCA/tzCDIbhh8)
] |
[Question]
[
Given a dictionary file (a text file containing a word or phrase on each line, with possible punctuation but no numbers; lines are alphabetized), you must output each combination of words where one letter can be removed from a word to make another; the removed letter should be encased in parentheses.
For example, the input
```
cat
cart
code
golf
ode
verify
versify
```
should give an output of
```
ca(r)t
(c)ode
ver(s)ify
```
Multiple ways to get the same pair must only be displayed once. You can output `scra(p)ped` or `scrap(p)ed`, but not both.
The output should be ordered *alphabetically* by the longer entry;
```
mart
mar
mat
ma
```
should have an output of
```
ma(r)
ma(t)
ma(r)t
mar(t)
```
and the latter two could be in either order.
The dictionary file may include capitalizations, spaces, hyphens, or apostrophes; these should be ignored. For instance,
```
inlay
in-play
```
should produce `in(p)lay`. Your output should all be in the same case. Extra whitespace is allowed.
Input can be STDIN or from a file; it is separated by newlines.
Output can be return value of a function or STDOUT (or written to a file if you wanted).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
(This is my first challenge on PPCG - let me know if I've done anything wrong and I'll fix it.)
[Answer]
# JavaScript (ES6), 225
A function with a string parameter, no input from file. I asked OP if this could be valid.
Test running the snippet in an EcmaScript 6 compliant browser (implementing arrow functions, template string, spread operator - Firefox, maybe Safari or MS Edge, not Chrome)
```
f=t=>t.split`
`.map(w=>(d[k=w.replace(/\W/g,'').toLowerCase()]={},k),d={},r=[]).map(w=>[...w].map((c,i,v)=>(d[v[i]='',x=v.join``]&&!d[x][w]&&r.push(d[x][w]=(v[i]=`(${c})`,v.join``)),v[i]=c)))&&r.sort((a,b)=>a.length-b.length)
// LESS GOLFED
Q=t=>{
// convert to canonical form and put in a dictionary
// each value in the dictionary is an hashtable tha will store the list
// of words that can generate the current word, removing a letter
d={},
t=t.split`\n`.map(w=>(k=w.replace(/\W/g,'').toLowerCase(),d[k]={},k))
r=[], // result array
t.forEach(w =>
[...w].forEach((c,i,v)=>( // for each letter in word, try to remove
v[i]='', x=v.join``, // build string with missing letter
v[i]='('+c+')', y=v.join``, // and build string with brackets
v[i]=c, // restore the current letter
d[x] && // if the word with removed letter is present in the dictionary
!d[x][w] && // and not already from the same generating word
r.push(d[x][w]=y) // update dictionary and add word to result array
))
)
return r.sort((a,b)=>a.length-b.length) // sort result by length
}
// TEST
function test() { R.innerHTML=f(I.value) }
```
```
textarea { height: 20em }
```
```
Test <button onclick="test()">-></button>
<span id=R></span>
<br><textarea id=I>cat
cart
code
golf
node
scraped
scrapped
verify
versify
mart
mar
mat
ma</textarea>
```
[Answer]
# Ruby, 173
```
->d{o=[]
c={}
d=d.sort_by{|w|[w.size,w]}.map{|w|w=w.upcase.gsub /[^A-Z]/,''
c[w]=l=1
w.size.times{|i|p,x,s=w[0...i],w[i],w[i+1..-1]
c[p+s]&&l!=x&&o<<p+"(#{w[i]})"+s
l=x}}
o}
```
Test it here: <http://ideone.com/86avbe>
Readable version here: <http://ideone.com/ynFItB>
[Answer]
# Perl -an0, 101+3 bytes
```
@F=sort{length$a<=>length$b}map{s/\W//g;lc}@F;map{$`.$'~~@F?print"$`($1)$'\n":$\while/(.)(?!\1)/g}@F;
```
where
* `@F` is the dictionary, stored in an array, provided by runtime flag magic. *(b-oost, BoO#@%@#$%$#@T)*
* `map{s/\W//g;lc}@F` removes all symbols from the words and turns everything lowercase. *(boost, boot)*
* `sort{length$b<=>length$a}` sorts on length. *(boot, boost)*
* `map{ (...) while/(.)(?!\1)/g}@F` matches all characters that aren't followed up by the same character *([b]oot, bo[o]t,boo[t],...)*
* `print"$`($1)$'\n"` prints the parts that precede, parenthesize, and succeed a match... *(boo(s)t)*
* `if $`.$'~~@F` ...if the concatenation of everything before and after the match is in the dictionary. *([boo]s[t])*
[Answer]
# Ruby, 211
I decided I'd take a different approach to solve this, using regex.
```
->d{o=[]
d.map{|x|x.upcase!.gsub! /[-' ]/,''}
d.map{|x|(x.size+1).times{|i|o+=d.map{|w|w.b.sub! /(#{x[0...i]})(.)(#{x[i..-1]})/,'\1(\2)\3'if w[i]!=w[i+1]}}}
o.compact.sort_by{|w|[w.size,w.gsub(/[()]/,'')]}.uniq}
```
[Answer]
# Perl 5, 210
The code loads the input in an sorted array, and checks for each value against all values in the array that are 1 byte longer.
```
map{@W=split//,$w=$_;map{@X=split//,$x=$_;if(@W+1==@X){$i=0;while($W[$i]eq$X[$i]&&$i<@W){$i++}$c=$X[$i];$e=substr($w,$i);print substr($w,0,$i)."($c)$e\n",if substr($x,$i+1)eq$e}}@D}@D=sort(map{s/[^\w]//g;lc}<>)
```
### Test
```
$ perl dictionairy_same_words.pl dictionairywords.txt
ca(r)t
in(p)lay
ma(r)
ma(t)
mar(t)
ma(r)t
(c)ode
ver(s)ify
```
[Answer]
# Haskell, 201 bytes
```
import Data.List
import Data.Char
a#(b:c)=(a,b,c)
g a=[l++'(':m:')':n|x<-a,((l,m,n):_)<-[[o|o@(i,j,k)<-zipWith(#)(inits x)$init$tails x,elem(i++k)a]]]
f=sortOn length.g.map(filter isLetter.map toLower)
```
I'm not sure what input format is allowed. `f` takes a list of strings. If only a single string (with nl separated words) is allowed, add `.lines` to `f` (+6 bytes).
Usage example:
```
f ["cat","cart","code","golf","od-e","verify","versify","on","s-o-n","Scrapped","scraped"]
["(s)on","ca(r)t","(c)ode","ver(s)ify","scra(p)ped"]
```
How it works: turn every word to lowercase and keep only the letters. Split every word `x` into two parts at every possible position and make triples `(i,j,k)` where `i` is the first part, `j` is the first character of the second part and `k` is the tail of the second part. Keep the triples where `i++k` also appears in the word list. If this list is non-empty, take the first element, call it `(l,m,n)`. Turn all those list heads into the required output format by surrounding `m` with `()` and putting it between `l` and `n`.
] |
[Question]
[
I like to golf in `dc`, but I'm sometimes frustrated because `dc` doesn't have bitwise operations.
# Challenge
Provide four named functions which implement the equivalent of the c bitwise operations `&`, `|`, `~` and `^` (bitwise AND, OR, NOT and XOR). Each function will take two operands (`~` takes only one) which are at least 32-bit unsigned integers. Each function will return an unsigned integer of the same bit-width as the operands.
### Restriction
You may only use operations that are supported by `dc`. These are:
* `+` `-` `*` `/` Arithmetic addition, subtraction, multiplication and division
* `~` modulo (or divmod if your language supports it)
* `^` exponentiation
* `|` modular exponentiation
* `v` square root
* `>` `>=` `==` `!=` `<=` `<` standard equality/inequality operators
* `>>` `<<` bit shift operators. `dc` doesn't have these, but since they are trivially implemented in terms of division/multiplication by powers of 2, then I will allow these.
Control structures in `dc` my be clumsily built using (recursive) macros and (in)equality operations. You may use whatever built-in control structures your language has.
You **may also use logical operators** `&&` `||` `!`, even though these aren't directly available in `dc`.
You **must not use the bitwise operators** `&`, `|`, `~` and `^` or any functions that trivially implement them.
In addition you must not use built-in base-conversion-of-string operators or functions.
---
Please also consider providing a test program or online compiler snippet (not included in the golf score) to help verify your answer.
[Answer]
# C, 134
The C preprocessor is pretty fun to abuse. Basically this macro defines the 3 functions, `a`, `o`, and `x`, for `and`, `or`, and `xor` respectively. The only difference in the algorithm for these operations is the criteria for setting the bit in the result.
`not` is the function `n`.
```
#define f(n,c)n(a,b){for(r=0,i=31;i+1;--i)if(((a>>i)%2+(b>>i)%2)c)r+=1<<i;return r;}
i,r;n(a){return 0xffffffff-a;}f(a,/2)f(o,)f(x,%2)
```
Tester program (takes a long time, I didn't spend any time optimizing it at all, but it does test every test case possible, beside MAX\_INT related ones):
```
#define m_assert(expected, condition, actual)\
if(!((expected) condition (actual)))\
printf("assert fail @ line %i, expected: %x, actual %x, condition "#condition"\n", __LINE__, expected, actual);
int main() {
unsigned int j,k;
for(j=0; j<0xffff; ++j) {
m_assert(~j, ==, n(j));
for(k=0; k<0xffff; ++k) {
m_assert(j & k, ==, a(j,k));
m_assert(j | k, ==, o(j,k));
m_assert(j ^ k, ==, x(j,k));
}
}
```
[Answer]
# ised 76 bytes
ised also doesn't have bitwise operations - usually annoying, but now welcome, because we really *need* to implement them.
Functions will be stored in numbered memory slots (no verbose names).
Conversion to and from binary:
```
@5{:x/2^[32]%2:};
@6{:x@:2^[32]:};
```
NOT could be `@1{:$6::{1-$5::x}:}` but it's obviously easier to just subtract:
```
@1{:2^32-x-1:};
```
OR:
```
@2{:$6::{$5::{x_0}:+$5::{x_1}>0}:};
```
AND:
```
@3{:$6::{$5::{x_0}:*$5::{x_1}}:};
```
XOR:
```
@4{:$6::{$5::{x_0}:<>$5::{x_1}}:};
```
This would bring us to 156 bytes (with newlines and semicolons). A test code would just be (NOT, OR, AND, XOR in succession, found under names $1,$2,$3,$4):
```
> $1::{6}
4294967289
> $2::{12 11}
15
> $3::{12 11}
8
> $4::{12 11}
7
```
---
But of course OR and NOT are all we really need and things can be simplified:
```
@1{:2^32-x-1:};
@2{:@+{2^U{?{$5::x}%32}}:};
@3{:${1 2 1}::x:};
@4{:$3::{$2::x${1 2}::x}:};
@5{:x/2^[32]%2:};
```
That's 109 characters. When newlines and semicolons are skipped, and with a bit more golfing, we have 76 characters:
```
@3{@1{:2^32-x-1:}@2{:@+{2^U{?{x/2^[32]%2}%32}}:}$1}@4{{:$2::x${1 2}::x:}$3};
```
[Answer]
# Nim (537)(490)
*Nim Compiler 0.10.2*
I've been looking for a reason to learn nim so here we go.
For code golf, I have leveraged variable parameters and implicit returns. The variable parameters, [per the documentation](http://nim-lang.org/tut1.html#parameters) are less stack efficient. Personally, I find the implicit returns harder to read and would probably only use them in trivial procedures.
As for the algorithms, they are simple enough. For all operations except NOT, we compare each bit and manually compare them to our expected truth table. Set each bit as needed along the way in our output variable. In Nim, result is the implicit return value.
I wasn't sure if we were allowed to use built-in OR and AND for asserting two boolean conditions so the notZero procedure was put in their place.
```
proc s(x, y, b: var int)=
x = x div 2
y = y div 2
b *= 2
proc n(x: var int): int =
return -(x+1)
proc a(x, y: var int): int =
var b = 1
while x > 0 and y > 0:
if (x mod 2 + y mod 2) == 2:
result += b
s(x,y,b)
proc o(x, y: var int): int =
var b = 1
while x + y > 0:
if (x mod 2 + y mod 2) >= 1:
result += b
s(x,y,b)
proc r(x, y: var int): int =
var b = 1
while x + y > 0:
if (x mod 2 + y mod 2) == 1:
result += b
s(x,y,b)
```
Still looking for a better method...
[Here is the non-squished version plus full test harness to run on your own machine.](https://gist.github.com/corytodd/4269f212de3ea3225f04)
If you just want to run a couple of inputs, here is [test case lite](http://goo.gl/QAqfMz).
[Answer]
# CJam, 71 bytes
```
{:F;0{:R;2md@2md@+F~!2I#*R+}64fI\;\;}:B{"2-"B}:A{'!B}:O{0SB}:N{'(B}:X];
```
### Explanation
```
"B : UInt64 UInt64 String -> UInt64
Computes a bitwise operation on the two given unsigned integers. The operation
is defined by the logical inverse of the result of evaluating the given string
given the sum of two input bits.";
{
:F; "Save the operation string.";
0 "Initialize the result to 0.";
{ "For I from 0 through 63:";
:R; "Save the result.";
2md@2md@ "Divide each input by 2 and collect the remainders as the
next pair of bits to process.";
+F~! "Compute the logical inverse of the result of evaluating
the operation string given the sum of the two bits.";
2I#* "Adjust the resulting bit to be in the correct output
position by multiplying it by 2^I.";
R+ "Add the location-adjusted bit to the result.";
}64fI
\;\; "Clean up.";
}:B
"A : UInt64 UInt64 -> UInt64
Computes the bitwise AND of the two given unsigned integers.
This is done by passing the inputs along to B with an operation such that:
bit_out = !((bit_in_1 + bit_in_2) - 2)";
{"2-"B}:A
"O : UInt64 UInt64 -> UInt64
Computes the bitwise OR of the two given unsigned integers.
This is done by passing the inputs along to B with an operation such that:
bit_out = !(!(bit_in_1 + bit_in_2))";
{'!B}:O
"N : UInt64 -> UInt64
Computes the bitwise NOT of the given unsigned integer.
This is done by passing the input and 0 along to B with an operation such that:
bit_out = !((bit_in + 0))";
{0SB}:N
"X : UInt64 UInt64 -> UInt64
Computes the bitwise XOR of the two given unsigned integers.
This is done by passing the inputs along to B with an operation such that:
bit_out = !((bit_in_1 + bit_in_2) - 1)";
{'(B}:X
]; "Clean up.";
```
### [Test suite](http://cjam.aditsu.net/#code=N%3AL%3B%0A%7B%3AF%3B0%7B%3AR%3B2md%402md%40%2BF~!2I%23*R%2B%7D64fI%5C%3B%5C%3B%7D%3AB%7B%222-%22B%7D%3AA%7B'!B%7D%3AO%7B0SB%7D%3AN%7B'(B%7D%3AX%5D%3B%0A%7B%3BY32%23__mr*%5Cmr%2B%7D2e2%252%2F%7B~%3AU%3B%3AV%3B%22A%26O%7CX%5E%222%2F%7B%5B%7BUS%40SV%22%20%3D%20%22UV5%24~L%7D%2F9%242%24%3D%7B%5D%3B%7D%7B%5DoLo%7D%3F%7D%2F%22N~%22%5B%7BU%22%20%3D%20%22U3%24~Y64%23(%26L%7D%2F6%242%24%3D%7B%5D%3B%7D%7B%5DoLo%7D%3F%7D%2F)
This code tests runs of each of my and, or, not, and xor functions 100 times with uniformly-distributed 64-bit unsigned inputs and compares the result with that produced by the built-in operator. Due to gratuitous use of the eval operator, it's quite slow and may take up to about a minute with the online interpreter. But if all goes well, execution should end with no output, because any discrepancies found are printed.
```
N:L;
{:F;0{:R;2md@2md@+F~!2I#*R+}64fI\;\;}:B{"2-"B}:A{'!B}:O{0SB}:N{'(B}:X];
{;Y32#__mr*\mr+}2e2%2/{~:U;:V;"A&O|X^"2/{[{US@SV" = "UV5$~L}/9$2$={];}{]oLo}?}/"N~"[{U" = "U3$~Y64#(&L}/6$2$={];}{]oLo}?}/
```
[Answer]
# JavaScript ~~294~~ 267
Was able to shave off a few more bytes with @AlexA.'s and @kennytm's suggestions.
Functions:
```
B=(n,m,t)=>{for(var p=4294967296,y=0;p>=1;p/=2)y+=t=='x'&&(n>=p||m>=p)&& !(n>=p&&m>=p)?p:0,y+=t=='a'&&n>=p&&m>=p?p:0,y+=t=='o'&&(n>=p||m>=p)?p:0,n-=n>=p?p:0,m-=m>=p?p:0
return y}
N=(n)=>{return 4294967295-n}
A=(n,m)=>B(n,m,'a')
O=(n,m)=>B(n,m,'o')
X=(n,m)=>B(n,m,'x')
```
example:
```
var n = 300;
var m = 256;
console.log(X(n,m) + ", " + (n ^ m));
console.log(O(n,m) + ", " + (n | m));
console.log(A(n,m) + ", " + (n & m));
console.log(N(n) + ", " + (~n>>>0));
console.log(N(m) + ", " + (~m>>>0));
```
output:
```
44, 44
300, 300
256, 256
4294966995, 4294966995
4294967039, 4294967039
```
] |
[Question]
[
# Food shortage in the Snakepit
For the first time in 35 years, the snakepit is running out of food. The inhabitant snakes now have to fight each other in order to survive this food shortage. Only one snake can stand at the top of the food chain!
---
## Leaderboard
*Not here yet!*
*Last update on February, 24th*
[Link to visualizations of last matches](https://github.com/redevined/Snakepit/tree/master/records)
---
## Description
If you want to fight for the last remaining apples/cherries/whatever, you have to provide a snake in form of a program that accepts a given input and returns its next move.
The only twist is that you're not alone in your pit. Another snake will try to get the rare food too! But it's dark inside the snakepit so you can only see yourself and the apple. Crashing into your opponent will result in your death, just like biting yourself or hitting a wall. Additionally, because apples are rare these days, you starve if your opponent ate enough to reach a length of 7.
The snakepit is a two-dimensional map with a width and height of 15, while the outermost tiles build an impassable wall:
```
0 1 2 . . . c d e
0 # # # # # # # # #
1 # #
2 # x #
. # #
. # #
. # #
c # #
d # #
e # # # # # # # # #
```
Coordinates are zero-indexed, so the point where the `x` is would be `12,2`.
Your bot will be called with two arguments:
* The location of the food
* The locations of your body segments, separated by `/`
It should then write one of the following to stdout:
* `L` for a quarter left turn as its next move
* `R` for a quarter right turn
* Anything else for a move in the same direction
Example:
```
Projects/Snakepit> python bot.py 12,2 4,8/4,9/3,9/2,9
'R'
Projects/Snakepit>
```
---
## Rules
Your bot is allowed to:
* Output anything, because anything is a valid move
* Read/write files in its own directory which is located under ./snakes/ThisIsYourSnake
* Run on Ubuntu 14.04 and Windows 7 (it actually has to)
Your bot must not:
* Read/write files outside its own directory
* Use external resources such as the internet
* Have a runtime above 10 seconds per execution
You have to provide in your answer:
* The source code of the bot
* A bot/snake name
* (Your own name)
* A command to run your bot
>
> If you want to make my life easier, please provide a line like `CoolSnake MyOwnName python bot.py`.
>
>
>
---
## Scoring
Your snake gets a point for winning a game against another snake. A game is won under the following circumstances:
* Your opponent hits himself, you or a wall
* You reach length 7
Additionally, both snakes starve after 200 cycles.
Each snake will fight 10 matches for their survival against each other snake.
---
## Example Bots
Just to give you an idea, I'll provide these two (participating) example snakes:
**SneakySnake**
```
#!/usr/bin/env python
import sys, random
def main(food, me) :
food = [int(i) for i in food.split(",")]
me = [[int(i) for i in seg.split(",")] for seg in me.split("/")]
head = me[0]
v = [head[0] - me[1][0], head[1] - me[1][1]]
if food[0] < head[0] :
vn = [-1, 0]
elif food[0] > head[0] :
vn = [1, 0]
elif food[0] == head[0] :
if food[1] < head[1] :
vn = [0, -1]
elif food[1] > head[1] :
vn = [0, 1]
if v == vn :
return "..."
elif [-v[1], v[0]] == vn :
return "R"
elif [v[1], -v[0]] == vn :
return "L"
else :
return random.choice(("R", "L"))
if __name__ == "__main__" :
print main(*sys.argv[1:3])
```
>
> `SneakySnake Cipher python bot.py`
>
>
>
**ViciousViper**
```
#!/usr/bin/env python
import sys, random
def main(food, me) :
food = [int(i) for i in food.split(",")]
me = [[int(i) for i in seg.split(",")] for seg in me.split("/")]
head = me[0]
v = [head[0] - me[1][0], head[1] - me[1][1]]
vn = [food[0] - head[0], food[1] - head[1]]
if 0 not in vn :
vn[v.index(0)-1] = 0
vn[vn.index(0)-1] = vn[vn.index(0)-1] / abs(vn[vn.index(0)-1])
if v == vn :
return "..."
elif [v[0] + vn[0], v[1] + vn[1]] == [0, 0] :
return random.choice(("R", "L"))
else :
return "R" if [-v[1], v[0]] == vn else "L"
if __name__ == "__main__" :
print main(*sys.argv[1:3])
```
>
> `ViciousViper Cipher python bot.py`
>
>
>
And their matches:


## Example match 3
## Control program
You can find the control program on [github](https://github.com/redevined/Snakepit), along with all bots and records of past matches.
**Requirements:**
* Python 2 + the libraries `numpy` and `pillow` (you can check if they are present via `python -c "import numpy, PIL"`, if it throws errors the modules are missing)
* Copying the full folder structure is required in order for the controller to work
* Register your bot(s) in the `./snakes/list.txt` file in the style of `CoolSnake MyOwnName Command To Run My Bot`
* Place your bot inside a directory with its name under `./snakes`
* Neither your, nor your bot's name is allowed to contain whitespaces!
**Usage:**
>
> `python run.py [-h] [-n int] [-s int] [-l int] [-c int] [-g]`
>
>
>
`python run.py` will run the tournament with all bots registered in list.txt and the standard properties. Advanced options are:
* `-h` displays a help message
* `-n int` rounds of battles for each combination of opponents
* `-s int` determines the size of the grid (width and height)
* `-l int` sets the required length to win
* `-c int` sets the limit of cycles
* `-g` or `--no-gifs` creates no gifs of the matches
[Answer]
# Zen - C++enter image description here
This [Codémon](https://codegolf.stackexchange.com/a/46958/38099) is not here to eat but to fight. He knows that a dead enemy will not stole his apples.
---
`Name| Author |Launch with`
## `Zen GholGoth21 Zen.exe`
---
## Strategy
Everybody (excepted CircleOfLife) rush to the apples, but not Zen, not always. If the enemy can reach the food before him, he simply wait at the center (what? but what are you doing here, CircleOfLife?). Else, Zen goes at the apple and turns around while waiting that something happens. In fact, he uses the apple as a bait.
I didn't coded anything against the curious strategy of CircleOfLife because he can only win with very very much luck.
## The code
This is the complete code of the C++ project. Cut the 11 source files and the Makefile and compile with `make`
```
$ cat src/* Makefile
/*
* @file Enemy.cpp
* @author GholGoth21
* @date Créé le 1 mars 2015 à 14:10
*/
#include "Enemy.h"
#include <fstream>
Enemy::Enemy()
{
}
Enemy::~Enemy()
{
}
std::ostream &operator<<(std::ostream &os, const Enemy& e)
{
return os<<e.m_pos<<" "<<e.m_date;
}
std::istream &operator>>(std::istream &is, Enemy& e)
{
return is>>e.m_pos>>e.m_date;
}
int Enemy::distTo(int2 const &target, int date) const
{
return m_pos.distTo(target)-(date-m_date);
}
bool Enemy::recentActivity(int2 const &pos, int date, int maxDelay) const
{
return pos.distTo(m_pos)<=date-m_date && date-m_date<=maxDelay;
}
/*
* @file Enemy.h
* @author GholGoth21
* @date Créé le 1 mars 2015 à 14:10
*/
#ifndef ENEMY_H
#define ENEMY_H
#include "int2.h"
class Enemy
{
public:
Enemy();
virtual ~Enemy();
public:
void setPos(int2 const &pos, int date) { m_pos=pos; m_date=date; }
int distTo(int2 const &target, int date) const;
int2 const &pos() const { return m_pos; }
bool recentActivity(int2 const &pos, int date, int maxDelay) const;
friend std::ostream &operator<<(std::ostream &os, const Enemy& e);
friend std::istream &operator>>(std::istream &is, Enemy& e);
private:
int2 m_pos;
int m_date;
};
#endif /* ENEMY_H */
/*
* @file Snake.cpp
* @author GholGoth21
* @date Créé le 28 février 2015 à 17:47
*/
#include "Snake.h"
#include "enums.h"
#include "StrManip.h"
#include "Enemy.h"
#include <vector>
#include <cmath>
Snake::Snake(std::string const &body)
{
std::vector<std::string> posList;
split(body, '/', posList);
for(auto &pos : posList)
m_body.push_back(int2(pos));
}
Snake::~Snake()
{
}
Command Snake::move(int2 food, int date, Enemy const &enemy)
{
Command bestCommand[Command::count];
int myDist=curPos().distTo(food);
int enemyDist=enemy.distTo(food,date);
if(myDist>=enemyDist && enemyDist>2)
{
orderCommand(int2(MAPSIZE/2,MAPSIZE/2), bestCommand);
for(int i=0; i<Command::count; i++)
if(validCommand(bestCommand[i]) && !enemy.recentActivity(nextPos(bestCommand[i]),date,5))
return bestCommand[i];
}
if((myDist==1 && enemyDist>((len()-1)/2)*2+3) || enemyDist<-5)
{
orderCommand(food, bestCommand);
for(int i=0; i<Command::count; i++)
if(validCommand(bestCommand[i]))
return bestCommand[i];
}
int2 embushPoint;
int minDist=-1;
foreach_enum(Direction, d)
{
int2 point(food+d.vector());
int dist=point.quadDistTo(enemy.pos());
if(dist<minDist || minDist<0)
{
minDist=dist;
embushPoint=point;
}
}
if(curPos().distTo(embushPoint)<enemy.distTo(embushPoint,date)-((len()-1)/2)*2)
{
int minimalAction=-1;
int qMinDist = curPos().quadDistTo(embushPoint);
Command minimalCommand;
foreach_enum(Command, c)
{
int2 np=nextPos(c);
int qDist = np.quadDistTo(embushPoint);
if((qDist<minimalAction || minimalAction<0) && qDist>qMinDist && validCommand(c))
{
minimalAction=qDist;
minimalCommand=c;
}
}
return minimalCommand;
}
else
{
orderCommand(embushPoint, food, bestCommand);
for(int i=0; i<Command::count; i++)
if(validCommand(bestCommand[i]) && nextPos(bestCommand[i])!=food)
return bestCommand[i];
}
return Command::forward;
}
bool Snake::validCommand(Command c) const
{
if(!c.isValid())
return false;
int2 np = nextPos(c);
if(!(0<np.x && np.x<MAPSIZE-1 && 0<np.y && np.y<MAPSIZE-1))
return false;
for(unsigned int i=2; i<m_body.size()-1; i++)
if(np==m_body.at(i))
return false;
return true;
}
bool Snake::isStarting() const
{
if(m_body.size()==3)
{
if(m_body.at(0)==int2(3,(MAPSIZE)/2) && m_body.at(1)==int2(2,(MAPSIZE)/2) && m_body.at(2)==int2(1,(MAPSIZE)/2))
return true;
else if(m_body.at(0)==int2(MAPSIZE-4,(MAPSIZE)/2) && m_body.at(1)==int2(MAPSIZE-3,(MAPSIZE)/2) && m_body.at(2)==int2(MAPSIZE-2,(MAPSIZE)/2))
return true;
}
return false;
}
void Snake::orderCommand(int2 target, Command *tab)
{
int weight[Command::count];
foreach_enum(Command, c)
{
int2 np = nextPos(c);
weight[c]=np.quadDistTo(target);
tab[c]=c;
}
for(int i=0; i<Command::count-1; i++)
{
while(i>=0 && weight[tab[i]]>weight[tab[i+1]])
{
varSwitch(tab[i], tab[i+1]);
i--;
}
}
}
void Snake::orderCommand(int2 target1, int2 target2, Command *tab)
{
int weight[Command::count];
foreach_enum(Command, c)
{
int2 np = nextPos(c);
weight[c]=np.quadDistTo(target1)+np.quadDistTo(target2);
tab[c]=c;
}
for(int i=0; i<Command::count-1; i++)
{
while(i>=0 && weight[tab[i]]>weight[tab[i+1]])
{
varSwitch(tab[i], tab[i+1]);
i--;
}
}
}
/*
* @file Snake.h
* @author GholGoth21
* @date Créé le 28 février 2015 à 17:47
*/
#ifndef SNAKE_H
#define SNAKE_H
#include "int2.h"
#include <vector>
#define MAPSIZE 15
class Enemy;
class Snake
{
public:
Snake(std::string const &body);
virtual ~Snake();
public:
Command move(int2 food, int date, Enemy const &enemy);
Direction curDir() const { return (m_body.at(0)-m_body.at(1)).direction(); }
int2 curPos() const { return m_body.at(0); }
int2 nextPos(Command c) const { return curPos()+curDir().applyCommand(c).vector(); }
bool validCommand(Command c) const;
bool isStarting() const;
void orderCommand(int2 target, Command *tab);
void orderCommand(int2 target1, int2 target2, Command *tab);
int len() const { return m_body.size(); }
private:
std::vector<int2> m_body;
};
#endif /* SNAKE_H */
/*
* @file StrManip.cpp
* @author GholGoth21
* @date Créé le 7 février 2015 à 17:26
*/
#include "StrManip.h"
#include <sstream>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim))
elems.push_back(item);
return elems;
}
int atoi(std::string const &text)
{
std::stringstream ss(text);
int val;
ss >> val;
return val;
}
/*
* @file StrManip.h
* @author GholGoth21
* @date Créé le 7 février 2015 à 17:26
*/
#ifndef STRMANIP_H
#define STRMANIP_H
#include <string>
#include <vector>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems);
int atoi(std::string const &text);
#endif /* STRMANIP_H */
/*
* @file enums.cpp
* @author GholGoth21
* @date Créé le 28 février 2015 à 17:55
*/
#include "enums.h"
#include "int2.h"
Command Direction::turnTo(Direction newDir) const
{
if(!isValid() || !newDir.isValid())
return Command::count; //Invalid
else if((m_value==Direction::up && newDir==Direction::left) || (m_value==Direction::left && newDir==Direction::down) ||
(m_value==Direction::down && newDir==Direction::right) || (m_value==Direction::right && newDir==Direction::up))
return Command::left;
else if((m_value==Direction::up && newDir==Direction::right) || (m_value==Direction::right && newDir==Direction::down) ||
(m_value==Direction::down && newDir==Direction::left) || (m_value==Direction::left && newDir==Direction::up))
return Command::right;
else if(m_value==newDir)
return Command::forward;
else
return Command::count; // Invalid
}
Direction Direction::applyCommand(Command c) const
{
if(c==Command::forward)
return m_value;
else if(c==Command::left)
{
switch(m_value)
{
case Direction::left:
return Direction::down;
case Direction::up:
return Direction::left;
case Direction::right:
return Direction::up;
case Direction::down:
return Direction::right;
default:
break;
}
}
else if(c==Command::right)
{
switch(m_value)
{
case Direction::left:
return Direction::up;
case Direction::up:
return Direction::right;
case Direction::right:
return Direction::down;
case Direction::down:
return Direction::left;
default:
break;
}
}
return Direction::count; // Invalid
}
int2 Direction::vector() const
{
switch(m_value)
{
case Direction::left:
return int2(-1,0);
case Direction::up:
return int2(0,-1);
case Direction::right:
return int2(1,0);
case Direction::down:
return int2(0,1);
default:
return int2(0,0);
}
}
std::ostream &operator<<(std::ostream &os, const Command& c)
{
switch(c.m_value)
{
case Command::left:
return os<<"L";
case Command::right:
return os<<"R";
default:
return os<<"F";
}
}
/*
* @file enums.h
* @author GholGoth21
* @date Créé le 28 février 2015 à 17:55
*/
#ifndef ENUMS_H
#define ENUMS_H
#include <ostream>
struct int2;
#define DECL_ENUM_STRUCT(_name) \
_name() : m_value(static_cast<Type>(0)) {} \
_name(Type value) : m_value(value) {} \
_name(int value) : m_value(static_cast<Type>(value)) {} \
static Type begin() { return static_cast<Type>(0); } \
static Type end() { return count; } \
_name &operator++() { m_value=static_cast<Type>(static_cast<int>(m_value)+1); return *this; } \
operator int() const { return static_cast<Type>(m_value); } \
Type m_value;
#define foreach_enum(_type,_var) for(_type _var = _type::begin(); _var<_type::end(); ++_var)
struct Command
{
enum Type
{
left,
forward,
right,
count
};
bool isValid() const { return m_value<count; }
friend std::ostream &operator<<(std::ostream &os, const Command& c);
DECL_ENUM_STRUCT(Command)
};
struct Direction
{
enum Type
{
left,
up,
right,
down,
count
};
bool isValid() const { return m_value<count; }
Command turnTo(Direction newDir) const;
Direction applyCommand(Command c) const;
int2 vector() const;
DECL_ENUM_STRUCT(Direction)
};
#endif /* ENUMS_H */
/*
* @file int2.cpp
* @author GholGoth21
* @date Créé le 28 février 2015 à 17:37
*/
#include "int2.h"
#include "enums.h"
#include "StrManip.h"
#include <vector>
#include <cmath>
int2::int2()
{
}
int2::~int2()
{
}
int2::int2(std::string const &text)
{
std::vector<std::string> posList;
split(text, ',', posList);
x=atoi(posList.at(0));
y=atoi(posList.at(1));
}
Direction int2::direction() const
{
if(x==0 && y==0)
return Direction::count; // Invalid
else if(y>=std::abs(x))
return Direction::down;
else if(x>=std::abs(y))
return Direction::right;
else if(x<=-std::abs(y))
return Direction::left;
else
return Direction::up;
}
Direction int2::secondary() const
{
if(x==0 || y==0)
return Direction::count; //Invalid
else if(y<=std::abs(x) && y>=0)
return Direction::down;
else if(x<=std::abs(y) && x>=0)
return Direction::right;
else if(x>=-std::abs(y) && x<=0)
return Direction::left;
else
return Direction::up;
}
int int2::distTo(int2 const &other) const
{
return std::abs(x-other.x)+std::abs(y-other.y);
}
int int2::quadDistTo(int2 const &other) const
{
return sq(x-other.x)+sq(y-other.y);
}
int2 int2::operator+(int2 const &other) const
{
return int2(x+other.x,y+other.y);
}
int2 int2::operator-(int2 const &other) const
{
return int2(x-other.x,y-other.y);
}
std::ostream &operator<<(std::ostream &os, const int2& c)
{
return os<<c.x<<","<<c.y;
}
std::istream &operator>>(std::istream &is, int2& c)
{
std::string text;
is>>text;
c=int2(text);
return is;
}
/*
* @file int2.h
* @author GholGoth21
* @date Créé le 28 février 2015 à 17:37
*/
#ifndef INT2_H
#define INT2_H
#include "enums.h"
#include <string>
struct int2
{
public:
int2();
int2(int p_x, int p_y) : x(p_x), y(p_y) {}
int2(std::string const &text);
virtual ~int2();
public:
Direction direction() const;
Direction secondary() const;
int distTo(int2 const &other) const;
int quadDistTo(int2 const &other) const;
int2 operator+(int2 const &other) const;
int2 operator-(int2 const &other) const;
bool operator==(int2 const &other) const { return x==other.x && y==other.y; }
bool operator!=(int2 const &other) const { return x!=other.x || y!=other.y; }
friend std::ostream &operator<<(std::ostream &os, const int2& c);
friend std::istream &operator>>(std::istream &is, int2& c);
public:
int x;
int y;
};
inline int sq(int val) { return val*val; }
template<typename T>
inline void varSwitch(T &a, T &b) { T tmp=a; a=b; b=tmp; }
#endif /* INT2_H */
/*
* @file main.cpp
* @author GholGoth21
* @date Créé le 28 février 2015 à 17:23
*/
#include "int2.h"
#include "Snake.h"
#include "Enemy.h"
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
/*
* @brief La fonction principale du programme.
* @param argc Le nombre de paramètres passés en ligne de commandes.
* @param argv La liste des paramètres passés en ligne de commandes.
*/
int main(int argc, char** argv)
{
/* Error handling */
if(argc<3)
{
cerr<<"Error : not enough arguments on the command line."<<endl;
cout<<"F"<<endl;
return 1;
}
/* Init and load */
int2 prevFood;
int date = 0;
Enemy enemy;
ifstream load("PreviousState.txt");
if(load)
{
load>>date;
load>>prevFood;
load>>enemy;
load.close();
}
int2 food(argv[1]);
Snake me(argv[2]);
if(me.isStarting())
{
date=0;
if(me.curPos().x<MAPSIZE/2)
enemy.setPos(int2(MAPSIZE-4,MAPSIZE/2), 0);
else
enemy.setPos(int2(3,MAPSIZE/2), 0);
}
else if(prevFood!=food && me.curPos()!=prevFood)
{
enemy.setPos(prevFood, date);
}
/* Moving */
cout<<me.move(food,date,enemy)<<endl;
/* Saving */
ofstream save("PreviousState.txt");
if(save)
{
save<<++date<<endl;
save<<food<<endl;
save<<enemy<<endl;
save.close();
}
return 0;
}
# Makefile
HEADERS = $(wildcard $(SRCPATH)/*.h)
SOURCES = $(wildcard $(SRCPATH)/*.cpp)
OBJECTS = $(patsubst $(SRCPATH)/%.cpp,$(BUILDPATH)/%.o,$(SOURCES))
M = Makefile
CFLAGS = -Wall -std=c++11
BINPATH = bin
BUILDPATH = build
SRCPATH = src
ifeq ($(OS),Windows_NT)
EXE = Zen.exe
else
EXE = Zen
endif
$(BINPATH)/$(EXE): $(BINPATH) $(BUILDPATH) $(OBJECTS)
g++ -o $@ $(OBJECTS)
$(BUILDPATH)/%.o: $(SRCPATH)/%.cpp $(HEADERS) $M
g++ $(CFLAGS) -o $@ -c $<
$(BINPATH) $(BUILDPATH):
mkdir $@
clean:
rm $(OBJECTS)
```
Or download the zip file : [Zen.zip](http://dl.free.fr/kcxmHabeY)
## Results
```
| Name | Master | Score |
|--------------|------------|-------|
| Zen | GholGoth21 | 24 |
| SneakySnake | Cipher | 10 |
| ViciousViper | Cipher | 6 |
| CircleOfLife | Manu | 4 |
```
And some typical battles (ViciousViper vs Zen and SneakySnake vs Zen) :
 
**Edit** : I add this very intersting battle against CircleOfLife :

[Answer]
## CircleOfLife (Java)
`CircleOfLife Manu java CircleOfLife` (Compile with `javac CircleOfLife.java`)
Runs towards the middle and stays there. I hope that some submissions will crash into it on their way to the food.
```
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
public class CircleOfLife {
private static final int UP = 0;
private static final int DOWN = 1;
private static final int LEFT = 2;
private static final int RIGHT = 3;
private static final String GO_RIGHT = "R";
private static final String GO_LEFT = "L";
private static final String GO_FORWARD = "F";
private static int currentDirection = UP;
private static List<Point> snakeParts = new ArrayList<>();
public static void main(String[] args) {
String[] parts = args[1].split("/");
for (String part : parts) {
String[] pos = part.split(",");
int x = Integer.parseInt(pos[0]);
int y = Integer.parseInt(pos[1]);
snakeParts.add(new Point(x,y));
}
Point head = snakeParts.get(0);
Point neck = snakeParts.get(1);
if (head.y - neck.y == 1) {
currentDirection = DOWN;
} else if (head.x - neck.x == -1) {
currentDirection = LEFT;
} else if (head.x - neck.x == 1) {
currentDirection = RIGHT;
}
if (isInMiddle(head)) {
makeCircle();
} else {
runToMiddle();
}
}
private static void makeCircle() {
if (!isInMiddle(snakeParts.get(1))) {
System.out.println(GO_FORWARD);
return;
}
Point head = snakeParts.get(0);
Point neck = snakeParts.get(1);
String output = GO_FORWARD;
if (head.x == 8 && neck.x == 8) {
output = currentDirection == UP ? GO_LEFT : GO_RIGHT;
} else if (head.x == 7 && neck.x == 7) {
output = currentDirection == UP ? GO_RIGHT : GO_LEFT;
} else if (head.y == 8 && neck.y == 8) {
output = currentDirection == RIGHT ? GO_LEFT : GO_RIGHT;
} else if (head.y == 7 && neck.y == 7) {
output = currentDirection == RIGHT ? GO_RIGHT : GO_LEFT;
}
System.out.println(output);
}
private static void runToMiddle() {
Point head = snakeParts.get(0);
int dX = 8 - head.x;
int dY = 8 - head.y;
String output = GO_FORWARD;
if (Math.abs(dX) > Math.abs(dY)) {
switch (currentDirection) {
case DOWN: output = dX < 0 ? GO_RIGHT : GO_LEFT; break;
case UP: output = dX < 0 ? GO_LEFT : GO_RIGHT; break;
case RIGHT: output = dX < 0 ? GO_RIGHT : GO_FORWARD; break;
case LEFT: output = dX < 0 ? GO_FORWARD : GO_RIGHT; break;
}
} else {
switch (currentDirection) {
case DOWN: output = dY < 0 ? GO_RIGHT : GO_FORWARD; break;
case UP: output = dY < 0 ? GO_FORWARD : GO_RIGHT; break;
case RIGHT: output = dY < 0 ? GO_LEFT : GO_RIGHT; break;
case LEFT: output = dY < 0 ? GO_RIGHT : GO_LEFT; break;
}
}
System.out.println(output);
}
public static boolean isInMiddle(Point snakePart) {
if ((snakePart.x == 7 || snakePart.x == 8) &&
(snakePart.y == 7 || snakePart.y == 8)) {
return true;
}
return false;
}
}
```
] |
[Question]
[
Given a string where the first line contains spaces and one period (`.`, the "ball"), followed by lines containing spaces, forward slashes (`/`), and backslashes (`\`), determine what column the ball will land in after falling from its starting position. Each `/` moves it to the left by 1 column and each `\` moves it to the right by 1 column.
### Sample input
```
.
/ \ \
/ /
\ \/ \
\ /\
\ /\ \
\ /
```
### Sample output
The ball starts in column 5, hits the `/` on line 3, then the three `\`'s on lines 5 through 7 for a final position of:
```
7
```
Note that columns are 1-indexed, mostly for consistency with text editor conventions.
### Edge cases
If the ball hits a `/` in the first column, it's eternally stuck in the nonexistent column 0. Your program should handle this correctly by printing `0`.
If the ball hits either side of a `\/` pattern, the result is undefined. Your program is permitted to terminate with no output, loop infinitely, or print an error message (my solution prints `-1`), but it must not print anything that can be perceived to be valid output.
If the ball hits the left slash in a `\\` pattern, it should end up directly beneath the right slash, not to the right of it. The solution I originally envisioned was prone to getting this wrong, so don't go down that path!
There may or may not be spaces after the `.` or the last `/` or `\` on each line. Your program should not rely on such padding being available. On a similar note, there may or may not be any lines following the first line.
You may assume that the first line will have zero or more spaces and exactly one `.`. Subsequent lines, if any, will have zero or more spaces and zero or more slashes.
### Implementation details
Your program may read from a file (specified as a command-line argument) or read from standard input, at your convenience.
Your program must output a single number to standard output. (Yes, a trailing newline is fine. Yes, the number may have more than one digit.)
### Test cases
>
> Input:
>
>
>
> ```
> .
>
> ```
>
> Output:
>
>
>
> ```
> 1
>
> ```
>
> Note that the input here is exactly one byte. This is the smallest case you should be able to handle.
>
>
>
>
> Input:
>
>
>
> ```
> .
> \
> \
> \
> \
>
> ```
>
> Output:
>
>
>
> ```
> 6
>
> ```
>
> Note that there are no spaces after these slashes.
>
>
>
>
> Input:
>
>
>
> ```
> .
> /
> /\\ / \
> //\ \/// //
> \\/ \/\ /\/
>
> ```
>
> Output:
>
>
>
> ```
> 0
>
> ```
>
>
>
> Input:
>
>
>
> ```
> .
> / / /
> \\\
> /\\
> / \
>
> ```
>
> Output:
>
>
>
> ```
> 1
>
> ```
>
>
>
> Input:
>
>
>
> ```
> .
>
>
> \
> /
> /
>
> \
>
> ```
>
> Output:
>
>
>
> ```
> 4
>
> ```
>
>
>
> Input:
>
>
>
> ```
> .
> \
>
> \/\/\/
>
> ```
>
> Output:
>
>
>
> ```
> (anything but a nonnegative number)
>
> ```
>
>
### Closing remarks
This question is similar to [Simulate a (gravity-based) billiard-ball-type computer](https://codegolf.stackexchange.com/questions/3809/simulate-a-gravity-based-billiard-ball-type-computer), but significantly simpler, so hopefully it will gain more interest.
I have a 169-character solution in Python. I'm sure the talented golfers here can tear that record to pieces, though. :^)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in characters will be accepted at the end of the month!
[Answer]
# Python, 143B
```
import sys
for l in sys.stdin:
a=l.find('.')
if a>-1:F=a
elif F>-1:
if'\\/'in l[F-1:F+2]:z
F+={'\\':1,'/':-1}.get((l+' '*F)[F],0)
print F+1
```
Using the space/tab indentation trick. I haven't done anything particularly clever here. `F` is the current index, `l` is the current line; `z` is undefined so it throws an exception, which is definitely not a positive integer, handling the `\/` situation.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¶¡ð«ć'.ksvU…/ \yXD>‚èJD„\/Qiõqëнk<X+]>
```
Input as a multi-line string. Outputs `\/` if the ball is stuck.
[Try it online](https://tio.run/##yy9OTMpM/f//0LZDCw9vOLT6SLu6XnZxWeijhmX6CjGVES52jxpmHV7h5fKoYV6MfmBm4eHVF/Zm20Rox9r9/6@kpKSgx6UQw8UVow@CQD4A) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W@f/QtkMLD284tPpIu7pednFZ6KOGZfoKMZURLnaPGmYdXuHl8qhhXox@YKZO4eHVF/Zm20Ro19ba/df5H62kp6SjoKSgF5OnEBMDJKAkjALSYHmwAgV9IKEPlIkBMiFK9IFcIENfX18ByMwDyemD@EBRINaH6wVKg3XHQADYLAhDH8kSkEoQhNuuALZTHyymgOQcmHNBNupDkFIsAA).
**Explanation:**
```
¶¡ # Split the (implicit) input-string on newlines
# (work-around instead of `|`, because it will stop at empty lines)
ð« # Add a trailing space to each line (work-around because indexing
# -1 in 05AB1E will wrap around to the other side)
ć # Extract head; pop and push the remainder-lines and first line
# separated to the stack
'.k '# Get the 0-based index of "." in this first line
s # Swap to get the remainder-list of lines
v # Loop over each line `y`:
U # Pop and store the top value (the index) in variable `X`
X # Push the current index `X`
D> # Duplicate it, and increase the copy by 1
‚ # Pair to [X, X+1]
y è # Index both of those into the current line `y`
JD # Join the two characters together, and duplicate it
„\/Qi # If it's equal to "\/":
q # Stop the program
# (after which the string is output implicitly as result)
ë # Else:
н # Only leave the first character (at index `X`)
…/ \ k # Get its 0-based index in string "/ \"
< # Decrease it by 1
X+ # And add it to `X`
] # After the loop:
> # Increase the top of the stack (`X`) by 1
# (after which it's output implicitly as result)
```
[Answer]
## CJam, 61 bytes
```
qN/('.#)\_:,0+:e>f{' e]" /"f#0\+}{1$1$=\@2$-_@=@[\]$[W1]#/z}/
```
If the rule regarding `\/` is lifted (and we are not required to handle it), this can be shortened to **41** bytes:
```
qN/('.#)\_:,:e>f{' e]" /"f#0\+0+}{1$=-}/
```
[Answer]
# [Python 3](https://docs.python.org/3/), 124 bytes
```
import sys
for l in sys.stdin:i=('.'in l)*l.find('.')or(i<0)*i-2*('\\/'in l[i-1:i+2])or' \\'.find((l+i*' ')[i])+i
print(i+1)
```
[Try it online!](https://tio.run/##NYs9DoMwDEb3nMKb8yOSQjdET4LZEKqlNEEhC6dPE2gtS/Z7/ryf@R3DsxT@7DFlOM5DbDGBBw4N7JFXDiO/JFqsyivt7cZhbaxikjw9lOZu0BKJ3BWZuetHNsNS7whEeD9Ib1gjoJp5UYbFnjhkyaZXpUAtKwBcnVRbNNHAicZA7icbuPtMdflHLw/uCw "Python 3 – Try It Online")
Also works in Python 2.
### Explanation
```
for l in sys.stdin:i= # Change value i for each line in the input
('.'in l)*l.find('.') # Set i to (0-indexed) dot position if present
or(i<0)*i # Keep i fixed if it is below zero
-2*('\\/'in l[i-1:i+2]) # Set i to -2 if \/ trap is encountered
or' \\'.find((l+i*' ')[i])+i # Else: move position based on character
print(i+1) # Print final 1-indexed position
```
[Answer]
# Java 11, ~~213~~ ~~208~~ ~~190~~ ~~175~~ ~~162~~ 160 bytes
```
s->{int r=s.indexOf('.'),c;for(var x:s.split("\n"))if((c=(x+=" ".repeat(r+2)).charAt(r))!=46&&(r+=c<33?0:c<48?-1:x.charAt(r+1)==47?r/0:1)<0)return 0;return++r;}
```
Throws a division by zero error when we are stuck inside a `\/`.
-5 bytes thanks to *@EdgyNerd*
-17 bytes thanks to *@ceilingcat*
[Try it online.](https://tio.run/##fVLBctsgEL33K7Y6JDCqwW48bce26ukhxyaHHKseKMYNqYM0C/Iok/G3uwtIbprxRALm7fJ29y3woPZq8rD5c9Q75T18V9Y9vwOwLhjcKm3gJprJAZrdBbTuN3i@JOeBJg0fVLAabsBBBUc/@focuVh5Yd3G9Ldbdiku@Qe93DbI9gqhX3jh250NrKhdwbndMqYr1pdVAYVA0xoVGJYfORf6XuE3Mjh/X80/XVyQu9Krq6v1dKFX8y/ryWzRn0jljFfV/PMa5XQx46spRxM6dDBdZlCWuDwco/K2@7UjyYPyfWM38EiND@39@AmK566D8aQyIlE7AEmgruOMVrYlweijRZ52kkOONLLky7C8DbJIxzhWEf@bqWKOOCUd071iDuJoiSXrpCuSZaxKsqQEgi7uyWhnPfJMFiIODaXP5SYikGcLx5j4/2st6ZDJB2fFjm1FPTKP4vScXt5I4g8Pzrq2C@Od4FMGAHdPPphH0XRBtMQLO8ec0Cyzh7IH0Croe3bda9MG2zgwPX8jQXGN2CA0WneIZrOAoqSAIVeSeTj@BQ)
**Explanation:**
```
s->{ // Method with String parameter and integer return-type
int r=s.indexOf('.'), // Get the index of the dot on the first line
c; // Temp integer
for(var x:s.split("\n")) // Split the input by newlines, and loop over the lines:
if((c=(x+=" ".repeat(r+2)) // Append trailing spaces to the line if necessary
.charAt(r)) // Get the character at the current index of this line
!=46 // If this is NOT the first line (the char isn't a dot):
&&(r+=c<33? // If the current char is a space:
0 // Index `r` remains the same
:c<48? // Else-if it's a '/':
-1 // Index `r` is decreased by 1
:x.charAt(r+1)==47? // Else-if we're stuck in a `\/`:
r/0 // Divide by 0 to exit with an error
: // Else (it's a '\'):
1) // Index `r` is increased by 1
<0) // If `r` is now -1:
return 0; // Return 0
return++r;} // After the loop: return the index `r` + 1
```
[Answer]
# [J](http://jsoftware.com/), 95 bytes
```
[:>[:(<"1@|.@}.([:(1&{+_*0>[:*/2-/\])(]+{~ ::])^:(<3))&.>/@,2<@i.~{.)[:(0,'/ \'<:@i.]);._1 LF,]
```
[Try it online!](https://tio.run/##ZY/BbsIwDIbvfopfHEgDxW7ZtEPWokqTOHHaFZcepiGYhPYAHbx657RdhcbBThzl@/Plq5uxO6IMcEiRIVitGG/vu223D5t9SIpZXv1wdeXEhnzeLptFZucLWa9Ea5/Uy/aGEGp/sLtP3s95I1W6Lqoz31r2BmWpE6grgh3V/pWbHLttWnee6PPj9I0cJY5w7IguKBnXKBEyAhOU0NfQrP9BLz10MWQgRiQyEIKo2hoBEYWKCERI1URsFhUL6nOyfzlTjAExSDW@LLHLKHAn/cAZSDTKIpoIjfuJfJ7Ix8@S2d3JNcPV7hc "J – Try It Online")
Returns infinity `_` when the ball gets stuck. Lost many bytes handling that special case. Otherwise it's more or less a simple reduction of the rows. Could surely be golfed further.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 123 bytes
```
x=>(g=(i,c)=>y[j++][i]==c?g:y[j]+1?(k=y[j][i])=='/'?g(i-1,'\\'):k=='\\'?g(i+1,'/'):g(i,g):i)(x.indexOf`.`,j=0,y=x.split`
`)
```
[Try it online!](https://tio.run/##PY7BboMwEETv/grfbAviTW4V0oZbrz30mEUCgUEmBCiQCr6erhsUWR6P345G2xa/xVxOflxO/VC5vcZ9xatuUPu4NHjdbm0UZTefIZZpk/A3iy6pvmNwjA2iApU22p8usSJSJrkzYhNYxAwYsY0bk3ijV@v7yq1fdW7zuMVzvOFq57HzSy5ys4vJ/Tz95LSqZ2Xs5Irq03fue@tLfY7Vc6k/GL/y1CP1uX0Uo@aVy6Gfh87Zbmh0rVdjzG4FCmmFJCH/70tYGQcuQUgg4jdAAJIEABJAEAF74ikcYcYhThQ6ICi8q3gsxFEuQyuIw9N7A8F1fP4A "JavaScript (Node.js) – Try It Online")
0-index, output `g` if stucked
] |
[Question]
[
`xxd` is a utility, bundled with `vim`, that has been used to encode answers to code golf problems on this site. It converts a binary file into a hex dump and back again.
Implement the `xxd` and `xxd -r` commands in the programming language(s) of your choice. Scoring is based on the character/byte lengths of a) your program(s) and b) any command line argument(s) necessary to switch a combined program between modes (they need not be `-r`). As in golf, lower scores are better.
* For two separate programs: *forward code* + *reverse code*
* For a combined program: *combined code* + sum(*forward arguments*) + sum(*reverse arguments*) - 2
## Specification of the chosen `xxd` subset
The forward command (*e.g.* `xxd`) accepts 0 ≤ *n* ≤ 216 bytes from standard input and generates ceil(*n* / 16) lines of standard output in the following format (all hex digits lowercase):
* Offset of the first encoded byte (format string `"%07x:"`); ends in `"0"`
* At most 16 hex-encoded bytes, grouped into pairs (format string `" %02x"` for even bytes, `"%02x"` for odd bytes) and right-padded with spaces to 42 characters
* The encoded bytes interpreted as ASCII characters, values not between 0x20 and 0x7e (`'\40'` and `'\176'`) inclusive becoming `"."`
* A newline (`"\n"`; `"\r\n"` allowed when standard output is in binary mode)
Minimal ungolfed C implementation:
```
#include <stdio.h>
int main() {
unsigned char L[16];
int t = 0, n, i, s;
for (; (n = fread(L, 1, 16, stdin)); t += n) {
printf("%07x:", t);
s = 42;
for (i = 0; i < n; i++)
s -= printf(i & 1 ? "%02x" : " %02x", L[i]);
printf("%*s", s, "");
for (i = 0; i < n; i++)
putchar(L[i] > '\37' && L[i] < '\177' ? L[i] : '.');
printf("\n");
}
return 0;
}
```
The reverse command (*e.g.* `xxd -r`) accepts any unmodified output of the forward command (given a valid input to that command) and produces that original input.
## Example usage
```
$ xxd < /dev/null | wc -c
0
$ php -r 'echo join(range("\0",~"\0"));' | xxd
0000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f ................
0000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f ................
0000020: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f !"#$%&'()*+,-./
0000030: 3031 3233 3435 3637 3839 3a3b 3c3d 3e3f 0123456789:;<=>?
0000040: 4041 4243 4445 4647 4849 4a4b 4c4d 4e4f @ABCDEFGHIJKLMNO
0000050: 5051 5253 5455 5657 5859 5a5b 5c5d 5e5f PQRSTUVWXYZ[\]^_
0000060: 6061 6263 6465 6667 6869 6a6b 6c6d 6e6f `abcdefghijklmno
0000070: 7071 7273 7475 7677 7879 7a7b 7c7d 7e7f pqrstuvwxyz{|}~.
0000080: 8081 8283 8485 8687 8889 8a8b 8c8d 8e8f ................
0000090: 9091 9293 9495 9697 9899 9a9b 9c9d 9e9f ................
00000a0: a0a1 a2a3 a4a5 a6a7 a8a9 aaab acad aeaf ................
00000b0: b0b1 b2b3 b4b5 b6b7 b8b9 babb bcbd bebf ................
00000c0: c0c1 c2c3 c4c5 c6c7 c8c9 cacb cccd cecf ................
00000d0: d0d1 d2d3 d4d5 d6d7 d8d9 dadb dcdd dedf ................
00000e0: e0e1 e2e3 e4e5 e6e7 e8e9 eaeb eced eeef ................
00000f0: f0f1 f2f3 f4f5 f6f7 f8f9 fafb fcfd feff ................
$ xxd <<< 'The quick brown fox jumps over the lazy dog.'
0000000: 5468 6520 7175 6963 6b20 6272 6f77 6e20 The quick brown
0000010: 666f 7820 6a75 6d70 7320 6f76 6572 2074 fox jumps over t
0000020: 6865 206c 617a 7920 646f 672e 0a he lazy dog..
$ xxd <<< 'The quick brown fox jumps over the lazy dog.' | xxd -r
The quick brown fox jumps over the lazy dog.
```
[Answer]
## Perl, ~~122 + 54 = 176~~ 122 + 45 = 167
The forward script:
```
$/=$,;for(<>=~/.{1,16}/gs){$h="";$h.=sprintf"%*s%02x",++$m%2,"",ord for/./gs;
s/[^ -~]/./g;printf"%06x0:%-42s",$n++,$h;say}
```
And the reverse script:
```
/:(.+?) /,print map{chr hex}$1=~/\w\w/gfor<>
```
(This one is interesting; there are all kinds of obscure bugs that can show up in the reverse script depending on the input, if you're not careful.)
[Answer]
## Javascript, ~~247 + 61 = 308~~ 225 + 63 = 288
*-20 or so thanks to ASCII-only*
Forward:
```
b=>[...Array(b.length+15>>4)].map((_,i)=>(P=j=>i=>i.toString(x=16).padStart(j,0))(7)(i)+"0: "+(p=b.splice(0,x)).map(P(2)).join``.replace(/.{4}/g,"$& ").padEnd(42)+p.map(l=>String.fromCharCode(l>31&l<127?l:46)).join``).join`
`
```
[Try it online!](https://tio.run/##ZZBRa8IwEMff/RRZGHJHs9h2VYcsGSKDPQo@OpnRtpoS2xCDc4x99i6rbi@Dgzu4@//u7l@pkzpunbb@7vTQlqLdCLnknE@dUx@w4aaod34fJUMpM1zxg7IAb0yjkDAXlZA6BPfNwjtd7@AskhFyq/KFV85DxWJEGCNojGg8ITQCKzb8aI3eFhCzM2JHnEMaqqrR9XrNXWGNCu0B/8y@BjtGb/uEdtDnOocsxch2IiPkZSsvXXOY7ZWbNXkBRt4nffOYpOMnM8lGf9xr7q1bG0QeSljGLGHpCklE6GtNsffboC@FMQ0j740z@Q3t7vVA6eVYT4Qknm@vC6cewpP/IRcD02Hwo9TGhKFf84jGH4QOqvYb "JavaScript (V8) – Try It Online")
Reverse:
```
d=>d.match(/[^:]{40}/g).join``.match(/\S\S/g).map(t=>+("0x"+t))
```
[Try it online!](https://tio.run/##hdRrc1RFEAbg7/6Kl0Vxl8BmpuceTeSqeAGVeGfB9EzPQEKyiWENKMJfj3MKVssq6tgfTp3qU/XUzLx95oDP@Fk53T9ZXT2L5237XLZ3ZH7Eq/Jkuvng0dbDl1a92nw8mx8c7y/39tZfFruL3aF7xCfT1fbOxnSiXkw2VrPZ@cnp/nI1bb3xtrbQHxqK8P81n88nM2xgslhOZu@9g7LRO/jiC3yjAlIh9LdAQ8@C9L/UnXp4eHwFz49PD@XCOPp2fcpAWeWgvApQUSUoVhmqKIGqqr1Z339qsXxj6K5opTU0aQNttYP2OkBHnaBZZ@iiBbrqMYW6QqpvgogMyJIDeQqgSAnElEGFBFRpUHBhMbn4/geXPpzOLm9cuTrfXDOmM0YZDUPGwFjjYLwJMNEkGDYZphiBqWZglCZjnQ8xbX308fbOJ2vFDqetrIYla2CtdbDehp6ATbBsM2yxAlvtoFy7fuPmrduffnbn8y@@/Oruva/XiuuKU07DkTNw1jk47wJcdAmOXYYrTuCqG5Rvvr2/@933P/z408@/PFgsHj76dc34znjlNTx5A2@HIfC@Rx99gmefh/wFvvqB2eNcpLbHT/YPnh4eLY/XSuhKUEEjUDAINjgE3wcoxJAQOGSEEgShhkE5@e302er3s@cv/vjz5V@vXv@TUuxKVFEjUjSINjpEHwNijAmRY0YsURBrHMs6dSWppJEoGSSbHJJPASmmhMQpI5UkSDWNKdwVVqzBxAZs2YE9B3DkBGbO4MICrjym5K5klTUyZYNss0P2OSDHnJA5Z@SSBbnmMaV0paiiUagYFFsc@n8aUGJJKFwySimCUsuYIl0RJRpCYiBWHMRLgERJEJYMKSKQKmNK7UpVVaNSNai2OlRfA2qsCZVrRi1VUGsdU1pXmmoajZpBs82h9csGLbaExi2jlSZotb1LmfTL8G8 "JavaScript (V8) – Try It Online")
Might make an explanation at some point.
[Answer]
# 253
# [JavaScript (V8)](https://v8.dev/), 200 bytes
```
b=>{for(i=0,P=j=>i=>i.toString(16).padStart(j,0);t=b.slice(i,i+16),t+t;i+=16)print(P(7)(i)+': '+t.map(P(2)).join``.replace(/.{4}/g,"$& ").padEnd(42)+String.fromCharCode(...t.map(c=>c<32|c>126?46:c)))}
```
[Try it online!](https://tio.run/##VZBNSwMxEIbv/ooYxE5ITLdrrdKalVIEj4UeVWy6H3WWdLOkQ0Vqf/uatl6EOQwz87wPTG13dpsHbOlm99BVpluZbF/5AGgSNTe1yTCWJr@ggM0aBiOhW1ssyAaCWiViQmaltw7zElChjHtFkiYoTWzbyBDM4V4ACtkbs54kvbFtHKVC6Npjs1zqULbORr6v98NDf6341TXjJ81zU8AwFfIs11Xwm9mnDTNflKC1PmflJssfb9OfPBuko6fhaJwLIQ7dBCp4TdRApe@CScbfGi4ujkP@UjrnFfvywRWXXG9bhwQ8Go9pxEzGSOd/milBEuP@BUxDsN@Q3sVXVOhcPDiR8KEYiiOOkeh@AQ "JavaScript (V8) – Try It Online")
# [JavaScript (V8)](https://v8.dev/), ~~57~~ 53 bytes
```
d=>d.match(/(?<=:.*)\w\w(?=.{19})/g).map(t=>"0x"+t-0)
```
[Try it online!](https://tio.run/##hdRrc5Q1FAfw936KP4uXfSjdJif3yrYKKqh4Ae@6Xk5yEiiWtpalRRC@es0zsDrOMI/nRSaTzPwmyT/JAz7jR@X04GS9fRYv2vJClnuyeMjrcn@@M9@/ttxdXBlW56vz@f5y8Uyn58POvaHPn8zXy72ZejLbWm@r4eLk9OBoPW/zmXpVu@iNhiL8fy0Wi9mALcxWR7PhjddQNnoHX3yBb1RAKoTeCzSOWZD@l7pVDw@Pr@L8@PRQLk2jr9anDJRVDsqrABVVgmKVoYoSqKray/X9p1ZHLw3dFa20hiZtoK120F4H6KgTNOsMXbRAVz2lUFdI9U0QkQFZciBPARQpgZgyqJCAKo0KLq1ml9986@135sOVravbi50NYzpjlNEwZAyMNQ7GmwATTYJhk2GKEZhqRkZpMtb5ENPuu9eWe/sbxY6nrayGJWtgrXWw3oaegE2wbDNssQJb7ai89/71Gx98@NHNWx9/8untzz7/YqO4rjjlNBw5A2edg/MuwEWX4NhluOIErrpR@fLO3a@@/ubb777/4cefVquff/l1w/jOeOU1PHkDb8dL4H2PPvoEzz6P@Qt89SPzG@citd27f/Dg98OHR8cbJXQlqKARKBgEGxyC7xcoxJAQOGSEEgShhlE5@eP00frx2fmTP58@@@v5i39Sil2JKmpEigbRRofoY0CMMSFyzIglCmKNU1mnriSVNBIlg2STQ/IpIMWUkDhlpJIEqaYphbvCijWY2IAtO7DnAI6cwMwZXFjAlaeU3JWsskambJBtdsg@B@SYEzLnjFyyINc8pZSuFFU0ChWDYotDf6cBJZaEwiWjlCIotUwp0hVRoiEkBmLFQbwESJQEYcmQIgKpMqXUrlRVNSpVg2qrQ/U1oMaaULlm1FIFtdYppXWlqabRqBk02xxa/2zQYkto3DJaaYJW2@uU2TBc/A0 "JavaScript (V8) – Try It Online")
optimized from [Redwolf Programs's answer](https://codegolf.stackexchange.com/a/215790/)
[Answer]
## [C (clang)](http://clang.llvm.org/), ~~222 + 108 = 330~~ ~~189 + 105 = 294~~ 186 + 104 = 290 bytes
**Forward** (*-36 thanks to @[ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*):
```
#define P printf(
t,n,s;main(i){for(char z[16];n=read(i=0,z,16);t+=n){P"%07x:",t);for(s=42;i<n;)s-=P" %02x"+i%2,z[i++]);for(i=!P"%*s",s,"");i<n;i++)P"%c",isprint(z[i])?z[i]:46);P"\n");}}
```
[Try it online!](https://tio.run/##JY7BTsMwEETv/YrFKJJNXJRGVZFqLH4hB24lB@M47UK7LrYLIVW/PbjlMoeZeZqxc7s3tJ2m@871SA4aOAak1PNZkiSjOhgkjuLc@8DtzgQYN4tVq0gHZzqOupKjXKyESqUmcW5YUT0NayaTUFci6mWt8JmUiHPdMCiqemAlFrUcN1iW7X8L9V0GHyKTUTImbkBORTYtkxhvj3gmWvFy1fUyDzbsjXL3cpmm152DrxPaT3gP/oeg9wN8nA7HCP7bBUg53pvxFzq/fZz9AQ "C (clang) – Try It Online")
**Reverse** (*-4 thanks to @[ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*):
```
b;main(a){for(char z[80];gets(z);)for(a=9;z[a]-32;a+=5)b=strtol(z+a,0,16),b=b>>8?ntohs(b):b,printf(&b);}
```
[Try it online!](https://tio.run/##Nc5NboMwEAXgfU4xq8pWSGRMGEMs0kt0F2VhEwykBKfG6Q9Vz07tRp3dG837NPWmHtTYLouWV9WPRNFvYx2pO@VgPhbsJNvGT2Smksa9qko5H9Vpk3Gp1lVOdTV55@1A5rVKWJIiTXSlD4fiefS2m4ime53cXD96Q540lT/Lwh6zh3yHBWDOGYhU5IAlZoA6ROSCAxohAJsQ4aVr4O3e16@gnf0YYfUHpIFARAOiiB0VibMIWBajERjs4HAmdgDGfsLlfr1NYN8bB/5B8EgUmIcjrAFToUCUsb0LLAreAFPwP@GJQc1fcLbtdrv6BQ "C (clang) – Try It Online")
] |
[Question]
[
I think everyone is familiar with the game of [snakes & ladders](https://en.wikipedia.org/wiki/Snakes_and_Ladders)1. Imagine we have a 10x10 board like this:
```
=============================================================
| | | | | | | | | | |
| 100 | 99 | 98 | 97 | 96 | 95 | 94 | 93 | 92 | 91 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 80 | 79 | 78 | 77 | 76 | 75 | 74 | 73 | 72 | 71 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 60 | 59 | 58 | 57 | 56 | 55 | 54 | 53 | 52 | 51 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 40 | 39 | 38 | 37 | 36 | 35 | 34 | 33 | 32 | 31 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 20 | 19 | 18 | 17 | 16 | 15 | 14 | 13 | 12 | 11 |
------+-----+-----+-----+-----+-----+-----+-----+-----+------
| | | | | | | | | | |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
=============================================================
```
The task is to (sort of) paint a ladder on this board from a smaller number to a bigger one. Kind of an ASCII art using these characters `/\ | _` only.
The board's dimensions are 61x31 characters fixed like above. To illustrate the task, let's draw some ladders e.g. from 7 to 31, 22 to 77, 54 to 96, and 68 to 89 like this:
```
=============================================================
| | | | | | | | | | |
| 100 | 99 | 98 | 97 | 96 | 95 | 94 | 93 | 92 | 91 |
------+-----+-----+-----+-\_\-+-----+-----+-----+-----+------
| | | | | \_\| | | | | |
| 81 | 82 | 83 | 84 | 85\_\ 86 | 87 | 88 | 89 | 90 |
------+-----+-----+-----+----\_\----+-----+-----+/_/--+------
| | | | | \_\ | | /_/ | |
| 80 | 79 | 78 | 77 | 76 |\_\ | 74 | 73 /_/72 | 71 |
------+-----+-----+/_/--+-----+-\_\-+-----+---/_/-----+------
| | | /_/ | | \_\| | /_/| | |
| 61 | 62 | 63 /_/64 | 65 | 66\_\ 67 | / / | 69 | 70 |
------+-----+---/_/-----+-----+----\_\----+-----+-----+------
| | | /_/| | | \_\ | | | |
| 60 | 59 | /_/ | 57 | 56 | 55 |\ \ | 53 | 52 | 51 |
------+-----+/_/--+-----+-----+-----+-----+-----+-----+------
| | /_/ | | | | | | | |
| 41 | 42 /_/43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 |
------+---/_/-----+-----+-----+-----+-----+-----+-----+------
| | /_/| | | | | | | | |
| 40 | /_/ | 38 | 37 | 36 | 35 | 34 | 33 | 32 | 31 |
------+-|_|-+-----+-----+-----+-----+-----+-----+-----+/_/---
| | |_| | | | | | | | /_/ |
| 21 | | | | 23 | 24 | 25 | 26 | 27 | 28 | 29 /_/30 |
------+-----+-----+-----+-----+-----+-----+-----+---/_/------
| | | | | | | | | /_/| |
| 20 | 19 | 18 | 17 | 16 | 15 | 14 | 13 | /_/ | 11 |
------+-----+-----+-----+-----+-----+-----+-----+/_/--+------
| | | | | | | __________/_/ | |
| 1 | 2 | 3 | 4 | 5 | 6 | _________/_/9 | 10 |
=============================================================
```
## Challenge
Given the two distinct numbers that are both in the range of `1..100`, draw a ladder from the smaller number to the bigger one, assuming that their arrangements and positions are fixed like above. **You are not required to print the whole table**. Only the ladder would suffice, but it must be placed in the right position on a 31`x`61 ASCII sheet.
Note that sometimes the ladder has two parts, i.e. direct (horizontal or vertical) and slant. The direct part must always come first.
# Rules
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. If any clarifications or more rules are needed, please inform me in the comments. Happy golfing!
1. In case you have never heard of it (which would be really odd), please refer to the linked Wikipedia article. I skipped elaborating the game rules for the sake of brevity **and** being on topic.
[Answer]
# [Python 2](https://docs.python.org/2/), 316 bytes
```
def f(m):
r=[list(' '*61)for y in range(31)]
(y,x),(b,a)=[[(109-p)/10*3,1+min(p%20,19-p%20)*6]for p in[max(m)-1,min(m)-1]]
while y<b:c=cmp(a,x);r[y][x:x+4]=r" /|\___/|\ "[c%3::3];x+=c;y+=1
if x==a:r[y-1][x+2-(r[y-1][x]>' ')]=" "
while x-a:c=cmp(a,x)+1;r[y-2][x+c:x+2+c]="__";r[y-1][x+c*3/2]="_";x+=c-1
print r
```
[Try it online! (footer paints over grid for pretty output)](https://tio.run/##zZbBcpswEIbvPIXKTMZgBEESCLBLX4QwHkJxQ8fGDHbGeCbv7q5@4tTtMbmgwy8hpN3v34u2v5xeDp28Xn82W7Z19u7KYkNe7NrjyVkEi6UW7vYwsAtrOzZU3a/GUcItLeZc@Ohy55lXbl4Ujggzv3cfRbhUXHj7tnP6BxlyQbs0u0tdmig9RSn21UhpfMHNKbMoKdz5pd017PL9eVXn9b53Koq@HopLWYyr0YvKfLCD4PHtabPZkAZ2UT@o1UqV69HL6/XFy4XF2i0b87xa0TUKWoye9J3buvxBZtwyt5l9Szb61V0yT5h0vjT3akopvZpObzb2@iNcvVSP0mzayOpTyqE5vQ5UmOuR5cy27fwrw3pjZnxS6bYIQ/rKMrOXpdAEqqExNIIqqIQKc9vH8D6l/pfJU8PAUvCkYEvBmYI5BX8KLyl8pZPHcAbkhoEl4EnAloAzAXMC/gReEvhK4DGZQc01aq7Bo8GmwanBrMGv4UXDl548zqDmGjWPwRODLQZnDOYY/DG8xPAVw2M8g5pHqHkEnghsETgjMEfgj@Algq9o8jiDmkeouQKPApsCpwKzAr@CFwVfCh7VDGouUXMJHgk2CU4JZgl@CS8SvuTkcQY1l6i5AI8AmwCnALMAv4AXAV8CHsUMai7wJaEKGkFjqIYm0BSaQQVq/qU3lN5gy0KrUbWD6VmKItM8jkpepBnXKc1S8yQxs5zmhCtBk9JchDTTI/q@4Bm1JtQO0Riafkcv/NYxYV1sdc15Y179qVUaDmeXmby0MGmPwbHftSfHfups0y7RQBvFbwea7nXfDNWpcUxsd0pzOzZyVv93iOL/PWMGdTs1@0ZdR2D/@@MDDt1TSYg1/vdD253uDEzfi6duEfw@UCu2eJ9NqjsnCOXeXyFPxpV1/QM "Python 2 – Try It Online")
Function that inputs a list of two numbers and outputs a list of lists of characters.
### How it works
We find character coordinates of the higher point (e.g. 96), then translate it along diagonal, vertical, or horizontal movements to the coordinates of the lower point (e.g. 54), modifying the character matrix `r` as we go.
```
def f(m):
r = [list('.'*61) for y in range(31)]
m = [max(m)-1,min(m)-1]
# (x,y) is the higher point
# (a,b) is the lower point
# x increases right; y increases down
(y,x),(b,a) = [[(109-p)/10*3,1+min(p%20,19-p%20)*6] for p in m]
# move (x,y) to (a,b) via 1-unit translations
# \ diagonal
while x < a and y < b:
r[y][x+1:x+4] = "\\_\\"
x += 1
y += 1
# / diagonal
while x > a and y < b:
r[y][x:x+3] = "/_/"
x -= 1
y += 1
# straight down
while x == a and y < b:
r[y][x+1:x+4] = "|_|"
y += 1
# remove space at the bottom of the ladder
# (r[y-1][x]!='.' deals with off-by-one error in the case of
# \ diagonals with no straight segment)
if x == a:
r[y-1][x+2-(r[y-1][x]!='.')] = " "
# left
while x > a:
r[y-2][x+1] = "_"
r[y-2][x] = "_"
r[y-1][x] = "_"
x -= 1
# right
while x < a:
r[y-2][x+2] = "_"
r[y-2][x+3] = "_"
r[y-1][x+3] = "_"
x += 1
return r
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 130 bytes
```
FχFχ⊞υ×⁶⎇﹪ι²⁻⁹κκ≔⁻LυNθ≔⁻LυNη≔⊕§υηζ≔׳÷ηχηJ§υθ׳÷θχ F›ζⅈ«≦⊕ζ »F⁻ζ⁺ⅈ⁻ⅉηG←←↑→↘→²_F⁻ⅈ⁺ζ⁻ⅉηG↑←↙→²_W›ⅉη«≔⎇›⁻ⅉη↔⁻ζⅈ²∨›ζⅈ³ιP✳ι¹←←✳ι¹→¿›ⅉη_
```
[Try it online!](https://tio.run/##jVRda9swFH1uf4Xwk8Q0qN21YR17CA2MjKY1JYPtabiJYospkiPL6ZLS3@5dSZadL8IeEuteH51zz9WVZ0WmZyoTTTNRa4aTa4oeWZ4ZWBLy5TLVXBo85UtW4ehrRFHs0g57N1Kv8oEtjE3UwvDSgV0agDcBd0vR3XnYQmmEbwh6u7zomSF/GO3stoQU3R6kBzZOd/mjDxHk3r3EJ4LuVbmxFV1B9pktBJuZpzXTIis7nf1099YrxnGoN74iqFukdVXgmiLfKeCfMi0zvcETNa@FwpyihFA04bKu8GeK/hD7I4HrgcncAAFxPfheL8upwkMzlnP219JyEqjhfMbSjPiaz5llBXHSm77PKoO9SEdpdxPXg2FV8Vwevx/LsjaP9fKFaUwgXgH6f7FFjx3LmWZLJg2b79ZeWNi2h53wUXgfnu3Y/eq0@1Xn3puPUBT6@U0zGGGNtxT9hDL9ZGXlcaG@sotdgnZWvHMgSAU8gSWc3i/sCrWsqRKbXMkwG@Hxo4S/Z54XNrBDFdbtM4Gx/N3V6lmdgJPanhNy1K1MuH4niF8LLljfhsBk2xBOoZ3PANmTpGj4UilRw1ega4PrI3EaT/qwwRRdEzdo@9dxxDVcJA6F2wGO@xvdfg4OovT8JmfShnxxwlp7hM7@e9MkCRoMmo9r8Q8 "Charcoal – Try It Online") Link is to verbose version of full 198-byte program that includes drawing the entire background. Explanation:
```
FχFχ⊞υ×⁶⎇﹪ι²⁻⁹κκ
```
Get the X-coordinates of all 100 squares (since each row reverses direction).
```
≔⁻LυNθ≔⁻LυNη
```
Input the starting and ending square, but subtract from 100.
```
≔⊕§υηζ≔׳÷ηχη
```
Calculate the destination character.
```
J§υθ׳÷θχ
```
Jump to the start character.
```
F›ζⅈ«≦⊕ζ »
```
Erase the start character, and if this is a right-leaning ladder, then erase the next character too (this is because right-leaning ladders start 1 character further right than left-leaning ladders for some reason).
```
F⁻ζ⁺ⅈ⁻ⅉηG←←↑→↘→²_
```
Draw the horizontal part of a right-leaning ladder, if applicable. This is complicated slightly because the horizontal part does not start 1 character further right.
```
F⁻ⅈ⁺ζ⁻ⅉηG↑←↙→²_
```
Draw the horizontal part of a left-leaning ladder, if applicable.
```
W›ⅉη«
```
Repeat until the top of the ladder is reached.
```
≔⎇›⁻ⅉη↔⁻ζⅈ²∨›ζⅈ³ι
```
Work out which direction we're going in (3 = up left, 2 = up, 1 (default) = up right).
```
P✳ι¹←←✳ι¹→
```
Draw the next section of ladder.
```
¿›ⅉη_
```
Draw the next rung, unless we've got to the top of the ladder.
] |
[Question]
[
You are given an [countable ordinal](https://en.wikipedia.org/wiki/Ordinal_number) \$1 < r < \varepsilon\_0\$. Determine whether or not it is [prime](https://en.wikipedia.org/wiki/Ordinal_arithmetic#Factorization_into_primes). If not, provide exactly two ordinals \$r\_0, r\_1 < r\$ such that \$r\_0r\_1 = r\$, following rules of [ordinal multiplication](https://en.wikipedia.org/wiki/Ordinal_arithmetic#Multiplication), and furthermore satisfy at least one (**not necessarily both**) of the following:
1. \$r\_0\$ is a limit ordinal
2. \$r\_0 \le r\_1\$
More accurately, an ordinal expressed in Cantor normal form is a list \$[a\_1, a\_2, a\_3, \dots, a\_{n-1}, a\_n]\$, where when \$1 \le i < n\$, \$a\_i\$ is an ordinal expressed in Cantor normal form and \$a\_n\$ is an integer. Furthermore, for \$1 < i < n\$, the [ordinal inequality](https://en.wikipedia.org/wiki/Well-order) \$a\_{i-1} \ge a\_i\$ holds.
## Input
Any input that can provably describe any ordinal also expressible in [Cantor normal form](https://en.wikipedia.org/wiki/Ordinal_arithmetic#Cantor_normal_form) is accepted. For input forms deviating greatly from Cantor normal form, please also provide a brief way to convert a Cantor normal form ordinal to input.
## Output
If the given ordinal is prime, then a **constant result, distinct from non-prime inputs** must be returned.
Otherwise, return two ordinals, expressed the same way as the input, representing \$r\_0\$ and \$r\_1\$, respectively.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program (in bytes) wins.
## Examples
An input of \$\omega^2+1\$, or `[2,1]` in Cantor normal form, would be marked prime.
On the other hand, an input of \$\omega+2\$, or `[1,2]` in Cantor normal form, would be composite and the program should return a pair `([2],[1,1])` in whatever form it accepted.
Remember that integers are ordinals too.
**You do not need to consider \$r=1\$.**
More examples:
```
[1,100] => [100] * [1, 1]
[2,1] => prime
[3,0] => [2,0] * [1,0]
[[1,1],2] => [2] * [[1,1],1]
[[1,1],0] => [[1,0],0] * [1,0]
[[1,0],0] => prime
[1,1,1] => [1,1] * [2]
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~1068 1042~~ 1012 bytes
-30, mostly from replacing if/then with guards. I'm sure it can be golfed more.
```
data W=W[W]Int deriving Show
f EQ y=y
f x _=x
m=1<0
k=1>0
[]#[]=EQ
[]#_=LT
_#[]=GT
(W x y:z)#(W a b:d)=f(x#a)$f(compare y b)$z#d
x?y=x#y>EQ
b x=break(\(W y _)->y#x/=GT)
x&[]=x
d&(x@(W v w):u)=case b v d of(y,W f m:_)|f#v>LT->y++(W v$m+w):u;(y,_)->y++x:u
x![]=x
d!(W v w:u)=case b v d of(_:_,_)->d;(_,W f m:g)->if w<m then(W f$m-w):g else g!u
[]%_=([],k)
x@(W g h:d)%b@(W e f:_)|b?x=([],m)|g!e?[]=(\(q,r)->([W(g!e)h]&q,r))$d%b|k=(\q->(q,(foldl(&)[]$t b<$>q)#x==EQ))[W[]$div h f]
t(W x y:z)(W[]n)=(W x$y*n):z
t(W x _:_)(W b n)=[W(x&b)n]
l=all(\(W e _)->e?[])
q=max
o[]=0
o(W e n:u)=q n$q(o e)$o u
v[]=0
v(W e n:u)=q(1+length u)$q(v e)$v u
d[]=0
d(W e n:u)=q(1+d e)$d u
e(W x _:[])(W y _:_)=x?y
e(_:x)y=e x y
g _ 0_ n=[[W[]x]|x<-[1..n]]
g m d s n|p<-g m(d-1)s n=fst$h s$filter(m?)$p++[[W x y]|x<-p,y<-[1..n]]
h 1z=(z,z)
h n z|(a,p)<-h(n-1)z,n<-[x++y|x<-z,y<-p,e x y]=(a++n,n)
r x=p x$g x(d x)(v x)$o x
p _[]="p"
p x(y:z)|(q,r)<-x%y,x?y&&x?q&&r&&(l y||not(l y&&l q||d y<2&&d q<2)||y#q<GT)=show y++"*"++show q|k=p x z
```
[Try it online!](https://tio.run/##bVNLb5tAEL7vr5gYgnYDbo2rHuKydi9VVSmXKJF8oAhBlodlWMDGzi7iv6ezJM1D7YmZ@Wa@/eZBmRz3WVU9PYmkT2DLt@E2@iV7ENlhd97JAu7K5pHk8OMWNNdoKIi5IjX3gwXZc3@9IGFkhRH/cWuMmN/ck9j4P@8J3WK2Xg3MQiuBdCUYz6myEmbn9KGp2@SQgYaU2YMliNporiy9RqIUFE8PWbKnv7FSQ8zma22pz0jKiHKQXRHhUPUd0TM8stWJ8YfkmEGKroAmp9rbQg71KmZjbp3XN/dI4Lom3a5dU/ANUyZa11WrE1EXz6QXz4z/EsareMoX32j8wl2gu8vhMaihLzOJlbldz5G8gKzC2uLihCO5jDkNI2@Pwo3cAkocw2Vq7AxyIzDdqCmlZmNxkW1QCLbdeQekp@GWYoyVkWMCzBaX6bhHvEOs82jeVKKiDgsju4c0sNcdsxTHXTAWbjEodmcoIY9I/7oLinHJuPFtfSXZangBsUMEsWNE8VnlpExGpOJJVU1ryKY1GH2MdLxOFGlQ6oI0EybNyDqQdkcbyJjdwImcJ/z8Dqe@W2Wy6Es4Mcw8m8wzZoopU3zMFAYViGYv@vDl53NApRzPBYF4pZjmmemNFBDDIgbJQ9O7ikYVzEP/0ycZRYjVuMcjyLEN5uhQMfcZujw/9nYJRzvfVX12oPWG2a3rIoOhnChaT7/xlOAPnA7ewNCUMIw08VoWzEsqkXDwJKYq19WmcDCFrTeJw50mris9ycgBj7vF4RegqADFcArKzEuRFmKcw6ydoaWoWdY43UEwV5faw4YdR206xzk4Dq1Aj6NsemM4TgXdOArQwdJxBHTBko2jtroA/xd@xB8Y8MxnVzPXnZwOTwhfgOHpwWg59Xf94UbaE4biZ8DXgLkolNTJTnLREHjAmeJUl5Hv4ceP/kYmx/8QeA29BY0z1S0Wb7Ev/9B4b5/l/6H3jMv3SqLl9eLL12s/evoD "Haskell – Try It Online")
Or try a [version that pretty-prints the inputs and outputs](https://tio.run/##bVNNj5tIEL33r6jBDOoe8KxxtIc4tL2HjVYrzSXKSD6wBIGbrxgasLGnQfz32WrsxF5lT1TVq3r96oM8Ou6Tsnx/L6qmPnTwZ9RFzy/FsSMCLdjyrb8N/pYdiORQnAuZwde8fiMpfP4CPe/RUBByRSrueguy5@56Qfxg5gf88xdthPzllYTa/@uV0C1m96uBzdCKIF4JxlOqZhEzU7qrqyY6JNBDzMxhJoja9FzN@jUSxaB4fEiiPf0HK3sI2Xzdz9RvSMqIspBdEWFR9QeiZ3hjqxPju@iYQIyugDqlvbOFFKpVyMZ0dl6/vCKBbet0s7J1wSdMmWhtW61ORD1cSB8ujL8ShqtwyhefaHjlztAtUnjzKujyRGJlalZzJM8gKbE2ezjhSB5DTv3A2aNwLTeDHMfwGGs7gVQLjDdqSqnYmD0kGxSCbbfOAempv6UYY3lg6QAzxWM87hFvEWsdmtalKKnF/MDsIPbMdctmiuMuGPO3GBTFGXJIA9L93AXFuGRc@2b/JNlquILYIYLYMaL4rLJiJgNS8qgspzUk0xq0PkZaXkWK1Ch1QeoJk3pkLUizpTUkzKzhRM4Tfr7DqWuXicy6HE4MM88684yZYsoU/80UGhWIJld9@PLlHFApx3NBIFwp1vNE90YyCGERguS@7l0Fo/Lmvvv8LIMAsQr3eAQ5Nt4cHSrmLkOXp8fOzOFopkXZJQdabZjZ2DYyaMqJonH6G08O7sDp4AwMTQnDSCOnYd48pxIJB0diqrLtXhcOurBxJnG408i2pSMZOeBxNzj8DBQVoBhOQel5KdJAiHMwGgMtRfWyxukOvLl67B1s2LLUprWsg2XREvpxlHWnDcsqoR1HAb23tCwBrbdk49jPWg//F25Qw7YLwEM32NPFbrVt4CHhOzCQghcSm99FZdQlBthgPFdRA0dy4kf9938HlxsGfiQ3npDgBJIcr3f0w0bP1b7xhgnfb8H9JfhtKtvfQ1PFtebbXRV0cIldtHaT1gl93@nRnbqv3eFFmloa4KwN4Bym1Iuz1g4OmVRRIbmoCewury0D15ke/RG5KrgP/AzdgtqZ6haLW@zDLzTO7bP8f@iecXmvJFh@XHz4/aMbvP8L "Haskell – Try It Online").
# Input Format
The input format is Cantor normal form, written as \$\omega ^{\beta \_{1}}c\_{1}+\omega ^{\beta \_{2}}c\_{2}+\cdots+\omega ^{\beta \_{k}}c\_{k}\$, where \$k\$ is a natural number, \$ c\_{1},c\_{2},\ldots ,c\_{k}\$ are positive integers, and \$ \beta \_{1}>\beta \_{2}>\ldots >\beta \_{k}\geq 0 \$ are ordinal numbers.
Each term \$\omega ^{b}c\$ is written as `W b c` and terms are written as a list in `[]` separated by commas.
Examples:
`[]`\$ = 0\$
`[W[]1]`\$ = 1\$
`[W[W[]1]1]`\$ = \omega\$
`[W[W[]1]1,W[]1]`\$ = \omega + 1\$
`[W[W[]2]3,W[]4]` \$=\omega^2\cdot 3 + 4\$
`[W[W[W[]2]1]1,W[]4]` \$=\omega^{\omega^2} + 4\$
`[W[W[W[]1]1,W[]1]1,W[]1]`\$ = \omega^{\omega+1} + 1\$
# Test Cases
Output from the main version:
```
[W [W [] 2] 1,W [] 1] => p
[W [W [W [] 1] 1] 1] => p
[W [W [W [W [] 1] 1] 1] 1] => p
[W [W [] 1] 1,W [] 100] => [W [] 2]*[W [W [] 1] 1,W [] 50]
[W [W [] 3] 1] => [W [W [] 1] 1]*[W [W [] 2] 1]
[W [W [W [] 1] 1,W [] 1] 1,W [] 2] => [W [] 2]*[W [W [W [] 1] 1,W [] 1] 1,W [] 1]
[W [W [W [] 1] 1,W [] 1] 1] => [W [W [W [] 1] 1] 1]*[W [W [] 1] 1]
[W [W [] 1] 2,W [] 1] => [W [W [] 1] 1,W [] 1]*[W [] 2]
[W [] 2903591] => [W [] 1699]*[W [] 1709]
```
Output from the pretty-print version:
```
[W [W [] 2] 1,W [] 1] == w^2 + 1 => p
[W [W [W [] 1] 1] 1] == w^w => p
[W [W [W [W [] 1] 1] 1] 1] == w^(w^w) => p
[W [W [] 1] 1,W [] 100] == w + 100 => (2)*(w + 50)
[W [W [] 3] 1] == w^3 => (w)*(w^2)
[W [W [W [] 1] 1,W [] 1] 1,W [] 2] == w^(w + 1) + 2 => (2)*(w^(w + 1) + 1)
[W [W [W [] 1] 1,W [] 1] 1] == w^(w + 1) => (w^w)*(w)
[W [W [] 1] 2,W [] 1] == w*2 + 1 => (w + 1)*(2)
[W [] 2903591] == 2903591 => (1699)*(1709)
```
# Strategy
This is probably not the fastest solution, but I thought it might be relatively short for code golf. It works for all of the test cases and works well for natural numbers. For ordinals with many terms, this may take a very long time to run.
* Generate a sequence of ordinals which may divide the input.
* Test each ordinal in the sequence to determine whether it divides the input and meets the additional criteria. If it does, return a formatted string containing the divisor and quotient.
* If the sequence was exhausted, return "p" for prime.
# Implementation
I started with [code I found online](https://github.com/damast93/ordinals) that implements ordinal addition and multiplication and uses the QuickCheck library to test that properties (theorems) are true for a large number of inputs.
I implemented left subtraction and then left division with remainder and verified that the operations were consistent with the following theorems.
[Left subtraction](https://proofwiki.org/wiki/Ordinal_Subtraction_when_Possible_is_Unique): Let \$x\$ and \$y\$ be ordinals such that \$x \geq y\$. Then there exists a unique ordinal \$z\$ such that \$x = y + z\$.
[Left division](https://proofwiki.org/wiki/Division_Theorem_for_Ordinals): Let \$x\$ and \$y\$ be ordinals. Suppose \$y\neq0\$. Then there exist unique ordinals \$z\$ and \$w\$ such that \$x=y\cdot z+w\$ and \$w < y\$.
# Generated Sequences
To test whether an ordinal is prime, I generate a list of potential divisors. This would be easy for natural numbers, but infinite ordinals are greater than infinitely many ordinals.
I check the given ordinal to determine the depth, maximum number of terms (at each depth), and maximum coefficient.
I then recursively generate ordinals that are less than the given one and up to the given depth, term count, maximum coefficient. I don't have a proof that this is sufficient, but intuitively it seems like it would be.
Here are some examples.
Example 1: \$\omega^2\cdot 3 + 4\$. Depth: 2, Max term count: 2, Max coefficient: 4. Generated list of potential divisors, length 26: \$1, 2, \omega, \omega + 1, \omega + 2, \omega\cdot2, \omega\cdot2 + 1, \omega\cdot2 + 2, \omega^2, \omega^2 + 1, \omega^2 + 2, \omega^2 + \omega, \omega^2 + \omega + 1, \omega^2 + \omega + 2, \omega^2 + \omega\cdot2, \omega^2 + \omega\cdot2 + 1, \omega^2 + \omega\cdot2 + 2, \omega^2\cdot2, \omega^2\cdot2 + 1, \omega^2\cdot2 + 2, \omega^2\cdot2 + \omega, \omega^2\cdot2 + \omega + 1, \omega^2\cdot2 + \omega + 2, \omega^2\cdot2 + \omega\cdot2, \omega^2\cdot2 + \omega\cdot2 + 1, \omega^2\cdot2 + \omega\cdot2 + 2\$
Example 2: \$\omega^\omega\cdot3+4\$. Depth: 3, Max term count: 2, Max coefficient: 4. Generated terms list length: 151,994.
Since that list is generated lazily, the program still gives a fast answer.
As the depth and maximum term count increase, the lengths of the generated sequences increase very quickly.
# Note
For the last given test case, \$\omega\cdot2+1=(\omega+1)\cdot2\$, I was unable to satisfy either of the two given additional criteria (\$ùëü\_0\$ is a limit ordinal, \$ùëü\_0 \leq r\_1\$). However, I was able to satisfy the following criteria stated on Wikipedia, which is a slight variation of the given criteria:
* Every limit prime occurs before every successor prime
* If two consecutive primes of the prime factorization are both limits or both finite, then the second one is at most the first one.
If anyone is interested, I could provide a less golfed version of this code.
] |
[Question]
[
Many programming language provide operators for manipulating the binary (base-2) digits of integers. Here is one way to generalize these operators to other bases:
Let *x* and *y* be single-digit numbers in base *B*. Define the unary operator `~` and binary operators `&`, `|`, and `^` such that:
* ~x = (B - 1) - x
* x & y = min(x, y)
* x | y = max(x, y)
* x ^ y = (x & ~y) | (y & ~x)
Note that if B=2, we get the familiar bitwise NOT, AND, OR, and XOR operators.
For B=10, we get the “decimal XOR” table:
```
^ │ 0 1 2 3 4 5 6 7 8 9
──┼────────────────────
0 │ 0 1 2 3 4 5 6 7 8 9
1 │ 1 1 2 3 4 5 6 7 8 8
2 │ 2 2 2 3 4 5 6 7 7 7
3 │ 3 3 3 3 4 5 6 6 6 6
4 │ 4 4 4 4 4 5 5 5 5 5
5 │ 5 5 5 5 5 4 4 4 4 4
6 │ 6 6 6 6 5 4 3 3 3 3
7 │ 7 7 7 6 5 4 3 2 2 2
8 │ 8 8 7 6 5 4 3 2 1 1
9 │ 9 8 7 6 5 4 3 2 1 0
```
For multi-digit numbers, apply the single-digit operator digit-by-digit. For example, 12345 ^ 24680 = 24655, because:
* 1 ^ 2 = 2
* 2 ^ 4 = 4
* 3 ^ 6 = 6
* 4 ^ 8 = 5
* 5 ^ 0 = 5
If the operands are different lengths, then pad the shorter one with leading zeros.
# The challenge
Write, in as few bytes as possible, a program or function that takes as input two integers (which may be assumed to be between 0 and 999 999 999, inclusive) and outputs the “decimal XOR” of the two numbers as defined above.
# Test cases
* 12345, 24680 → 24655
* 12345, 6789 → 16654
* 2019, 5779 → 5770
* 0, 999999999 → 999999999
* 0, 0 → 0
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
DUz0«9_ṚƊṀƊ€UḌ
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//RFV6MMKrOV/huZrGiuG5gMaK4oKsVeG4jP///zgyMzQ1LDY3ODk "Jelly – Try It Online")
[Grid of all single digit pairs](https://tio.run/##ATEAzv9qZWxsef//RFV6MMKrOV/huZrGiuG5gMaK4oKsVeG4jP/igbXhuLYsw4fCpcO@YEf/ "Jelly – Try It Online")
A monadic link taking a list of two integers as its argument and returning an integer.
## Explanation
```
D | Decimal digits
U | Reverse order of each set of digits
z0 | Transpose with 0 as filler
Ɗ€ | For each pair of digits, do the following as a monad:
« Ɗ | - Minimum of the two digits and the following as a monad (vectorises):
9_ | - 9 minus the digits
Ṛ | - Reverse the order
Ṁ | - Maximum
U | Reverse the order of the answer to restore the orignal order of digits
Ḍ | Convert back from decimal digits to integer
```
If a digit matrix is acceptable input/output:
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Uz0«9_ṚƊṀƊ€U
```
[Try it online!](https://tio.run/##y0rNyan8/z@0yuDQasv4hztnHet6uLPhWNejpjWh////jzbUMdIx1jHRMY3ViTYC0mY6FjoGsQA "Jelly – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 31 bytes
```
LhS,hb-9ebjkmeS,ydy_d_.t_MjRTQ0
```
[Try it online!](https://tio.run/##K6gsyfj/3ycjWCcjSdcyNSkrOzc1WKcypTI@JV6vJN43Kygk0OD//2hDI2MTUx0FM3MLy1gA "Pyth – Try It Online")
```
LhS,hb-9eb # Helper function, computes the (x & ~y) part
L # y = lambda b:
S # sorted( )
, # [ , ]
hb # b[0]
-9eb # 9-b[-1]
h # [0] # sorted(...)[0] = minimum
jkmeS,ydy_d_.t_MjRTQ0 # Main program (example input Q: [123, 45])
jRTQ # convert each input to a list of digits -> [[1,2,3],[4,5]]
_M # reverse each -> [[3,2,1],[5,4]]
.t 0 # transpose, padding right with 0 -> [[3,5],[2,4],[1,0]]
_ # reverse -> [[1,0],[2,4],[3,5]]
m # map that over lambda d:
S, # sorted([ , ])
yd # y(d)
y_d # y(d[::-1]) # reversed
e # [-1] # sorted(...)[-1] = maximum
jk # ''.join( ^^^ )
```
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
f=lambda n,m,T=10:n+m and max(min(n%T,~m%T),min(m%T,~n%T))+f(n/T,m/T)*T
```
[Try it online!](https://tio.run/##XchBDoIwEEDRvaeYDUlHJqGtQMGEW8wFakgjiTMQw0I3Xr3Kwkj8u/@W53qd1eechluUyxhBSYgHZ89aCkQdQeLDyKRGC6aXFIy0nWz3IcQyGa2YpGI8cl7uk66QjPOnuiHwddtZPPxpG7r@h966nqAJYWeWoP@2V4v5DQ "Python 2 – Try It Online")
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 111 bytes
```
: m 10 /mod rot ;
: t 9 swap - min ;
: f 2dup + 0> if m m recurse 10 * -rot 2dup swap t -rot t max + 1 then * ;
```
[Try it online!](https://tio.run/##TY3NDoIwEITvPsWEo6bQVv4KCe9CgAqHQlNK9O1xWzVxD7uZyXw7enN@Zg8dznk2MBAcmdlGuM2jvTTwUNifvQWDWdZoacjxsLiBd1g0MQZuGg63T4G@ggU2RiLoP4aH6V8ECfh5WinWUp/9yxVIXXhAO00A1iGhqhSDo1Yh73kBmZc1h/2qsqoVCcmFQlFVCiQ41G@iCunzDQ "Forth (gforth) – Try It Online")
### Code Explanation
```
: m \ start a new word definition
10 /mod \ get quotient and remainder of dividing by 10
rot \ move item in 3rd stack position to top of stack
; \ end word definition
\ word implementing "not" followed by "and"
: t \ start a new word definition
9 swap - \ subtract top stack element from 9
min \ get the minimum of the top two stack elements
; \ end word definition
: f \ start a new word definition
2dup + \ duplicate top two stack elements and add them together
0> if \ if greater than 0
m m \ divide both by 10, move remainders behind quotients
recurse \ call self recursively
10 * \ multiply result by 10 (decimal left shift of 1)
-rot \ get remainders from original division
2dup \ duplicate both remainders
swap t \ swap order and call t (b & !a)
-rot t \ move result back and call t on other pair (a & !b)
max + 1 \ get the max of the two results and add to total. put 1 on top of stack
then \ end if block
* \ multiply top two stack results (cheaper way of getting rid of extra 0)
; \ end word definition
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 75 bytes
```
a=>b=>a.Select((x,y)=>Math.Max(9-x<(y=y<b.Count?b[y]:0)?9-x:y,9-y<x?9-y:x))
```
Saved 6 bytes thanks to @someone
[Try it online!](https://tio.run/##XU67CsIwFN39CscEbkt9om0SB1EQdFJwKA5pSDVQIzQpJojfHuNj8kznCUeYRBgV1p0WZLPS3VW2vGokUdoy@LhbZWz/q/8LjNU0cMoqyni6l40UFiEHHlO24/aS7rhD88QR5KknVbq8ddouqtKf8gwvYpB7mCeeuMh97jAORe/YKiuRsa3S5zjQgltUIy3v5ekxgCGMYAyTJ/45w6imMIPsmR5u76MIRxThBQ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~111~~ 109 bytes
```
for(;''<($a=$argv[1][-++$i]).$b=$argv[2][-$i];)$s=min($a<5?9-$a:$a,max($a<5?$a:9-$a,$a<5?$b:9-$b)).$s;echo$s;
```
[Try it online!](https://tio.run/##LczbCkBAEIDhl5lic4h1CLvyIHIxK6cLbJS8/RhxM9P/NY2dLenG8hz3w1WOo13AGvCYrjbu2sDzYOlECOY3ycaiBJz1umx8rLOmDAArQH/F@wPO1/wvzBtG8JdTDf288yKiWCZpRjLNi@gB "PHP – Try It Online")
Tests: [Try it online!](https://tio.run/##ZY/RaoMwFIbv8xSHEohS26ozWhulD@JkxJJVoVoxdmyMPbs70bRQem6S7@fj55y@7qfs2Nc9IXRUetSQQ0EAp2BB@BZxBh6wMIr3Pis9k8NuB8icv1hxsk/vkrGCOOaRtUI/SBkYiyfJk4XsW8lnc4hSeh9jovTgF/Oxlq3zSSkI@bwOSp5qcOxRUsP8c@F3bqByOH/hqXIY5M9Hq4azcorudrlg2SKKCTscwVjmUJnPfhGUxWa9pk3pbmllsxAzTIRLdd42HcoZP6YbKg9Ueq38XgJEk3kLVAYqF1u0UKf6is9ktjJ/WL13KzEveeu0Gh3auE@oEf@mfw "PHP – Try It Online")
If we call the digits we want to XOR, `$a` and `$b`, I found that:
* When `$a` is less than 5, `XOR = min(9-$a, max($a, $b))`
* When `$a` is equal to or more than 5, `XOR = min($a, max(9-$a, 9-$b))`
So I implemented this logic plus a hack to handle numbers with different lengths. I take each digit form the end of both input numbers (with negative indexes like `input[-1]`, `input[-2]`, ...) and compute the XOR and put the result in reversed order in a string to be printed at the end. Since I take digits from the end of numbers, XOR results should be put together in reversed order. When one of the inputs is longer than the other one, the negative index on shorter input results in an empty string which is equal to 0.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~85~~ 59 bytes
```
^'0P`.+
N$`.
$.%`
¶
/../_(`^
$"
T`d`Rd`.¶.
%N`.
^N`..
L`^.
```
[Try it online!](https://tio.run/##NYpBCsIwFAX37xiSYMHw@hPbprmDFFHX8Qvtwo0L8Ww9QC8WA@IshlnMe/k8Xw9fbHNVV/JezsoDJqOEoVVsK9CS7b3RDLPDTWe9zMptJexUr1xFnDSzFB@OXe9CN4yCXw9xTAjik@tjTBCX/tSWLw "Retina – Try It Online") Takes input as separate lines, but link is to test suite that reformats comma-separated input. Explanation:
```
^'0P`.+
```
Left-pad with zeros both lines to the same length.
```
N$`.
$.%`
¶
```
Sort each digit by its column index, then delete the newline. This has the effect of pairing the digits together in much the same way as a transpose would.
```
/../_(`
```
Apply separately to each pair of digits, joining the results together.
```
^
$"
```
Duplicate the pair.
```
T`d`Rd`.¶.
```
Reverse the second digit of the first pair and the first digit of the second, so we now have `x ~y` on one line and `~x y` on the other.
```
%N`.
```
Sort the digits of each line in order, so that the first digit is now `x & ~y` or `~x & y` as appropriate.
```
^N`..
```
Reverse sort the lines.
```
L`^.
```
And extract the first digit, which is the desired result.
] |
[Question]
[
This was inspired by a [now removed CS.SE question](https://cs.stackexchange.com/q/63892/23039).
### Task
Given two non-empty input strings A and B, output the smallest distance from A to a palindrome that contains B as a substring. Distance is defined by the number of character replacements ([Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance)).
### Restrictions
* Sensible input: a palindrome exists. This means |A| ≥ |B|.
* A and B contain only lower ASCII characters, lowercase and uppercase are distinct (as are all other characters).
* If your language cannot deal with ASCII characters, you may use integers (or some other reasonable data type) as well, and you may choose to limit the range to 128 elements.
* You may take input from stdin, function arguments, command line arguments, etc.
* You may give the result on stdout, return value, etc.
* You do not need to give a working palindrome, the smallest distance to one is sufficient.
### Examples
```
A B Output
thilloaoyreot hello 4 (thelloaolleht)
benjonson stack 9 (stackcats)
neversaynever! odd 9 (neveroddoreven)
ppcggcpp gg 0 (ppcggcpp)
stars tat 1 (stats)
```
### Scoring
This is code golf, shortest code in bytes wins.
[Answer]
# Pyth, 19 bytes
```
hSmsnVQd/#z_I#^+Qzl
```
[Demonstration](https://pyth.herokuapp.com/?code=hSmsnVQd%2F%23z_I%23%5E%2BQzl&input=%22isaac%22%0Ahi&debug=0)
Extreme brute force approach. Generate all strings of the appropriate length with characters in either string, filter for palindromes and for containing the second input, map to hamming distance from first string, output smallest.
Explanation:
```
hSmsnVQd/#z_I#^+Qzl
hSmsnVQd/#z_I#^+QzlQ Variable introduction
Q = string A, z = string B.
+Qz Concatenate A and B
^ lQ Form every string of length equal to len(A)using
characters from the concatenation.
# Filter on
_I Invariance under reversal (palindrome)
# Filter on
/ z Nonzero occurences of B
m Map to
nV !=, vectorized over
Qd A and the map input
s Sum (gives the hamming weight)
hS Min
```
[Answer]
# Pyth, 45 bytes
```
hSmsnVQdf}zTsmm+hc2KsXcd+Bklz1z_hc2PKh-lQlz_B
```
[Try it online.](http://pyth.herokuapp.com/?code=hSmsnVQdf%7DzTsmm%2Bhc2KsXcd%2BBklz1z_hc2PKh-ldlz_B&input=%22thilloaoyreot%22%0Ahello&test_suite_input=%22thilloaoyreot%22%0Ahello%0A%22benjonson%22%0Astack%0A%22neversaynever%21%22%0Aodd%0A%22ppcggcpp%22%0Agg&debug=0&input_size=2) [Test suite.](http://pyth.herokuapp.com/?code=hSmsnVQdf%7DzTsmm%2Bhc2KsXcd%2BBklz1z_hc2PKh-ldlz_B&input=%22thilloaoyreot%22%0Ahello&test_suite=1&test_suite_input=%22thilloaoyreot%22%0Ahello%0A%22benjonson%22%0Astack%0A%22neversaynever%21%22%0Aodd%0A%22ppcggcpp%22%0Agg&debug=0&input_size=2)
I'm still not exactly satisfied with how this turned out. But at least it's quite hard to understand without an explanation now. (Success, I guess?)
### Explanation
* Take in A as `Q` and B as `z`.
* `m`…`_BQ` Compute the following for both A and its reverse as `d`:
+ `m`…`h-ldlz` Compute the following for all `k` from 0 to `len(A) - len(B)` inclusive:
- `+Bklz` Get the pair `k, k + len(B)`.
- `cd` Split `d` at those indices.
- `X`…`1z` Replace the second (middle) part with B.
- `Ks` Concatenate the pieces and save to `K`. B is now inserted at position `k` in A or its reverse.
- `hc2` Split the resulting string in two and keep the first piece. This gives half of the string with the possible middle character.
- `hc2PK` Remove the last character and do the same split, keeping the first piece. This gives half of the string without the possible middle character.
- `+`…`_` Add the reverse of the shorter piece to the longer piece. We now have a palindrome.
* `s` Concatenate the results for A and its reverse.
* `f}zT` Remove all strings that don't contain B.
* `m` Compute the following for all the resulting strings `d`:
+ `nVQd` Get the pairwise inequality with A. This gives True for pairs that need to be changed.
+ `s` Sum the list. This gives the Hamming distance.
* `hS` Take the minimum result.
[Answer]
# JavaScript (Firefox 30+), ~~152~~ 146 bytes
```
(A,B)=>Math.min(...[...Array(A[l='length']-B[l]+1)].map((_,i)=>[for(c of q=A.slice(j=t=0,i)+B+A.slice(i+B[l]))t+=(c!=A[j])+(c!=q[q[l]-++j])/2]|t))
```
Brute force approach: generate each possible overlap of A and B, make each into a palindrome, calculate Hamming distances from A, and take the smallest of the resulting distances.
Probably could be golfed a bit more...
### Test snippet
```
f=(A,B)=>Math.min(...[...Array(A[l='length']-B[l]+1)].map((_,i)=>[for(c of q=A.slice(j=t=0,i)+B+A.slice(i+B[l]))t+=(c!=A[j])+(c!=q[q[l]-++j])/2]|t))
g=(A,B)=>console.log("A:",A," B:",B," f(A,B):",f(A,B))
g("thilloaoyreot", "hello")
g("benjonson", "stack")
g("neversaynever!", "odd")
g("ppcggcpp", "gg")
```
```
<input id=A value="amanaplanacanalrussia">
<input id=B value="panama">
<button onclick="g(A.value,B.value)">Run</button>
```
] |
[Question]
[
You are given a set of logic statements. Your challenge is to remove any ones that contradict the others, but in the optimal way (i.e. removing a minimal number of statements).
### Challenge
You will write a program or a function that takes as input a list of statements, removes **the minimal number** of statements such that there is a **solution** and outputs the rest.
### Logic
Statements consist of *variables* `A-Z` and *operators* between them.
There are 5 *operators*: `-` (not), `v` (or), `^` (and), `->` (if) and `<->` (iff).
Truth table:
```
A | B | -A | AvB | A^B | A->B | A<->B
0 | 0 | 1 | 0 | 0 | 1 | 1
0 | 1 | 1 | 1 | 0 | 1 | 0
1 | 0 | 0 | 1 | 0 | 0 | 0
1 | 1 | 0 | 1 | 1 | 1 | 1
```
These *operators* can be combined together with parenthesis `()`:
```
A | B | -(AvB) | Av(-A) | A^(-A) | (AvB)->(-B)
0 | 0 | 1 | 1 | 0 | 1
0 | 1 | 0 | 1 | 0 | 0
1 | 0 | 0 | 1 | 0 | 1
1 | 1 | 0 | 1 | 0 | 0
```
*Logic systems* consist of 1 or more *statements*.
A *solution* to the *logic system* is a state where all of the *statements* are simultaneously true.
### Examples of logic systems:
```
AvB
-(A<->B)
(AvB)->(-B)
```
The only *solution* is `A = 1, B = 0`.
```
A^B
-(B<->A)
```
This one has no *solution*; with no combination of `A` and `B` both of the *statements* are true.
### Input
You will receive a set of *statements* as input. This can be taken via STDIN or function arguments, formatted as an array (in a convenient format) or a newline-separated or space-separated string.
The statements will be of the following form (in almost-[ABNF](https://www.rfc-editor.org/rfc/rfc5234)):
```
statement = variable / operation
operation = not-operation / binary-operation
not-operation = "-" operand
binary-operation = operand binary-operator operand
operand = variable / "(" operation ")"
variable = "A"-"Z"
binary-operator = "v" / "^" / "->" / "<->"
```
Example statements:
```
A
Av(-B)
(A<->(Q^C))v((-B)vH)
```
### Output
You must return the (possibly) reduced set of statements, in the exact form you received them. Again, the list can be formatted as an array of strings or a newline-separated or space-separated string.
### Rules
* You should always remove the minimal number of statements. If there are multiple possible solutions, output one of them.
* You may assume that the input always contains at least 1 statement and that no statements are repeated in the input.
* You may not assume that the output always contains a statement. (see examples)
* Using standard loopholes contradicts with your answer being valid, and one of them must be removed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
### Examples
Input:
```
A^(-A)
```
Output:
```
(nothing)
```
Input:
```
A^B A<->(-B) A<->B
```
Output:
```
A^B A<->B
```
Input:
```
["AvB","A^B"]
```
Output:
```
["AvB","A^B"]
```
[Answer]
# Python 3, 431 bytes
Not very golfed right now, but I figure I'd get the ball rolling with an answer. Try it [here](https://repl.it/BCyz/11), `g()` is the main function.
```
import re,itertools as H
def g(i):
y=re.sub(r'\W','',''.join(set(i)).upper());l=i.split()
def e(s):
def f(a):
for v,w in a:exec(v+'='+w)
return eval(re.sub('[^A-Z()]+',lambda x:{'v':' or ','^':'*','<->':'==','->':'<=','-':'not '}[x.group()],s))
return[c for c in H.product("01",repeat=len(y))if f(zip(y,c))]
for n in range(len(l),-1,-1):
for q in H.combinations(l,n):
if e('('+')^('.join(q)+')'):return' '.join(q)
```
[Answer]
# Ruby, ~~299~~ ~~298~~ ~~283~~ 279 bytes
```
class Object;def * o;!self|o;end;def s;w=join.gsub(/\W/,"").chars.uniq;n=w.size;(0..2**n).any?{|i|n.times{|j|eval(w[j]+"=#{i[j]>0}")};all?{|e|eval([%w[<-> ==],%w[-> *],%w[- !],%w[^ &],%w[v |]].inject(e){|x,i|x.gsub(*i)})}}?self:combination(size-1).map(&:s).max_by(&:size);end;end
```
* Expects an array of expressions.
* If you're going to run it, set $VERBOSE=nil from inside ruby so you don't get lots of warnings about redefining constants.
* Note that it actually sets the variable "v" as well but it doesn't make a difference.
* Uses truth values because they have all of the required operators already, except implication. Unfortunately Ruby doesn't have a boolean class so we have to monkey-patch Object to get implication :)
* Could make it shorter if we just set ALL of the uppercase variables, but then it would take a huge amount of time to run. Should probably have a caveat in the question about that.
Ungolfed:
```
class Object
def * o
!self|o
end
end
def sat? exs
#exs: an array of expressions
s=[%w[<-> ==], %w[-> *], "-!", "^&", %w[v ||]]
w=exs.join.gsub(/\W/,"").chars.uniq #variable names
n=w.size
if (0...2**n).any? {|i|
n.times do |vi|
eval("#{w[vi]}=#{i[vi]==1}")
end
exs.all?{|ex|eval(s.inject(ex){|x,i|x.gsub(i[0],i[1])})}
}
exs
else
exs.combination(exs.size-1).map{|sm|sat?(sm)}.max_by(&:size)
end
end
```
] |
[Question]
[
# Fast Trigonometry Calculations
Your task is to create a program which can calculate the sine, cosine and tangent of an angle in degrees.
## Rules
* No built-in trigonometry functions (not even secant, cosecant and cotangent if your language has them).
* You may use lookup tables, but their total size must not exceed 3000 members (for all of the three operations put together). Please make it read the tables from a file (e.g. `trig.lookup`) so they don't confuse the code.
* No network access.
* You must correctly round your output as explained below. Don't use floor or ceiling.
* You may use any method to calculate the values, for example [continued fractions](https://en.wikipedia.org/wiki/Sine#Continued_fraction), as long as it is correct to 7 significant figures.
* Your code must be able to time itself. Exclude the file I/O operations from your time - so just time the function(s) that do(es) the trig and any rounding.
* I must be able to run your code. Please post a link to a freely available compiler/interpreter and give the instructions needed to compile/run the code (e.g. what options to pass to GCC).
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply.
## Input Format
* Read from a file called `trig.in` unless your language doesn't support file I/O.
* Angles are between 0 and 360 inclusive.
* Input will consist of angles to ten significant figures in decimal digits, separated by new lines. For example:
>
> 90.00000000
>
> 74.54390000
>
> 175.5000000
>
>
>
## Output Format
* For each angle supplied, you must output its sine, cosine and tangent to 7 significant figures, separated by spaces, on a single line. Use "scientific notation", e.g. `1.745329E-5` for `tan 0.001` or `1.000000E+0` for `sin 90`.
* Denote infinity or NaN by `n`, for example the output for `90.00000000` should be `1.000000 0.000000 n`.
* If the input is three angles separated by newlines, your output should consist of three lines, each containing the sine, cosine and tangent.
* You may not output anything else.
* Output to a file called `trig.out` unless your language does not support file I/O.
## Scoring
* [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'"). The challenge is to write a program which computes these three values as quickly as possible. Fastest time wins.
* Everyone will receive the same test input of many angles.
* Times will be recorded on my machine.
* Your score is the average of three runs on the same input (you can't save anything in between runs obviously).
* Compiling time not included. This challenge is more about the method used than the language. (If someone could point me to how I would exclude compilation time for languages such as Java, I'd be very grateful)
* My machine is an Ubuntu 14.04 install. The processor's stats are [on Pastebin](http://pastebin.com/dM1TW2S5) (obtained by running `cat /proc/cpuinfo`).
* I will edit your time into your answer when I've tested it.
[Answer]
# Fortran 90
I employ the [CORDIC](http://en.wikipedia.org/wiki/Cordic) method with a pre-tabulated array of 60 arctan values (see Wiki article for details on why that's necessary).
This code requires a file, `trig.in`, with all the values on newlines to be stored in the same folder as the Fortran executable. Compiling this is,
```
gfortran -O3 -o file file.f90
```
where `file` is whatever filename you give it (probably `SinCosTan.f90` would be easiest, though it's not necessary to match program name and file name). If you have the Intel compiler, I'd recommend using
```
ifort -O3 -xHost -o file file.f90
```
as the `-xHost` (which doesn't exist for gfortran) provides higher level optimizations available to your processor.
My test runs were giving me about 10 microseconds per calculation when testing 1000 random angles using gfortran 4.4 (4.7 or 4.8 is available in the Ubuntu repos) and around 9.5 microseconds using ifort 12.1. Testing only 10 random angles will result in an indeterminable time using Fortran routines, as the timing routine is accurate to the millisecond and simple math says it should take 0.100 milliseconds to run all 10 numbers.
---
**EDIT** Apparently I was timing IO which (a) made the timing longer than necessary and (b) is contrary to bullet #6. I've updated the code to reflect this. I've also discovered that using a `kind=8` integer with the intrinsic subroutine `system_clock` gives microsecond accuracy.
With this updated code, **I am now computing each set of values of the trigonometric functions in about 0.3 microseconds** (the significant digits in the end vary run-to-run, but it's consistently hovering near 0.31 us), a significant reduction from the previous iteration that timed IO.
---
```
program SinCosTan
implicit none
integer, parameter :: real64 = selected_real_kind(15,307)
real(real64), parameter :: PI = 3.1415926535897932384626433832795028842
real(real64), parameter :: TAU = 6.2831853071795864769252867665590057684
real(real64), parameter :: half = 0.500000000000000000000_real64
real(real64), allocatable :: trigs(:,:), angles(:)
real(real64) :: time(2), times, b
character(len=12) :: tout
integer :: i,j,ierr,amax
integer(kind=8) :: cnt(2)
open(unit=10,file='trig.out',status='replace')
open(unit=12,file='CodeGolf/trig.in',status='old')
! check to see how many angles there are
i=0
do
read(12,*,iostat=ierr) b
if(ierr/=0) exit
i=i+1
enddo !-
print '(a,i0,a)',"There are ",i," angles"
amax = i
! allocate array
allocate(trigs(3,amax),angles(amax))
! rewind the file then read the angles into the array
rewind(12)
do i=1,amax
read(12,*) angles(i)
enddo !- i
! compute trig functions & time it
times = 0.0_real64
call system_clock(cnt(1)) ! <-- system_clock with an 8-bit INT can time to us
do i=1,amax
call CORDIC(angles(i), trigs(:,i), 40)
enddo !- i
call system_clock(cnt(2))
times = times + (cnt(2) - cnt(1))
! write the angles to the file
do i=1,amax
do j=1,3
if(trigs(j,i) > 1d100) then
write(tout,'(a1)') 'n'
elseif(abs(trigs(j,i)) > 1.0) then
write(tout,'(f10.6)') trigs(j,i)
elseif(abs(trigs(j,i)) < 0.1) then
write(tout,'(f10.8)') trigs(j,i)
else
write(tout,'(f9.7)') trigs(j,i)
endif
write(10,'(a)',advance='no') tout
enddo !- j
write(10,*)" "
enddo !- i
print *,"computation took",times/real(i,real64),"us per angle"
close(10); close(12)
contains
!> @brief compute sine/cosine/tangent
subroutine CORDIC(a,t,n)
real(real64), intent(in) :: a
real(real64), intent(inout) :: t(3)
integer, intent(in) :: n
! local variables
real(real64), parameter :: deg2rad = 1.745329252e-2
real(real64), parameter :: angles(60) = &
[ 7.8539816339744830962e-01_real64, 4.6364760900080611621e-01_real64, &
2.4497866312686415417e-01_real64, 1.2435499454676143503e-01_real64, &
6.2418809995957348474e-02_real64, 3.1239833430268276254e-02_real64, &
1.5623728620476830803e-02_real64, 7.8123410601011112965e-03_real64, &
3.9062301319669718276e-03_real64, 1.9531225164788186851e-03_real64, &
9.7656218955931943040e-04_real64, 4.8828121119489827547e-04_real64, &
2.4414062014936176402e-04_real64, 1.2207031189367020424e-04_real64, &
6.1035156174208775022e-05_real64, 3.0517578115526096862e-05_real64, &
1.5258789061315762107e-05_real64, 7.6293945311019702634e-06_real64, &
3.8146972656064962829e-06_real64, 1.9073486328101870354e-06_real64, &
9.5367431640596087942e-07_real64, 4.7683715820308885993e-07_real64, &
2.3841857910155798249e-07_real64, 1.1920928955078068531e-07_real64, &
5.9604644775390554414e-08_real64, 2.9802322387695303677e-08_real64, &
1.4901161193847655147e-08_real64, 7.4505805969238279871e-09_real64, &
3.7252902984619140453e-09_real64, 1.8626451492309570291e-09_real64, &
9.3132257461547851536e-10_real64, 4.6566128730773925778e-10_real64, &
2.3283064365386962890e-10_real64, 1.1641532182693481445e-10_real64, &
5.8207660913467407226e-11_real64, 2.9103830456733703613e-11_real64, &
1.4551915228366851807e-11_real64, 7.2759576141834259033e-12_real64, &
3.6379788070917129517e-12_real64, 1.8189894035458564758e-12_real64, &
9.0949470177292823792e-13_real64, 4.5474735088646411896e-13_real64, &
2.2737367544323205948e-13_real64, 1.1368683772161602974e-13_real64, &
5.6843418860808014870e-14_real64, 2.8421709430404007435e-14_real64, &
1.4210854715202003717e-14_real64, 7.1054273576010018587e-15_real64, &
3.5527136788005009294e-15_real64, 1.7763568394002504647e-15_real64, &
8.8817841970012523234e-16_real64, 4.4408920985006261617e-16_real64, &
2.2204460492503130808e-16_real64, 1.1102230246251565404e-16_real64, &
5.5511151231257827021e-17_real64, 2.7755575615628913511e-17_real64, &
1.3877787807814456755e-17_real64, 6.9388939039072283776e-18_real64, &
3.4694469519536141888e-18_real64, 1.7347234759768070944e-18_real64]
real(real64), parameter :: kvalues(33) = &
[ 0.70710678118654752440e+00_real64, 0.63245553203367586640e+00_real64, &
0.61357199107789634961e+00_real64, 0.60883391251775242102e+00_real64, &
0.60764825625616820093e+00_real64, 0.60735177014129595905e+00_real64, &
0.60727764409352599905e+00_real64, 0.60725911229889273006e+00_real64, &
0.60725447933256232972e+00_real64, 0.60725332108987516334e+00_real64, &
0.60725303152913433540e+00_real64, 0.60725295913894481363e+00_real64, &
0.60725294104139716351e+00_real64, 0.60725293651701023413e+00_real64, &
0.60725293538591350073e+00_real64, 0.60725293510313931731e+00_real64, &
0.60725293503244577146e+00_real64, 0.60725293501477238499e+00_real64, &
0.60725293501035403837e+00_real64, 0.60725293500924945172e+00_real64, &
0.60725293500897330506e+00_real64, 0.60725293500890426839e+00_real64, &
0.60725293500888700922e+00_real64, 0.60725293500888269443e+00_real64, &
0.60725293500888161574e+00_real64, 0.60725293500888134606e+00_real64, &
0.60725293500888127864e+00_real64, 0.60725293500888126179e+00_real64, &
0.60725293500888125757e+00_real64, 0.60725293500888125652e+00_real64, &
0.60725293500888125626e+00_real64, 0.60725293500888125619e+00_real64, &
0.60725293500888125617e+00_real64 ]
real(real64) :: beta, c, c2, factor, poweroftwo, s
real(real64) :: s2, sigma, sign_factor, theta, angle
integer :: j
! scale to radians
beta = a*deg2rad
! ensure angle is shifted to appropriate range
call angleShift(beta, -PI, theta)
! check for signs
if( theta < -half*PI) then
theta = theta + PI
sign_factor = -1.0_real64
else if( half*PI < theta) then
theta = theta - PI
sign_factor = -1.0_real64
else
sign_factor = +1.0_real64
endif
! set up some initializations...
c = 1.0_real64
s = 0.0_real64
poweroftwo = 1.0_real64
angle = angles(1)
! run for 30 iterations (should be good enough, need testing)
do j=1,n
sigma = merge(-1.0_real64, +1.0_real64, theta < 0.0_real64)
factor = sigma*poweroftwo
c2 = c - factor*s
s2 = factor*c + s
c = c2
s = s2
! update remaining angle
theta = theta - sigma*angle
poweroftwo = poweroftwo*0.5_real64
if(j+1 > 60) then
angle = angle * 0.5_real64
else
angle = angles(j+1)
endif
enddo !- j
if(n > 0) then
c = c*Kvalues(min(n,33))
s = s*Kvalues(min(n,33))
endif
c = c*sign_factor
s = s*sign_factor
t = [s, c, s/c]
end subroutine CORDIC
subroutine angleShift(alpha, beta, gamma)
real(real64), intent(in) :: alpha, beta
real(real64), intent(out) :: gamma
if(alpha < beta) then
gamma = beta - mod(beta - alpha, TAU) + TAU
else
gamma = beta + mod(alpha - beta, TAU)
endif
end subroutine angleShift
end program SinCosTan
```
[Answer]
# Python 2.7.x or Java (Take your pick)
A free Python interpreter can be downloaded from [here](https://www.python.org/downloads/).
A free Java interpreter can be downloaded from [here](http://www.oracle.com/technetwork/java/javase/downloads/index.html).
The program can take input both from a file named `trig.in` located in the same directory as the program file. Input is separated by newlines.
I originally did this in python because - well, I love python. But, since I wanna try to win as well, I rewrote it in java afterwards...
**Python Version:** I got about 21µs per run on my computer. I got about 32µs when running it [on IDEone](http://ideone.com/iBBC9K).
**Java version:** I get about 0.4µs per run on my computer, and 1.8µs [on IDEone](http://ideone.com/lNbyOh).
**Computer specs:**
* Windows 8.1 update 1 64-bit with intel core i7-3632QM - 2.2GHz)
**Test:**
* Time per run" is the cumulative time it takes to calculate the `sin`, `cos`, and `tan` all of the input angles.
* The test input used for both is as follows:
```
90.00000000
74.54390000
175.5000000
3600000.000
```
**About The Code:**
The premise for this program was to estimate `sin` and `cos` using their Taylor polynomials with 14 terms, which was what I calculated was necessary to have an error estimate of less than 1e-8. However I found it was faster to calculate `sin` than `cos`, so decided to instead calculate `cos` by using `cos=sqrt(1-sin^2)`
>
> 
> 
>
>
>
---
# [Python Version:](http://ideone.com/iBBC9K)
```
import math
import timeit
import sys
import os
from functools import partial
#Global Variabls
pi2 = 6.28318530718
piover2 = 1.57079632679
#Global Lists
factorialList = [1.0,
-6.0,
120.0,
-5040.0,
362880.0,
-39916800.0,
6227020800.0,
-1307674368000.0,
355687428096000.0,
-121645100408832000.0,
51090942171709440000.0,
-25852016738884976640000.0,
15511210043330985984000000.0,
-10888869450418352160768000000.0,
8841761993739701954543616000000.0]
#simplifies angles and converts them to radians
def torad(x):
rev = float(x)/360.0
if (rev>1) or (rev<0):
return (rev - math.floor(rev))*pi2
return rev*pi2
def sinyield(x):
squared = x*x
for n in factorialList:
yield x/n
x*=squared
def tanfastdivide(sin, cos):
if (cos == 0):
return "infinity"
return sin/cos
#start calculating sin cos and tan
def calcyield(outList):
for angle in outList[0]:
angle = torad(angle)
sin = round(math.fsum(sinyield(angle)), 7)
cos=math.copysign(math.sqrt(1-(sin*sin)),(piover2-angle))
yield sin
yield cos
yield tanfastdivide(sin, cos) #tan
def calculations(IOList):
calcyieldgen = calcyield(IOList)
for angle in IOList[0]:
IOList[1].append(next(calcyieldgen))
IOList[2].append(next(calcyieldgen))
IOList[3].append(next(calcyieldgen))
return IOList
#Begin input from file
def ImportFile():
try:
infile = open("trig.in", "r")
except:
infile = sys.stdin
inList = [[], [], [], []]
#take input from file
for line in infile:
inList[0].extend([float(line)])
return inList
#Begin output to file
def OutputResults(outList):
try:
outfile = open("trig.out", "w")
PrintOutput(outList, outfile)
except:
print 'Failed to write to file. Printing to stdout instead...'
finally:
PrintOutput(outList, sys.stdout)
def PrintOutput(outList, outfile):
#outList[0][i] holds original angles
#outList[1][i] holds sin values
#outList[2][i] holds cos values
#outList[3][i] holds tan values
outfile.write('-----------------------------------------------------\n')
outfile.write(' TRIG RESULTS \n')
outfile.write('-----------------------------------------------------\n')
for i in range(len(outList[0])):
if (i):
outfile.write('\n')
outfile.write("For angle: ")
outfile.write(str(outList[0][i]))
outfile.write('\n ')
outfile.write("Sin: ")
outfile.write(str('%.7E' % float(outList[1][i])))
outfile.write('\n ')
outfile.write("Cos: ")
outfile.write(str('%.7E' % float(outList[2][i])))
outfile.write('\n ')
outfile.write("Tan: ")
outfile.write(str('%.7E' % float(outList[3][i])))
#Run the Program first
inList = ImportFile()
OutputResults(calculations(inList))
#Begin Runtime estimation
def timeTest(IOList):
for output in calcyield(IOList):
pass
def baselined(inList):
for x in inList:
pass
totime = timeit.Timer(partial(timeTest, inList))
baseline = timeit.Timer(partial(baselined, inList))
print '\n-----------------------------------------------------'
print ' TIME RESULTS: '
print '-----------------------------------------------------'
OverheadwithCalcTime = min(totime.repeat(repeat=10, number=10000))
Overhead = min(baseline.repeat(repeat=1, number=10000))
estimatedCalcTime = (OverheadwithCalcTime - Overhead)
estimatedTimePerAngle = estimatedCalcTime/len(inList)
estimatedTimePerCalc = estimatedTimePerAngle/3
print ' Estimated CalcTime+Overhead:.....', '%.10f' % (OverheadwithCalcTime*100), 'µsec'
print ' Estimated Overhead Time:..........', '%.10f' % (Overhead*100), 'µsec'
print ''
print ' Estimated CalcTime/Run:..........', '%.10f' % (estimatedCalcTime*100), 'µsec'
print ' Estimated CalcTime/Angle:.........', '%.10f' % (estimatedTimePerAngle*100), 'µsec'
print ' Estimated CalcTime/Cacluation:....', '%.10f' % (estimatedTimePerCalc*100), 'µsec'
print '-----------------------------------------------------'
print " COOL, IT WORKED! "
print '-----------------------------------------------------'
```
# [Java Version:](http://ideone.com/lNbyOh)
```
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Math;
class Trig {
/**
*Global Variables
**/
static final double pi2 = 6.28318530718;
public long totalTime = 0L;
static final double piover2 = 1.57079632679;
static final double plusinfty = Double.POSITIVE_INFINITY;
static final double minusinfty = Double.NEGATIVE_INFINITY;
static final double factoriallist[] =
new double[]{
-6.0,120.0,-5040.0,362880.0,-39916800.0,
6227020800.0,-1307674368000.0,355687428096000.0,
-121645100408832000.0,51090942171709440000.0,
-25852016738884976640000.0,
15511210043330985984000000.0,
-10888869450418352160768000000.0,
8841761993739701954543616000000.0
};
//Begin Program
public static void main(String[] args) {
Trig mytrig = new Trig();
double[] input = mytrig.getInput();
double[][] output = mytrig.calculate(input);
mytrig.OutputResults(output);
Trig testIt = new Trig();
testIt.timeIt(input);
}
//Begin Timing
public void timeIt(double[] input) {
double overhead = 0L;
totalTime = 0L;
for (int i = 0; i < 1000001; i++) {
calculate(input);
if (i == 0) {
overhead = totalTime;
totalTime = 0L;
}
}
double averageTime = ((Double.valueOf(totalTime-overhead))/1000000.0);
double perAngleTime = averageTime/input.length;
double perOpperationTime = perAngleTime/3;
NumberFormat formatter = new DecimalFormat("0000.0000");
System.out.println("\n-----------------------------------------------------");
System.out.println(" TIME RESULTS: ");
System.out.println("-----------------------------------------------------");
System.out.println("Average Total Runtime:.......... " + formatter.format(averageTime) + " nsec");
System.out.println(" = " + formatter.format(averageTime/1000) + " usec\n");
System.out.println("Average Runtime Per Angle:....... " + formatter.format(perAngleTime) + " nsec");
System.out.println(" = " + formatter.format(perAngleTime/1000) + " usec\n");
System.out.println("Average Runtime Per Opperation:.. " + formatter.format(perOpperationTime) + " nsec");
System.out.println(" = " + formatter.format(perOpperationTime/1000) + " usec");
}
//Begin Input
double[] getInput() {
Scanner in;
ArrayList<Double> input = new ArrayList<Double>();
try {
in = new Scanner(new File("trig.in"));
} catch (FileNotFoundException e) {
new FileNotFoundException("Failed to read from file. Reading from stdin instead...").printStackTrace();
in= new Scanner(System.in);
}
while (in.hasNextLine()) {
Double toadd = Double.parseDouble(in.nextLine());
input.add(toadd);
}
in.close();
double[] returnable = new double[input.size()];
for(int i = 0; i < input.size(); i++) {returnable[i] = input.get(i);}
return returnable;
}
//Begin OutputStream Choice
void OutputResults(double[][] outList) {
PrintStream out;
try {
out = new PrintStream("trig.out");
PrintOutput(outList, out);
PrintOutput(outList, System.out);
} catch (FileNotFoundException e) {
new FileNotFoundException("Failed to write to file. Printing to stdout instead...").printStackTrace();
PrintOutput(outList, System.out);
}
}
//Begin Output
static void PrintOutput(double[][] outList, PrintStream out) {
/**
*outList[0][i] holds original angles
*outList[1][i] holds sin values
*outList[2][i] holds cos values
*outList[3][i] holds tan values
*/
NumberFormat formatter = new DecimalFormat("0.0000000E0");
out.println("-----------------------------------------------------");
out.println(" TRIG RESULTS ");
out.println("-----------------------------------------------------");
for (int i=0; i<outList[0].length; i++) {
out.println("For Angle: " + outList[0][i]);
out.println(" sin: " + formatter.format(outList[1][i]));
out.println(" cos: " + formatter.format(outList[2][i]));
if (Double.valueOf(outList[3][i]).isInfinite() || Double.valueOf(outList[3][i]).isNaN()) {
out.println(" tan: " + outList[3][i]);
}
else out.println(" tan: " + formatter.format(outList[3][i]));
}
if (out != System.out) out.close();
}
//Begin Calculations
double[][] calculate(double[] IOList) {
double[][] outList = new double[4][IOList.length];
double sin;
double cos;
double tan;
double rads;
int i = 0;
long calctime = 0L;
long startTime;
long endTime;
for (double input : IOList) {
startTime = System.nanoTime();
rads = toRad(input);
sin=sin(rads);
cos = ((piover2-rads)>=0) ? Math.sqrt((1.0-(sin*sin))) : -Math.sqrt((1.0-(sin*sin)));
tan = (cos!=0.0d) ? sin/cos : ((sin>0) ? plusinfty : minusinfty);
endTime = System.nanoTime();
calctime = calctime + endTime - startTime;
outList[0][i] = input;
outList[1][i] = sin;
outList[2][i] = cos;
outList[3][i] = tan;
i++;
}
totalTime = totalTime + calctime;
return outList;
}
//Convert Degrees to Radians
double toRad(double deg) {
double rev = deg/360.0;
return (rev>1 || rev<0) ? Math.abs(rev - ((int)rev))*pi2 : rev*pi2;
}
//Get sin
double sin(double angle) {
double sqr = angle*angle;
double value = angle;
for (double fct : factoriallist) {
value += ((angle*=sqr)/fct);
}
return ((long)((value + Math.copySign(0.0000000005d, value))*10000000.0))/10000000.0;
}
}
```
[Answer]
# [Cobra](http://cobra-language.com/)
```
class Trig
const mod as float = 0.0174532925199433f #0.0174532925199432957692369076848861271344287188854172f
var time as System.Diagnostics.Stopwatch = System.Diagnostics.Stopwatch()
var file as String[] = File.readAllLines('trig.in')
var sin_out as float[] = float[](1)
var cos_out as float[] = float[](1)
var tan_out as float[] = float[](1)
def main
.compute(@[1f])
.time.reset
input = float[](.file.length)
for num, line in .file.numbered, input[num] = float.parse(line)
.compute(input)
for num in .file.length, .file[num] = (.sin_out[num].toString('0.000000E+0') + ' ' + .cos_out[num].toString('0.000000E+0') + ' ' + .tan_out[num].toString('0.000000E+0'))
File.writeAllLines('trig.out', .file)
print .time.elapsed
def compute(list as float[])
.sin_out = float[](list.length)
.cos_out = float[](list.length)
.tan_out = float[](list.length)
.time.start
for index in list.length
degrees as float = list[index]
#add `degrees %= 360` for numbers greater than 360
rad as float = sin as float = degrees * .mod
two as float = rad * rad
sin -= (rad *= two) / 6
sin += (rad *= two) / 120
sin -= (rad *= two) / 5040
sin += (rad *= two) / 362880
sin -= (rad *= two) / 39916800
sin += (rad *= two) / 6227020800
sin -= (rad *= two) / 1307674368000
sin += (rad *= two) / 355687428096000
sin -= (rad *= two) / 121645100408832000
sin += (rad *= two) / 51090942171709440000f
sin -= (rad *= two) / 25852016738884976640000f
sin += (rad *= two) / 15511210043330985984000000f
sin -= (rad *= two) / 10888869450418352160768000000f
sin += (rad *= two) / 8841761993739701954543616000000f
cos as float = (1 - (sin * sin)).sqrt * ((degrees - 180).abs - 90).sign
if cos.isNaN, cos = 0
.tan_out[index] = Math.round((sin / cos) * 10000000) / 10000000
.sin_out[index] = Math.round(sin * 10000000) / 10000000
.cos_out[index] = Math.round(cos * 10000000) / 10000000
.time.stop
```
Compile it with `cobra filename -turbo`
**Tests:** AMD FX6300 @5.1GHz
* The 360 \* 10000 test used by the C answer runs in 365ms (vs 190ms)
* The 4-entry test used by the Python and Java answers runs in 0.32µs (vs 30µs, 3µs)
* The 1000 random angle test used by the Fortran answer runs at 100ns per angle (vs 10µs)
[Answer]
# Octave (or Matlab) & C
A bit of a complicated build process, but kind of a novel approach and the results were encouraging.
The approach is to generate approximating quadratic polynomials for each degree. So degree = [0, 1), degree = [1, 2), ..., degree = [359, 360) will each have a different polynomial.
## Octave - building part
Octave is publicly available - Google `download octave`.
This determines the best fit quadratic polynomial for every degree.
Save as `build-fast-trig.m`:
```
format long;
for d = 0:359
x = (d-1):0.1:(d+1);
y = sin(x / 360 * 2 * pi);
polyfit(x, y, 2)
endfor
```
## C - building part
This converts doubles in text format to native binary format on your system.
Save as `build-fast-trig.c`:
```
#include <stdio.h>
int main()
{
double d[3];
while (scanf("%lf %lf %lf", d, d + 1, d + 2) == 3)
fwrite(d, sizeof(double), 3, stdout);
return 0;
}
```
Compile:
```
gcc -o build-fast-trig build-fast-trig.c
```
## Generating the coefficients file
Run:
```
octave build-fast-trig.m | grep '^ ' | ./build-fast-trig > qcoeffs.dat
```
Now we have `qcoeffs.dat` as the data file to use for the actual program.
## C - fast-trig part
Save as `fast-trig.c`:
```
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#define INPUT "qcoeffs.dat"
#define DEGREES 360
typedef struct {double a, b, c;} QCOEFFS;
double normalize(double d)
{
if (d < 0.0)
d += ceil(d / -(double)DEGREES) * (double)DEGREES;
if (d >= (double)DEGREES)
d -= floor(d / (double)DEGREES) * (double)DEGREES;
return d;
}
int main()
{
FILE *f;
time_t tm;
double d;
QCOEFFS qc[DEGREES];
if (!(f = fopen(INPUT, "rb")) || fread(qc, sizeof(QCOEFFS), DEGREES, f) < DEGREES)
{
fprintf(stderr, "Problem with %s - aborting.", INPUT);
return EXIT_FAILURE;
}
fclose(f);
tm = -clock();
while (scanf("%lf", &d) > 0)
{
int i;
double e, f;
/* sin */
d = normalize(d);
i = (int)d;
e = (qc[i].a * d + qc[i].b) * d + qc[i].c;
/* cos */
d = normalize((double)DEGREES / 4.0 - d);
i = (int)d;
f = (qc[i].a * d + qc[i].b) * d + qc[i].c;
/* tan = sin / cos */
/* output - format closest to specs, AFAICT */
if (d != 0.0 && d != 180.0)
printf("%.6e %.6e %.6e\n", e, f, e / f);
else
printf("%.6e %.6e n\n", e, f);
}
tm += clock();
fprintf(stderr, "time: %.3fs\n", (double)tm/(double)CLOCKS_PER_SEC);
return EXIT_SUCCESS;
}
```
Compile:
```
gcc -o fast-trig fast-trig.c -lm
```
Run:
```
./fast-trig < trig.in > trig.out
```
It will read from `trig.in`, save to `trig.out` and print to console the elapsed time with millisecond precision.
Depending on the testing methods used it may fail on certain input, e.g.:
```
$ ./fast-trig
0
-6.194924e-19 1.000000e+00 -6.194924e-19
```
The correct output should be `0.000000e+00 1.000000e+00 0.000000e+00`. If the results are validated using strings, the input will fail, if they are validated using absolute error, e.g. `fabs(actual - result) < 1e-06`, the input will pass.
The maximum absolute error for `sin` and `cos` was ≤ 3e-07. For `tan`, because the result isn't limited to ± 1 and you can divide a relatively large number by a relatively small number, the absolute error could be larger. From -1 ≤ tan(x) ≤ +1, the maximum absolute error was ≤ 4e-07. For tan(x) > 1 and tan(x) < -1, the maximum *relative* error, e.g. `fabs((actual - result) / actual)` was usually < 1e-06 until you get in the area of (90 ± 5) or (270 ± 5) degrees, then the error gets worse.
In testing, the average time per single input was (1.053 ± 0.007) µs, which on my machine was about 0.070 µs faster than native `sin` and `cos`, `tan` being defined the same way.
[Answer]
# C
Here's my attempt. It works like this:
Build a table of all values of sin(x) from 0 to 450 degrees. Equivalently this is all values of cos(x) from -90 to 360 degrees. With 2926 elements, there is enough space for a value every 1/6.5 degrees. The program unit is therefore 1/6.5 degrees, and there are 585 units in a quarter turn.
Convert input degrees into program units (multiply by `6.5==110.1 binary.`) Find the nearest values for sin and cos from the table. then convert the remaining part of the input (dx) into radians.
apply the formula `sin(x+dx) == sin x +(d(sin x)/dx)*dx.` note that `(d(sin x)/dx)==cos x,` but only if we use radians.
unfortunately that isn't accurate enough on its own, so another term is required, based on the next derivative `d2(sin x)/dx2 == -sin x.` This needs to be multiplied by `dx*dx/2` (not sure where the factor of 2 comes from, but it works.)
Follow the analogous procedure for `cos x`, then calculate `tan x == sin x / cos x`.
**Code**
There are about 17 floating point operations in here. That can be improved somewhat. The program contains table-building and test output using the native trig functions, but the algorithm does not. I will add timing and edit to comply with I/O requirements later (hopefully this weekend.) It matches the native function output except for very small values of sin x and cos x, which should be improvable to better than the native function output with some tweaking.
```
<#include <math.h> //only for table building and testing
int a;
double t[2926], //a table for sin x from 0 to 360+90=450deg every 1/6.5 degrees
x, //input
s,c, //first guess sin and cos (from table)
sn,cs, //output sin and cos
pi1170=3.1415926535897932384626433832795/1170, // there are 1170 units of 1/6.5 degrees in a half circle
pi180=3.1415926535897932384626433832795/180; // pi/180 only used for testing
main(){
for (a=0;a<=2925;a++)t[a]=sin(a*pi1170); //build table.
scanf("%lf",&x); //input
printf("%le %le %le\n",sin(x*pi180),cos(x*pi180),tan(x*pi180)); //native output for testing purposes
x*=6.5; //convert from deg to program units. 6.5=110.1 in binary, a fairly round number.
a=x+0.5; //a=round(x) add 0.5 to round, not truncate. Assigning to int, this is probably faster than the round function.
x=(x-a)*pi1170; //(x-a)=dx in program units. Divide to get radians.
s=t[a]; //get sin(a) from table
c=t[a+585]; //cos(a)=sin(a+90degrees)=sin(a+585units)
sn=s+c*x-s*x*x/2; //sin(x+dx)=sin(x)+cos(dx)-sin(dx^2/2)
cs=c-s*x-c*x*x/2; //cos(x+dx)=cos(x)-sin(dx)-cos(dx^2/2)
printf("%le %le %le\n",sn,cs,sn/cs); //print sin,cos and tan=sin/cos
}
```
] |
[Question]
[
[Beal's Conjecture](http://en.wikipedia.org/wiki/Beal%27s_conjecture) has a million dollar prize if you prove/disprove it.
It states that if  where A, B, C, x, y, and z are positive integers with x, y, z > 2, then A, B, and C have a common prime factor.
The challenge is to write a program that searches for a counter example to disprove this!
## Rules
* Write a program searching for a counter example of Beal's Conjecture
* You can perform an exhaustive search (i.e., all possible combinations of numbers that fit this form) or use some optimizations (e.g., A and B are symmetrical).
* You must use arbitrary-precision integers.
## Notes
* This is a popularity contest, be creative!
* Speed isn't necessary, but makes it more interesting. Optimize!
* I am also interested in seeing the shortest code too. You will get a +1 from me!
* **I'll run the winning program on a supercomputer that I have access to!**
* This conjecture is considered to be true, but that doesn't mean we can't try!
* Peter Norvig of Google has attempted this problem too. You may use his [page](http://norvig.com/beal.html) as guidance. He has a short Python program you can use as an example.
* Some other guy (who also happens to work at Google) has greatly improved on Norvig's approach, his page (with source code) can be found [here](http://www.danvk.org/wp/beals-conjecture/).
* My SO question related to this from two years ago may also be helpful: [Fin all A^x in a given range](https://stackoverflow.com/q/9814333/938695).
[Answer]
I'm being pathetically lazy (pun intended), but why not... seems to fulfill the rules.
## Haskell, 204
```
import Control.Monad
import Control.Monad.Omega
main=print.filter(\[(a,x),(b,y),(c,z)]
->and$(a^x+b^y==c^z):zipWith(((>1).).gcd)[a,b,c][b,c,a])
.runOmega$mapM(\_->liftM2(,)(each[1..])$each[3..])"123"
```
This prints1 all combinations which fulfill the counterexample property. I used the [control-monad-omega package](http://hackage.haskell.org/package/control-monad-omega-0.3.1/docs/Control-Monad-Omega.html) for diagonalising ℕ6... might be considered library-cheating. But seeing as someone will later post an APL answer where all this stuff is built into the language (or isn't it?), I don't give too much about it...
Of course, the program is way too slow (naïve exhaustion, and linked-lists as data structure) to be expectable of actually yielding a counterexample, but Haskell itself can actually achieve decent performance.
---
1Since it prints the tuples in list format, i.e. in one line, you need to switch your terminal's buffering off or you won't see when a result comes in. Alternatively, you can replace `print` with `mapM_ print` so you get a newline after each result, flushing a line-buffered terminal.
To test the program, change `each[3..]` to `each[2..]`, then you'll simply get all non-coprime pythagorean tuples as result.
[Answer]
# C#, no loops
OK, I skimmed a couple of those links, but to be honest they were a bit boring. I'm not interested in optimizing the hell out of it with hash tables and whatnot. Why should I need to? You've got a goddamn supercomputer!
Hell, I don't even want to bother with loops! **This solution will follow the [no-loops rule](https://codegolf.stackexchange.com/questions/22971)**.
Please note that the code I'm about to write is not good code, or the kind of code I'd write in real life (in case any prospective employers happen to read this). This code emphasises brevity and the ability to work in a narrative, and deemphasises the proper conventions and rituals and loops and so on.
To demonstrate what I'm talking about, we'll start with a shocking class with public fields to store the operands of the equation:
```
class BealOperands
{
public BigInteger A, B, C, x, y, z;
}
```
OK, we'll start with what is probably the hardest challenge. We need to figure out a way to permute through every combination of those operands. There are undoubtedly ways to do it more efficiently than checking every permutation, but I can't be bothered figuring them out. And why should I? We've got a goddamn supercomputer!
Here's the algorithm I came up with. It's incredibly inefficient, and goes over the same operands over and over again, but who cares? Supercomputer!
* Treat the six operands as a base-2 number, and permute through every combination.
* Treat the six operands as a base-3 number, and permute through every combination.
* Treat the six operands as a base-4 number, and permute through every combination.
* (...)
How to do all this without loops? Easy! Just implement an `IEnumerable` and associated `IEnumerator` to pump out the permutations. Later, we'll use LINQ to query it.
```
class BealOperandGenerator : IEnumerable<BealOperands>
{
// Implementation of IEnumerable<> and IEnumerable -- basically boilerplate to get to BealOperandGeneratorEnumerator.
public IEnumerator<BealOperands> GetEnumerator() { return new BealOperandGeneratorEnumerator(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
class BealOperandGeneratorEnumerator : IEnumerator<BealOperands>
{
public BealOperandGeneratorEnumerator() { Reset(); }
private BealOperands operands;
private BigInteger @base;
public void Reset()
{
// A is set to 0, which is "before" its minimum value, because IEnumerators are supposed to
// point to their first element *after* the first call to MoveNext().
// All other operands are set to their minimum values.
operands = new BealOperands { A = 0, B = 1, C = 1, x = 3, y = 3, z = 3 };
@base = 2;
}
public BealOperands Current
{
get
{
// We need to return a copy, since we'll be manipulating our internal one.
return new BealOperands {
A = operands.A, B = operands.B, C = operands.C,
x = operands.x, y = operands.y, z = operands.z };
}
}
public bool MoveNext()
{
// Increment the lowest "digit" and "carry" as necessary.
operands.A++;
if (operands.A - 1 >= @base)
{
operands.A = 1; operands.B++;
if (operands.B - 1 >= @base)
{
operands.B = 1; operands.C++;
if (operands.C - 1 >= @base)
{
operands.C = 1; operands.x++;
if (operands.x - 3 >= @base)
{
operands.x = 3; operands.y++;
if (operands.y - 3 >= @base)
{
operands.y = 3; operands.z++;
if (operands.z - 3 >= @base)
{
operands.z = 3; @base++;
}
}
}
}
}
}
// There will always be more elements in this sequence.
return true;
}
// More boilerplate
object System.Collections.IEnumerator.Current { get { return Current; } }
public void Dispose() { }
}
```
Now we're in business! All we need to do is enumerate an instance of `BealOperandGenerator` and find a counterexample of Beal's Conjecture.
Our next big problem is that there doesn't seem to be a built-in way to raise a `BigInteger` to the power of a `BigInteger`. There's `BigInteger.Pow(BigInteger value, int exponent)`, and `BigInteger.ModPow(BigInteger value, BigInteger exponent, BigInteger modulus)`, but no method to raise a `BigInteger`, to the power of another `BigInteger`, modulo infinity.
What a shiny nail of a problem! It looks like it was made to be solved with our `IEnumerable`/`IEnumerator` hammer!
```
class BigIntegerPowerEnumerable : IEnumerable<Tuple<BigInteger, BigInteger>>
{
public BigIntegerPowerEnumerable(BigInteger @base, BigInteger exponent) { this.@base = @base; this.exponent = exponent; }
BigInteger @base, exponent;
public IEnumerator<Tuple<BigInteger, BigInteger>> GetEnumerator() { return new BigIntegerPowerEnumerator(@base, exponent); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
class BigIntegerPowerEnumerator : IEnumerator<Tuple<BigInteger, BigInteger>>
{
public BigIntegerPowerEnumerator(BigInteger @base, BigInteger exponent)
{
originalBase = @base;
originalExponent = exponent;
Reset();
}
BigInteger originalBase, currentBase, originalExponent, currentExponent;
bool finished;
public void Reset()
{
// IEnumerable.Reset() is a silly method. You're required to implement it when you implement IEnumerable,
// but it isn't used by foreach or LINQ or anything. If you want to re-enumerate the enumerable, just get
// a brand new enumerator.
// In this case it gets in the way. The only reason I'm storing the original values is so I can implement
// this useless method properly. I supposed I could just throw a NotImplementedException or something,
// but it's done now.
currentBase = originalBase;
currentExponent = originalExponent;
finished = false;
}
public bool MoveNext()
{
if (finished) return false;
if (currentExponent <= Int32.MaxValue)
{
currentBase = BigInteger.Pow(currentBase, (Int32)currentExponent);
currentExponent = 1;
finished = true;
}
else
{
currentBase = BigInteger.Pow(currentBase, Int32.MaxValue);
currentExponent -= Int32.MaxValue;
}
return true;
}
public Tuple<BigInteger, BigInteger> Current
{
get { return new Tuple<BigInteger, BigInteger>(currentBase, currentExponent); }
}
object System.Collections.IEnumerator.Current { get { return Current; } }
public void Dispose() { }
}
static class BigIntegerPowExtension
{
public static BigInteger Pow(this BigInteger @base, BigInteger exponent)
{
return new BigIntegerPowerEnumerable(@base, exponent).Last().Item1;
}
}
```
Now we've got an extension method `Pow`, that can be called on a `BigInteger`, and takes a `BigInteger` exponent and no modulus.
OK, let's step back. How can we tell if a particular `BealOperands` is a counterexample of Beal's Conjecture? Well, two things need to be true:
* The operands, when plugged into that formula up at the top of the page, must form a true equation.
* A, B, and C must NOT have a common prime factor (i.e. their GCD is 1).
We've got what we need to check the first condition. And it turns out the second condition is a lot easier to check than it sounds. `BigInteger` provides a lovely `GreatestCommonDivisor` method, which allows us to conveniently sidestep the whole nightmare of trying to implement that without loops.
So we're ready to write a method to check if a `BealOperands` is a counterexample. Here goes...
```
static class BealOperandsExtensions
{
public static bool IsBealsConjectureCounterExample(this BealOperands o)
{
// If the equation isn't even true, we don't have a counter example unfortunately
if (o.A.Pow(o.x) + o.B.Pow(o.y) != o.C.Pow(o.z))
{
return false;
}
// We have a counterexample if A, B and C are coprime
return BigInteger.GreatestCommonDivisor(o.A, o.B) == 1 &&
BigInteger.GreatestCommonDivisor(o.A, o.C) == 1 &&
BigInteger.GreatestCommonDivisor(o.B, o.C) == 1;
}
}
```
And finally we can bring it all together with this rather slick `Main` method:
```
static class Program
{
static void Main()
{
var bealOperandGenerator = new BealOperandGenerator();
if (bealOperandGenerator.Any(o => o.IsBealsConjectureCounterExample()))
{
Console.WriteLine("IN YOUR FACE, BEAL!");
}
}
}
```
[Answer]
There are no counterexamples with C^Z <= 1.0E27.
As of Feb. 2019 I’m checking out to C^Z <= 1.0E29 on the assumption that either the “X” and/or “Y” exponent must be >= 5.
Current version of this program (“X” and/or “Y” >= 5) takes less than 1 second on an AMD 2920X to find all solutions out to C^Z <= 1.0E15. (But all of the gcd(A,B,C) are >= 2)
Details at <http://www.durangobill.com/BealsConjecture.html>
I can modify the current code (Uses “C” and OpenMP) out beyond these limits but will need more than 128GB of RAM to run it. (Hundreds of CPUs would also help. Thousands of CPUs would be even better.) (If you have free access to something like this, please contact me.)
My email address is on my home page at <http://www.durangobill.com>
[Answer]
The 2nd variation of the Beal’s search program has finished. The results are:
1) There are no counterexamples with \$C^Z < 10^{26}\$.
A complete list of all general solutions to \$A^X + B^Y = C^Z\$ with at least one of the exponents \$(X,Y) >= 4\$ can be seen at: <http://www.durangobill.com/BealXgt3e27.txt>
2) If you assume that at least of of the exponents \$(X,Y)\$ must be \$>= 5\$, there are no counterexamples with \$C^Z < 10^{28}\$.
A complete list of all general solutions to \$A^X + B^Y = C^Z\$ with at least one of the exponents \$(X,Y) >= 5\$ and C^Z < 1.0E29 can be seen at: <http://www.durangobill.com/BealXgt4e29.txt>
Details at: <http://www.durangobill.com/BealsConjecture.html>
The next two questions are::
1) Can a supercomputer extend the search?
2) If a supercomputer could extend the search, would it be practical?
1) To extend either of the above searches to 1.0E30, 300GB of RAM would be required per core unless cores can share the 300GB. For each additional further incremental increase in the exponential power beyond 1.0E30, the amount of required RAM increases by a factor of at least 2.2.
2) The amount of processing power needed for each further incremental increase in the exponent to and beyond 1.0E30 multiplies the combined CPU time by about 3.8. The search to 1.0E29 took 2 weeks using 12 cores. Supercomputer time is not generally “free”, and there is very little prospect that there are any counterexamples.
As a guide to the efficiency of the code at durangobill.com/BealE29code.txt, each of the 12 cores averaged 220 million loop iterations per second for the inner loop. (Average is for the 2-week run.) (An increase in RAM memory beyond what I have would increase this average speed by up to a factor of 2.)
I’ll let Austin answer 1) and 2) since he has access to a supercomputer and I don’t. (If by any remote chance that both 1) and 2) are a "go", I can supply the "C" code with the caveat that I'm not familiar with multi-thread instructions for large supercomputer clusters.)
[Answer]
Had to put this in 2 comments to get it to fit.
The major arrays are allocated as follows:
```
SortHeads = calloc(PRIME1+1, 8);
X2YmodPrime1 = calloc(ARRAYSIZE+1, 4);
X2YmodPrime2 = calloc(ARRAYSIZE+1, 4);
Base = calloc(ARRAYSIZE+1, 4);
Power = malloc(ARRAYSIZE+1);
```
(You will need 128GB of RAM for these arrays)
with:
```
#define PRIME1 2147483647LLU
#define PRIME2 2147483629LLU
#define ARRAYSIZE 4700000000LL
```
“Base” actually needs 33 bits (`cbrt(1.0E29)`) - the extra bit is stuffed in “Power” (which only needs 7 bits.)
The arrays operate similar to a hash table. However, since they are sorted by PRIME1 and only used as look-up tables, you don’t need the linked lists to access them. The result is thus a very fast linear time lookup to see if a trial A^X + B^Y = any C^Z.
Thus statements in the innermost loop are only two loops deep.
“Pragma” statements control the number of multi processing cores that are used (in this case 12) - all can access the single copy of the arrays.
Here’s the “main” code (in “C”) (Hope the comments fit the posted line length. If not, copy them out and paste the code in some document that has a longer line length.)
] |
[Question]
[
Your task is to generate a nonsense word that is reasonably pronounceable with the specified number of 'syllables'. Each time the program is run possibly results in a different nonsense word.
# Pronounceability
A pronounceable word is made up of syllables, which are in turn made up of a vowel group that is possibly sandwiched between two consonant groups. Not all sounds are pronounceable in all positions, and since this depends on the language, we'll use patterns understandable to English speakers
Starting consonant groups:
b
c
d
f
g
h
j
k
l
m
n
p
r
s
t
v
w
y
z
bl
br
ch
cl
cr
dr
fl
fr
gh
gl
gn
gr
kn
ph
pl
pr
qu
sc
sh
sk
sl
sm
sn
sp
st
th
tr
wh
wr
sch
scr
shm
shr
squ
str
thr
Vowel Groups:
a
e
i
o
u
ae
ai
ao
au
ea
ee
ei
eu
ia
ie
io
oa
oe
oi
oo
ou
ue
ui
Ending Consonant groups:
b
c
d
f
g
l
m
n
p
r
s
t
x
z
bt
ch
ck
ct
ft
gh
gn
lb
ld
lf
lk
ll
lm
ln
lp
lt
mb
mn
mp
nk
ng
nt
ph
pt
rb
rc
rd
rf
rg
rk
rl
rm
rn
rp
rt
rv
rz
sh
sk
sp
ss
st
zz
lch
lsh
lth
rch
rsh
rst
rth
sch
tch
## Combining Syllables
Both starting and ending consonant groups are optional in general, however you cannot place a syllable ending with a vowel immediately before one starting with a vowel.
### Disclaimer
In the interest of simplicity, certain English words can't actually be generated this way, such as vacuum, xylophone, mnemonic, pterodactyl, beautiful, blah, they, wow, and most plurals.
## Overview
Possible syllable patterns using this key:
(SC) = starting consonant; (V) = vowel group; (EC) = ending consonant
For one syllable:
* (SC)(V)(EC)
* (V)(EC)
* (SC)(V)
* (V)
With two syllables:
* (SC)(V)(EC)(SC)(V)(EC)
* (SC)(V)(EC)(SC)(V)
* (SC)(V)(EC)(V)(EC)
* (SC)(V)(EC)(V)
* (SC)(V)(SC)(V)(EC)
* (SC)(V)(SC)(V)
* (V)(EC)(SC)(V)(EC)
* (V)(EC)(SC)(V)
* (V)(EC)(V)(EC)
* (V)(EC)(V)
* (V)(SC)(V)(EC)
* (V)(SC)(V)
... and so on
# Examples
### 1 syllable
* charst
* tigh
* shriegn
* eess
* shue
* oo
* cheezz
### 2 syllables
* jazzcrap
* whylprog
* eating
* umba
* ola
* have
* ingsoc
* greespheurz
* bleuspoo
### 3 syllables
* brokiompic
* squirdshlicker
* capital
* opengtrass
* doublethink
* bigbrother
* phoebliaptmoo
* skolfblauquent
### 4 syllables
* strawishoepick
* patchworkzombie
* prearneajoomie
* slephotoschou
* doubleplusgood
# Coding
Input: an integer for the number of syllables to generate
Output: a (probably) nonsense word that many syllables long
# Rules
* Some form of (psuedo)randomness is required. All combinations of syllables should be (theoretically) possible to generate, though the distribution does not have to be uniform.
+ You may assume that your generator is aperiodic, so it doesn't have to be mathematically possible to generate every possible word (It might not have a long enough period in reality) and you don't need to provide any sort of proof that your generator can, in fact, produce every possible word.
+ Your generator must actually be able to produce at least 255 distinct values, so you can't [just return 4](https://xkcd.com/221/) every time the generator is called.
+ What's ultimately important is that you somehow include all the above letter groups in your code, that each letter group has a nonzero probability of being picked, and each syllable pattern has a nonzero probability of occurring (if provided with true randomness).
* You must support up to 16 syllable words
* In addition to the rules on combining syllables, the output word must not have:
+ 3 consecutive vowels (`a` `e` `i` `o` `u`; this can happen for `qu` words)
+ 3 consecutive matching consonants
Good luck!
---
Note that this is distinct from [Generate a pronounceable word](https://codegolf.stackexchange.com/questions/11877/generate-a-pronounceable-word) for a few reasons:
* Variable number of syllables specified by input rather than a strict 10-letter requirement.
* This challenge adds non-exhaustive letter groups that must be (cleverly) encoded and allows for more variants of syllables, so code can't just be copied from the other challenge
* Squirdshlicker. Need I say more?
*I also forgot to dupe check, but it turns out this brings enough new to the table that it doesn't matter. After all, there are hundreds of quine variant challenges.*
[Answer]
# JavaScript (ES6), ~~407~~ 403 bytes
```
f=n=>/[aeiou]{3}|(.)\1\1/.test(s=(h=k=>k?(g=s=>p=s.match(/.[a-z]*/g)[Math.random()*99|0]||(s>x&&p?'':g(s)))(x+'lBrClCrDrFlFrGlGrHJKKnPlPrQuScScrShmShrSlSmSnSquStrThThrTrVWWhWrY')+g('AAeAiAoAuEEaEeEiEuIIaIeIoOOaOeOiOoOuUUeUi')+g(x+'tCkCtFtLbLchLdLfLkLlLmLnLpLshLtLthMbMnMpNgNkNtPtRbRcRchRdRfRgRkRlRmRnRpRshRstRtRthRvRzSsTchXZz')+h(k-1):'')(n,p=x='BCChDFGGhGnLMNPPhRSSchShSkSpStTZB').toLowerCase())?f(n):s
```
[Try it online!](https://tio.run/##XY1db9owFIbv9yt8MdV2GaFo20WhAdEUGKshzIaxlSLVBBNncZzMdjrGx29naaVdbDoXr87ReZ/nB3/mNjJJ4eo634jzeetrv9NYcpHk5erw/nREHn5sPjYbnhPWIesj6ad@J@2i2Ld@p/Ctl3EXSdTwlry@X102Yrwccyc9w/UmzxC@vL4@Xq2OR2Q7u4uLogthK0YWY4x2NahuTaACc2cGamCGamg@fb6/11M1NV9KFrHIMJkxaZhiGdPsZ8mcmcmZNDPzdbGQC/Md4lqMYK8nekkv75X9Pu@LftIvRyM@EqM8DHkowiTMw3I@F/Pk9b3yuiAN3MCRNYkk2ZAtSYkiGdGkIFYSR5wcr8d6XEziSTpxU0fXNKKRpBu6pTFNqaIZ1bSgVlLraDWSPtM9s7NIfnvYVxaJ0noTtyDESL8r/J0Pb4NA3g2GQznUZDyZTiVlLJJMspQVzM0ebiH2XE7yX8IE3AqEcXeLNG7Z8zY3SAMfNNtAgxsffKiyVsPg8AaAKNc2V8JTeYye3h70CdjfSvG1EtUCOqAJugBaCFoAwlPrCberzgsvqXhXbZCAG/Cxir@4f4Ev/tfG6T9TdTyd/wA "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~237~~ ~~234~~ ~~230~~ 228 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•O0¦"ÐD›ô:ΓF9—∊‘àÕGÌ•3LŽZв₂в×S£V[1U.µ\µTΩiY.•1θ₆Ω–¸‡ÊΔιÃмº³ô»ÝAïG3_@|å“₄bÒs₃l¬t©ïÙK:≠•3LŽII₂в×S£«Ω1U}XižM•·Áy&ŒGηΩ¼αŸKq•6вèJ•Λ1"•bS>£Ω¼0U}TΩiY.•E–æƵHl¨åñyBY±(ú,ā]JùË‚aEuŒ—[K³|C~ôÙŸ„#¼ÑûĀdš+¢zsÄΘä¹ÊÌ₅ôθ•3LŽAE₆в×S£«Ω1U}J}Dγ€g3‹P#
```
-2 byte thanks to *@MagicOctopusUrn*.
[Try it online](https://tio.run/##VZDbSkJREIbfRSGCQtxsCPIisjRTiwIzMotQihCECOvC0FhuLcq6KDXSTnhIcZMgnvBYFzPuLhc@w3oRW1IUXc0w8zP/N/@Bz@X27A2HGkayK1ooqPDGwEgH6zoaX5hmJMEuoowkMY13JrzmInFJed8cVJkkDap4b4PculOwa6CxBY01Knsco0MCbTHpnMqMxKHFSAajNEHbGB70oAM1rEMXn/VYNok7swHMM/LEpIgbYz4mhb1QOgIZy5iy6thl@sfQbP7zgzcqC/bghkf5WOZraGLIP6bETLRJZejRitKyHvL5FJcXLbyhj4KKF7dtBnIjhdYe/AU1ckIsfDYWvVDEPFb8cw6ojGNnsh/atmAbrxh5cBmPlRgPwmmFWmD@FOuYUvhTL2ro4S12@2RXyUxA9sSHEZrEV2hjlAclnWGdp/CNrzfyOP7jW4IGWmNSaV9kpL2qHg7FLw) or [get a few more outputs](https://tio.run/##VZBZS0JhEIb/ShhEkUgiFXnR6snUNjCjlVCKEA5EnLowOvF5WijrotRoD20RD0XilmsFM54uP/wN3x@xT4qiqxlmXuZ95l2R3B7vUq1TGAVVhx8Nkk8U3R5xqVlqMTfo9O0CvFhqBkbuxtogpsNjCyNFzJhpaLCLkTDbDzByjhE8teIRF5mGtbeZaoopSjWFZ064n5w1ugyQnYPsBFW90/VDRppnyh5VGQlBnpEoBmiYFnC7WoYipDEDJbzpw4TVtNC7iY@MXDNlx4NBiSnbIjyvgYoJvHCY2UHkx9Bm@/ODJ6oaXfKUV3sf4WvIod/XpAWtNEdVKNOklnes8nkHl8ftvKFXRh0vHmc33NcVbS75F1TghBj7zA6JEMdHTPr6pyHZjEV9xT9vxwIeMnLpFta1IA9i1gHpzYEtzOCFxp@6bYQynmCpQha1aCvcbUi4Q8/xAQoY4EEpu5jhKXzj9wk8jv/4dtlC00x5XjYxUhhvrMl6GV57al8).
**Explanation:**
```
.•O0¦"ÐD›ô:ΓF9—∊‘àÕGÌ•
"# Push compressed string "bcdfglmnprstzchghgnphshskspstsch"
3L # Push list [1,2,3]
ŽA; # Push compressed integer 8997
₂в # Converted to Base-26 as list: [13,8,1]
× # Repeat the digits [1,2,3] that many times: ["1111111111111","22222222","3"]
S # Convert it to a list of flattened digits
£ # Split the string into parts of that size
V # Pop and store this string-list in variable `Y`
[ # Start an infinite loop:
1U # Reset variable `X` to 1
.µ # Reset the counter_variable to 0
\ # Discard the top of the stack (if any)
µ # Loop while the counter_variable is not equal to the (implicit) input:
TΩi # If a random boolean is truthy:
Y # Push the string-list we stored in variable `Y`
.•1θ₆Ω–¸‡ÊΔιÃмº³ô»ÝAïG3_@|å“₄bÒs₃l¬t©ïÙK:≠•
# Push compressed string "hjkvwyblbrclcrdrflfrglgrknplprquscslsmsnthtrwhwrscrshmshrsqustrthr"
3L # Push list [1,2,3]
ŽII # Push compressed integer 4608
₂в # Converted to Base-26 as list: [6,21,6]
× # Repeat the digits [1,2,3] that many times: ["111111","222222222222222222222","333333"]
S # Convert it to a list of flattened digits
£ # Split the string into parts of that size
« # Merge it with list `Y`
Ω # Pop and push a random starting consonant group from this list
1U # And set variable `X` to 1
} # Close the if-statement
Xi # If variable `X` is 1:
žM # Push builtin string "aeiou"
•·Áy&ŒGηΩ¼αŸKq•
# Push compressed integer 13814931869773709280202935082102
6в # Converted to Base-6 as list: [1,0,1,1,1,2,1,4,0,1,0,2,0,3,0,4,2,0,2,1,2,3,3,0,3,1,3,2,3,3,3,4,4,1,4,2,0,1,2,3,4]
èJ # Index each into the string "aeiou", and join together: "aeaiaoaueaeeeieuiaieiooaoeoiooouueuiaeiou"
•Λ1"• "# Push compressed integer 8388576
b # Converted to binary: "11111111111111111100000"
S> # Split into a list of digits, and each increased by 1
£ # Split the string into parts of that size
Ω # Pop and push a random vowel group from this list
¼ # Increase the counter_variable by 1
0U # And then set variable `X` to 0
} # Close the if-statement
TΩi # If a random boolean is truthy:
Y # Push the string-list we stored in variable `Y`
.•E–æƵHl¨åñyBY±(ú,ā]JùË‚aEuŒ—[K³|C~ôÙŸ„#¼ÑûĀdš+¢zsÄΘä¹ÊÌ₅ôθ•
# Push compressed string "xbtckctftlbldlflklllmlnlpltmbmnmpnkngntptrbrcrdrfrgrkrlrmrnrprtrvrzsszzlchlshlthrchrshrstrthtch"
3L # Push list [1,2,3]
ŽAE # Push compressed integer 2564
₆в # Converted to Base-36 as list: [1,35,8]
× # Repeat the digits [1,2,3] that many times: ["1","222...222","33333333"]
S # Convert it to a list of flattened digits
£ # Split the string into parts of that size
« # Merge it with list `Y`
Ω # Pop and push a random ending consonant group from this list
1U # And set variable `X` to 1
} # Close the if-statement
J # Join all strings on the stack together
}D # After the while-loop: duplicate the resulting string
γ # Split the copy into chunks, with adjacent characters that are
# the same grouped together
€g # Get the length of each chunk
3‹ # Check for each length if it's smaller than 3
P # Check if all are truthy by taking the product, and if it is:
# # Stop the infinite loop
# (after which the string at the top of the stack is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression parts works.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 231 bytes
```
e€ØẹŒrḢƇ,ŒɠF>2Ẹ
“yŒʠT¬ḅɼṬɦṀUżGv¶æɲCĊQ>ṙȦẇɼṄ0IḤhDẋDċṀĊṪɗĖƇẊ;1JƒṾỊżỵhṖ8>Ȯ⁶]¦Qṭ|Ṛṇẹm⁵ØKƈBNɦÇȯ¢ṣḟPṇMʠ¬YėĊÇẒỊĿXJÑḷÞeȮȮɼ$ỴœeṂṠɲẓḊ⁺ċŻ⁽⁶Ẓ⁹<>#nẇṬ⁴\¤ÐṡḞF5ƙẇwḶȤYḍ¡¢~ṚⱮ-ṃƲ⁻Ṙ6ɱṬ?İẆḌỊþEØ»Ḳµe€ØẹIkḣ3)Z;€“squ“qu”$1¦
“ئµ£‘ḃ3$Xµ³Ð¡ḊFµ⁺wØ2$¿ịÇX€Fß¹Ñ?
```
[Try it online!](https://tio.run/##PZBRaxNBFIXf/RvmRVAwLRahkoLWSCuKBYVU9DFQtAoqWgoi2VZd2VRot9BuRds0CfsgMdrYjXN3Ywszs8tO/8WZP7LevPhy4d455853z5P68vJqUdTtWk8FiCn1X0K0M/di6ptWtTKBWJyzja@rqX/Wui97EB/MCNQzIajxIB3deiOHKjSDG9pbqID28hCxO1a8vzwH0V2aRdyc1U0Waw/03ezqncxF7E2X5zMfdILES0dIoiXQztVK3rfO8LEMF0A/3oK@gFhLz6wTqeB29un6XRMqN/8p26AOxME9fr9z1pK9Rb2rPcVan/fp09q82oL4o/breT/vm1EJyXG6XQetgVpmgHgbwrNOrJtpYp2//Cc7rUPXKuefMz6fZ53jR7KrNkGHEPvVK9kez1cghnl3EeKzPJTtd8xnj/qXQOvZwDoJKJgyR@yd0b8Qf4TYYBZ1clMFMoEYyOh/xHNPITqTFx5O84CjffXiNddx@VYqy3CcNntCGcmObQQQ65OlGje/1aZkGK8qI0ZfUcFESZ4iaSq3xnuq6kCS2popiqI89Q8 "Jelly – Try It Online")
A full program that takes a single argument, the number of syllables required.
### Explanation
The core of this is a 66-word compressed dictionary string. If the words are split into groups of consonants and vowels and the first 3 groups taken for each word, they generate the desired starting, vowel and end groups from the question. The exceptions are `qu` and `squ` because they have a vowel in, so these are added manually. The word list was built algorithmically from the Jelly dictionary using a Python script. Note some letter groups are repeated, but the question allows the outputs to not uniformly represent each possible combination. If this were preferred, it would be straightforward to make each group unique at the cost of two bytes (`Q€`).
Helper link 1: check whether more than 3 vowels in a row or more than 3 of the same letter in a row
```
| Sample input: branggag
e€Øẹ | For each letter, is it a vowel? [0, 0, 1, 0, 0, 0, 1, 0]
Œr | Run-length encode [[0, 2], [1, 1], [0, 3], [1, 1], [0, 1]]
ḢƇ | Filter only those with true first value, popping first value [[1], [1]]
, | Pair with
Œɠ | Run lengths of input [[[1], [1]], [1, 1, 1, 1, 2, 1, 1]
F | Flatten [1, 1, 1, 1, 1, 1, 2, 1, 1]
>2 | Greater than 2 [0, 0, 0, 0, 0, 0, 0, 0, 0]
Ẹ | Any 0
```
Helper link 2: The three groups of strings
```
“yŒʠ...þEØ» | Compressed string: shmooze gaolbird hailshot shriech waeful furze ghaut cruelness stealthier gneiss shoeshine wheelchair wring build priorship knosp spoilfive karst through coalpit teschenite schoolkid theurgic zabtieh skiamachies yirth snazzier slimnastics scripted smirch droskies strift blepharism chaulmoogra glegness scarf fratch clerk brank jarvey flourless vorpal grex nard plumb larn philter sorbo tractabilities parcel mart damp rearm back bast bag bant baba boll bad bap becap basal ban bail bare
Ḳ | Split at spaces
µ ) | For each word: e.g. hailshot
e€Øẹ | Check whether each character is a vowel [0, 1, 1, 0, 0, 0, 1, 0]
I | Increments of this [1, 0, -1, 0, 0, 1, -1]
k | Split word at truthy values of this [h, ai, lsh, o, t]
ḣ3 | Take the first three [h, ai, lsh]
Z | Transpose (so now have three lists, start consonants, vowels, end consonants)
€ $1¦ | For the first group
; “squ“qu” | Append squ and qu
```
Main link
```
µ³Ð¡ | Repeat the following the input number of times, collecting results:
“ئµ£‘ | 18, 5, 9, 2
ḃ3$ | bijective base 3: [1,2,3],[1,2],[2,3],[2]
X | Take one at random
Ḋ | Remove first item (which will be the input to the link because if the way С works
F | Flatten; we now have e.g. [1,2,3,2,3,1,2,3,2]. This corresponds to SC V EC V EC AC V EC V
µ⁺ ¿ | Do everything so far once and then repeat while:
wØ2$ | The output contains two twos (i.e. vowel-vowel)
ịÇ | Look these up in the previous link, so we now have a group of letter groups for each position
X€F | Pick a random letter group for each position
ß¹Ñ? | If helper link 1 is true, retry the whole of this link again. Otherwise implicitly output
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~522~~ 510 bytes
```
from random import*
import re
c=choice
S,V,E=[map(str.lower,re.findall('[A-Z][a-z]*',x))for x in'BCDFGHJKLMNPRSTVWYZBlBrChClCrDrFlFrGhGlGnGrKnPhPlPrQuScShSkSlSmSnSpStThTrWhWrSchScrShmShrSquStrThr','AeAiAoAuEaEeEiEuIaIeIoOaOeOiOoOuUeUiAEIOU','BCDFGLMNPRSTXZBtChCkCtFtGhGnLbLdLfLkLlLmLnLpLtMbMnMpNkNgNtPhPtRbRcRdRfRgRkRlRmRnRpRtRvRzShSkSpSsStZzLchLshLthRchRshRstRthSchTch']
def f(n):w=c(['',c(S)]);exec"e=c(E);w+=c(V)[-(w[-1:]in V):]+c([c(S),e,e+c([x for x in S if x[0]*2!=e])])*(n>1);n-=1;"*n;return w+c(['',e])
```
[Try it online!](https://tio.run/##fZJBj9owEIXv/Ap3L0kgrBbaE4hKgQ2UriHUDtASRVUwDrZwnHRwCuXPU8O2PVUrWXqW3/P404yrX0aUunu95lAWCDK9syKLqgTTbLwqAt5gAyZKyXiD@is/HCRFVrlHA4@qPHHwgT/mUu8ypVwnCdqbNMnal7Tp@GfPy0tAZyS1Mxw9jyefPr/g2XxBaLxaf9sM1RBGYqRG8AxjNYaJmKiJnsCLXoiFWsCXmjIq6IEqWlBNK2piEcNarIEyQRlQUVAB9EdNDcQCHN8JeCCDMqjDLOShDOtpNuXTMsoiHsmojOolX8ognEZLm70D/aH5uhkaS3IYmbGxFBpv8Q7n@IAVLrDGFTaz7UzPqvlhvp8bS2fIljCyIznZkwNRpCCaVMSQn@RyJ67okZrNBTOBjwIbQZggR7sMMZZcxEw4aWPHc5S72uudBsxNHMdnLvVSr8/PnD1wexZ6/VPL6spL2u4paXd6qdRo5fXSlr1wS/vc57f9Gf1tNKJI5uicPKXN7rsBT23Bpqs/dry@bg86/Yem7gM3NWh0ar2@ajPXCqQ2KMndzn1i32@F7G/Yc7fz5KWNf3b3bfv92/aH/9nX3w "Python 2 – Try It Online")
[Answer]
# Pyth, ~~346~~ 335 bytes
```
McG.u+NYr9,VHSlH1smjOgs@L"eaiou"jC" ¤E̽]¢¨¦l#"5,4 17*Vd,Og"bcdfghjklmnprstvwyzblbrchclcrdrflfrghglgngrknphplprquscshskslsmsnspstthtrwhwrschscrshmshrsqustrthr"[18 29 6)Og"bcdfglmnprstxzbtchckctftghgnlbldlflklllmlnlpltmbmnmpnkngntphptrbrcrdrfrgrkrlrmrnrprtrvrzshskspssstzzlchlshlthrchrshrstrthschtch"[13 43 8)tuaGO<W!eeG^,1Z2 2Q]1
```
Try it online [here](https://pyth.herokuapp.com/?code=McG.u%2BNYr9%2CVHSlH1smjOgs%40L%22eaiou%22jC%22+%C2%A4E%11%C3%8C%C2%BD%5D%C2%A2%C2%A8%C2%A6l%23%225%2C4+17%2aVd%2COg%22bcdfghjklmnprstvwyzblbrchclcrdrflfrghglgngrknphplprquscshskslsmsnspstthtrwhwrschscrshmshrsqustrthr%22%5B18+29+6%29Og%22bcdfglmnprstxzbtchckctftghgnlbldlflklllmlnlpltmbmnmpnkngntphptrbrcrdrfrgrkrlrmrnrprtrvrzshskspssstzzlchlshlthrchrshrstrthschtch%22%5B13+43+8%29tuaGO%3CW%21eeG%5E%2C1Z2+2Q%5D1&input=2&debug=0).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~381~~ ~~379~~ 375 bytes
Uses messy regex matches to get the consonant groups. Could probably be optimized.
```
->n,w=?a..s='zzz',a=[1]{s=(1..n).map{a=[w.grep(/^([^aeiouq]|[bcfgp][lr]|s?ch|dr|gn|kn|ph|s?qu|s[ct]r?|sh[mr]?|th?r?|s[klmnp]|wh|wr|gh)$/)+(a[-1]?[p]:[]),w.grep(/^[aeiou]{,2}$/),w.grep(/^([^aeiouqhjkvwy]|[bcflnprs]t|ck|gh|gn|l[bdfk-np]|m[bnp]|nk|ng|ph|r[bcdfgk-npvz]|[lr]?[stc]h|s[kps]|zz|rst|[st]ch)$/)<<p].map(&:sample)}*''while s=~/[aeiou]{3}|(.)\1\1|aa|eo|ii|iu|u[aou]/;s}
```
[Try it online!](https://tio.run/##ZZDdUoMwEIVfxQtHwFIQO97UIg@y3c6E3yCQpgmUKSy@OiZ19MarnZyTk/Nl1ZDe1jI@rtsP4Y9xwoJAx840TY7PYohw1rEbBYHwgo7J2UhjUKlCuuHJhRMr6vNwQYI0KyuJ0CoknWScckWVoEaQ5Ea4DKQh61ElpDl0ChPqeWJP0LSdkEgjp9FEuPcYehuXwTbCBCTuAT3/rxDudTj7r4u55v8H4Z/Ndbz94LRCKo09ZY151sK0kOZls7VtHaR2iIZEZQmVCeRlZc3rZOLmGwnoPkNuCaVGmiZSuicjYnaHPBwk2o24T3vNOtkW3vLsOCOv2@JBx1/hL@tuITfwjtExIsaoOFNdUz3QAMy44bte1reXoK@7Qs9y6PVDCdFGMZG7Ow@X9Rs "Ruby – Try It Online")
] |
[Question]
[
### Introduction
Let a field be a rectangle filled with *only* the characters `-` and `[0-9]`. An example of a field is:
```
11-011123
111-010--
0010---01
111-01234
```
You see that this field has been separated into three smaller areas:
[](https://i.stack.imgur.com/uFprW.png)
To calculate the score of a smaller area, we just add all numbers up. For example:
```
11
111
0010
111
1 + 1 + 1 + 1 + 1 + 0 + 0 + 1 + 0 + 1 + 1 + 1 = 9
```
The total score for this area is **9**. We now do the same thing for the second area:
```
011123
010
0 + 1 + 1 + 1 + 2 + 3 + 0 + 1 + 0 = 9
```
The total score is also **9**. Now we have to examine the last area:
```
01
01234
0 + 1 + 0 + 1 + 2 + 3 + 4 = 11
```
This has a total score of **11**. The highest score on the field is 11, so this is what we need to output.
### The Task
Given a field (in the form of a 2D string, an array, etc.), output the **highest score** on the field. You may assume that the given fields will *always* contain at least 1 digit. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
### Test cases
Test case 1:
```
Input:
1
Output:
1
```
Test case 2:
```
Input:
1-1-1-1
-1-1-1-
2-1-1-1
-1-1-1-
Output:
2
```
Test case 3:
```
Input:
12-45-
4-65-9
87-654
12-487
45----
684764
Output:
69
```
Test case 4:
```
Input:
111-12
------
21--10
Output:
3
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~54~~ ~~51~~ 49 bytes
```
n:"G~1@(2Y6Z+leG45>1e*5M@)*]vtz:"otY*g]G48-X:*sX>
```
Input is a 2D char array in MATL(AB) format, with `;` as row separator. The inputs in the example and in the test cases are respectively:
```
['11-011123';'111-010--';'0010---01';'111-01234']
['1']
['1-1-1-1';'-1-1-1-';'2-1-1-1';'-1-1-1-']
['12-45-';'4-65-9';'87-654';'12-487';'45----';'684764']
['111-12';'------';'21--10']
```
[**Try it online!**](http://matl.tryitonline.net/#code=bjoiR34xQCgyWTZaK2xlRzQ1PjFlKjVNQCkqXXZ0ejoib3RZKmddRzQ4LVg6KnNYPg&input=WycxMi00NS0nOyc0LTY1LTknOyc4Ny02NTQnOycxMi00ODcnOyc0NS0tLS0nOyc2ODQ3NjQnXQ)
### Explanation
This works by building an adjacency matrix of the graph defined by the relation "being connected". As an example, consider the 3×4 field
```
52-4
15-8
3-72
```
Entries in a 2D array are easily described in MATL using (column-major) linear indexing. In the 3×4 case, the linear index of each entry is given as
```
1 4 7 10
2 5 8 11
3 6 9 12
```
The adjacency matrix is built in steps using matrix multiplication. In the first step, *immediate* neighbours are considered. For example, the point indexed 3 is neighbour of itself and of that with index 2. It's not a neighbour of 6 because that point doesn't contain a number according to the field. In this example the adjacency matrix of the relation "immediate-neighbour" is the 12×12 matrix **L** given as
```
1 1 0 1 0 0 0 0 0 0 0 0
1 1 1 0 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0 0 0
1 0 0 1 1 0 0 0 0 0 0 0
0 1 0 1 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 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 1
0 0 0 0 0 0 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 1 0 1 1
```
(It can seen that column 3 has value `1` at rows 2 and 3.) This matrix is always symmetric and its diagonal has value `1` for points that don't contain `-`.
The next step would be the adjacency matrix of the relation "connected with *at most one point in between*". To obtain it, it suffices to multiply **L** by itself and set nonzero entries to `1`. In general, the adjacency matrix of the relation "connected by *some* path", **M**, is obtained by raising **L** to an exponent (in matrix sense) that represents the maximum possible path length. An upper bound of the maximum path length is the number of nonzero entries in **L**.
Computing the matrix power directly may cause overflow, because large numbers quickly occur. So it's better to gradually multiply by the same matrix, converting nonzero entries into 1 after each step to prevent large numbers from building up.
Column *i* of **M** represents the points that are connected (by any path) with point *i*. Now, the level field can be reduced to a column vector **c** in linear order, where each entry contains the corresponding number or an undefined value for `-`. So in this case **c** would be
```
5
1
3
2
5
-
-
-
7
4
8
2
```
Mutiplying each column of **M** by **c** element-wise and computing the sum of each column gives, for each point *i*, the total score of the area point *i* belongs to. An area is defined by all points that are mutually connected. Note that many columns will give the same result; namely, columns *i* and *j* will give the same sum if points *i* and *j* are connected (belong to the same area). The final result is the maximum of those sums.
```
% Implicitly take input: 2D char array
n: % Range [1,...,N], where N is number of entries in the input
" % For loop. Each iteration builds a row of matrix L
G % Push input again
~ % Logical negate: transform into matrix of zeros
1 % Push 1, to be written into a matrix entry
@ % Iteration index. Ranges from 1 to N
( % Write that 1 into the N-th entry (linear order)
2Y6 % Push array [0 1 0; 1 1 1; 0 1 0]: mask of immediate neighbours
Z+ % Convolve and keep same-size result
le % Linearize into row array
G45> % Array of same size as the input that contains 1 for numbers, 0 for '-'
1e % Linearize into row array
* % Multiply element-wise
5M % Push last array again: 1 for numbers, 0 for '-'
@) % Get 0 or 1 value of that array corresponding to current iteration
* % Multiply. This is to give a row of zeros for non-numbers
] % End. We have all rows of L in the stack
v % Concatenate all rows into a matrix: L.
tz: % Duplicate. Range [1,...,K], where K is the number of nonzeros in L
" % For loop. Repear K times. This loop computes the 0/1 matrix power
o % Convert matrix entries to double
tY* % Duplicate and matrix-multiply
g % Convert to logical values, that is, nonzero values become 1
] % End. We have matrix M
G48- % Convert input chars to the corresponding numbers by subtractig 48
X: % Linearize into column array. This is vector c
* % Element-wise multiplication with broadcast (implicit repetition)
s % Sum of each column. Gives a row array
X> % Maximum of that row array
% Implicitly display
```
[Answer]
# JavaScript (ES6), 157 bytes
```
s=>[...o=s].map((n,i)=>o=n<'.'|(a=[...s]).map(_=>a.map((c,j)=>c>'-'&c<10&(a[j+1]|a[j-1]|a[j+l]|a[j-l])>90?a[n-=-c,j]=99:0),a[i]=99)|o>n?o:n,l=~s.search`
`)|o
```
## Explanation
Takes an input field as a string. For each number in the field, sums all numbers in the area. It does this by iterating over each number in the field multiple times, adding the number to the score if an adjacent cell contains a previously counted number. Counted numbers that are part of the area are represented by setting them to 99 so that they are not counted again. Outputs the highest score as a number.
```
var solution =
s=>
[...o=s].map((n,i)=>o=n<'.'| // for each number on the field
// n = area score
(a=[...s]) // a = array of each field character
.map(_=> // loop to ensure whole area is found
a.map((c,j)=> // for each cell c at index j
c>'-'&c<10& // if the current cell is a number
(a[j+1]|a[j-1]|a[j+l]|a[j-l])>90 // and an adjacent cells is in the area
?a[n-=-c,j]=99:0 // add the cell to the area
), // and the number to the score
a[i]=99 // mark the starting cell as counted
)
|o>n?o:n, // o = output (max of o and n)
l=~s.search`
` // l = line length of field
)
|o // return o
```
```
<textarea id="input" rows="6" cols="40">12-45-
4-65-9
87-654
12-487
45----
684764</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Pyth, 93 bytes
```
A,hlh.zjJ\-.zKsm?qdJd\#HD'b=KXKbJR+i@HbTsm?&&gd0<dlKq@Kd\#'d0[tbhb-bG+bG;Wh=NxK\#=+Y'N)h.MZY
```
[Try it online!](http://pyth.herokuapp.com/?code=A%2Chlh.zjJ%5C-.zKsm%3FqdJd%5C%23HD%27b%3DKXKbJR%2Bi%40HbTsm%3F%26%26gd0%3CdlKq%40Kd%5C%23%27d0[tbhb-bG%2BbG%3BWh%3DNxK%5C%23%3DY%2BY%27N%29h.MZY&input=11-011123%0A111-010--%0A0010---01%0A111-01234&debug=1)
## How it works
---
### First step: read the input
```
A,hlh.zjJ\-.zKsm?qdJd\#H
A, Assign the following to G and H:
hlh.z G = increment(length(first(all_input())))
jJ\-.z H = join(J="-",all_input())
m H for d in H:
?qdJ if equal(d,J):
d add d to the list
else:
\# add "#" to the list
end
s sum the list
K assign to K
Sample input:
11-011123
111-010--
0010---01
111-01234
G = 10
H = "11-011123-111-010---0010---01-111-01234" (note the extra dashes connecting each line)
J = "-"
K = "##-######-###-###---####---##-###-#####"
```
### Second step: define a function to evaluate one area
```
D'b=KXKbJR+i@HbTsm?&&gd0<dlKq@Kd\#'d0[tbhb-bG+bG;
D'b ; def quote(b):
=KXKbJ K[b] = J
R+ return the sum of A and B, where:
i@HbT A = to_integer(H[b],10)
m [tbhb-bG+bG for d in {dec(b), inc(b), minus(b,G), add(b,G)}:
?&& if .... and ........ and ............... :
gd0 d>=0
<dlK d<len(K)
q@Kd\# equal(K[d],"#")
'd add quote(d) to temp_list
else:
0 add 0 to temp_list
s B = sum(temp_list)
Basically, this function (quote) is given a starting
point (b), and then recursively find its neighbour and
add their values to the output.
```
### Third step: read all the areas and find the rqeuired maximum
```
Wh=NxK\#=+Y'N)h.MZY
Wh=NxK\# ) while inc(N=find(K,"#")): --while K still has "#"
=+Y'N Y+= quote(N)
.MZY find the maximum of Y,
h then print the first.
```
] |
[Question]
[
After you wake in a dark room, you see a rectangular grid of lights with corresponding switches. You decide to use a coordinate system with the bottom left light representing (1,1) and the coordinates increasing as you go up (y direction) and to the right (x direction). The grids are identical in that flipping the switch at (a,b) toggles (turns from off to on or from on to off) the light at (a,b) as well as the lights in the same column or same row as (a,b).
Your input will be a rectangular grid of two distinct characters representing on and off (I use 1 and 0, respectively). Also, a part of the input will be a series of at least one coordinate pair (with whatever format and separation you want) that will represent switches that you flip.
The output will be the same grid, with the "flip" applied at each of the coordinate pairs that were given as input. You may choose how to format your input, though the output must be a grid, not an array.
---
**Samples**
Sample input 1
```
111111
111111
111111
111111
(3,2)
```
Sample output 1
```
110111
110111
000000
110111
```
Sample input 2
```
01101
10100
00010
11111
10110
(1,1), (5,5)
```
Sample output 2
```
00010
00101
10011
01110
01000
```
Sample input 3
```
1
(1,1)
```
Sample output 3
```
0
```
Sample input 4
```
00000
11111
00000
11111
(2,3), (2,3)
```
Sample output 4
```
00000
11111
00000
11111
```
---
This is code golf. Standard rules apply. Shortest code in bytes wins.
[Answer]
## Dyalog APL, 20 bytes
```
{⍵≠⊃⊃≠/∘.∨/¨⍺=⊂⍳¨⍴⍵}
```
This is a dyadic function that takes the initial grid on the right and the list of coordinates on the left.
To input a single coordinate pair, use e.g. `(⊂2 3)` as the left argument.
Try it [here](http://tryapl.org/?a=%28%u22822%203%29%7B%u2375%u2260%u2283%u2283%u2260/%u2218.%u2228/%A8%u237A%3D%u2282%u2373%A8%u2374%u2375%7D%284%205%u23741%201%201%201%201%200%200%200%200%200%29&run).
[Answer]
## CJam, ~~37~~ 36 bytes
```
qN/W%(~{1$::!\{1a\Te[f.|z}/..^}/W%N*
```
Input should have the grid first, using any two non-NULL characters that only differ in the last bit (so `0` and `1` work), followed by a CJam-style list of coordinate pairs.
```
01101
10100
00010
11111
10110
[[1 1] [5 5]]
```
[Test it here.](http://cjam.aditsu.net/#code=qN%2FW%25(~%7B1%24%3A%3A!%5C%7B1a%5CTe%5Bf.%7Cz%7D%2F..%5E%7D%2FW%25N*&input=01101%0A10100%0A00010%0A11111%0A10110%0A%5B%5B1%201%5D%20%5B5%205%5D%5D)
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 39 bytes
```
i,-1H$X!tyZ}:XJx:!XIxi"I@1)=J@2)=|+]2\X!
```
Input is of the following form (the example corresponds to sample input 2 in the challenge):
```
[0 1 1 0 1; 1 0 1 0 0; 0 0 0 1 0; 1 1 1 1 1; 1 0 1 1 0]
[1 5; 1 5]
```
First input is a matrix defining the grid of `0` and `1`. `;` is the row separator. Second input is a matrix of coordinate pairs, where each *column* is a pair.
### Example
```
>> matl i1_2$X!tyZ}:XJx:!XIxi"I@1)=J@2)=|+]2\X!
> [0 1 1 0 1; 1 0 1 0 0; 0 0 0 1 0; 1 1 1 1 1; 1 0 1 1 0]
> [1 5; 1 5]
0 0 0 1 0
0 0 1 0 1
1 0 0 1 1
0 1 1 1 0
0 1 0 0 0
```
### Explanation
```
i, % input matrix
-1H$X! % rotate clockwise to accomodate input to matrix coordinates
tyZ} % get numbers of rows (r) and of cols (c)
:XJx % row vector 1,2,,...,c. Copy to clipboard J and delete
:!XIx % col vector 1,2,,...,r. Copy to clipboard I and delete
i % input coordinates (matrix; each col is a coordinate)
" % for each col of coordinate matrix
I@1)= % compare col vector of rows with row from coordinate
J@2)= % compare row vector of cols with col from coordinate
| % "or" with singleton expansion to generate mask
+ % add that to matrix of values
] % end for
2\ % modulo 2 to transform result into zeros and ones
X! % undo rotation
```
[Answer]
# Ruby 114 bytes
Takes as input:
`g`, an array of arrays representing the starting grid.
`o`, an array of points, each point being an array with two elements, like `[x, y]`.
```
->g,o{o.map{|i|(r=g[i[1]-1])[e=(i[0]-1)]-=1;r.map!{|j|j+1};g.map{|x|x[e]+=1}};puts g.map{|i|i.map{|j|j%2}.join""}}
```
] |
[Question]
[
In this challence, your task is to locate substrings with a given structure.
# Input
Your input shall be two non-empty alphanumeric strings, a *pattern* `p` and a *text* `t`.
The idea is that each character of `p` represents a contiguous non-empty substring of `t` which occur next to each other, and `p` represents their concatenation.
Identical characters correspond to identical substrings; for example, the pattern `aa` represents any non-empty square (a string obtained by concatenating a shorter string to itself).
Thus the pattern `aa` can match the substring `byebye`, with each `a` matching `bye`.
# Output
If the text `t` contains a substring that `p` matches, then your output shall be that substring, with colons `:` inserted between the strings that correspond to characters of `p`.
For example, if we have `t = byebyenow` and `p = aa`, then `bye:bye` is an acceptable output.
There may be several choices for the matching substring, but you shall only output one of them.
If `t` does not contain a matching substring, your output shall be a sad face `:(`.
# Rules and Clarifications
Different characters of `p` can correspond to identical substrings, so `p = aba` can match the string `AAA`.
Note that the characters must correspond to non-empty strings; in particular, if `p` is longer than `t`, the output must be `:(`.
You can write a full program or a function, and you can also change the order of the two inputs.
The lowest byte count wins, and standard loopholes are disallowed.
# Test Cases
Given in the format `pattern text -> output`.
Note that other acceptable outputs may exist.
```
a Not -> N
aa Not -> :(
abcd Not -> :(
aaa rerere -> re:re:re
xx ABAAAB -> A:A
MMM ABABBAABBAABBA -> ABBA:ABBA:ABBA
x33x 10100110011001 -> 10:1001:1001:10
abcacb 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> c:a0aa:0c:c:0c:a0aa
abccab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> a:a:0c0:0c0:a:a
abcbcab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> :(
abcbdcab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> 00:c:ca0aa0c:c:0:ca0aa0c:00:c
```
[Answer]
# Python, 207 bytes
```
import re
h=lambda x:"a"+str(ord(x))
def g(a,b):
c,d="",set()
for e in a:
c+=["(?P<"+h(e)+">.+)","(?P="+h(e)+")"][e in d]
d.add(e)
f=re.search(c,b)
return f and":".join(f.group(h(e))for e in a)or":("
```
Call with `g(pattern, string)`
Uses the `re` module to do most of the work.
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45) (ES5.1), 198 bytes
**Since ES6 was released in June 2015, I post the ES5.1 version of the code together with the ES6 equivalent, but declare ES5.1 version as the main answer.**
Greedy match, so the first case returns "Not" instead of "N".
```
function(a,b){c=[o="indexOf"];r=a.split("");return(m=RegExp(r.map(function(i){return(e=c[o](i))>0?"\\"+e:(c.push(i),"(.+)")}).join("")).exec(b))?r.map(function(x){return m[c[o](x)]}).join(":"):":("}
```
[Try it online!](https://tio.run/##jVI9b4MwEN35FZYnW0mJaTYjGhGpY1KpK2EwxrRuE4wMiaii/Pb0jhCGTBG@r3f3TmfOP@qkWu1t0720jS2NP7j61/xdT8qTiiTkWh1r3VlXMzUv@FknmUuorUvTf1Q0j32iwrbZ245RymNvuqOv2SH5NF/vfcN8eFANmzpYfh4rTKIzlwPA38SK7nZ0ZiTTYXNsvwGcUxbOOOUXHv44W2NrHpreaFZwvnpo2t@bkkM2NO15PhEl5ZJKRi/XOMAbadWaFm6VBVSRrevIyxvZ0jlEUwjVGBe6fECgxBv8EPNGDgczfU/SdZqma0ykMkVss9kguAZ8lCEJVk5q4C6XPYlEJER0FyyMhET3rsaJlC6IUEJorYRSYMToAAQWHORqiaAUWmpUGIx8rZ7hK4lkMQj4I7d4jjz9vaJ8jiAEjDkmcODJxwQN8jionCcMl2eJq24b5OQcEIS8aY/7Dha6wBdDBgVN0S5uL8byOCDa1a3bm3DvvljFbqQsyucjP3vN@eQvc2Bcrv8 "JavaScript (SpiderMonkey) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org) (ES6), 141 bytes
```
a=>b=>(c=[o="indexOf"],r=[...a],m=RegExp(r.map(i=>(e=c[o](i))>0?"\\"+e:(c.push(i),"(.+)")).join``).exec(b))?r.map(x=>m[c[o](x)]).join`:`:":("
```
[Try it online!](https://tio.run/##jVLBboMwDL3zFVFOiUrTsN5ShYpKO7aTdmVIDSF0VC1B0FZI076dxZBy2KkisZ@f/SwL56weqtNt1dyWtS3MUMpByTiXMdEytRJXdWH6jxJnYStTxpjKwqv8NKf3viEtu6qGVK7WSJ3ajFSUxnyLv77wwgiiWXPvvh0ZYsIWFFPKzraqj0fKTG80ySndTi16GV/TsUNPM18ljgILgodN8FAt0qozHZIoDbBCB3tDyxgdcOiiOXTFEOe6@Me4ktbAB1xrxHgg0/co2SVJsoNEIhLg9vs9kDvH@zsmnRezGbXrdY8iHnEePS8URlwAfBo/kdI54opzrRVXyjnugaOcdwC0WgApuBYaDARer9UreiVAzMfrsNfmr4nnv5cXrwk4d2P6BAw8Y0jgINsEpW0RgeVVyJbTBin6CRBQrenul5tb6AqeBhqNawp@Nb2Oim4CpG3d2YthF3siJZlEaZTRJ3zLaOh7pevMKX6HPw "JavaScript (Node.js) – Try It Online")
Takes the arguments in currying syntax: `f(a)(b)`
Explanation (and ungolfed):
```
function matchPattern(a, b) { // Main function
var c = ["indexOf"]; // Array used for the capturing groups
var r = [...a]; // Split the pattern first
var m = RegExp(r.map(function(i) { // Create the regex
var e = c.indexOf(i); // Check if the character is found before
if (e > 0) // If so
return "\\" + e; // Append the back reference to the regex
else { // If not
c.push(i); // Append the character to the array
return "(.+)"; // Append a capturing group to the regex
}
}).join("")).exec(b); // Execute the regex
if (m != null) // If the pattern matches the string
return r.map(function(x) { // Replace each letter
return m[c.indexOf(x)]; // With the corresponding substring
}).join(":"); // And join them with ":"
else // If there is no match
return ":("; // Return ":("
}
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 35 bytes
```
sᵗ~cᵗXlᵛ∧Xzdz≠ʰ∧Xt~ṇ{Ḷ∧":"|}ᵐ.∨":("
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Oh81NdQ@3Drhf/HDrdPrkoFERM7DrbMfdSyPqEqpetS54NQGELuk7uHO9uqHO7YBOUpWSjUgLXqPOlYoWWko/f8frRCtlKiko@SXX6IUqwNko3CSklNQuGBJPz@oShCvKBUEwQIVFUC@o5OjoxOY6@vrC@E7gYQgGKLO2Bik0tDA0MDAEIZh9iUmJwHlDBINDJKTEw0SE4GUAZQBFALSQAZMbXIi8WqTSFKcQpxqhVgA "Brachylog – Try It Online")
On not-quite-small inputs, ***very*** slow. I-haven't-actually-done-the-sixth-test-case-but-not-for-lack-of-trying slow. (Probably owing to brute-forcing every partition of every substring, starting with the largest, and then checking if it's a match.) Takes input as a list `[pattern,string]`.
### Condensed and divided explanation:
`sᵗ~cᵗX`
X is the pattern paired with a partition of a substring of the input string.
`lᵛ`
The pattern and the partition have the same number of elements.
`Xzdz≠ʰ`
No two unique `pattern char, matched substring` pairs share a pattern character. That is, no pattern character maps to multiple substrings, although multiple pattern characters may map to one substring.
`Xt~ṇ{Ḷ∧":"|}ᵐ.∨":("`
The output is the elements of the partition joined by colons, unless something couldn't be done, in which case it's `:(` instead.
### Monolithic explanation:
```
The input
ᵗ ᵗ with its last element replaced with
~c a list which concatenates to
s a substring of it
X is X,
ᵛ the elements of which all have the same
l length.
∧ And,
X X
z zipped
d with duplicate pairs removed
z and zipped back
ʰ has a first element
≠ with no duplicate values.
∧ Furthermore,
t the last element of
X X
~ṇ with its elements joined by newlines
{ }ᵐ where each character of the joined string
Ḷ is a newline
∧ and
| is replaced with
":" a colon
| or is passed through unchanged
. is the output.
∨ If doing any part of that is impossible,
the output is
":(" ":(".
```
] |
[Question]
[
Given a string representing the current state of a game of [Monopoly](http://en.wikipedia.org/wiki/Monopoly_%28game%29) at the beginning of a player's turn, compress all the necessary data into the smallest output. Answers will be judged by **output size** and **source size**.
Note: There are many regional variations, but all references in this post to property names, etc, are based on [this board](http://www.sundown-farm-and-ranch.com/album/vintage%20monopoly%20games/Monopoly%20games%20-%201935/1935%20patent%20pending%20board%20-%20early%20version.jpg).
---
## Input:
Input will be given as a single `;` separated string. This string is given to the program in whatever way is customary in your chosen language, whether that's stdin, arguments, etc.
The unformatted input looks like this:
```
numPlayers (1 to 8)
whose turn (0 to numPlayers-1)
for each player:
bankrupt? (true/false)
money (0 to 2^16-1)
get-out-of-jail-free cards (0 to 2)
position (0 to 39)
jail turns (-1 to 2)
for 28 properties:
owner (-1 to numPlayers-1)
mortgaged? (true/false)
improvement level (0 to 5)
for 16 chance cards in deck:
card index (-1 to 15)
for 16 community chest cards in deck:
card index (-1 to 15)
```
An example *formatted* input is this:
```
3;1;false;1546;0;14;-1;false;7692;1;10;1;true;1;false;1;1;false;0;0;true;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;3;12;7;4;5;2;13;11;15;6;8;9;10;1;14;-1;
```
Taken bit by bit:
```
3;1;
```
There are 3 players, and it is player 1's turn (zero-indexed, so the *second* player)
**Players**
```
false;1546;0;14;-1;
false;7692;1;10;1;
true;
```
The first player:
* is not bankrupt
* has $1546 cash on hand
* owns 0 get-out-of-jail-free cards
* is on position 14 (Virginia Ave)
* is not in jail
The second player **is** in jail, and has been for one turn. I'm not sure *why*, since he has a GOoJF card, but he's there.
The third player is bankrupt, and more information is neither required nor given.
**Properties**
```
1;false;1;
1;false;0;
0;true;0;
-1;false;0;
-1;false;0;
-1;false;0;
...
```
Properties are listed in order around the board, starting from Mediterranean and ending at Boardwalk. Properties that cannot be owned are not included in this list, so there will be a total of 28. Improvement level `0` means unimproved. Level `1` is one house, up to level `5` for a hotel. A `-1` for owner means it is not owned by any player.
According to standard rules, a property that is mortgaged *must* be owned and *must not* be improved. A property that is improved *must* be owned and *must not* be mortgaged.
In addition, for a property to be improved, a player *must* own the entire color block. For the purposes of this game, we do not care if properties are being improved "evenly".
Note that these positions are *not* the same as the player positions given above. For instance, a player on the `5` position would be on Reading Railroad, which is the *third* property in the list (since Go, Community Chest, and Income Tax cannot be owned). Player positions run from `0`(Go) clockwise to `39`(Boardwalk).
**Cards**
```
0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;
3;12;7;4;5;2;13;11;15;6;8;9;10;1;14;-1;
```
Each of the Chance and Community Chest decks have `16` total cards. The numbers are presented as they appear in the currently shuffled deck. For this example, the first card pulled off the Chance deck will be card `0`, followed by card `1` (whoever shuffled that deck sucks). The first card pulled from Community chest is card `3`, then `12`.
Don't worry about what each card *means* (the card text), except for card `0`. That is the Get Out of Jail Free card for that deck. If a player owns it, it will be at the end of the list, represented as `-1`.
---
## Output:
You must output (to console, stdout, or file) a representation of the game state. This must include all information **required** to represent the game. For example, you could omit (or abbreviate) unowned properties, since they can neither be improved or mortgaged. The input cannot omit them because it is an unindexed list.
Compression should be done in a way that you can compute worst-case output size. This may disqualify certain compression algorithms (unless you can prove the worst case, and give an example of worst-case input).
Unless your source code is *unreasonably* verbose, give an explanation of how the game is represented. Answers consisting of nothing but a golfed program and compressed output are discouraged. For example, if you are omitting certain values, explain how it is possible to derive them from the output.
---
## Scoring/Rules:
Scoring is based both on **worst-case** compression size in **bits**, and source code size in **bytes**:
```
score = (outputBits * 2) + encoderSourceBytes
```
A complete answer must include:
* Output example
* Encoder source
* Decoder source (not counted against score)
All encoders must be complete programs, and [standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/14215) are forbidden. Using built-in or external compression libraries is also forbidden.
The winner is the answer with the **lowest** score, as defined above.
[Answer]
(An answer was recently edited, which brought this question to my attention, and I decided to give it a try although its an old question.)
# Swift 1.2 - 1016 Points (2\*81 + 854)
The output is at worst 81 bytes, and changes with the amount of players.
Either of the two methods work. The Playground version is slightly longer.
**Compress Playground**
(Assumes `Input.txt` is in the `Playground Documents Directory`)
```
// Compressor e(inputFileName, outputFileName)
import Cocoa;typealias S=String;typealias U=UInt8;func e(a:S,b:S){var d=NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)as![S],g=d[0],r=S(contentsOfFile:"\(g)/\(a)",encoding:4,error:nil)!.componentsSeparatedByString(";"),z=[U](count:4,repeatedValue:0),c=[U](),p:()->Int={r.removeAtIndex(0).toInt()!},f:()->Bool={r.removeAtIndex(0)=="true" ?true:false},j=U(p());c+=[(j<<4)|(U(p()))];for _ in 0..<j{if f(){c+=[255]}else{let(t,g,v)=(UInt16(p()),U(p()),U(p()));c+=[(U(p()))|(g<<2),v,U(t>>8),U(t&255)]}};for _ in 0..<28{c+=[(U(bitPattern:Int8(p()))<<4)|((f() ?1:0)<<3)|(U(p()))]};for h in 0..<16{let y=h>7 ?1:0,x=Int8(p()),w=Int8(p());c+=[(U(bitPattern:x)<<4)|(U(bitPattern:w)&15)];z[y]=z[y]<<1;if x == -1{z[y]|=1};z[y+1]=z[y+1]<<1;if w == -1{z[y+1]|=1}};NSData(bytes:c+z,length:c.count+4).writeToFile("\(g)/\(b)",atomically:true)}
// Decompressor d(inputFileName, outputFileName)
func d(a:S,b:S){var d = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)as![String],e=d[0],i=NSData(contentsOfFile:"\(e)/\(a)")!,n=[UInt8](count:i.length,repeatedValue:0),o="";i.getBytes(&n,length:i.length);let k=n.removeAtIndex(0),j=k>>4;o+="\(j);\(k&15);";for _ in 0..<j{let h=n.removeAtIndex(0);if h>>7 == 1{o+="true;";continue};let p=n.removeAtIndex(0),b=n.removeAtIndex(0),c=n.removeAtIndex(0);o+="false;\(UInt16(b)<<8|UInt16(c));\(h>>2);\(p);\(h&0b11);"};for _ in 0..<28{let p=Int8(bitPattern:n.removeAtIndex(0)),mortgage=((p>>3)&1)==1 ?"true":"false";o+="\(p>>4);\(mortgage);\(p&7);"};var m=[U](count:4,repeatedValue:0);for i in reverse(0..<4){m[i]=n.removeLast()};for h in 0..<16{var i=h>7 ?1:0,z=n.removeAtIndex(0),x=Int8(z>>4),y=Int8(z&15),isUnowned1=m[i]&128;m[i]=m[i]<<1;let isUnowned2=m[i+1]&128;m[i+1]=m[i+1]<<1;if isUnowned1 != 0 {x=(-1)};if isUnowned2 != 0 {y=(-1)};o+="\(x);\(y);"};o.writeToFile("\(e)/\(b)",atomically:true,encoding:4,error:nil)}
// Test function to compare the files
func t(a:S,b:S)->Bool{let d=NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)as![String],c=d[0],i=S(contentsOfFile:"\(c)/\(a)",encoding:4,error:nil)!,j=S(contentsOfFile:"\(c)/\(b)",encoding:4,error:nil)!;return i==j}
// Usage
e("Input.txt", "Output.bin") // Encode
d("Output.bin", "Output.txt") // Decode
t("Input.txt", "Output.txt") // Test -> Should output 'true'
```
**Compress.swift** - run in Terminal using `swift Compress.swift`
(Assumes `Input.txt` is on the `Desktop`)
```
// Compressor - 854 Bytes
import Cocoa;typealias S=String;typealias U=UInt8;func e(a:S,b:S){var d=NSSearchPathForDirectoriesInDomains(.DesktopDirectory,.UserDomainMask, true)as![S],g=d[0],r=S(contentsOfFile:"\(g)/\(a)",encoding:4,error:nil)!.componentsSeparatedByString(";"),z=[U](count:4,repeatedValue:0),c=[U](),p:()->Int={r.removeAtIndex(0).toInt()!},f:()->Bool={r.removeAtIndex(0)=="true" ?true:false},j=U(p());c+=[(j<<4)|(U(p()))];for _ in 0..<j{if f(){c+=[255]}else{let(t,g,v)=(UInt16(p()),U(p()),U(p()));c+=[(U(p()))|(g<<2),v,U(t>>8),U(t&255)]}};for _ in 0..<28{c+=[(U(bitPattern:Int8(p()))<<4)|((f() ?1:0)<<3)|(U(p()))]};for h in 0..<16{let y=h>7 ?1:0,x=Int8(p()),w=Int8(p());c+=[(U(bitPattern:x)<<4)|(U(bitPattern:w)&15)];z[y]=z[y]<<1;if x == -1{z[y]|=1};z[y+1]=z[y+1]<<1;if w == -1{z[y+1]|=1}};NSData(bytes:c+z,length:c.count+4).writeToFile("\(g)/\(b)",atomically:true)}
// Decompressor
func d(a:S,b:S){var d = NSSearchPathForDirectoriesInDomains(.DesktopDirectory,.UserDomainMask,true)as![String],e=d[0],i=NSData(contentsOfFile:"\(e)/\(a)")!,n=[UInt8](count:i.length,repeatedValue:0),o="";i.getBytes(&n,length:i.length);let k=n.removeAtIndex(0),j=k>>4;o+="\(j);\(k&15);";for _ in 0..<j{let h=n.removeAtIndex(0);if h>>7 == 1{o+="true;";continue};let p=n.removeAtIndex(0),b=n.removeAtIndex(0),c=n.removeAtIndex(0);o+="false;\(UInt16(b)<<8|UInt16(c));\(h>>2);\(p);\(h&0b11);"};for _ in 0..<28{let p=Int8(bitPattern:n.removeAtIndex(0)),mortgage=((p>>3)&1)==1 ?"true":"false";o+="\(p>>4);\(mortgage);\(p&7);"};var m=[U](count:4,repeatedValue:0);for i in reverse(0..<4){m[i]=n.removeLast()};for h in 0..<16{var i=h>7 ?1:0,z=n.removeAtIndex(0),x=Int8(z>>4),y=Int8(z&15),isUnowned1=m[i]&128;m[i]=m[i]<<1;let isUnowned2=m[i+1]&128;m[i+1]=m[i+1]<<1;if isUnowned1 != 0 {x=(-1)};if isUnowned2 != 0 {y=(-1)};o+="\(x);\(y);"};o.writeToFile("\(e)/\(b)",atomically:true,encoding:4,error:nil)}
func t(a:S,b:S)->Bool{let d=NSSearchPathForDirectoriesInDomains(.DesktopDirectory,.UserDomainMask,true)as![String],c=d[0],i=S(contentsOfFile:"\(c)/\(a)",encoding:4,error:nil)!,j=S(contentsOfFile:"\(c)/\(b)",encoding:4,error:nil)!;return i==j}
e("Input.txt", "Output.bin")
d("Output.bin", "Output.txt")
println(t("Input.txt", "Output.txt"))
```
**Sample Input/Output**
```
3;1;false;1534;0;14;0;false;34;1;10;1;true;1;false;1;1;false;0;0;true;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;3;12;6;9;4;-1;4;8;4;2;9;5;11;10;14;7;
```
.
```
31 00 0E 05 FE 05 0A 00 22 FF 11 10 08 F0 F0 F0
F0 F0 F0 F0 F0 F0 F0 F0 F0 F0 F0 F0 F0 F0 F0 F0
F0 F0 F0 F0 F0 F0 01 23 45 67 89 AB CD EF 3C 69
4F 48 42 95 BA E7 00 00 20 00
```
[Answer]
## Pure C (3592 points)
The output is 182 bytes. The size is O(1), so this is the worst case.
This uses sscanf extensively to read the files, and simply dumps the structs to disk.
I had to slightly modify the input, as your example didn't include 28 properties.
For variables, I named them from the first letter of what it is, or if that would conflict, the second (or subsequent) letter. For example, Game, pLayer, pRoperty, etc.
**compress.c** (680 bytes):
```
#import <stdio.h>
#import <stdint.h>
#define T(X) for(int i=0;i<(X);i++)
typedef uint8_t U;typedef struct{U p;U t;U a[16];U e[16];}G;typedef struct{U b;uint16_t m;U c;U p;U t;}L;typedef struct{int8_t o;U m;U i;}R;G g;L l[8];R r[28];main(){FILE *f=fopen("input.txt","r");fscanf(f,"%d;%d;",&g.p,&g.t);T(g.p){l[i].b=(fgetc(f)=='t');while(fgetc(f)!=';');if(!l[i].b){fscanf(f,"%d;%d;%d;%d;",&l[i].m,&l[i].c,&l[i].p,&l[i].t);}}T(28){fscanf(f,"%d;",&r[i].o);r[i].m=(fgetc(f)=='t');while(fgetc(f)!=';');fscanf(f,"%d;",&r[i].i);}T(16){fscanf(f,"%d;",&g.a[i]);}T(16){fscanf(f,"%d;",&g.e[i]);}f=fopen("c.dat","w");fwrite(&g,sizeof(G),1,f);fwrite(&l,sizeof(L),8,f);fwrite(&r,sizeof(R),28,f);}
```
**compress.c (pre-golfed)**
```
#include "m.h"
#define NEXT_FIELD b=strchr(b,';')+1;
G g;
L l[8];
R r[28];
char a[1024];
char *b = a;
main() {
FILE *i = fopen("input.txt", "r");
fgets(a, 1024, i);
fclose(i);
sscanf(b, "%d;%d;", &g.p, &g.t);
NEXT_FIELD NEXT_FIELD
TIMES(g.p) {
l[i].b = (*b == 't'); NEXT_FIELD
if(!l[i].b) {
sscanf(b, "%d;%d;%d;%d;", &l[i].m, &l[i].c, &l[i].p, &l[i].t);
NEXT_FIELD NEXT_FIELD NEXT_FIELD NEXT_FIELD
}
}
TIMES(28) {
sscanf(b, "%d;", &r[i].o); NEXT_FIELD
r[i].m = (*b == 't'); NEXT_FIELD
sscanf(b, "%d;", &r[i].i); NEXT_FIELD
}
TIMES(16) {
sscanf(b, "%d", &g.a[i]);
NEXT_FIELD
}
TIMES(16) {
sscanf(b, "%d", &g.e[i]);
NEXT_FIELD
}
FILE *c = fopen("c.dat", "w");
fwrite(&g, sizeof(G), 1, c);
fwrite(&l, sizeof(L), 8, c);
fwrite(&r, sizeof(R), 28, c);
fclose(c);
}
```
**decompress.c**:
```
#import <stdio.h>
#import <stdint.h>
#define T(X) for(int i = 0; i < (X); i++)
typedef uint8_t U;
typedef struct {
U p;
U t;
U a[16];
U e[16];
} G;
typedef struct {
U b;
uint16_t m;
U c;
U p;
U t;
} L;
typedef struct {
int8_t o;
U m;
U i;
} R;
G g;
L l[8];
R r[28];
main() {
FILE *c = fopen("c.dat", "r");
fread(&g, sizeof(G), 1, c);
fread(&l, sizeof(L), 8, c);
fread(&r, sizeof(R), 28, c);
fclose(c);
FILE *d = fopen("output.txt", "w");
fprintf(d, "%d;%d;", g.p, g.t);
T(g.p) {
fprintf(d, "%s;", l[i].b ? "true" : "false");
if(!l[i].b){
fprintf(d, "%d;%d;%d;%d;", l[i].m, l[i].c, l[i].p, l[i].t);
}
}
T(28) {
fprintf(d, "%d;%s;%d;", r[i].o, r[i].m ? "true" : "false", r[i].i);
}
T(16) { fprintf(d, "%d;", g.a[i] != 255 ? g.a[i] : -1); }
T(16) { fprintf(d, "%d;", g.e[i] != 255 ? g.e[i] : -1); }
fclose(d);
}
```
**Input / output**:
```
3;1;false;1546;0;14;0;false;7692;1;10;1;true;1;false;1;1;false;0;0;true;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;-1;false;0;0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;3;12;7;4;5;2;13;11;15;6;8;9;10;1;14;-1;
```
**Compressed** (182 bytes):
```
0301 0001 0203 0405 0607 0809 0a0b 0c0d
0e0f 030c 0704 0502 0d0b 0f06 0809 0a01
0eff 0000 0a06 000e 0000 0000 0c1e 010a
0100 0100 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0100 0101 0000 0001 00ff 0000 ff00
00ff 0000 ff00 00ff 0000 ff00 00ff 0000
ff00 00ff 0000 ff00 00ff 0000 ff00 00ff
0000 ff00 00ff 0000 ff00 00ff 0000 ff00
00ff 0000 ff00 00ff 0000 ff00 00ff 0000
ff00 00ff 0000
```
**Run it!**
```
$ make compress decompress && ./compress && ./decompress && md5 input.txt output.txt
MD5 (input.txt) = fa655a5a17d67b188424ab0dcfdfb825
MD5 (output.txt) = fa655a5a17d67b188424ab0dcfdfb825
```
] |
[Question]
[
**WARNING: this is a fairly complex problem, in a king-of-the-hill combat style, with an added randomness to it, the best code may not always win. Please read all rules in full, as it is quite complex!**
# Flavor text
Bill and Steve decided to have a "friendly" duel, however being so rich and smart, decided to let their best programmers try their hand at coming up with the code to beat each other. You are said programmer.
# Objective
In fencing, your goal is to score the most hits on your opponent, while getting hit the least yourself
# Moves
Your code will have the following choices of "moves"
* Attack
* Parry
* Block
* Lunge
**AND**
* Head
* Chest
* Feet
# Scoring
Attacking beats Parrying, *for 1 point*
Lunging beats Blocking, *for 1 point*
Parrying Beats Lunging, *for 1 point*
Blocking beats Attacking, *for 1 point*
Lunging ties Attacking, *with the lunging player unable to block or parry the next round, and the attacking player unable to attack or lunge the next round*
Blocking ties Parrying, *with the parrying player unable to block or parry the next round, and the blocking player unable to attack or lunge the next round*
# Height of action
You will also choose a "height" for your action, whereupon the outcomes above only take place if the heights of both players match the attack height. if the heights do not match, both players may no longer select the same action (height is not restricted) as the previous tying rounds, until a point is scored, or all 4 actions have been filled (once a tie is broken, all actions are available again)
# Code requirements
For each round, it should prompt the move of the opponent the previous round (barring round 1), compare it with its own, determine the outcome of the previous round, then output the next round number, the score, and its choice / position for that round
ex:
INPUT: LC (lunge chest)
OUTPUT: previous round: PM vs LC - PM scores! score is now 2-1, action for next round is AH (attack head)
# Winner
The game ends after 50 rounds, or after 3 points have been scored
# Against other players
The first answer will be given an instant guaranteed win, as long as it functions to actually work/play. Each answer will be evaluated, in order of posting, against the previous winner, and if winning, will be declared the new winner. I ask that while winning, or waiting to compete, that you do NOT change your code. Once being defeated, you may no longer compete for championship status with that same language, you may however submit a different language answer (must be significantly different, no using variations of the same base stuff).
I will attempt to run each challenge and will post the results in the comments of the champion and challenger, as well as declare a new winner - as I may not be able to run every language, especially some of the more obscure ones, I ask any possible help you can give to make sure your answer gets run be taken into consideration.
[Answer]
## Python
En garde!
My warrior combines unpredictability with a keen eye for weakness in his opponent's stance. He's pretty confident he'll be able to dispose of aggressive foes but his trainer (me) may have failed to anticipate certain scenarios or, perhaps more worrying, may have misinterpreted the rules (bugs!!).
Anyway I'm new so hopefully this is an ok format for the code:
```
from random import choice, random
def cleverly_pick_move(me_allowed,op_allowed,opp_last_move=None) :
""" Behold the genius you're up against!
Pretty much everything else is just flavour text or match rules
so you'll probably only want to read this...
"""
heights = ['head','chest','feet']
rand_choice = lambda a,h : {'type':choice([t for t in a if a[t]]),
'height':choice(h)}
if opp_last_move is None or feeling_like_a_lucky_punk():
return rand_choice(me_allowed,heights)
if sum(1 for x in op_allowed if op_allowed[x]) == 3 :
for i in op_allowed:
if not op_allowed[i] :
weakness = i
break
return {'type':exploit_weakness(weakness,me_allowed),
'height':choice(heights)}
return rand_choice(me_allowed,heights)
def exploit_weakness(weakness,me_allowed) :
moves = ['attack','parry','lunge','block']
for i,move in enumerate(moves) :
if move == weakness :
if me_allowed[moves[(i+1) % 4]] :
return moves[(i+1) % 4]
break
if me_allowed[weakness] :
return weakness
return choice([x for x in me_allowed if me_allowed[x]])
def feeling_like_a_lucky_punk() :
return random() > 0.8
def main():
this_round = 1
opp_last_move = None
score = {'myself':0, 'the blaggard':0}
quips = ['blaggard', 'fool', 'scum', 'raggamuffin']
adverbs = ['deftly', 'skillfully', 'gracefully', 'clumsily']
me_allowed = {'attack':True,'block':True,'lunge':True,'parry':True}
op_allowed = {'attack':True,'block':True,'lunge':True,'parry':True}
while (this_round <= 50 and
all([points < 3 for points in score.values()])) :
if this_round == 1 :
move = cleverly_pick_move(me_allowed,op_allowed)
else:
move = cleverly_pick_move(me_allowed,op_allowed,
opp_last_move=opp_last_move)
print "Our hero %s %ss at the %s's %s" % (
choice(adverbs),
move['type'],
choice(quips),
move['height']
)
print "We await the %s's response..." % choice(quips)
print "Our hero's move: " + (move['type'][0]+move['height'][0]).upper()
opp_move = parse_move(raw_input("Opponent's move: "))
outcome,me_allowed,op_allowed = get_outcome(move,opp_move,me_allowed,
op_allowed)
if outcome == 'WIN' :
print "Our hero pulls off an excellent round!"
score['myself'] += 1
elif outcome == 'LOSE' :
print "Never before have we seen such blatant cheating!"
score['the blaggard'] += 1
else :
print "Our hero is clearly toying with his opponent as he allows \
a drawn round."
print ("""The score after round %d:\nOur hero:\t%d\nHis opponent:\t%d"""
% (this_round, score['myself'], score['the blaggard']))
opp_last_move = opp_move
this_round += 1
print "Match over, surely the victory is mine!"
print """Final score:\n
Our hero:\t%d\nOpponent:\t%d""" % (score['myself'],
score['the blaggard'])
if score['myself'] > score['the blaggard'] :
print "My victory was inevitable!"
elif score['myself'] == score['the blaggard'] :
print "An even match! Huzzar!"
else :
print ""
return
def reset_allowed(dictionary) :
return dict((x,True) for x in dictionary)
def get_outcome(mymove,opmove,me_allowed,op_allowed) :
result = ''
if not me_allowed[mymove['type']] :
print "Whoops, I forgot I couldn't do that..."
result = 'LOSE'
if not op_allowed[opmove['type']] :
print "Haha! What a clutz!"
result = 'WIN'
if mymove['height'] != opmove['height'] :
print "The combatants flail at each other with little effect!"
print "They'll have to try something else next round!"
result = 'DRAW'
if mymove['type'] == opmove['type'] :
if mymove['type'] in ['attack','lunge']:
print "The combatants' blades clash dramatically!"
else :
print "Both combatants take a moment to practice their \
defensive stance..."
result = 'DRAW'
if result :
me_allowed, op_allowed = (reset_allowed(me_allowed),
reset_allowed(op_allowed))
if mymove['height'] != opmove['height'] :
me_allowed[mymove['type']] = op_allowed[opmove['type']] = False
return (result, me_allowed,op_allowed)
else :
return compare_attacks(mymove,opmove,me_allowed,op_allowed)
def compare_attacks(mymove,opmove,me_allowed,op_allowed) :
"""
0 A > P 1
^ x v
3 B < L 2
"""
print "Our hero %ss, his opponent %ss!" % (mymove['type'],opmove['type'])
move_val = {'attack':0,'parry':1,'lunge':2,'block':3}
result_num = (move_val[opmove['type']] - move_val[mymove['type']]) % 4
results = ['DRAW','WIN','DRAW','LOSE']
me_allowed, op_allowed = (reset_allowed(me_allowed),
reset_allowed(op_allowed))
if result_num == 1 :
print "Our hero easily outwits his foe! *Huge cheers from crowd*"
return ('WIN',me_allowed,op_allowed)
elif result_num == 3 :
print "Our hero graciously allows his opponent a charity point.\
*A torrent of boos from the crowd*"
return ('LOSE',me_allowed,op_allowed)
else:
# Combatants drew and will have their moves restricted next round.
if mymove['type'] in ['attack','parry'] :
me_allowed['attack'] = me_allowed['lunge'] = False
me_allowed['parry'] = me_allowed['block'] = True
op_allowed['parry'] = op_allowed['block'] = False
op_allowed['attack'] = op_allowed['lunge'] = True
else :
me_allowed['parry'] = me_allowed['block'] = False
me_allowed['attack'] = me_allowed['lunge'] = True
op_allowed['attack'] = me_allowed['lunge'] = False
op_allowed['parry'] = op_allowed['block'] = True
return ('DRAW',me_allowed,op_allowed)
def parse_move(move_string) :
m_types = {'A':'attack','B':'block','L':'lunge','P':'parry'}
m_heights = {'C':'chest','H':'head','F':'feet'}
move_string = move_string.strip().upper()
if not move_string :
print "Couldn't understand your input: %s" % move_string
return parse_move(raw_input("Opponent's move: "))
if move_string[0] not in m_types :
move_string = move_string[::-1]
try :
move = {'type':m_types[move_string[0]],
'height':m_heights[move_string[1]]}
return move
except KeyError :
print "Couldn't understand your input: %s" % move_string
return parse_move(raw_input("Opponent's move: "))
if __name__ == '__main__' :
main()
```
[Answer]
I claim the hill!
This includes a framework which takes care of the match, input and output. All you have to do is define your own versions of two functions in the "A.I.h" header which define the first move and every other move.
This compiles in VS2012 (free version). To the best of my knowledge it will compile in any standards-compliant compiler.
I call this A.I. "Unsophisticated Barbarian." I'm sure it won't take long for someone to beat it.
```
// A.I.h
#pragma once
#include "Fencer.h"
#include <algorithm>
Move Fencer::chooseFirstMove() const
{
// Choose first move here.
return Move( Action::Attack , Height::Head );
}
Move Fencer::chooseNextMove() const
{
using namespace std;
// Implement A.I. here.
auto legalActions = match.legalActions();
auto isLegal = [&legalActions]( Action a ) {
return find( begin(legalActions) , end(legalActions) , a ) == end(legalActions);
};
if( isLegal( Action::Attack ) )
return Move( Action::Attack , Height::Head );
if( isLegal( Action::Lunge ) )
return Move( Action::Lunge , Height::Head );
if( isLegal( Action::Block ) )
return Move( Action::Lunge , Height::Head );
if( isLegal( Action::Parry ) )
return Move( Action::Parry , Height::Head );
}
// Fencer.h
#pragma once
#include "Match.h"
class Fencer
{
public:
std::string nextRound( const std::string& oppsMove );
std::string getNextMove() const { return nextMove.toStr(); }
bool matchInProgress() const { return match.inProgress(); }
Fencer( unsigned int targetScore = 3 , unsigned int match_rounds = 50 );
private:
Move chooseNextMove() const;
Move chooseFirstMove() const;
Move nextMove;
Match match;
};
// Match.h
#pragma once
#include <vector>
#include <string>
enum class Action : char
{
Attack,
Parry,
Block,
Lunge,
UNITIALIZED
};
enum class Height : char
{
Head,
Chest,
Feet,
UNITIALIZED
};
enum class Result : char
{
Win,
Tie,
Lose,
UNITIALIZED
};
struct Move
{
Action action;
Height height;
Move( Action a , Height h )
: action(a) , height(h) {}
std::string toStr() const;
// For the STL. Please don't use these.
Move() : action( Action::UNITIALIZED ) , height( Height::UNITIALIZED ) {}
Move operator=( const Move& );
};
Result scoreRound( Move me , Move opp );
struct Round
{
Move myMove;
Move oppsMove;
Result result;
Round( Move me , Move opp )
: myMove(me) , oppsMove(opp) , result(scoreRound(me,opp)) {}
// For the STL. Please don't use these.
Round() : myMove() , oppsMove() , result( Result::UNITIALIZED ) {}
Round operator=( const Round& );
};
class Match
{
public:
// Constructor.
Match( unsigned int winningScore, unsigned int rounds );
// Generate a list of legal actions.
std::vector<Action> legalActions() const;
// Get a copy of all previous rounds.
std::vector<Round> getHistory() const { return results; }
// Gets the scores
unsigned int myScore() const;
unsigned int oppsScore() const;
bool inProgress() const { return in_progress; }
// Perform next round. Returns the TTY for the round.
std::string nextRound( const std::string& myMove , const std::string& oppsMove );
private:
const unsigned int winning_score;
const unsigned int n_rounds;
std::vector<Round> results;
bool in_progress;
};
// Fencer.cpp
#include "AI.h"
#include <algorithm>
using namespace std;
Fencer::Fencer( unsigned int target , unsigned int rounds ) :
match( target , rounds ) , nextMove( chooseFirstMove() )
{}
string Fencer::nextRound( const string& oppsMove )
{
string output = match.nextRound( nextMove.toStr() , oppsMove );
if( match.inProgress() ) {
nextMove = chooseNextMove();
vector<Action> legalActions = match.legalActions();
auto it = find( legalActions.begin() , legalActions.end() , nextMove.action );
auto it2 = legalActions.end();
if( legalActions.end() == it ) {
output += "\n\nWARNING! Chosen move is illegal!\n\n";
}
output += " Action for next round is " + getNextMove() + ".";
}
return output;
}
// Match.cpp
#include "Match.h"
#include <algorithm>
#include <sstream>
#include <cassert>
#include <functional>
using namespace std;
string Move::toStr() const
{
string str;
switch( action )
{
case Action::Attack:
str.push_back( 'A' );
break;
case Action::Block:
str.push_back( 'B' );
break;
case Action::Lunge:
str.push_back( 'L' );
break;
case Action::Parry:
str.push_back( 'P' );
break;
default:
assert( false );
break;
}
switch( height )
{
case Height::Head:
str.push_back( 'H' );
break;
case Height::Chest:
str.push_back( 'C' );
break;
case Height::Feet:
str.push_back( 'F' );
break;
default:
assert( false );
break;
}
return str;
}
Move Move::operator=( const Move& rhs )
{
action = rhs.action;
height = rhs.height;
return *this;
}
Result scoreRound( Move me , Move opp )
{
if( me.height != opp.height ) {
return Result::Tie;
}
if( me.action == opp.action ) {
return Result::Tie;
}
switch ( me.action ) {
case Action::Attack:
switch( opp.action ) {
case Action::Parry:
return Result::Win;
case Action::Lunge:
return Result::Tie;
case Action::Block:
return Result::Lose;
default:
assert( false );
}
case Action::Lunge:
switch( opp.action ) {
case Action::Block:
return Result::Win;
case Action::Attack:
return Result::Tie;
case Action::Parry:
return Result::Lose;
default:
assert( false );
}
case Action::Parry:
switch( opp.action ) {
case Action::Lunge:
return Result::Win;
case Action::Block:
return Result::Tie;
case Action::Attack:
return Result::Lose;
default:
assert( false );
}
case Action::Block:
switch( opp.action ) {
case Action::Attack:
return Result::Win;
case Action::Parry:
return Result::Tie;
case Action::Lunge:
return Result::Lose;
default:
assert( false );
}
default:
assert( false );
}
return Result::Tie;
}
Round Round::operator=( const Round& rhs )
{
myMove = rhs.myMove;
oppsMove = rhs.oppsMove;
result = rhs.result;
return *this;
}
Match::Match( unsigned int targetScore , unsigned int rounds ) :
winning_score( targetScore ) , n_rounds( rounds) , results() , in_progress( true )
{
results.reserve( rounds );
}
vector<Action> Match::legalActions() const
{
typedef unsigned int ActionBits;
// Make a bitfield representing the four legal actions.
const ActionBits ATTACK = 0x1;
const ActionBits PARRY = 0x2;
const ActionBits BLOCK = 0x4;
const ActionBits LUNGE = 0x8;
const auto actionBitsToVector = [=](ActionBits ab) -> vector<Action> {
vector<Action> vec;
if( ab == 0 ) // Nothing is allowed
ab = ATTACK | PARRY | BLOCK | LUNGE; // So allow all actions
if( (ATTACK & ab) == ATTACK )
vec.push_back( Action::Attack );
if( (PARRY & ab) == PARRY )
vec.push_back( Action::Parry );
if( (BLOCK & ab) == BLOCK )
vec.push_back( Action::Block );
if( (LUNGE & ab) == LUNGE )
vec.push_back( Action::Lunge );
return vec;
};
auto availableActions = ATTACK | PARRY | BLOCK | LUNGE;
const auto lastResult = *results.rbegin();
// If a point was scored in the last round all actions are available.
if( lastResult.result != Result::Tie ) {
return actionBitsToVector( availableActions );
}
// If the heights do not match, both players may no longer
// select the same action (height is not restricted)
// as the previous tying rounds, until a point is scored,
// or all 4 actions have been filled.
if( lastResult.myMove.height != lastResult.oppsMove.height ) {
for( auto it = results.rbegin() ; it!= results.rend() ; ++it ) {
if( it->result != Result::Tie )
break;
else {
switch( it->myMove.action )
{
case Action::Attack:
availableActions &= ~ATTACK;
break;
case Action::Parry:
availableActions &= ~PARRY;
break;
case Action::Block:
availableActions &= ~BLOCK;
break;
case Action::Lunge:
availableActions &= ~LUNGE;
break;
default:
break;
}
}
}
return actionBitsToVector( availableActions );
}
// Attack vs. Lunge
if( lastResult.myMove.action == Action::Attack &&
lastResult.oppsMove.action == Action::Lunge ) {
return actionBitsToVector( PARRY | BLOCK );
}
if( lastResult.myMove.action == Action::Lunge &&
lastResult.oppsMove.action == Action::Attack ) {
return actionBitsToVector( ATTACK | LUNGE );
}
// Block vs Parry
if( lastResult.myMove.action == Action::Block &&
lastResult.oppsMove.action == Action::Parry ) {
return actionBitsToVector( ATTACK | LUNGE );
}
if( lastResult.myMove.action == Action::Parry &&
lastResult.oppsMove.action == Action::Block ) {
return actionBitsToVector( BLOCK | PARRY );
}
return actionBitsToVector( availableActions );
}
unsigned int Match::myScore() const
{
return count_if( begin(results) , end(results) ,
[=](const Round& r) {
return r.result == Result::Win;
});
}
unsigned int Match::oppsScore() const
{
return count_if( begin(results) , end(results) ,
[=](const Round& r) {
return r.result == Result::Lose;
});
}
string Match::nextRound( const string& myMove , const string& oppsMove )
{
if( !in_progress )
return "Match has already finished.\n";
stringstream output;
output << "Round " << results.size()+1 << ": ";
bool parseSuccessful = true;
auto getMove = [&]( const string& s ) {
if( s.length() < 2 ) {
output << "\nError: Move " << s << " does not have enough characters.";
return Move();
}
Action a = Action::UNITIALIZED;
switch( s[0] )
{
case 'a':
case 'A':
a = Action::Attack;
break;
case 'b':
case 'B':
a = Action::Block;
break;
case 'l':
case 'L':
a = Action::Lunge;
break;
case 'p':
case 'P':
a = Action::Parry;
break;
default:
parseSuccessful = false;
output << "\nFailed to parse action part (" << s[0] << ") of " << s;
break;
}
Height h = Height::UNITIALIZED;
switch( s[1] )
{
case 'h':
case 'H':
h = Height::Head;
break;
case 'c':
case 'C':
h = Height::Chest;
break;
case 'f':
case 'F':
h = Height::Feet;
break;
default:
parseSuccessful = false;
output << "\nFailed to parse height part (" << s[1] << ") of " << s;
break;
}
if( a == Action::UNITIALIZED || h == Height::UNITIALIZED )
return Move();
else
return Move( a , h );
};
Round thisRound( getMove( myMove ), getMove( oppsMove ) );
if ( parseSuccessful ) {
output << "Previous round: " << myMove << " vs " << oppsMove << " - ";
switch( thisRound.result )
{
case Result::Win:
output << myMove + " Wins! ";
break;
case Result::Lose:
output << oppsMove + " Wins! ";
break;
case Result::Tie:
output << "Tie! ";
break;
default:
assert( false );
break;
}
results.push_back( thisRound );
const auto score_me = myScore();
const auto score_opp = oppsScore();
output << "Score is now " << score_me << "-" << score_opp << ".";
if( score_me >= winning_score ) {
output << "\n\tI win! ";
in_progress = false;
}
if( score_opp >= winning_score ) {
output << "\n\tI lose. ";
in_progress = false;
}
if( results.size() >= n_rounds ) {
output << "\n\tTime's up. ";
if( score_me == score_opp )
output << "Match drawn. ";
else
output << "I " << (score_me > score_opp ? "win! " : "lose. " );
in_progress = false;
}
if (!in_progress ) {
output << "Final score: " << score_me << "-" << score_opp << endl;
}
}
return output.str();
}
```
] |
[Question]
[
In this challenge you will be asked to take a [knot](https://en.wikipedia.org/wiki/Knot_theory) and determine if it can be colored in a particular way.
First we draw a diagram of the knot. We use the standard way of drawing knots where we put gaps in strands where they pass under each other. Here is an example of some knots drawn this way:
[](https://i.stack.imgur.com/qI1xM.png)
[*Taken with permission from wikimedia user Jkasd*](https://en.wikipedia.org/wiki/File:Knot_table.svg)
Once we have drawn the knot we want to color the knot with three colors such that:
* Every contiguous length of string in the knot's diagram is colored with the same color (String on the opposite ends gaps where we pass under do not need to be the same color)
* The three strands that meet at an intersection are either
+ all the same color
+ or all different colors
* At least two colors must be used in total
Some knots can be drawn in this way for example:
[](https://i.stack.imgur.com/QEn3Z.png)
[*Taken with permission from wikimedia user n4nojohn*](https://en.wikipedia.org/wiki/File:FalseKnotTricolor.png)
and some cannot for example
[](https://i.stack.imgur.com/xxhTe.png)
[*Taken with permission from wikimedia user n4nojohn*](https://en.wikipedia.org/wiki/File:Figure8Knot4.png)
Your task is to take a knot as input and determine whether or not it can be colored. You may take a knot in any reasonable format (some examples listed below) and you may output two distinct consistent values one indicating that it can be colored one that it cannot.
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 input formats
Some nice ways of taking knots as input:
* [Dowker Notation](https://en.wikipedia.org/wiki/Dowker_notation), A list of pairs of positive integers
* [Gauss Code](https://en.wikipedia.org/wiki/Knot_theory#Gauss_code), A list of positive integers
[Answer]
# [Haskell](https://www.haskell.org/), ~~249~~ 246 bytes
```
(i#x)a=[head$[x|j==i]++[s]|(j,s)<-zip[0..]a]
(s%i)[]=i<2&&elem 2(concat s)
(s%i)((l,a):b)|l,[]<-s!!a=or[(a#[i,x]$s)%x$b|x<-[1..3]]|[]<-s!!a=(a#[i]$s)%i$b|[x]<-s!!a,x==i=s%i$b|[x]<-s!!a=s%(6-i-x)$b|u<-s!!a=mod(sum$i:u)3<1&&(s%i)b
f x=(x>>[[]])%1$x
```
[Try it online!](https://tio.run/##hY7RasIwFIbvfYqIbUkwKWsrY0jjpU/grsK5iBrn0bSVpoUw@u5dp2XqGOzunO//@fmO2p2NtX1PceaZlupo9D5QvjtJiTCfKwcdPXHHcvGJF/USx6BhQl2ITIHEPI0iY01BUrqryp1uiGO3lFLLNVtuWWe5gly46VTLqlZUzxRyD4FjoQ@2nc@FSuI4A@h@atfOtYFDQ/mRcz84SfcMh5@@ChSeDbQdWVHtqWuLAJcty/Ikiq5K28mBeEn9aqUUAAuTwPeFxlLuqwkhQpBNbQ4V2uG51Fg2wUHRtbbOcJIwTuimbocz/T5HnN1x8oDTO84Y3Lbfy3NZNQ/TI1/jR1sb8kZ@xf/N3vHib7cH5cWTMvRf "Haskell – Try It Online")
Takes input as a Gauss Code, (`[(Bool, Int)]`) where `False` represents crossing over and `True` represents under
## Explanation
This algorithm works by stepping though each intersection and trying to resolve the colors of that intersection. It keeps track of what color the strand is and branches if multiple colors are possible at a given point.
The function that we build to do this is called `r`. It takes, 3 arguments:
* The Gauss Code of the knot we are working on (which it will consume in order)
* A list of "intersections" and what colors we have already filled in
* The color of the strand where we are currently processing.
Our intersections are represented as a list of colors (`Int`), which we know to be at that intersection. There are three possible states for this:
* It is empty, meaning we have not visited this intersection yet.
* It has one element, meaning we visited the intersection going *over*.
* It has two elements (possibly equal), meaning we visited the intersection going *under*.
We can't have 3 elements because when we visit an intersection the second time we don't have to add the third element since we are never coming back. Since we don't have to and this is code-golf, we don't.
At each step of the way we can use a very simple case analysis to determine how to branch. Here is a diagram showing each case and the possible outputs (no possible outputs is a contradiction and return `False` if we reach it). Incoming color and location are indicated with the small arrow.
[](https://i.stack.imgur.com/CfkdP.png)
Here are some sample paths of execution on the granny knot and the figure 8 knot as shown in the question. I skip over steps where we went over a unvisited intersection, since they are quite trivial and the diagrams are quite large even without them.
[](https://i.stack.imgur.com/2BLNb.png)
Since Haskell is lazy we only ever evaluate two of these paths, the left-most path, and when that fails because the result doesn't have two colors we evaluate the second left-most. Since that one passes we exit without further evaluation.
[](https://i.stack.imgur.com/Co38i.png)
Here the only branch that does not encounter an error colors everything the same way.
Here is my code ungolfed a bit and commented. I will expand this a little bit shortly.
```
-- Update an element of a list
q i x a=[head$[x|j==i]++[s]|(j,s)<-zip[0..]a]
-- Perform the algorithm
-- Iterates through the intersections in order
-- It records colors at each intersection and searches for a contradiction
r[]s i=i<2&&elem 2(concat s)
r((l,a):b)s i
-- If we reach a new intersection passing under
-- Branch on the three possible colors
-- label the intersection with the incoming and outgoing colors
|l,[]<-s!!a=or[r b(q a[i,x]s)x|x<-[1..3]]
-- If we reach a new intersection passing over
-- label the intersection with the incoming color
|[]<-s!!a=r b(q a[i]s)i
-- If we reach an intersection going under where the over strand is the same color as the incoming
-- The outgoing strand is the same color
|[x]<-s!!a,x==i=r b s i
-- If we reach an intersection going under where the over strand is different from the incoming
-- The outgoing strand is the third color
|[x]<-s!!a=r b s(6-i-x)
-- If we reach an intersection going under
-- Check that the three strands have either all the same or all different colors
-- Since we use 1,2 and 3 for the colors this is the same as checking if their sum is divisible by 3
|u<-s!!a=mod(sum$i:u)3<1&&r b s i
f x=r x(x>>[[]])1
```
] |
[Question]
[
Sorting makes no sense for a 2-dimensional array... or does it?
Your task is to take an input grid and apply a bubble-sort-like algorithm to it until all values in the grid are non-decreasing from left to right and top to bottom along every row and column.
The algorithm works as follows:
* Each pass goes row by row, top to bottom, comparing/swapping each cell with its right and below neighbors.
+ if the cell is greater than only one of its right and below neighbors, swap with the one that it is greater than
+ if the cell is greater than both its right and below neighbors, swap with the smaller neighbor
+ if the cell is greater than both its right and below neighbors, which are the same value, then swap with the below neighbor.
+ if the cell is not greater than either of its right and below neighbors, do nothing
* Continue this until no swaps are made throughout the entire pass. This will be when every row and column are in order, left to right and top to bottom.
## Example
```
4 2 1
3 3 5
7 2 1
```
The first row of the pass will swap the 4 and the 2, then the 4 with the 1.
```
2 1 4
3 3 5
7 2 1
```
When we get the the middle 3, it will be swapped with the 2 below
```
2 1 4
3 2 5
7 3 1
```
Then the 5 gets swapped with the 1 below
```
2 1 4
3 2 1
7 3 5
```
The last row of the first pass moves the 7 all the way to the right
```
2 1 4
3 2 1
3 5 7
```
Then we go back to the top row again
```
1 2 1
3 2 4
3 5 7
```
And continue row by row...
```
1 2 1
2 3 4
3 5 7
```
... until the grid is "sorted"
```
1 1 2
2 3 4
3 5 7
```
## Another Example
```
3 1 1
1 1 1
1 8 9
```
becomes
```
1 1 1
1 1 1
3 8 9
```
rather than
```
1 1 1
1 1 3
1 8 9
```
because the downward swap takes priority when both the right and below neighbors of a cell are equal.
A step-by-step reference implementation [can be found here](https://tio.run/##hVRNb9swDD1bv4LIpfZiFPlYh6Wod9xx2GG3wCgkW4mFyZIhK3CLor89IyU3dpYBQ2BHfCSfHkXK3atvrNmez6yWB2jUsdH4@LT3TpljDpU1tfLKmuKXO8nskSVO@pMzcFjs32LQe7kAdZgiQepeoh8@/LBggb1Dyz8fnapTeuXQ2b74YU2gPVgHLgdnB1BIYU6tdNzLEEn@JGSnn/aTRkxpuU8rqXUOd7C9y3JIXV5lUBTEnQGRVlgERlyz4jZZmUVZ4iSElpv6stUABWhpgr1fYVjSzBA0lbGulg5BUs8SYukH3qU8BxHEGmu0rTjtGkIRmpK@czwgRDjWyysEOBoCDUGGQMO3Ha7C/tyVe16VCM7ND69AU0ze0UQvMjAUiqsVFtQoLYEa@HglhBACYFnA@nLEh8VP3vfwpt4XWGtsDJ2e4@Yo0ybUF9BqQoeIJq1EWqykCtZNw1uZTY40rkNzxnJQfigmSRx1eA4v12WYsuUanmCIM7Z73u1unpAupLbDJR1zkZfSXUhv/pfu/FjGch3pSCHmfhRGQkj2Nwg6Y@0zNGw/ogTHap6u8SSMTCtx6H02YqTr1i/06J@7b7Kl/reAv2gwaJyA4BdO8t@XW03nxZhqO4tH0L/2bNbCyz3Zs2RP/XuJF@yFxkArI@/7TitsaxlvM0HkQpr73te4wq1jHH4XOmx/mWXsfN7CZ3iADU7gA3yBr7CFDdvB@GMrfIeHjf@w@wM).
## Test cases
```
5 3 2 6 7 3 1 0
3 2 1 9 9 8 3 0
3 2 2 8 9 8 7 6
```
becomes
```
0 0 1 1 2 2 3 6
2 2 3 3 6 7 8 8
3 3 5 7 8 9 9 9
```
---
```
2 1 2 7 8 2 1 0
2 2 2 2 3 2 1 0
1 2 3 4 5 4 3 2
9 8 7 6 5 4 3 6
6 5 4 3 2 2 1 0
```
becomes
```
0 0 0 1 1 1 2 2
1 1 2 2 2 2 2 2
2 2 2 2 3 3 3 3
3 4 4 4 4 5 6 6
5 5 6 7 7 8 8 9
```
## Rules
* You can take the input grid in any convenient format
* You may assume the grid values are all non-negative integers in the unsigned 16-bit range (0-65535).
* You may assume the grid is a perfect rectangle and not a jagged array. The grid will be at least 2x2.
* If you use another algorithm of sorting, you must supply a proof that it will *always* produce the same resulting order as this particular brand of 2D bubble sorting, no matter what the input is. I expect this to be a non-trivial proof, so you're probably better off using the described algorithm.
Happy Golfing!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 129 bytes
```
a=>[...a+''].map(t=>a.map((l,y)=>l.map((v,x)=>(L=a[y+1]||[],d=L[X=x],r=l[x+1],v>r?r>=d||(L=l,X++):v>d||(L=l),l[x]=L[X],L[X]=v))))
```
[Try it online!](https://tio.run/##rVFba4MwFH7Przj0xQRtqHa9E/e0h0FhrwUrNLR2s8QLNpWWud/uTjRljO5xhsTvds7BeJK1PO@rtNTDvDgk7VG0UoQR51y6jhPzTJZUi1B2gCrvxkSoelJ7VyR0LWR0c/24aaLYO4h1tBHX2KuEiq6oenVYPVehODQNJpW3cV22rENLmYep2NTEnjlEzfBpNQjYkScIwCdjGMOEzDqMxMeXb885LAiZoB/AFGZgzBExzIcFrjkqPQ9MFPcMpoQYO0A474IjEkC/xpb7HX6CCW7UiC20fEruKLD5HdFcV2lGGT@XKtXU2ebb3GH8WFQvcv9BMxAhfBKAFD8r@wlhxNyjMra6y2DV2qguXscKC/dFfi5UwlXxTgeveXnRy8GDkfbdzO85FWnetWIWmmEPBZ1wpOnjiLeL/s8Zv3oPB7xKykRqGoz@zH@xVfsN "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 75 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Thanks to @Adám for saving 11 bytes.
```
{m⊣{d r←⍵∘(s⌊+)¨↓∘.=⍨⍳2⋄∨/c>a c b←m[r⍵d]:m⊢←⌽@⍵(d r⊃⍨1+b>a)⊢m⋄⍬}¨⍳s←⍴m←⍵}⍣≡
```
[Try it online!](https://tio.run/##PY29SgNBFIX7PMUtEzJqZvY3gkGwMZVg7MRikyU2WZSkkpBKWeKaCYoItppmC8FCLW32Ue6LrGdmNzLs7D33nO9MdD3ZiW@iydVlWc4TzjbzmKacPrL@4eVrc8arrN0qck6fIXcPWOesvxQ/3PEy3xv1IhrREPHkfAoivthHxbvBV7@HWDRNWXYLSraHvagFMzGs/lgUpmhmX/pOqgcXrDd8/1aOrVzz@qV/Arr4dDh9ghqcHuE@O@4PyjE55IB0SZEUmMkTgZkb6G5sXYckXFnfIXX/3RCuh78inwIyuY4wSlIXJ8Sm0spQ@ALya9azrEkqbEPLdISi6ji1lnZ2kXbNTtQdtfbFdlJV/g8 "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 183 bytes
```
(R=#;{a,b}=Dimensions@R;e=1;g:=If[Subtract@@#>0,e++;Reverse@#,#]&;While[e>0,e=0;Do[If[j<b,c=R[[i,j;;j+1]];R[[i,j;;j+1]]=g@c]If[i<a,c=R[[i;;i+1,j]];R[[i;;i+1,j]]=g@c],{i,a},{j,b}]];R)&
```
[Try it online!](https://tio.run/##1Y6xboMwEIZ3nsISUtSKG7Db0jSOKw9ZulV06GB5MMgkRoVI4HaxeHZqTCjJI1SyrLv/@/@7a5Q96UZZU6pxvMtZTJ2CYmAH0@i2N@e25znVDNPjjr1V4uO7sJ0qLefxawo6SWiuf3TXax5DLDf082S@tNATYyk9nIXP1PsCSpYLYaCmtE6wlPSmY0deSm80e3UxUmoSDPXF@NcFIzgDagBX@zMnw/1mrHbsn54eRRYjhpzDgB4AEUAZoOdQeyUdALlZ9t1LeNsArwgJ2kx8MhsGGlkShs45EvTtMiZEyRIly96F4EV7BPQU/olPZF1xRbKJXAtkneYPid4701pRcYvlWhMZjb8 "Wolfram Language (Mathematica) – Try It Online")
I'm not a Mathematica expert, I'm sure it can be done shorter. Particularly I think that the double if statement could be shortened using `Transpose` but I don't know how.
[Answer]
# [R](https://www.r-project.org/), ~~169~~ ~~165~~ ~~144~~ 132 bytes
```
function(m,n=t(m)){while(any(F-(F=n)))for(i in 1:sum(1|n)){j=(j=i+c(0,r<-nrow(n),!!i%%r))[order(n[j])[1]];n[c(i,j)]=n[c(j,i)]};t(n)}
```
[Try it online!](https://tio.run/##jU5db8IwDHzPrzBISI4WUJPSD8by2j9R9aGDVqRaUykEwcT47Z1Tuuchy9bdyXe2G1s9thd78Gaw2AurPfac368n89Vgbb@xWGOhLee8HRwaMBbk@/nSo/wh8d5p7LR5O2Ak3MfauuGKlovFwqxWjvNycMfGoS27ipeyqva2PKARHa90QJ0wvHrsPVkeY4v1edPX3pkbuqY@bnz9SS@cdCF8c/N6ybagQLIYYkhYNuElvcX@N8YgaVnOM4fdq8aEbilIIYMQEbHAJOyoclKeXIVA6gzSV2NDiCJDPsVFTMGz4pnLCW8hoSaNzfEzT9kfUvN@ODv@Ag "R – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 240 bytes
```
import StdEnv
$l=limit(iterate?l)
?[]=[]
?l#[a:b]= @l
=[a: ?b]
@[[a,b:c]:t]#(t,[u:v])=case t of[[p:q]:t]=([q:t],if(a>p&&b>=p)[b,p,a]if(a>b)[a,b,p][b,a,p]);_=(t,sortBy(>)[a,b])
=[v%(i,i)++j\\i<-[0..]&j<- @[[u:c]:t]]
@l=sort(take 2l)++drop 2l
```
[Try it online!](https://tio.run/##hVDRbtMwFH2ev@KqHZWjuVVX2AZhbgeCh0iTilTeXAs5qVM87CRL3G6V@HbCdZI@8YAsx@fec3zOdTKrVdG6cnewGpwyRWtcVdYeNn73tTiSS8utccZT43WtvF7ZiKyE5EKSlR0LFaeSw4MlHCGsUkkehFAsjTMZezmmnolDfJQRz1SjwUOZC1HFz4HkVDzjwUxO1bKaTNIlryKRsoop2fXSKDixSmJT4RF9/MHRsMHpPp/osmNlhMnHN9QwE11dPW235n4q5rOZnDzdTwFnOfST4FyWh5vUq18aFhbVu7qsELUkr0sHm1PjtZslaxh@QBxDsmaw1/7RFJqBPiqbrHvxd/3qz7rMqqbpOrSprPERA1M0XhWZ7nUbX5tiTwjZeIX6F3IxBmrRs2HwEgEPEZ@sDSlNzzqFV16REcKXSYFRsN3iB5/URcAIV3CQoR9AoDpLSS44XA4OhPxj3QUPuf2Lzi8M/O/ejHMYjVBAhQzS/w0chIGO@wmCqF3ANSzgDt5DQHOygH69HerrDr@DG9zYIx9QeQe3Q31LzmjR6/9kuVX7pp0mj@2XU6Gcyfrim1U@L2vXTn@2N/O5@ws)
Implements the algorithm exactly as described.
Link includes input parsing to take the format in the question.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~215~~ 208 bytes
```
m=input()
h=len(m);w=len(m[0])
while 1:
M=eval(`m`)
for k in range(h*w):i,j=k/w,k%w;v,b,a=min([(M[x][y],y,x)for x,y in(i,j),(i+(i<h-1),j),(i,j+(j<w-1))]);M[i][j],M[a][b]=M[a][b],M[i][j]
M!=m or exit(M);m=M
```
[Try it online!](https://tio.run/##LU7RasMwDHzPV2gPA2lV2dJtDJr6E/wFQtAUvNlJ7JaS1snXZy4NHOjuuDt0mUd/TrtliSaky21EqrwZXMJITX4S@VCqsg@Dg3pfgTXu3g54jEeq4Pd8hR5Cgmub/hz6t0z7wJ3p3zP3r7m584lbE0NCQSuTyqw880SP3sRzaWKJE2PYYDj4bU1Pxd0Gu0MumpQaK0GlU7bSqpzUrJdXv/z0YiKUSTeFES010dhlEfli2DHUyiCfDAXfD/qzuvoP "Python 2 – Try It Online")
-7 bytes, thanks to ovs
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 310 bytes
Without LINQ. Uses using System.Collections.Generic only for formatting the output after the function is returned. Thing is stupid huge. Looking forward to the golfs!
```
a=>{int x=a.GetLength(0),y=a.GetLength(1);bool u,o;int j=0,k,l,t,z;for(;j<x*y;j++)for(k=0;k<x;k++)for(l=0;l<y;){o=l>y-2?0>1:a[k,l+1]<a[k,l];u=k>x-2?0>1:a[k+1,l]<a[k,l];z=t=a[k,l];if((u&!o)|((u&o)&&(a[k,l+1]>=a[k+1,l]))){t=a[k+1,l];a[k+1,l]=z;}else if((!u&o)|(u&o)){t=a[k,l+1];a[k,l+1]=z;}a[k,l++]=t;}return a;}
```
[Try it online!](https://tio.run/##lZRRT9swEMefm09x8MCS1S1NgBZwnGlD2vYA0qQ97AGqKaSmhKZ26zisJeSzd2enATIB0tJWvr/vd2fn7tQk7yVS8U2Rp2IKP9e55vP@mcwynuhUirz/jQuu0oQ6LwnqJFmc5/BDyamK56UDsCiuszSBXMcal3uZTuAiToXrGSfA10IkYSr0JRmTeolgwjYxi0qUsGIxnqTPuZjqW3fgkXVrw/fotZQZFERSg9@xAZmRjGjyQG@kculduPq4pnfdrmfkjA3oLFzR2VZnqLNwTb1Ssixa94JPg8g/jS8xRdcfh9YY04LNotWzr@vjZuN7YJptzfTGdYu9Hek9mlV6e3tukyliTZzneaV@UrQx2AOteJZzMEl2TPSjzbGFbRLaGAau7e6YaVoprgslIKbVhjrO/n6vB/CdZwuuYKFMVW6wxqZp0INYqXgNaQ51EJ9AKiDVH3LIpdIosSzzvvPZ8mHTEJvmggODBbAInNIU7z5WsMQCLsNFq0V0idV9IhQSqkVgzxQSZzhEMuP9XyrV3F1cLokad3dh16Ntz@6VwL2qwlc7T3P9dKffGSq8keB/4KWjdMxOLeyENU/ZUnYHjggcEAgIDAmMrO0TGEBFXmFrEP0n9nts8XfZwFI1i9mHULVQjPyPqwbEJwEZkWNirDfODUj9OXgP8i1wSI7wh@BrzAkeMyLDLTJ8DWmcQX3Ue6/WMW/U6ZSHdQXRieLA1u@oFqOtx6CVY3rt4ADxOLl16xwwNYNqe45/HJ3tQLpTjzqd1rycp8LOzBeeyDnPT6@EnZ/nkAkGvRl1JXr/PE083qpyNn8B "C# (.NET Core) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 198 bytes
```
G=input()
O=e=enumerate
while O!=G:
O=eval(`G`)
for i,k in e(G):
for j,l in e(k):v,x,y=min((G[i+x/2][j+x%2],x&1,x/2)for x in(0,1,2)if i+x/2<len(G)and j+x%2<len(k));G[i][j],G[i+y][j+x]=v,l
print G
```
[Try it online!](https://tio.run/##LYxBCsIwEEXX5hTjQklwQBsVoZp1lh4gBCwYadqYltLW9PQxrcIs5r@Z/9qpLxvPY5TC@nboKSN3YYTxw9t0RW/Ip7TOwH0tZE4gncbC0Yd8MAKvpgOLNVgPhkqWk9VMKnQ/UrN8xICTeFtPqVR2F/Zcq2oXNlxj2GaYMpsrIRXoATPkzL5g@bs545Oz8E9YCkuuGbsmT3JonH3TYtNiREfazvoeZIxKnRA4QqYR1BEhzXleL3@qvw "Python 2 – Try It Online")
Developed independently from TFeld's answer, has some differences.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 118 bytes
```
≔I9.e999η≧⁻ηηFθ⊞ιη⊞θ⟦η⟧FΣEθLι«FLθ«≔§θκιFLι«≔§ιλζ≔§ι⊕λε≔§§θ⊕κλδ¿››ζδ›δε«§≔§θ⊕κλζ§≔ιλδ»¿›ζε«§≔ι⊕λζ§≔ιλε»»»»¿⊟θ¿Eθ⊟ιEθ⪫ι
```
[Try it online!](https://tio.run/##jVHRToMwFH0eX3HDU0mqcVOnZE@LD2bGJYs@Eh7I6EYzVjYoxszw7XhvKcgmMRIo7Tn3nHPbrpMoX2dRWtfzopBbxZ6iQjPXvxa@77seh8SbOcvo0LBvcptotpSqLJBpyE2WAzt6sCqLhMkGM/MjhyAJ24r3cs/Qh9BXobYaaz184MsZGd6CxwYa2W7meqFi8UmqHTYj0W10Vi9t/aUAG0lRcDKCAXKh1rnYC6VFzFIPK8VgZS@/r9iRgvzjRiU3wJ5zEWmRd/8TsRzaZUwRbbM25l8p3SYuRNJwtoEKRFoI6PdxMoGDeb/2/3eGPZrKMV/lVA7lrLKDuS2a24sliG4VVrlUukVfMqnIyQUXuVldB4ETTDiMOeD4wOHRTHB5E3LDdO/tGTNusTsO92YknhjfmKDVtMdMiekDkx@3MKyvPtJv "Charcoal – Try It Online") Link is to verbose version of code. I've also spent a few bytes on some prettier formatting. Explanation:
```
≔I9.e999η≧⁻ηηFθ⊞ιη⊞θ⟦η⟧
```
JavaScript has the convenient property that `a[i]>a[i+1]` is false if `i` is the last element of the array. To emulate that in Charcoal, I calculate a `nan` by casting `9.e999` to float and then subtracting it from itself. (Charcoal doesn't support exponential float constants.) I then pad the original array on the right with the `nan` and also add an additional row containing just the `nan`. (Charcoal's cyclic indexing means that I only need one element in that row.)
```
FΣEθLι«
```
Loop for each element in the array. This should be more than enough loops to get the job done, as I'm including all the extra `nan`s too.
```
FLθ«≔§θκι
```
Loop over each row index and get the row at that index. (Charcoal can do both with an expression but not with a command.) This includes the dummy row but that's not a problem because all of the comparisons will fail.
```
FLι«≔§ιλζ
```
Loop over each column index and get the value at that index. Again, this will loop over the dummy values but the comparisons will just fail again.
```
≔§ι⊕λε≔§§θ⊕κλδ
```
Also get the values to the right and below.
```
¿››ζδ›δε«§≔§θ⊕κλζ§≔ιλδ»
```
If the cell is greater than the value below and it's not true that the value below is greater than the value to the right then swap the cell with the value below.
```
¿›ζε«§≔ι⊕λζ§≔ιλε»»»»
```
Otherwise if the cell is greater than the value to the right then swap them.
```
¿⊟θ¿Eθ⊟ιEθ⪫ι
```
Remove the `nan` values and format the array for implicit output.
[Answer]
# [Kotlin](https://kotlinlang.org), 325 bytes
```
{m:Array<Array<Int>>->val v={r:Int,c:Int->if(r<m.size&&c<m[r].size)m[r][c]
else 65536}
do{var s=0>1
for(r in m.indices)for(c in m[r].indices)when{v(r,c)>v(r+1,c)&&v(r+1,c)<=v(r,c+1)->m[r][c]=m[r+1][c].also{m[r+1][c]=m[r][c]
s=0<1}
v(r,c)>v(r,c+1)&&v(r,c+1)<v(r+1,c)->m[r][c]=m[r][c+1].also{m[r][c+1]=m[r][c]
s=0<1}}}while(s)}
```
[Try it online!](https://tio.run/##tVptbxs3Ev6uX0Ebd66Eyoolx45j2C6Spi8G2gtwOaA4BPmw0lLSXnaXKrlrWXX923PPzJC7XFlKU/QuTuIVOTMcDuflGa4@mirPyk/PnqnbclVX7lKVplpm5UJVRq2smWnnlL5PilWuncozV@lUTXVu1j3wGKuqtaFfhbEa0yWIdDJbqpkpqyQrWdBSK5cUmhjKuphqq8xcZWWlF9o61ScJBUiLuhhgmOltUi40yIjnhFQ5Pzs7PRv16PO3ViekxZxWX2YOa6VaLUw@v6TpZVWt3OWzZzRKgyNXJbOP@n62JJmjmSme/VprV2WmdM/GFyfj8Utimxy/yQpdOgwnuXpdT6e5Vu@MrXhNeqC9FMlH7LA0yoFUswoJWNOWlagTa5PNaDQiw6QGDFn1DYv5t6mhc@I@KqiNXVUQp5ISu4bt1cJmKT7h32qVb1RCHFNW5Nhh/eM8I@p8YWxWLQvizypVl1WWYzRXd0mOfRGTN6LIw7mUpjxO9Qx2c7SJuTWFyvW8IhE2WywrVhoLV2ZFY1NTVSBJcgNqfaftRlmzZoqZyeuilIP41zJWZ23sR6cSB6PkcA93yTRKfUfusErgRgsyBQmasrxhd7mhkON8VomFms/cGnYgfcWhNLa4xkrYtGu1VqwVO6QqNUanxrqRzCh1rLI5m4K5YfMF@w75DaxuSljZlJrdsXKBSYn0XYKHipQSNUgsmFsuyKzoRLaW@TJdYIMnO1O7d7ethCtw@tq2PIHy/7DyepnhLMin4qiWP@x/Q5ootzTsitl/Okg9Xd00JHC6aFdpNN2tYGpCAhOWb5GHsrLWkikkWCh8oZ/jfRRJSpPW1Iulqf3@SSkNWsyT547g6uBeZ1BzqmEE7LATFsF1KTZYKiLQ2FTbYTfOoiATFnF9CafvJMvy83M1UWN6OMXPGT284JEQdvPMuopXN2JCDjBWkE1PQ8@DZvRh4g9GJpqTGcvSEK2e71nuF2JbI5voilnoX5GlKdLj6ZD8PZiF41Xzio38ia8VW4tMwiKn7Z5EtzNaxwVZkaL7BI2DoLPGOHnStY0Yiy1UmDvkIBp8QTkzWGedbDgdU@XhKNi9DBZRL1p9ySjIXqgugZmOll1igdrHhOOWdxKkBSGvOJ96/2zzIgpHl3UCni1WKi7izE2ih4MeUpnQ6aFnh4A97K8oRhBYscudEkdg9A8X6iXPTTXSMmrL1vQ4bC3Q2YTFctp7Qnv6RGZSO/Gn1KzLdWJT77xcZFc2o8qy4XBjBuN9YW/404EnnE2kCiOIf62TXMz5SgG7rI6nm2P6rayea6vLGWKVTID6XSWECdSMciKntbmpsQY2pH29A2rAtPOGOOMzPRcvVieNp6iX@LnAczM0oU3j3wt1/sScJ/jho@JzOpcDm3AgkugLddHEJX8k4S8b/5zw2CSsP/E/p@3QWM4f3M9pmIa8Kn6IlwwfJp5xl5aiJ2va@Ff7012ef0Tx5/7nDIuci93OeGu8Ob@Xf9a5Xwl/gJL4FBgd0YFH8AiJNSk3FDZ3usxwaJ4HSKxIqlhCgZhGyNeFbmNEIBJ7ho9@KpdAR6Ve4PTvdAtLPYaqAesWJTLR@Px4moXVBJ72T44Zlg5Gf7QuYjNRK23neobMhP/An4fSSY5MlS9R/0kWC516@MipjLlDgk3C8rmmDDe5nzQL387VBmtTPCU@tltkhqhwgl@HROVZihoyXC1Qk6A@Z0uBMLxikiMtBlSE@bSetWUfu3B1zpiYCx0BPyqxgTzBerM6T6yaWtoghE/eeDTbalOaoExSUdFf0/rtiWeovLfoPlZkNi7ghBYbu/HJVTa7y4DYeQOARoa2@BUVbmumyRSbm2qS7ZnMfA4rhbYk1W5msynZPFhLTPojys9G/YD2AaQHPPSzrpaGqjcUqjTVcQj4KaOUkFNpwQR7pa3IiYxAajlLQQxRSxS8bNSb1yULubotq5tRZV4RfX@grntKyTPte@Sy3/RAPbAR3mfVB/W4X6ef6wr71jtVk@4An/eqxqMu7tBEyUjqFSvGGv95lb@vyxnn2ai/9P7A2jfOj9MWdyIceL@CE@GYsAdqs0Jlz5NimiaCEpCsKIkL@P@HqfRl1B1KcwLGbpBx7I3vuUThpDXcTWICCjluqprE4FNHvYq6UbKL30MfHmyz@0uxQGwh2KAHy2xt3eqqtpJihFNpKUJDAsXcRQgT1s3SIXWSCKZFAMZFck/9Mqlo1nQuot9IeLzxPmc5NOrUQ4sBPRuSiDQDYLinbp/OhpcDR2a9yehcGUxuhIuSKSsp4JaQs@zEV1K/VZ3SKmQx1rQPoHOpbmm/Apv5gziRIhMQgbryxmFnUkdHAWJf9Xw34Offg/iDeFzvyfh7YfrAMzp32pPQIZ77o/llmcGGa0K2hC2WyR1lqUI3VyEETIbkI7xNYWKwklW0L7QdfMo8/kbPE@RGYguXKQHP9k9uxsifBEIBjTeVdoEJwNSqeQL1RgP1PY6bu15uk0OYyFLUaNlG4DXK8g0wlq@BYrasDHaDvhl4Bz2/Z/LCIFvMAvsvtSBYpzVZfk3eoSmrtEzRVpuV/Fk0i8khNCuGE@IE89BrPnt7M96HjwZn2W5L4UhdFmrUBe8FP2tHMnHWLoP0@FYwYEDoxBMj/WGXxzdP3Oy1PX60Lg50S6910/m0HjPyCUj62y69NxDHDRpOCkiGE8PQZCVden9lFhkHPLXtpgCJrojr5Cr4WcJ@Jv5VWeQIf2/jTJejkFoiN1wEJBhMV7pAMkzspnWHYCqKETYQDJnRpRkHtuD2J9RIKLO6SfI@b8tNEV0obrrUkjICdaNDvMcmi4QEMkAcNINfj9vho6OIrcMaU11dRyK3GITm6/FAHd90pnZkGZ/BdlN9PW7oRnQCiIsvIv6s0G6Ci//ESeIKcP3xr0eh9F4UEyEK25H9UdiJo@FWlG3T661FKOSiKNvyQlB1Qo4vQ6y@y0zNF0p6Sx82u1ywSmf3pS41jNxgv0vFVFcdT9vpU3/ZowIVnOWPPSoi/p95VJh55FxIrTo9r7me9j35oMezvo49gYFp5lY53cA0YEiglR//Emj1g7@cYowE3CupKIsB1khuorG9XpRjqKp@5QKf5EYPyAKBxABxoAZw@l0mLl6NucphdEkm9EEZvm9nRrrd8X4KYkYZdIu/KI31PIzNagDPlXEum@ZZlVEOr6Rk080FeSy21@T/67A/DLzeAHCjTOOxPzg4UI8HB@F5y1Dtixg5aoft/lpnlut@sLywxMWG4pWKVmXq2TLkZy9rqufNNgQqkJrrLEUhDd7mwUDrciL2ij6MTxAMarJzcnzCk6e7JjHHk893TNIcT541k4QAY5fG5Hlv24d7XajkQVXrTMPGaWWnT6HXIAKEW5CreclF6SKg/fKrqsm23I1YVw0bLEatiEfuYlBEOtXorAoMW3Ek7YB6S1cB68wJYhepgcMrQy@oaHFZh@4WUkasq2RGGDjyhcZBJbqCLwRYyDboc/PQJlBslZyeaG9ppj8IyJAwPhMjyZ60cBHwoaz6h3//2wNv9DE9HMndjsebDX@E5J9wHY938TXHgU7XLfkqgKMYjZ9/mchnIrthiXnZH/S8X4DCu8Ubb2dqr4pVtREJyVyqZpvDYiEsIpiSW3f029QONVmQmmC5cnLaIiX5LAS9EIB8UR2uH6ky@q68gJQ@0owL2fFdRe/Oosz4k4dau1YKifGd9mH7pFtMpsCNbBxM5ViM70hDbK84rumWb3Im3cynh@LySZo@viHiu@sHe0kN34z@P77J5n17VXDTdnQ0uyreW9/B0dP72YceByo3aY@91Dxw13ON/qkHdfqWI63pNmhoxkMkJoxSKD/c9e1wNrjBLxTh2eDoKDxdXfMUKvXxjV/zGr8ZdkkxfWg@XgeloMHV@LHXCmUBLJSfroL0jkz8DgX6ofm4JfPxkYtm3w0eP0kXT@@XfDQ@9QucEycPV8@oqM7rfChn0XaLQ2Xi8Jd3VTjImV6FU6ywxo7GlaPCcQcrHk44jPi5D/fYHgy/aWtGvnmmpTR3NfI1AL7kSFJ@JefMKLA01W@K2Y@hA5I7P7TXGbBebsxqGLAEM6Xw@ND75qLadXwj1T@hmya5fOLHE8TsY9ssk9aALD0pQQxNqBUatH0p3UFDW383cl/xJkbqdawk6YXYazm0XGzOSSCFSJMMAqokbeUq85qN8RPm@gP1zaXsvpMJQTXKdbmgankdZ0QhbVf92X9pQK5jGuP5e2tTNklt1PK8WwFJ0JykdbkCZEMO4VCrcNotQ7jKJHgiomEyciF@IR9cqGMN/pYBWsHKSdJim8nNkDS4A391srVE8DS5@YssJxu8FguOHG2hf6gOByPS@KEL3H1NuqZqVBkkmP4gIiALN5DwZDSSa/veEwQfjXTKi7zepwC4zXO9SPJXdlFTw/RdsET/CVQ@fJ2k4R5bLHhwOFCP7YVpdKS3iGMNe6Ryz0eFJHzhguEpO7Av1C0XMsFs2W14pIqFOAz3dy0LfdfGA759KSHYi9c8IKB/dOTPJgzx799/j7YczV@pSWvZP2O0yGBeRRgsMtI7uXDI@DskwSj8dZk0DbXb3@20TORcYVc@DbS6@nGmgZA@z4jyHgpm9HK0PaTWtvTCJv7qE9aOLNprbj06hiWz8mLbhvpyM0VGoiUbC4W80KRuulYCQQj1LdgaeKhIMBygB7JljCHrVcpftJJXPW3@9RXoWgzX@nMMmw7562SXhzLa7eQ8ZfdT4HtbV59hlBL3NnLZIX9jiKAJ6x@qn7zd4XLmRltovgFSMYpvKqsYpO3Gwug@67RoL3rvQJiJvurVvDH2wTpb0nd1kAwD3vJfrMvK5v2FYK4Rw84ZM/W1tcZeosu0ctk/8NmvMVrjFM6/3ApbP/B2ZGzuzw1r0cG9nYu/43evE8YYeD6kL4yMB8Nm5HRI3/Y4G3SvMcLsC08fTYepSMC4K3IcRnaKxNTFUL38nMgz1gkLnw/VC34G08keeUIJgpf894LpP088ERX4f8g//5wuInvChBdhqX3iJ0H8JOzgM8TjQIZDOeP/iWUPcatsRHy@hzimmbRq4E9TXXeH8@6A3g7pvUG9m71psvwjoKl0TdTjfPov "Kotlin – Try It Online")
] |
[Question]
[
*(no, not [those ones](https://oeis.org/A000217))*
## The Challenge
You'll be given two inputs. The first is a positive integer `n > 0`, which is used to output an `n x n` right triangle of the numbers `1, 2, 3, ... n`. This triangle starts in a corner and increases horizontally and vertically by one and diagonally by two. See examples below for clarification. Keep one space between columns and keep all numbers right-aligned in their particular columns. (This is [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") after all).
The second input, `x`, is one of four distinct single ASCII characters of your choice that determines the triangle's starting corner (and hence orientation). For example, you could use `1,2,3,4` or `a,b,c,d` or `#,*,!,)`, etc. Please specify in your answer how the orientation works.
For clarification in this challenge, I will use `1,2,3,4` which will correspond to `1` for the upper-left, `2` for the upper-right, and so on clockwise.
## The Examples
For example, for `n = 5`, `x = 1` output the following:
```
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
```
For input `n = 11`, `x = 1` output the following (note the extra spaces so the single digits are right-aligned):
```
1 2 3 4 5 6 7 8 9 10 11
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11
4 5 6 7 8 9 10 11
5 6 7 8 9 10 11
6 7 8 9 10 11
7 8 9 10 11
8 9 10 11
9 10 11
10 11
11
```
With input `n=6` and `x=2` output:
```
6 5 4 3 2 1
6 5 4 3 2
6 5 4 3
6 5 4
6 5
6
```
With input `n = 3` and `x = 4`, output:
```
3
2 3
1 2 3
```
With input `n = 1` and any `x`, output:
```
1
```
## The Rules
* Leading/trailing newlines or other whitespace are optional, provided that the numbers line up appropriately. (For example, trailing whitespace to make a square output is acceptable).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, saved as an image, returned as a list of strings, etc. [Any convenient and allowed format](https://codegolf.meta.stackexchange.com/q/2447/42963).
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
Rṫ`z⁶ṚH}¡U⁹¡G
```
[Try it online!](https://tio.run/##ASUA2v9qZWxsef//UuG5q2B64oG24bmaSH3CoVXigbnCoUf///8xMf8w "Jelly – Try It Online")
Left argument: `n`
Right argument: `x` (`0` = top-left, `1` = top-right, `2` = bottom-left, `3` = bottom-right)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 29 bytes
```
{' '@(=∘0)⌽∘⍉⍣⍺⊢↑⌽(⍳+⍵-⊢)¨⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqdQV1Bw3bRx0zDDQf9ewF0o96Ox/1Ln7Uu@tR16JHbROBghqPejdrP@rdqgsU0Ty0AsgDcmr//9cw1H3UC@KaaCoANeqlKYBUmmoCAA)
**How?**
`¨⍳⍵` - for each `i` in range of `n`
`(⍳+⍵-⊢)` - produce range of `i` with vectorized addition of `n - i`
`↑⌽` - reverse and flatten
`⌽∘⍉` - rotate right
`⍣⍺⊢` - `x` times
`' '@(=∘0)` - remove zeros
[Answer]
# JavaScript 130 128 154 142 138 135 133 bytes
\*fixed padding issues
```
A=(n,x)=>(j=>{for(;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S=O,i=j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+O:O).padStart(j.length+1)})(n+=s=O="")||s
console.log(A(6,1))
console.log(A(6,2))
console.log(A(6,3))
console.log(A(6,4))
console.log(A(12,1))
console.log(A(12,2))
console.log(A(12,3))
console.log(A(12,4))
/* 154 solution
A=(n,x)=>{s=""
for(j=n;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=j;i;S=i-->n?~-x%3?S+X:X+S:~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart((j+"").length+1)
return s
}
142 solution
A=(n,x)=>{s=""
for(j=n;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=j;i;S=i-->n ^ ~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart((j+"").length+1)
return s
}
138 solution
A=(n,x)=>{s=""
for(j=n+" ";n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=+j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart(j.length)
return s
}
135 solution
A=(n,x)=>{for(j=n+=s=O="";n--;s=x<3?S+`
`+s:s+S+`
`)
for(S=O,i=j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+O:O).padStart(j.length+1)
return s
}
*/
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 18 bytes
```
:&YhiX!VZ{' 0'2:YX
```
First input is `n`. Second input is `x`, which can be:
* `0`: top left
* `1`: bottom left
* `2`: bottom right
* `3`: top right
(Or it can be any other integer, which is interpreted modulo 4).
Try it at [**MATL Online!**](http://matl.io/?code=%3A%26YhiX%21VZ%7B%27+0%272%3AYX&inputs=11%0A0&version=20.4.2)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~124~~ 120 bytes
```
n,x=input()
r=range(n)
for l in zip(*[(r+[n]+['']*i)[-n:]for i in r][::1-x%4/2*2])[::1-x/3*2]:print' %%%ds'%len(`n`)*n%l
```
[Try it online!](https://tio.run/##JcpLCsIwFEbheVeRScijLcVUOgh0JSFQwaoXwt9wjVDdfLQ4Owe@/C6PDa5WdPtMyK@iTcMzX3BfNUxz21gkQRAfytoGzW1AbINS0ZIJPXw8BB2CY/D@1O/yPDjrovnfMP7aZyYUJaSU16eSaYVesBgLmWqduvEL "Python 2 – Try It Online") or [Try all test cases](https://tio.run/##JU5BCsMgELz3FXsRV2MImrQFS18iQgpJWiFsgs0h7eetNpfZWXZ2ZtbP9lrIpDSME0xIahf2BPEeH/QckcQJpiXCDIHgG1aUDmPlyFeOcy@DcDVZXxShKKJ31up6Z11jpPHi2Jo2c7vGQBsHxtjw5mweCXvqhSQ2p/Kfg4uDw7PSQqHW/3FRJuNVtRlb1ZVD5j43PKreDleefg "Python 2 – Try It Online")
`(r+[n]+['']*i)[-n:]` will add some empty strings to the number list, and chop to the right size, `zip` with `[::1-x%4/2*2]` and `[::1-x/3*2]` will make the rotation, and `%%%ds'%len(`n`)*n` will generate a string for fomating (like `' %3s %3s %3s'...`) to be used on each numbers+empty string list
[Answer]
# Mathematica, 89 bytes
```
(R=Reverse;Grid[{#&,R/@#&,R[R/@#]&,R@#&}[[#2]]@PadRight@Array[Range[#,s]&,s=#]/. 0->""])&
```
here is another solution that works in TIO
# Mathematica, 122 bytes
```
(R=Reverse;StringRiffle[""<>ToString/@#&/@({#&,R/@#&,R[R/@#]&,R@#&}[[#2]]@PadRight@Array[#~Range~s&,s=#]/. 0->" "),"\n"])&
```
[Try it online!](https://tio.run/##JYzRCsIgGEZfRRRkA8vYRTflsDcYf92ZF1LqhGagEkS0V7eNrs4538U3mTLayZRwM9UhgWoDAuzLpmwP55JC9BCce1iF8bG/PP8Tl4Ry2XwIZbA6A7VSL7LUVynSaS0Hc4fgxyJPKZm3IjOY6O2cKcuCaL5Fu02PEW4ZvkasW1qH5bsg6dSedbr@AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
Nτ≔EτEτ◧׋⁺ιλτI⊕⁺ιλLθσFN≔⮌EσEσ§μλσEσ⪫ι
```
[Try it online!](https://tio.run/##TY7BDoIwEETvfkXDaZvUA2dOxBMGDTH@QIUFmpSC3YX497UoGjbZzBwm86buta9HbUMo3DTzdR4e6IFldsiJTOfgoidgJTapdFNiy3A3AxKUSASVnQmMElYqwfFPmhgKV3sc0DE2u0A8JUp0HffwXD1FTjt6AXu4lGJj33BBT/jZQN8NUXIuXIMvGP6Va03ljeNf8jwatyITkcRAFkKaHtJwXOwb "Charcoal – Try It Online") Note: Trailing space. Link is to verbose version of code. Second value is number of *anticlockwise* rotations so 0 is upper left, 1 lower left, 2 lower right, 3 upper right. Explanation:
```
Nτ Assign the first input as an integer
EτEτ Map in two dimensions
⊕⁺ιλ Sum of zero-indexed coordinates plus 1
I Cast to string
‹⁺ιλτ Is this the upper left triangle?
× Repeat the string once if so
◧ Lθ Pad to length of first input
≔ σ Assign to variable
EσEσ§μλ Transpose the array
⮌ Reflect the array, giving a rotation
≔ σ Reassign to variable
N Second input as an integer
F Repeat that many times
Eσ Map over array
⪫ι Join with spaces and implicitly print
```
[Answer]
---
## Javascript (ES6), ~~241~~ ~~222~~ 214 bytes
```
let f =
(n,x)=>(L=x=>(''+x).length,M=b=>x&b?(c,i,a)=>a[n-1-i]:c=>c,Array(n).fill(b=' ').map((c,i)=>b.repeat(L(n)-L(++i))+i).map((c,i,a)=>a.map((v,j)=>j>i?b.repeat(L(n)):v)).map(M(1)).map(c=>c.map(M(2))).map(c=>c.join(b)))
function printTriangle() { // display array of strings returned by f
o.innerText = f(
+Length.value, // number
Rotate.value[0] // ASCII char
).join('\n');
}
```
```
Length: <input type="text" value="11" id="Length"><br>
Rotate: <input type="text" value="0" id="Rotate"> 0,1,2,3<br>
<button type="button" onclick="printTriangle()">
OK
</button>
<br>
<pre id="o"></pre>
```
### Less Golfed
```
(n,x)=>(
L= x=> (''+x).length, // strlen(x)
M= b=> x&b ? (c,i,a)=>a[n-1-i] : c=>c, // reverse or identity map
Array(n).fill(b=' ')
.map((c,i)=>b.repeat(L(n)-L(++i))+i) // a complete line of numbers
.map((c,i,a)=>a.map((v,j)=>j>i?b.repeat(L(n)):v)) // to 2-d array
// with spaces for blank numbers
.map(M(1)) // flip vertically?
.map(c=>c.map(M(2))) // flip horizontally?
.map(c=>c.join(b)) // convert lines to strings
)
```
### Note on orientation.
The second parameter is a character from {'0', '1', '2', '3'} and automatically type converted to a number by the `&` operator. If bit 0 (lsb) of the number is set, lines are flipped vertically. If bit 1 (nlsb) is set, columns are flipped horizontally. Other decimal digit characters can be used with predictable results.
### Trailing Spaces
Blank entries in the output string have been replaced with spaces, which means lines have trailing spaces in orientations '0' and '1'.
[Answer]
# Lua, 250 bytes
```
function f(w,m)d=""for y=1,w do for x=1,w do d=string.format("%s%"..tostring(w):len().."s ",d,m<2 and(y+x-1<=w and x+y-1 or"")or(m<3 and(x>=y and w-x+y or"")or(m<4 and(y+x-1>=w and w+w-x-y+1 or"")or(y>=x and w-y+x or""))))end;d=d.."\n"end;print(d)end
```
Takes parameters [w]idth and [m]ode using 1,2,3,4 for modes as described in the example.
[Answer]
# 05AB1E (61 bytes)
```
F¹N-LN+¹N-LN+Rõ¸N∍s«N>LN¹<--N>LN¹<--Rõ¸¹<N-∍s«)²èvy¹gyg-ú}ðý,
```
[Try it online](https://tio.run/##MzBNTDJM/f/f7dBOP10fP20oFXR466Edfo86eosPrfaz8/E7tNNGVxfOAMsCWX66EBWahzYdXlFWeWhnemW67uFdtYc3HN6r8/@/kQGXMQA)
] |
[Question]
[
(Inspired while drawing on a dry erase board)
### Challenge:
Given an input string containing characters that represent different colors of dry erase markers on a white board, output the order in which they were drawn, from first to last.
### Input:
A string which contains dry erase marker colors which are represented by alphabetical letters (upper ones are different than lowercase, you may substitute any characters used in my examples as long as each color has a distinct letter). The rest of the whiteboard will be white-space. There will only be one line of each color per board. There won't be inputs where all lines overlap each other (See test case `4`). All lines will be straight and either horizontal or vertical.
### Output:
The order in which the lines were drawn on the board, from the first one drawn to the last one. If there are multiple solutions for any input, you may output any one of them. The output can be formatted anyway you'd prefer: single string of characters or separated by spaces, newlines, etc. as long as the characters used match the ones used in your input.
### Test Cases:
Input 1:
```
R
R
BBRBB
R
```
Output 1:
```
BR
```
Input 2:
```
GY
GY
RRRRGYRRR
GY
GY
BBBBBBBB
GY
GY
```
Output 2:
```
RGYB // or RYGB
```
Input 3:
```
R P
R P
AAAARAAAAPA
R P
R P
GGGGRGGG P
R
```
Output 3:
```
AGPR // or APGR
```
Input 4:
```
O Y
RRRYR
O Y
GOGGG
O Y
```
Output 4:
```
// Undefined, does not need to be handled by your program
```
Input 5:
```
YYYB
B
B
```
Output 5:
```
// YB or BY
```
### Rules:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
[Answer]
# Perl, 103+2 = 105 bytes
```
s/$/$"x y===c/gem;$a=$_;$_.=$"while$a=~s/^./!($_.=$&)/gem;s/$1/-/g,$b="$&$b"while/\s(\w)(\1|-)+ /;say$b
```
Run with `-n0` (2 byte penalty).
Explanation:
```
# -n0: read entire input into `$_` at start of program
# (technically speaking it reads to the first NUL byte, but there aren't any)
# We want to be able to extract columns from the input, so we need to add spaces
# to the ends of each line such that each column is complete. Adding too many
# space is OK, so to ensure we have enough, we add a number of spaces equal to the
# length of the input.
s/$/ # At the end of {something},
$" x # append a number of spaces ($" is a space by default)
y===c # obtained by counting the characters in $_
/gem; # where {something} is each (g) line (m)
$a = $_; # store a copy of the transformed input in $a
# The next step is to create a transposition of the input. To do that, we
# repeatedly extract the first column of $a and append it to $_. This will lead to
# a bunch of junk whitespace at the end of $_ (of varying lengths, because once a
# line is empty it's omitted from the extracted column), but we're OK with that.
# To transpose properly, we'd want to place newlines between the extracted
# columns; however, it happens that the rest of the program treats space the same
# way it would newline, and separating via spaces is shorter, so we do that.
while ( # keep looping as long as there are matches
$a =~ s/^./ # replace the first character of {something related to $a}
!( # with the null string (NOT of something truthy)
$_.=$&) # but append that character ($&) to $_
/gem) { # {something} is each (g) line (m) of $a
$_.=$" # append a space ($", equivalent to newline here) to $_
}
# Finally, we repeatedly replace every character in the topmost line with the -
# character (treating a line as continuous through the - character but not through
# other characters), thus finding the lines from top to bottom. Because we
# appended the transpose of $_ to $_ above, each line appears twice: once
# horizontally, once vertically. We find only the horizontal copy, but replace
# both with hyphens.
# (Note: I rewrote the regex into a bit more readable of a form in this ungolfed
# version, because the original version wouldn't allow me room to write comments
# inside it. The two should be equivalent; I tested the golfed version.)
while ( # keep looping as long as there are matches
/\s(\w) # match a space or newline, $1 (a letter/digit/underscore),
(\1|-)+ # any positive number of $1s and hyphens,
\ /x) { # and a space
s/$1/-/g, # changes all $1s to spaces; set $& to $1, $1 becomes invalid
$b = "$&$b" # prepend $& to $b
}
# We need to output the lines from first (i.e. bottom) to last (i.e. top).
# We found them in the opposite order, but reversed them via prepending
# (not appending) the partial results to $b.
say $b # output $b
```
One slight subtlety here comes with input like this:
```
ABC
DDDDDDDDD
ABC
ABC
ABC
```
Look at the fourth line here. If the order of writing were BACBD, there could genuinely be a *horizontal* line of `B`s along there without violating any of the assumptions of the problem (other than that there's only one line of each colour, something that we don't check). In order to get around this, we ensure in the last regex that each line *starts* with a letter (or digit or underscore, but those are impossible), and rely on the fact that parallel lines will be found left-to-right and top-to-bottom (because the regex will find the first match within the string). As such, the first character of each ambiguous line here gets overwritten before the line itself is seen as a match, and that prevents the regex matching.
[Answer]
# Python 2, 199 bytes
```
l=input()
w=len(l[0])
j="".join(l)
c=set(j)-{" "}
def f(s):
for h in s:
i=j.index(h);I=j.rindex(h);o=f(s-{h})
if{0}>c-s&set(j[i:I:w**(i+w<=I)])and`o`>"Z":return[h]+o
if{0}>s:return[]
print f(c)
```
This ended up a lot longer than I initially thought it would. Apart from the `rindex` I could see this as a very good program to translate into Pyth.
Takes in a list of lines and outputs a list of characters. The code generates permutations recursively, making sure that none of the drawn lines are supposed to be drawn on top of the current line.
The code abuses a lot of Python's features, for example taking `w` to the power of a boolean, testing for empty sets by checking subsets of `{0}` (since my sets never contain non-strings), and my favorite, distinguishing any list from `None` by checking if its representation is greater than `Z`.
### Explained code
```
lines = input()
width = len(lines[0])
joined = "".join(lines)
characters = set(joined) - {" "} # find unique characters except space in input
def solve(chars_left): # returns a solution for the given set of lines
for try_char in chars_left: # try all lines left
start_index = joined.index(try_char) # find start position of this line
end_index = joined.rindex(try_char) # and end position
step = width ** (start_index + width <= end_index) # take every width'th character if start
# and end indices differ by at least width
used_chars = characters - chars_left # find all drawn lines
line_chars = set(joined[start_index:end_index:step]) # find the characters inside the current line
missed_chars = used_chars & line_chars # find all lines that are already drawn but should be on
# top of this line
solution = solve(chars_left - {try_char}) # find solutions if this line was drawn now
if {0} > missed_chars and `solution` > "Z": # there should be no missed lines and a solution
# should exist
return [try_char] + solution # solution found, prepend current character and return
if {0} > chars_left: # if no lines are left
return [] # solution found
print solve(characters) # solve for all lines
```
] |
[Question]
[
Leonardo da Pisano *a.k.a* Fibonacci was instrumental in bringing the Hindu-Arabic numeral system into Europe. Before that, mathematicians there worked in base sixty with Roman numerals.
For example, the square root of two might be approximated as: *one and twenty-four parts of sixty and fifty-one parts of three-thousand-six-hundred*, and written as: *i xxiv li*, with the scaling determined by context. At the time, “nothingness” was known (*i.e.* zero), but had no standard representation in this number system.
Had Fibonacci ignored these new-fangled decimal digits he encountered during his travels, he surely would have addressed the deficiencies in the current system. This improved system we'll call *Fibonacci’s sexagesimals*.
Your task is to write a program, function or code snippet which takes a floating point number in ASCII or binary format and outputs in base sixty Roman numerals. The input can be file, console, command line or function argument and output can be file or console, whichever is easiest.
The output can be upper or lower case, and must include these improvements:
* use *n* or *N* to indicate *null* meaning a place has no value, *i.e.* “zero” (a problem with the system)
* use *e* or *E* to indicate *et* corresponding to the sexagesimal point (another problem with the system)
* use a middle dot · or an asterisk \* to separate groups of Roman numerals (yet another problem with the system)
Assume the input will be floating point with mantissa not greater than *lix·lix·lix·lix·lix*. Fractions less than *n·e·n·n·n·n·i* can be ignored. So, provided the input has these restrictions, at most ten groups of Roman numerals with one *e* can be outputted.
Numbers less than *i* must have a leading *n·e* to ensure the context is clear.
Some examples: `input` → *output*
* `0` → *n*
* `1` → *i*
* `60` → *i·n*
* `0.1` → *n·e·vi*
* `3600` → *i·n·n*
* `10.5` → *x·e·xxx*
* `16777215` → *i·xvii·xl·xx·xv*
* `3.1415926536` → *iii·e·viii·xxix·xliv·n·xlvii*
The output must avoid unnecessary leading *n·* in the mantissa part, isolated *e*, or trailing *·n* in the fractional part of the output. So for example, *n·n·n·n·i*, *i·e*, and *i·e·n·n·n·n·n* are incorrect outputs for an input of `1`.
Differences of plus or minus *n·e·n·n·n·n·i* in the output are within tolerances and acceptable.
The input is any legal floating point in the language of your choice, so can include positive or negative exponents as long as the input doesn't fall outside the range specified above.
And finally, Roman numeral built-ins **are** allowed!
[Answer]
# C – 584 bytes
Non-competing (obviously), but to serve as inspiration:
```
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
char*f(int z){static char r[8];char*l[]={"","I","II","III","IV","V","VI","VII","VIII","IX"},*h[]={"","X","XX","XXX","XL","L"};if(!z)return"N";sprintf(r,"%s%s",h[z/10],l[z%10]);return r;}int main(int c,char**v){char*s="";int i,j,z[10],k=60;long x;double d,y;y=modf(atof(v[1]),&d);x=d;for(i=4;i>=0;i--){z[i]=x%k;x/=k;}for(i=5;i<=9;i++){z[i]=(y*=k);y-=z[i];}for(i=0;!z[i]&&i<4;i++);for(;i<5;i++){printf("%s%s",s,f(z[i]));s="*";}for(j=9;!z[j]&&j>=i;j--);if(i<=j)printf("*E");for(;i<=j;i++)printf("*%s",f(z[i]));printf("\n");return 0;}
```
Save as `fs.c`, build with `gcc -o fs fs.c -lm`, and run as `./fs <arg>`.
Test cases:
```
$ ./fs 0
N
$ ./fs 1
I
$ ./fs 60
I*N
$ ./fs 0.1
N*E*VI
$ ./fs 3600
I*N*N
$ ./fs 10.5
X*E*XXX
$ ./fs 16777215
I*XVII*XL*XX*XV
$ ./fs 3.1415926536
III*E*VIII*XXIX*XLIV*N*XLVII
```
Largest mantissa and fraction:
```
$ ./fs 777599999
LIX*LIX*LIX*LIX*LIX
$ ./fs 0.999999998713992
N*E*LIX*LIX*LIX*LIX*LIX
```
I'm using `double` as the working type, so the largest mantissa and fraction combined exceeds the native accuracy of that type. If I used `long double` instead it could handle it.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 90 bytes (using classic `⎕AV`)
```
⎕CY'dfns'
'(·E)?(·N)*·$'⎕R''∊'·',⍨¨¯5(↓,'E',↑)'N'@(0=≢¨)⊢roman'I'⍴⍨¨d↑⍨-6⌈≢d←60⊥⍣¯1⌊⎕×60*5
```
[Try it online!](https://tio.run/##TZC7SgNBFIZr5ym2EE42JGEmcSdaiIqkECSF2lhYbMyFhc2smBBGxE5iXLPBC5I@ImyXQmX78U3Oi8SZibdizsz5zzf8h98/C4vNCz@MOgsc3Zx2@4Q6OHx0BGH2DghfCoHKBKGlpSpU1lLZICAVTv/GhmC05FlBWkRKSRivVqtl5v1wchCYGpqp6UilxNaYt1HmXoUvIQNYA0vKwHBhMLAeMtQy0cua017g5Hn3GJpt0QMCOZXV3C1d625eZaughwcAOIpBZVDAJFWpmns5HD4VoKaF4YMLddjO0U28nanUxXh2HnV9AXuAybvlmxrSjyLH8UhDur3nFONXTF7UnOE41h6fU07zngnwe52eH/bBwbtrpyX8Rtg63Nk/IieNSAai40SC/F96hWqrS0wm0NYfMPmAK5Vi8rZOKGE6fRO6zdlm@5smwekd@wI "APL (Dyalog Unicode) – Try It Online")
A full program that takes a number (actually any expression that evaluates to a single number is fine) from stdin and prints the result to stdout. Uses uppercase letters and middle dot as digit separator. The middle dot allows to shorten the regex at the end (since it doesn't need to be escaped, unlike `*`), and the middle dot *is* in the classic character set.
### How it works
```
⎕CY'dfns' ⍝ Load the dfns library to access `roman`
⌊⎕×60*5 ⍝ Multiply input by 60^5 and floor (to do things over integers)
60⊥⍣¯1 ⍝ Convert to base 60 using as many base-60 digits as needed
d← ⍝ Assign to d
d↑⍨-6⌈≢ ⍝ Pad with zeros to get 6 digits if there were fewer
'I'⍴⍨¨ ⍝ Convert each number to that many copies of 'I'
⊢roman ⍝ Normalize the Roman numeral
'N'@(0=≢¨) ⍝ Insert 'N' at zero digits (normalized result is empty)
¯5(↓,'E',↑) ⍝ Insert 'E' at 5 places from the end
∊'·',⍨¨ ⍝ Append a center dot to each numeral and flatten
'(·E)?(·N)*·$'⎕R'' ⍝ Regex replace to remove trailing E/Ns
```
[Answer]
# Python 3, ~~323~~ ~~319~~ 320 bytes
This answer implements Fibonacci's sexagesimals with the delimiter `*` and without regard for Kolmogorov complexity in the lists of Roman numerals (for now, at least). Attempts were made to join the `while` and `for` loop under which the Roman numerals are generated under one loop, but those attempts have not yet met with success. Any golfing tips and suggestions are welcome and appreciated.
**Edit:** Bug fixing and golfing.
**Edit:** More bug fixing.
```
def f(x):
v=divmod;f=x%1;n=int(x);d=",I,II,III,IV,V,VI,VII,VIII,IX".split(",");t=",X,XX,XXX,XL,L".split(",");z=["N"];a=f>0;s=z*0**n+["E"]*a
while n:n,m=v(n,60);j,k=v(m,10);s=[z,[t[j]+d[k]]][m>0]+s
for i in range(5*a):m,f=v(f*60,1);j,k=v(int(m),10);s+=[z,[t[j]+d[k]]][m>0]
while s[-1:]==z*a:s.pop()
return"*".join(s)
```
**Ungolfed:**
```
def f(x):
integ = int(x)
frac = x % 1
units=",I,II,III,IV,V,VI,VII,VIII,IX".split(",")
tens=",X,XX,XXX,XL,L".split(",")
zero = ["N"]
output = []
a = frac != 0
if integ == 0:
output += z
if a:
output += ["E"]
while integ > 0:
integ, digit = divmod(integ, 60)
j, k = divmod(int(digit), 10)
if digit:
output += [tens[j], units[k]]
else:
output += zero
for i in range(5*a):
digit, frac = divmod(frac*60, 1)
j, k = divmod(int(digit), 10)
if digit:
output += [tens[j], units[k]]
else:
output += zero
while output[-1:] == zero * a:
output.pop()
return "*".join(output)
```
[Answer]
# JavaScript (Node.js), 537 531 430 bytes
*-101 bytes (**big**) thanks to [**Bubbler**](https://codegolf.stackexchange.com/users/78410/bubbler)!*
Usage of some math (logarythms in this case, to calculate starting value for the "for" loop) and a code converting decimal numbers to roman numerals from [here (w3resource)](https://www.w3resource.com/javascript-exercises/javascript-math-exercise-21.php). Actually, the task took me more time than I expected it to take and gave a lot of additional intuition while working with numeral systems other than the decimal one. Great one :)
Function itself is an anonymous one declared with arrow function declaration.
```
n=>{if(n==0||n==1)return"NI"[n];k="",j=-`${n-(n|0)}.`.split`.`[1].length||0;j<-5?j=-5:"";with(Math){l=m=ceil(log(n)/log(60))}for(;l>j;l--){x=n%60**l/60**(l-1)|0;x==0&&l==m?(k+="I*"):"";l==0&&j<0?(k+="E*"):"";d=`${+x}`.split``,o=" X XX XXX XL L LX LXX LXXX XC I II III IV V VI VII VIII IX".split` `,h="",i=2;while(i--)h=(o[+d.pop()+(i*10)]||"")+h;k+=x==0?"N*":`${Array(+d.join("")+1).join("M")+h}*`;}return k.substr(0,k.length-1)}
```
[Try it online!](https://tio.run/##bVDdSsMwGL33KUJQSdo1Jpvt0BqHiBcF56UMxqBz62y6mIy26mTts88vc15I5ftJODk5HE4x/5hXi1Jt6sDYZbZfyb2Rtzu1IkZK3jSwBS2z@r00@CnBUzOL1xLjXiGD9HRnAmIaTluWsmqjVZ2ydCpmTGfmtc6bhsfFTRCOgBteYxx/qjon43md052Wb3KRKU20fSWGXrgj4pS2K1uSWN8WsQ4CuttKcxZxz9MXbhMdCAqiW3B2fq6lfBuRtS9x4mHq9PUBL274D/xwhJcSnPrb9tdj2rMSowmauIZ5RFAT6MMAcI9QghLXMM8IKoE@DAATfNRBaS93USjZjz9zpTOiwHMuiZ36S7axG0J9ojzB6axpMKZ@HoMtZ36Enzx8Da7uynL@RYBdWGWI4wh6vI/dh9ZL4/YnfbRm1ftLVZeE99bHhCGOdr@wprI6Yy7CFYEMT/4iooNEXRJnXdog4v@ocRZ2wWg4HPZF92HAxKUIr/pROIgo3X8D "JavaScript (Node.js) – Try It Online")
[Answer]
# Haskell (~~333~~ ~~322~~ 315 bytes)
I'm not clear whether the last sexagesimal digit is supposed to be rounded when I do or whether truncation is allowed; this truncates, I think the Python3 one might too?
```
d n f 0=n;d n f x=f x
x!n=60*(x-fromInteger n)
f 0=[];f x=(\n->n:f(x!n))$floor x
l 0=[];l x=(\(d,m)->l d++[m])$divMod x 60
v=[50,40,10,9,5,4,1]
n&i|n==0=""|n>=v!!i=words"l xl x ix v iv i"!!i++(n-v!!i)&i|True=n&(i+1)
q=foldl1(\a x->a++'.':x).map(d"n"(&0))
p x=(\n->d"n"(q.l)n++d""((".e."++).q.take 5.f)(x!n))$floor x
```
(-9 bytes, thanks [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz)! -2 bytes by eliminating `where` for `(\->)$`, -5 more by inventing this `d` function and golfing `a++"."++x` to `a++'.':x`.)
Ungolfed:
```
-- this function gets called `d` for default
onZero :: (Eq n, Num n) => z -> (n -> z) -> n -> z
onZero def f x
| x == 0 = def
| otherwise = f x
-- this function gets called `f`
fracPart :: RealFrac a => a -> [Integer]
fracPart x
| x == 0 = []
| otherwise = n : fracPart (60 * (x - fromInteger n))
where n = floor x
-- this function gets called `l`
leadPart :: Integral n => n -> [Integer]
leadPart x
| x == 0 = []
| otherwise = leadPart div ++ [ mod ]
where (div, mod) = x `divMod` 60
-- these get called `v`
romanValues :: [Integer]
romanValues = [50, 40, 10, 9, 5, 4, 1]
-- these get inlined with `words`, and correspond to the values above
romanLetters :: [String]
romanLetters = ["l", "xl", "x", "ix", "v", "iv", "i"]
-- this becomes (&)
romanNumeralLoop :: Integer -> Int -> String
romanNumeralLoop n i
| n == 0 = ""
| n >= (romanValues !! i) = (romanLetters !! i) ++ romanNumeralLoop (n - (romanValues !! i)) i
| otherwise = romanNumeralLoop n (i + 1)
-- this becomes `q`
concatRomanWithDots :: [Integer] -> String
concatRomanWithDots numbers = concatWithDots (map toRoman numbers)
where
toRoman = onZero "n" (\x -> romanNumeralLoop x 0)
concatWithDots = foldl1 concatDot
concatDot acc item = acc ++ "." ++ item
-- this becomes `p`
solve x = onZero "n" elseRomanizeLeadPart n ++ onZero "" elseRomanizeFracPart f
where
n = floor x
f = 60 * (x - fromInteger n)
elseRomanizeLeadPart l = concatRomanWithDots (leadPart l)
elseRomanizeFracPart f = ".e." ++ concatRomanWithDots (take 5 (fracPart f))
```
The method of converting integers to roman numerals was stolen shamelessly from [Thomas Ahle on StackOverflow](https://stackoverflow.com/a/4033542/1113881) and just golfed a little.
] |
[Question]
[
I like ascii art and I get bored a lot, so I found some ascii characters and started to make random things, 8-bit mario castle, mazes, and arches. I found that the arches could easily be stacked in a neat way.
```
╔═══════╗
║╔═════╗║
║║╔═══╗║║
║║║╔═╗║║║
╨╨╨╨─╨╨╨╨
```
# Challenge
Create a program, function, or any other standard format that accepts an integer that is greater than or equal to 0 (unless you are doing the bonus) and outputs ascii art with the amount of arches specified.
# Test Cases
Input:
```
7
```
Output:
```
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨
```
Alt:
```
+-------------+
|+-----------+|
||+---------+||
|||+-------+|||
||||+-----+||||
|||||+---+|||||
||||||+-+||||||
||||||| |||||||
---------------
```
Input:
```
1
```
Output:
```
╔═╗
╨─╨
```
Alt:
```
+-+
| |
---
```
* If the integer is 0 then don't output anything
* This question will be in utf-8, each character will count as a "byte"
* This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'") so the shortest answer wins.
* You have the option of using `+-+` instead of `╔═╗`, `---` instead of `╨─╨`, and `|` instead of `║`
# Bonus (not decided whether to allow this on the alternate version because it wouldn't be as hard)
-10% if the program supports negative numbers and flips the arches like so
```
╥╥╥╥─╥╥╥╥
║║║╚═╝║║║
║║╚═══╝║║
║╚═════╝║
╚═══════╝
```
[Answer]
## Python 2, 106 bytes (94 chars)
```
n=input();j=1
exec"s=j/2*'‚ïë';print s+'‚ïî'+'‚ïê'*(2*n-j)+'‚ïó'+s;j+=2;"*n
if n:t='╨'*n;print t+'─'+t
```
Pretty straightforward. Prints line by line with a changing number of horizontal and vertical bars. The last line is printed separately.
I feel like I'm missing some optimizations. The fact that the chars are multiple bytes means you can't do something like `'║╨'[n>0]`, so I didn't find a good way to print the last line in the loop. It's ugly that there's so much manipulation going on with the counter. I'd like update strings directly, like `s+='║'`, but the index is also used for horizontal bars.
[Answer]
# Perl, 78 82 chars
```
$n='─';$_='══'x pop;while(s/══//){print"$s╔═$_╗$s\n";$s.="║";$n="╨$n╨"}$s&&print$n
```
Sadly, I couldn't figure out a way to take advantage of the bonus without increasing the size by more than 10%. I may yet prevail.
**Ungolfed**
Pretty straightforward, really. Builds up bottom line (`╨$n╨`) incrementally, while shortening top line (`══`) by two characters, ending when it can no longer be shortened, so I don't have to mess with counters.
```
$n = '─'; # Bottom line
$_ = '══'x pop; # "Top" line, length from commandline argument
while (s/══//) { # Shorten top line by two characters
print "$s╔═$_╗$s\n"; # Print current line with $s (sides)
$s .= "‚ïë"; # Append vertical bar to sides
$n = "‚ï®$n‚ï®"; # Widen bottom line
}
$s && print $n; # Print bottom line if input is not 0
```
[Answer]
# CJam, 59 bytes
```
qi:Lg"^Za"a{_0=1'Z3*tsa\{'[2*\*}%+}L(*'rL*a2*N*a+9462ff+N**
```
[Try it here!](http://cjam.aditsu.net/#code=qi%3AL%2C%22%5EZa%22a%7B_0%3D1'Z3*tsa%5C%7B'%5B2*%5C*%7D%25%2B%7DL(*'rL*a2*N*a%2B9462ff%2BN*e%26&input=9)
[Answer]
# Bash, 124 bytes (112 characters)
```
printf -vh %$1s
b=${h// /‚ï®}
h=${h// /‚ïê}
for((n=$1;n--;)){
echo $v‚ïî$h${h:1}‚ïó$v
h=${h#?}
v+=‚ïë
}
(($1))&&echo $b─$b
```
Sample run:
```
bash-4.3$ bash ascii-arch.sh 7
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨
bash-4.3$ bash ascii-arch.sh 1
╔═╗
╨─╨
bash-4.3$ bash ascii-arch.sh 0
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-R`, 29 bytes
Uses `+` & `-`. Sacrificed 4 bytes to handle the *bloody* input validation!
```
©Æ'+²¬q-p´UÑÄÃpS û| p-pNÑÄ)ªP
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=qcYnK7KscS1wtFXRxMNwUyD7fCBwLXBO0cQpqlA=&input=MAotUg==)
---
## Explanation
```
:Implicit input of integer U
© :Logical AND with U
Æ :Map the range [0,U)
'+ : Literal "+"
² : Repeat twice
¬ : Split
q : Join with
- : Literal "-"
p : Repeat
´U : Decrement U
Ñ : Multiply by 2
Ä : Add 1
à :End mapping
pS :Push a space
û| :Centre pad each element with "|" to the length of the longest element
p ) :Push
- : Literal "-"
p : Repeat
N : The array of inputs (which will be cast to an integer if we perform a mathematical operation on it)
ÑÄ : Multiply by 2 and add 1
ª :Logical OR
P :The empty string
:Implicitly join with newlines and output
```
[Answer]
# JavaScript (ES6), 101 characters
```
f=(n,i=0)=>n?i-n?(b="‚ïë"[r="repeat"](i))+`‚ïî${"‚ïê"[r]((n-i)*2-1)}‚ïó${b}
`+f(n,i+1):(g="╨"[r](n))+"─"+g:""
```
## Explanation
Recursive function that prints each line
```
f=(n,i=0)=> // f = recursive function, i = current line (default = 0)
n? // if n != 0
i-n? // if we are not in the last line, print the line
(b="‚ïë"[r="repeat"](i))+`‚ïî${"‚ïê"[r]((n-i)*2-1)}‚ïó${b}
`+f(n,i+1) // add the output of the next line
:(g="╨"[r](n))+"─"+g // if we ARE in the last line, print the last line
:"" // print nothing if n = 0
```
## Test
Test does not use default parameter for browser compatibility.
```
var solution = f=(n,i)=>n?(i|=0)-n?(b="‚ïë"[r="repeat"](i))+`‚ïî${"‚ïê"[r]((n-i)*2-1)}‚ïó${b}
`+f(n,i+1):(g="╨"[r](n))+"─"+g:""
```
```
<input type="number" oninput="result.textContent=solution(+this.value)" />
<pre id="result"></pre>
```
[Answer]
# PHP (109 chars)
```
$s='';for($b=($n=$argv[1])?'─':'';$n--;){echo$s.'╔═'.str_repeat('══',$n)."╗$s\n";$s.='║';$b="╨{$b}╨";}echo$b;
```
Still need to get rid of that str\_repeat but most alternatives won't handle mulyibyte chars.
```
$s = '';
// Initialise $b (bottom) to '─' or '' for n==0
for ($b = ($n = $argv[1]) ? '─' : ''; $n--;) {
// Echo sides + arch + sides
echo $s . '╔═' . str_repeat('══', $n) . "╗$s\n";
// Growing sides
$s .= '‚ïë';
// Growing bottom
$b = "‚ï®{$b}‚ï®";
}
// Show bottom
echo $b;
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 79 chars
```
.+
$0$*═$0$*═╗
^‚ïê
‚ïî
+`(║*)╔═(═+)═╗║*$
$0¶$1║╔$2╗║$1
(\S+)$
$0¶$1
T`═╔╗║`─╨`\S+$
```
[Try it online.](http://retina.tryitonline.net/#code=XGQrCiQwJCrilZAkMCQq4pWQ4pWXCl7ilZAK4pWUCitgKOKVkSop4pWU4pWQKOKVkCsp4pWQ4pWX4pWRKiQKJDDCtiQx4pWR4pWUJDLilZfilZEkMQooXFMrKSQKJDDCtiQxClRg4pWQ4pWU4pWX4pWRYOKUgOKVqGBcUysk&input=MTA)
This uses a new feature in Retina that replaces a decimal number `\d+` with a list of that many characters `$0$*‚ïê`.
[Answer]
# Swift (209 bytes)
Probably Swift is not the best language for this, this is my first time trying to do a code golf challenge:
```
func *(l:String,r: Int)->String{return r>0 ?l+(l*(r-1)):""}
let n=Int(readLine()!)!
for i in 0...(n-1){let a=("║"*i)+"╔═";let b=a+("══"*(n-1-i))+"╗"+("║"*i);print(b)};print("╨"*n+"─"+"╨"*n)
```
[Answer]
# Ruby, 90 bytes (74 characters)
```
->n{n.times{|i|puts ?║*i+?╔+?═*((n-i)*2-1)+?╗+?║*i}>0&&puts(?╨*n+?─+?╨*n)}
```
Sample run:
```
2.1.5 :001 > ->n{n.times{|i|puts ?║*i+?╔+?═*((n-i)*2-1)+?╗+?║*i}>0&&puts(?╨*n+?─+?╨*n)}[7]
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨
=> nil
2.1.5 :002 > ->n{n.times{|i|puts ?║*i+?╔+?═*((n-i)*2-1)+?╗+?║*i}>0&&puts(?╨*n+?─+?╨*n)}[1]
╔═╗
╨─╨
=> nil
2.1.5 :003 > ->n{n.times{|i|puts ?║*i+?╔+?═*((n-i)*2-1)+?╗+?║*i}>0&&puts(?╨*n+?─+?╨*n)}[0]
=> false
```
[Answer]
# Haskell, ~~151~~ 162 bytes
```
r=replicate
c=concat
f n=putStr$unlines[c[r i '║',"╔",r(2*(n-i)-1)'═',"╗",r i '║']|i<-[0..n-1]]++c[r n '╨',r(signum n)'─',r n '╨']
main=readLn>>=f
```
Edit: I forgot to deal with `0` as input
[Answer]
# ùîºùïäùïÑùïöùïü, 54 chars / 95 bytes
```
⩥ïⓜᵖ⟮ ⍘|ď⟯$+`+⦃⟮⍘-ď (ï⟯-$)*2-1)}+`+Ⅰ$;ï⅋ᵖⅠï+⬭+Ⅰï,Ⅱ*2+1
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=true&input=0&code=%E2%A9%A5%C3%AF%E2%93%9C%E1%B5%96%E2%9F%AE%20%E2%8D%98%7C%C4%8F%E2%9F%AF%24%2B%60%2B%E2%A6%83%E2%9F%AE%E2%8D%98-%C4%8F%20%28%C3%AF%E2%9F%AF-%24%29*2-1%29%7D%2B%60%2B%E2%85%A0%24%3B%E1%B5%96%E2%85%A0%C3%AF%2B%E2%AC%AD%2B%E2%85%A0%C3%AF%2C%E2%85%A1*2%2B1)`
# Explanation
```
⩥ïⓜᵖ⟮ ⍘|ď⟯$+`+⦃⟮⍘-ď (ï⟯-$)*2-1)}+`+Ⅰ$;ï⅋ᵖⅠï+⬭+Ⅰï,Ⅱ*2+1 // implicit: ï=input, $=mapped item
// PHASE 1
⩥ïⓜ // create a range to map over
ᵖ // push to stack:
⟮ ⍘|ď⟯$ // | repeated $ times
+`+⦃⟮⍘-ď (ï⟯-$)*2-1)}+` // & +[- repeated 2$-1 times]+
+‚Ö†$; // & | repeated $ times
// PHASE 2
ï⅋ // if ï>0
ᵖ // push to stack 2 items:
Ⅰï+⬭+Ⅰï, // | repeated $ times & [space] & | repeated $ times
Ⅱ*2+1 // and - repeated 2ï+1
// implicit stack output, newline-separated
```
NOTE: this makes use of good ol' copy blocks to get at the spots where ordinary variable declaring could not reach.
[Answer]
# Sed, 97 bytes (81 characters)
(96 bytes (80 characters) code + 1 character command line option)
```
s/.(.*)/2&\13/
t
:
H
s/(.+)11(.+)/4\1\24/
t
y/1234/─╨╨╨/
H
g
s/\n//
y/1234/═╔╗║/
```
Input expected as [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) integer.
Sample run:
```
bash-4.3$ sed -r 's/.(.*)/2&\13/;t;:;H;s/(.+)11(.+)/4\1\24/;t;y/1234/─╨╨╨/;H;g;s/\n//;y/1234/═╔╗║/' <<< '1111111'
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨
bash-4.3$ sed -r 's/.(.*)/2&\13/;t;:;H;s/(.+)11(.+)/4\1\24/;t;y/1234/─╨╨╨/;H;g;s/\n//;y/1234/═╔╗║/' <<< '1'
╔═╗
╨─╨
bash-4.3$ sed -r 's/.(.*)/2&\13/;t;:;H;s/(.+)11(.+)/4\1\24/;t;y/1234/─╨╨╨/;H;g;s/\n//;y/1234/═╔╗║/' <<< ''
```
# Sed, 105 bytes (75 characters)
(104 bytes (74 characters) code + 1 character command line option)
```
y/1/‚ïê/
s/.(.*)/‚ïî&\1‚ïó/
t
:
H
s/(.+)══(.+)/║\1\2║/
t
y/╔║╗═/╨╨╨─/
H
g
s/\n//
```
Input expected as [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) integer.
Sample run:
```
bash-4.3$ sed -r 'y/1/═/;s/.(.*)/╔&\1╗/;t;:;H;s/(.+)══(.+)/║\1\2║/;t;y/╔║╗═/╨╨╨─/;H;g;s/\n//' <<< '1111111'
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨
bash-4.3$ sed -r 'y/1/═/;s/.(.*)/╔&\1╗/;t;:;H;s/(.+)══(.+)/║\1\2║/;t;y/╔║╗═/╨╨╨─/;H;g;s/\n//' <<< '1'
╔═╗
╨─╨
bash-4.3$ sed -r 'y/1/═/;s/.(.*)/╔&\1╗/;t;:;H;s/(.+)══(.+)/║\1\2║/;t;y/╔║╗═/╨╨╨─/;H;g;s/\n//' <<< ''
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 15 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
-*+∔]⤢:↷±n│L-×∔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=LSV1RkYwQSsldTIyMTQldUZGM0QldTI5MjIldUZGMUEldTIxQjclQjEldUZGNEUldTI1MDIldUZGMkMtJUQ3JXUyMjE0,i=Nw__,v=3)
Explanation:
```
{ ] map over 1..input
-* repeat "-" counter times
+‚àî append "+" to that
‚§¢ transpose
: create a duplicate of that
↷± rotated 90°, then reversed horizontally
n overlap the 2
| and palindromize horizontally with 1 overlap
L get the with of that
-√ó repear "-" that many times
‚àî and add vertically to the rest of the output
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 30 bytes
```
(\|n*\++⁰n--øm,)\|*ð+øm¶+⁰d›-,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%28%5C%7Cn*%5C%2B%2B%E2%81%B0n--%C3%B8m%2C%29%5C%7C*%C3%B0%2B%C3%B8m%C2%B6%2B%E2%81%B0d%E2%80%BA-%2C&inputs=5&header=&footer=)
```
( ) # Input times...
\|n* # (iteration number) |s
\++ # With a plus appended
⁰n-- # And (input - iteration number) minuses
√∏m, # Palindromed and outputted
\|* # Input |s
√∞+ # Plus a space
√∏m # Palindromised
¶+ # Plus a newline
⁰d› # (2(iteration number) + 1)
-, # Minuses appended, and outputted
```
] |
[Question]
[
Your task in this challenge is to analyize a given "Matchstick Equation" like this one...

... and to find out whether it can be turned into a valid equation by rearranging the matches. If so, you are to output the least number of moves to do so and the resulting equation.
## Input
The input is a String that can be read from STDIN, taken as a function argument or even be stored in a file. It is an equation that represents a matchstick arrangement and can be described using the following EBNF:
```
input = term, "=", term ;
term = number | (term, ("+" | "-"), term) ;
number = "0" | (numeralExceptZero , {numeral}) ;
numeralExceptZero = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
numeral = "0" | numeralExceptZero ;
```
An example for a valid input would be `3+6-201=0+0+8`.
## Task
Consider the following illustration where each matchstick has a number assigned:

We now map each input symbol to the corresponding matchstick positions as follows:
```
0 ↦ 1,2,3,4,5,6
1 ↦ 4,5
2 ↦ 2,3,5,6,8
3 ↦ 3,4,5,6,8
4 ↦ 1,4,5,8
5 ↦ 1,3,4,6,8
6 ↦ 1,2,3,4,6,8
7 ↦ 4,5,6
8 ↦ 1,2,3,4,5,6,8
9 ↦ 1,3,4,5,6,8
- ↦ 8
+ ↦ 8,10
= ↦ 7,9
```
Each input formula can be turned into a matchstick arrangement. For example, the equation "45+6=92" becomes

where unused matchsticks are greyed out.
Your task is to find out the least number of matchsticks that have to be rearranged in order to make the equation valid.
## Output
We distinguish between three possible cases:
* If the input is not valid (i.e. it doesn't satisfy the above EBNF), output whatever you want.
* Otherwise, if there are ways to turn the equation into a valid one by rearranging the matchsticks, you have to output *both* the minimum number of rearrangements *and* the corresponding equation. Just as the input, the outputted equation must also satisfy the given EBNF. In the above example, the correct output would be
`1` and `46+6=52`. If there are multiple possibilities for the resulting equation, output any of them.
* Otherwise (so if the input is valid but there is no way to make the equation true), you have to output `-1`.
## Details
* You are not allowed to remove or to add matches. That means, if the input is built of `n` matchsticks, the output must also consist of exactly `n` matchsticks.
* "Empty" matchstick-blocks are only allowed at the end and the beginning of an equation, not in the middle. So, for example, turning `7-1=6` into `7 =6-1` by simply removing `-1` from the left side and adding it on the right side with just 3 matchstick rearrangements is not allowed.
* Since I don't really see the mapping from numbers to matchstick positions as an interesting part of this challenge, for a plus of **20 bytes**, you may either
+ access a file in which the mapping `(number/operation ↦ matchstick positions)` is stored in any reasonable way, or
+ if your programming language supports a `Map` datatype, assume that you have access to a map that is preinitialized with the `(number/operation ↦ matchstick positions)`-mapping. This map may for example look like that: `{(0,{1,2,3,4,5,6}),(1,{4,5}),(2,{2,3,5,6,8}),(3,{3,4,5,6,8}), ..., (-,{8}),(+,{8,10}),(=,{7,9})}`
## Examples
**Input:** `1+1=3` ↦ **Output:** `1` and `1+1=2`
**Input:** `15+6=21` ↦ **Output:** `0` and `15+6=21`
**Input:** `1=7` ↦ **Output:** `-1`
**Input:** `950-250=750` ↦ **Output:** `2` and `990-240=750`
**Input:** `1-2=9` ↦ **Output:** `1` and `1+2=3`
**Input:** `20 + 3=04` ↦ **Output:** anything
## Winner
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest correct answer (in bytes) wins. The winner will be chosen one week after the first correct answer is posted.
[Answer]
# Javascript, 1069 Bytes
### I've tested it with quite a few test equations and it seems to work all of the time now...
```
function w(t){function B(c,f){d=(c.length>f.length?f:c).split("");e=(c.length>f.length?c:f).split("");longer=Math.max(d.length,e.length);if(0!==d.length&&0!==e.length){c=[];for(x in d)for(y in c[x]=[],e)c[x][y]=1<y-x?-1:function(c,n){r=0;for(j in n)-1<c.indexOf(n[j])&&r++;return c.length+n.length-2*r}(a[d[x]],a[e[y]]);return v=function(f,n){for(var h=f.length-2;0<=h;h--)c[n.length-1][h]+=c[n.length-1][h+1];for(h=f.length-2;0<=h;h--)for(var q=0;q<n.length-1;q++)1>=h-q&&(c[q][h]+=-1==c[q][h+1]?c[q+1][h+1]:Math.min(c[q+1][h+1],c[q][h+1]));return c[0][0]/2}(e,d)}return-1}a=[[1,2,3,4,5,6],[4,5],[2,3,5,6,8],[3,4,5,6,8],[1,4,5,8],[1,3,4,6,8],[1,2,3,4,6,8],[4,5,6],[1,2,3,4,5,6,8],[1,3,4,5,6,8]];a["+"]=[8,0];a["-"]=[8];a["="]=[7,9];a[" "]=[];l=0;p=[];u=[];r=/^([1-9]\d*|0)([+-]([1-9]\d*|0))*=([1-9]\d*|0)([+-]([1-9]\d*|0))*$/;b=/(=.*=|[+=-]{2,}|^[+=-])/;if(!t.match(r))return-1;g=function(c,f,t){if(0===t&&f.match(r)&&eval(f.replace("=","==")))c.push(f);else for(var n in a)t>=a[n].length&&" "!=n&&!(f+n).match(b)&&g(c,f+n,t-a[n].length)};g(p,"",function(c){m=0;for(var f in c)m+=a[c[f]].length;return m}(t.split("")));for(var z in p)k=B(t,p[z]),u[k]||(u[k]=[]),u[k].push(p[z]);for(var A in u)return[A,u[A]];return-1}
```
Well this is my first time ever submitting an answer, so I don't see myself winning. This is basically a brute force method to figure out all answers and then it grabs and returns the smallest ones in an array. with the first argument being the length and the second being an array with the outputs.
if the input is "1-2=9" the output is [1,["1+2=3","7-2=5"]]
and here is the uncompressed code:
```
function ms(s) {
a=[[1,2,3,4,5,6],[4,5],[2,3,5,6,8],[3,4,5,6,8],[1,4,5,8],[1,3,4,6,8],[1,2,3,4,6,8],[4,5,6],[1,2,3,4,5,6,8],[1,3,4,5,6,8]];
a["+"] = [8, 0];
a["-"] = [8];
a["="] = [7, 9];
a[" "] = [];
l = 0;
p = [];
u = [];
r = /^([1-9]\d*|0)([+-]([1-9]\d*|0))*=([1-9]\d*|0)([+-]([1-9]\d*|0))*$/;
b = /(=.*=|[+=-]{2,}|^[+=-])/;
if (!s.match(r)) return -1;
function f(g,h)
{
d=(g.length>h.length?h:g).split('');
e=(g.length>h.length?g:h).split('');
longer=Math.max(d.length, e.length);
if(0!==d.length&&0!==e.length)
{
g=[];
for(x in d)
{
g[x]=[];
for(y in e)
{
g[x][y]=(y-x>1)?-1:function(g, h){r=0;for(j in h)if(g.indexOf(h[j])>-1)r++;return g.length+h.length-2*r;}(a[d[x]],a[e[y]]);
}
}
v=function(d,e)
{
for(var y=d.length-2;y>=0;y--) g[e.length-1][y]+=g[e.length-1][y+1];
for(var y=d.length-2;y>=0;y--)
for(var x=0;x<e.length-1;x++)
if(y-x<=1)
g[x][y]+=g[x][y+1]==-1?g[x+1][y+1]:Math.min(g[x+1][y+1], g[x][y+1]);
return g[0][0]/2}(e,d)
return v
}
return -1;
}
g=function(n, s, i){if (i===0 && s.match(r) && eval(s.replace('=','=='))){n.push(s);return;}for (var c in a) if(i>=a[c].length && c!=" " && !(s+c).match(b)) g(n, s+c, i-a[c].length);};
g(p, "", function(q){m=0;for(var t in q)m+=a[q[t]].length;return m}(s.split('')));
for (var i in p)
{
k=f(s, p[i]);
if (!u[k]) u[k] = [];
u[k].push(p[i]);
}
for (var q in u) return [q, u[q]];
return -1;
}
```
Warning: Don't do equations like 950-250=750 it uses ~45 Matchsticks and because this code uses brute force it will cause javascript to hang.
[Answer]
# Perl, 334
Fairly fast as long as the solution is reachable in 1 or 2 moves. When there is no solution you are up for a long wait even in the smallest case of `1=7`.
```
#!perl -p
@y=map{sprintf"%010b",$_}63,24,118,124,89,109,111,56,127,125,64,192,768;
$y{$z{$y[$c++]}=$_}=$y[$c]for 0..9,qw(- + =);
$"="|";$l=s/./$y{$&}/g;$x{$_}=1;for$m(0..y/1//){
last if$_=(map"$m $_",grep{s/@y/$z{$&}/g==$l&&/^\d.*\d$/&!/\D\D/&!/\b0\d/&y/=//==1&&eval s/=/==/r}keys%x)[0];
$_=-1;s/0/"$`1$'"=~s!1!$x{"$`0$'"}=1!ger/eg for keys%x}
```
Example:
```
$ time perl ~/matchstick.pl <<<950-250=750
2 990-250=740
real 0m39.835s
user 0m39.414s
sys 0m0.380s
```
This will not find solutions that change the length of the equasion like `11=4` -> `2 11=11`, but I am not sure it this would be allowed.
] |
[Question]
[
### Background
[Piet](https://github.com/gleitz/npiet) is an esoteric stack-based programming language in which programs are images meant to resemble abstract paintings.
To keep the challenge from being unnecessarily complex, you will not have to consider most of the colors present in Piet, which determine what instructions are executed; instead, each type of instruction will be assigned a specific number or character (more in **Code Instructions**).
A codel is the basic unit of Piet code, and can be at any size. For the sake of this challenge, you can assume that a codel is a number/character.
A color block is a contiguous region of codels of the same color which is bounded by codels of other colors, or the edge of the program image. A color block can contain another color block within itself, which is counted as a separate color block from the surrounding one. Codels that share corners are not considered to be part of the same color block.
Piet uses a stack to store all data values, which are integers.
### Code Execution
A Piet program begins execution in the color block which contains the top left codel of the program. The interpreter contains a Direction Pointer (DP), which initially points to the right. The DP can point up, down, left or right. The interpreter also contains a Codel Chooser (CC), which is initially pointing left. The CC can either point left or right.
As the program is executed, the interpreter travels through the program under the following rules:
1. The interpreter finds the edge of the current color block which is furthest in the direction of the DP. (This edge may be disjoint if the block is of a complex shape.)
2. The interpreter finds the codel of the current color block on that edge which is furthest to the CC's direction of the DP's direction of travel. (Visualize this as standing on the program and walking in the direction of the DP; see table at below.)
3. The interpreter travels from that codel into the color block containing the codel immediately in the direction of the DP.
The program continues following these rules until the code terminates.
(CC table)
| DP | CC | Codel Chosen |
| --- | --- | --- |
| right | left | uppermost |
| right | right | lowermost |
| down | left | rightmost |
| down | right | leftmost |
| left | left | lowermost |
| left | right | uppermost |
| up | left | leftmost |
| up | right | rightmost |
### More Info on Color Blocks
Each non-black and non-white color block (white and black are special colors; more on that later) represents a number equal to the number of codels in that block. Though the interpreter may pass through a color block during execution, it does not necessarily do anything with the color block's stored value; there are specific instructions that deal with these values.
Black color blocks and edges of the program restrict program flow. If the Piet interpreter attempts to move into a black block or off an edge, it is stopped and the CC is toggled. The interpreter then attempts to move from its current block again. If it fails a second time, the DP is moved clockwise one step. These attempts are repeated, with the CC and DP being changed between alternate attempts. If after eight attempts the interpreter cannot leave its current color block, there is no way out and the program terminates.
White color blocks are essentially no-op's in which the interpreter passes unhindered. When the interpreter moves into a white block, it follows the following steps:
* The interpreter "slides" across the white block in a straight line.
* If it hits a restriction, the CC is toggled. Since this results in no difference in where the interpreter is trying to go, the DP is immediately stepped clockwise.
* The interpreter now begins sliding from its current white codel, in the new direction of the DP, until it either enters a colored block or encounters another restriction.
* Each time the interpreter hits a restriction while within the white block, it toggles the CC and steps the DP clockwise, then tries to slide again. This process repeats until the interpreter either enters a colored block (where execution then continues); or until the interpreter begins retracing its route. If it retraces its route entirely within a white block, there is no way out of the white block and execution should terminate.
In the actual Piet language, no instructions are executed upon exiting a white color block. In this regard, this challenge is different from Piet; namely, instructions **are executed upon exiting a white color block**.
### Code Instructions
As stated at the very beginning, to simplify the challenge, colors will not be used. Instead, each instruction will be mapped to a specific number/character of your choosing. When the interpreter enters a color block of a certain number/character, the corresponding instruction is executed. Any operations which cannot be performed (such as popping values when not enough are on the stack) are simply ignored, and processing continues with the next command. The corresponding instruction of the top left color block is not executed when initially running the program (though it will still have a value), but will run on any subsequent visits to the color block.
The instructions are as follows (these are just a subset of all the Piet instructions):
* **Push**: Pushes the value of the color block just exited onto the top of the stack.
* **Pop**: Deletes the value on the top of the stack
* **Add**: Pops the top two values off the stack and pushes the sum of those two numbers onto the stack
* **Subtract**: Pops the top two values off the stack and pushes the difference between the second topmost value and the top value of the stack
* **Multiply**: Pops the top two values off the stack and pushes the product of those two numbers onto the stack
* **Divide**: Pops the top two values off the stack and pushes the quotient between the second topmost value and the top value
* **Pointer**: Pops the top value off the stack and rotates the DP clockwise that many steps (anticlockwise if negative).
* **Switch**: Pops the top value off the stack and toggles the CC that many times (the absolute value of that many times if negative).
### Task
Choose 10 distinct numbers/characters which each represent one of the code instructions and the black and white codels, and clearly specify which 10 you chose in your answer.
Given a 2d rectangular grid, matrix, or a similar [default I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) consisting of the 10 different characters/numbers of your choosing representing a Piet program, output the final state of the stack after the input program has halted. Assume that all input programs will eventually halt.
The output can be in any reasonable or [default output format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), as long as it's clear what the state of the stack is. You can also output the stack with the "first" value representing the top of the stack, or the "last" value representing the top of the stack. For example, if the final state of the stack has `2` as the top value, `3` as the second topmost value, and `4` at the bottom of the stack, then both `[2,3,4]` and `[4,3,2]` are acceptable output formats. Make sure to include in your answer which output format you are using out of the two.
You can also optionally take in the dimensions of the Piet program.
### Worked Example
In this example, `0` is push, `1` is pop, `2` is add, `3` is subtract, `4` is multiply, `5` is divide, `6` is pointer, `7` is switch, `8` is white, `9` is black.
I will also use `>`, `<`, `^`, `v` to indicate where the interpreter is and what direction the DP is pointing.
Program:
```
111090908004
911088808944
911069912399
```
The program starts in the color block containing the top left codel, which is the 3 by 3 block of `1`'s. Remember that the initial instruction upon running the code is not ran, so `pop` (the instruction mapped to `1` in our example) is not ran. Also note that this color block has a value of 7, because it consists of 7 codels.
```
>11090908001
911088808911
911069912399
```
Initially, the DP is pointing right, so the interpreter goes to the right edge of the color block. The CC is pointing left, which means that the interpreter first tests the top-right edge for any restrictions.
```
11>090908001
911088808911
911069912399
```
There are none, so it travels to the right into the next color block, which is the block of `0`'s. `0` represents the push instruction, so 7 is pushed to the top of the stack. The stack is now `[7]`. At this point, the DP is pointing right, and the CC is pointing left, so it first tests the top-right edge for restrictions.
```
111>90908004
911088808944
911069912399
```
There is a black codel (`9`) restricting the program flow, so the CC is toggled and is now pointing to the right. The bottom right edge is now tested:
```
111090908004
911088808944
911>69912399
```
There are no restrictions here, so the interpreter travels to the code block to the right, which is the `6`. `6` is the pointer instruction, which rotates the DP clockwise 7 times (7 is on the top of the stack) and pops the 7 off the stack, leaving the stack empty. The DP was pointing right, so after 7 clockwise rotations, it points up.
```
111090908004
911088808944
9110^9912399
```
There are no restrictions in that direction, so the interpreter moves into the white code block.
```
111090908004
9110^8808944
911069912399
```
In white code blocks, the interpreter slides across white codels in a straight line until it hits a restriction, after which the DP is rotated clockwise, and the CC is toggled once. In this case, right after entering the white codel, there is a restriction in the upwards direction, so the DP is turned to the right, and the CC is toggled from right to left.
```
111090908004
9110>8808944
911069912399
```
There are no restrictions in this direction, so the interpreter slides across the remaining white codels until it reaches the block of `0`'s. `0` is the push instruction, so it pushes 3 to the top of the stack (because the white block that the interpreter just exited contains 3 codels). The stack is now `[3]`. The DP is pointing right and the CC is pointing left, so the interpreter checks the top-right edge first:
```
1110909>8004
911088808944
911069912399
```
There are no restrictions in this direction, so it travels into the white block.
```
11109090>004
911088808944
911069912399
```
The interpreter slides across the white block in a straight line until it enters the block of `0`'s. `0` is the push command, so 2 (the value of the white block that the interpreter just exited) is pushed onto the top of the stack. The stack is now `[2,3]`. The DP is pointing right and the CC is pointing left, so the top-right edge is checked:
```
1110909080>4
911088808944
911069912399
```
There are no restrictions in that direction, so it enters into the block of `4`'s. `4` is the multiply command, so it pops the top two values off the stack and pushes the product of the two popped values. The stack is `[2,3]`, so the `2` and `3` are popped off, and `2*3=6` is pushed onto the stack. The stack is now `[6]`.
The DP is pointing the the right and the CC is pointing to the left, so the top right edge is tested first:
```
11109090800>
911088808944
911069912399
```
There is a restriction in that direction (namely, the edge of the program), so the CC is toggled, making it point to the right. The bottom right edge is now tested:
```
111090908004
91108880894>
911069912399
```
There is also a restriction in that direction, so the DP is rotated clockwise once, making it point downwards. The CC is pointing to the right, so the bottom left edge is tested:
```
111090908004
9110888089v4
911069912399
```
There is also a restriction in that direction, so the CC is toggled, making it point to the left. The bottom right edge is now tested:
```
111090908004
91108880894v
911069912399
```
There is also a restriction in that direction, so the DP is rotated clockwise once, making it point to the left. The CC is pointing to the right, so the top left edge is tested:
```
111090908004
9110888089<4
911069912399
```
There is a restriction in that direction, so the CC is toggled, making it point to the left. This results in the same edge being chosen, which we already established to have a restriction. The DP is then rotated clockwise once, making it point upwards. The CC is pointing to the left, so the top leftmost edge is tested:
```
11109090800^
911088808944
911069912399
```
There's also a restriction in that direction, so the CC is toggled, making it point to the right. This results in the same edge being chosen, which is already known to have a restriction. At this point, 8 unsuccessful attempts have been made at getting out of this color block, so the interpreter concludes that there is no way out of this color block and terminates the program.
The final state of the stack is `[6]`.
### Test Cases
Uses the same character set as the worked example above.
```
111090908004
911088808944
911069912399
-> [6]
1199999999999999
9890888898889889
8880888000888808
8880889888988898
-> [3,9,7,9,7]
21234567000880
99999900000999
40330000000088
44988888888889
-> [-22]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
---
Reference: [official Piet specification](https://www.dangermouse.net/esoteric/piet.html)
[Answer]
# Python3, 1383 bytes:
```
lambda b:M(set(),b,0,2,[],(0,0))
T={0:(L:={0:max,2:min}),1:(K:={0:min,2:max}),2:K,3:L}
Q={0:(0,1),1:(1,0),2:(0,-1),3:(-1,0)}
I={0:lambda s,v,*a:[*a,[v]+s],1:lambda s,v,*a:[*a,s[1:]],2:lambda s,v,*a:[*a,[sum(s[:2])]+s[2:]],3:lambda s,v,*a:[*a,[s[1]-s[0]]+s[2:]],4:lambda s,v,*a:[*a,[s[0]*s[1]]+s[2:]],5:lambda s,v,*a:[*a,[s[1]/s[0]]+s[2:]],6:lambda s,v,DC,CC:[(s[0]+DC)%4,CC,s[1:]]if s else[DC,CC,s],7:lambda s,v,DC,CC:[DC,[0,2][abs(s[0])%2],s[1:]]}
def V(b,x,y):
try:
return 0 if b[x][y]==9 or x<0 or y<0 else 1
except:return 0
def C(b,v,s):
q,S,D,d=[s],[s],{s[0]:[s[1]]},{s[1]:[s[0]]}
while q:
x,y=q.pop(0)
for n,m in Q.values():
if(X:=x+n)>=0 and(Y:=y+m)>=0:
try:
if(X,Y)not in S and b[X][Y]==v:q+=[(X,Y)];S+=[(X,Y)];D[X]=D.get(X,[])+[Y];d[Y]=d.get(Y,[])+[X]
except:1
return S,D,d
def M(H,b,DC,CC,s,c,P=0,E=[]):
if(_:=str([DC,CC,s,c,P,E,b[c[0]][c[1]]]))in H:return s
H.add(_)
x,*y=C(b,S:=b[c[0]][c[1]],c)
if P==8:return s
if S==8:X,Y=c
else:
if DC in[0,2]:X=T[DC][CC](y[1][(Y:=[max,min][DC==2](y[1]))])
else:Y=T[DC][CC](y[0][(X:=[max,min][DC==3](y[0]))])
if V(b,A:=X+Q[DC][0],B:=Y+Q[DC][1]):return M(H,b,*(I[b[A][B]](s,len(x),DC,CC)if b[A][B]in I and(s or b[A][B]<2)else[DC,CC,s]),(A,B),0,[])
if S!=8:return M(H,b,(DC+1)%4 if P%2 else DC,[0,2][CC==0]if not P%2 else CC,s,(X,Y),P+1,[])
return M(H,b,(DC+1)%4,[0,2][CC==0],s,(X,Y),0,E+[(X,Y)])
```
[Try it online!](https://tio.run/##dVVhb9pIEP18/hV7kaLu4klubWhqb7snJaZSoranRFQn0HYVGTCtJTAOdjhQxW/PzawdEu6okW1m5r23s7MzUG7rH8uiG5Wrp5n@9jRPF@NpysbqC6@ymgsYg4QQjAUuQQrhfdU/peKfFb0W6QZCtciLnYBA8U@NMy/ImW7QGapP0FWfd96dY0kIHDBAJYyhfYaOruJn5Nl5N4RqM6hgDZ1UmU4KZm39yiLx/6HKBMpa1DrCqh4XvDIqtALpJiRc9yjOBPasMtLuYb3jMGk7hN3D3v5K7Y8DtYvXsH4CSaIMJ4TfT8RpD@12G/mMVSybV5lxKMA9vzvCxZfBM7EmHVdOR5yGtpXYedNsxv7mY9jAViiP1astPtkqqx9XBZMM1xibjTVbq3XMliu2@SDptcUXLc0Cj2WbSVbW6pnjJBOUXENFkg8wgD5MtcH86P5JOSi3cbsjK3CWpGzYPz/yecYeKAfMSD@cl8uSS4HmDFctYMHygt2dr9P5Y1ZxkmeYIx8qvfEL8aeWLC2mfKT01l@Q6QDPu2qxMBLFsiahAaFxg0NrRrjBtXrwtXEA@37w8rWPAN0//44NPsTWFj6i30@JMnXOUeMcWrdGWw4sTFsRt31XlS/8GgekPS2YwK2W8FEjGbPDzO6VruoVN68A8BHGZkLFwScWzAqBeV8/F7vy2PV5Op3yeyzRBjpbTYUfKH1AgokgfXardfSKiZ4BeXCTesI8d55UJvT3EyyP6xo11F8xIWuSxPItqhmqrqFRxsm1GNI6bCJCWDooJzM6YElkDf/L6jaRhpU3XXip9NC/c0xp4UrpUWuh@nPmTRE7/MaMzaU1V9byCuZZwTeiKa1wTetCWKsb1xEVNW3r/BCKg6kRwC/hSuAPl2lTGfz@UqhmOd5P/ACnz5XxNGx6fz9ZCW5H0jxSX@3D7gxdC8GtHzTiR0UPVPYcbA2/7UDxVK6W35k@OTnxgiCQMX4iKXtejEYURTKKe41xEcdB2I1jj6BEClpSfHB5cRQTMYqbO/acCt7SuWXUOuI9Zq8YOsUQl@m9vXjnCNJrZCVdJN@T3a5sryjyej3SaK8mNxqHenk/XqarKS9xAH5rS2NMZ5GWPC9qyIWlqc9pVGf5vM5W/K9lkQErz6tyntf8zbfiDfaPh3khns/4iyImKvDv52gg@GUkxMjTvw)
] |
[Question]
[
# Cell Phone Keyboard Typing
[This question](https://codegolf.stackexchange.com/questions/42465/create-a-t9-keyboard) was asked a while back, but was closed due to poor specs. So, I'm redoing it, with better specs. [This question](https://codegolf.stackexchange.com/questions/32817/calculate-cell-phone-keypresses) is related, but goes in the opposite direction.
Before T9 came around, in order to type a character in a text message, you had to press one of the number keys a number of times to get the character you wanted. For reference, here is the standard mapping:
```
+-------+-------+-------+
| 1 | 2 | 3 |
| .?!1 | ABC2 | DEF3 |
+-------+-------+-------+
| 4 | 5 | 6 |
| GHI4 | JKL5 | MNO6 |
+-------+-------+-------+
| 7 | 8 | 9 |
| PQRS7 | TUV8 | WXYZ9 |
+-------+-------+-------+
| * | 0 | # |
| ← |SPACE 0| → |
+-------+-------+-------+
```
`*` is backspace, `0` is a space (`' '`) or the number `0`, and `#` confirms the current character. For the sake of simplicity, all characters are uppercase.
When you pressed a key multiple times, the selected character cycles through the possible characters for that key: `2 -> A`, `22 -> B`, `222 -> C`, `2222 -> 2`, `22222 -> A`, and so on. Note that, since `*` only has one option, pressing it repeatedly causes multiple backspaces to be entered. Pressing `#` multiple times in a row has no effect. A trailing `#` is unnecessary.
Additionally, if a different key is pressed immediately after pressing a key, the previous keypress is automatically confirmed. Thus, `223` is functionally identical to `22#3`.
Your challenge is to translate a series of keypresses into the corresponding string a cell phone would display.
## Examples
```
8#99999#055#33#999#22#666#2#777#3#1 -> T9 KEYBOARD
4433555#55566609666666677755533*3111 -> HELLO WORLD!
7##222#222**7#222#4 -> PPCG
00#0#00 -> 0 0
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest correct solution (in bytes) wins
* The winning answer will be chosen in one week
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
* Your answer may be in the form of a full program, a named function, or an anonymous function, taking input and producing output in one of the [standard methods](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
# Leaderboard
The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 61545; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
# K5, 112 bytes
```
{(20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)[.*x]20!#1_x}'(){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}
```
This one is really a mess, but I think there's a fair amount of room to golf it down.
First we need to construct a lookup table for the keymap. There are keys with 2, 4 and 5 characters mapped to them, so padding every entry out to 20 simplifies the process of cyclically indexing this table later:
```
(20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)
(" 0 0 0 0 0 0 0 0 0 0"
".?!1.?!1.?!1.?!1.?!1"
"ABC2ABC2ABC2ABC2ABC2"
"DEF3DEF3DEF3DEF3DEF3"
"GHI4GHI4GHI4GHI4GHI4"
"JKL5JKL5JKL5JKL5JKL5"
"MNO6MNO6MNO6MNO6MNO6"
"PQRS7PQRS7PQRS7PQRS7"
"TUV8TUV8TUV8TUV8TUV8"
"WXYZ9WXYZ9WXYZ9WXYZ9")
```
Then I split the input into runs:
```
{(&~0=':x)_x}"8#99999#055#33#999"
(,"8"
,"#"
"99999"
,"#"
,"0"
"55"
,"#"
"33"
,"#"
"999")
```
Drop any # runs and strip trailing runs every time I encounter a \*:
```
(){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}"8#99999#055#33#999"
(,"8"
"99999"
,"0"
"55"
"33"
"999")
```
And then I'm ready to simply index into that lookup table based on the length and first element of each run.
All together:
```
{(20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)[.*x]20!#1_x}'(){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}"4433555#55566609666666677755533*3111"
"HELLO WORLD!"
```
## Edit:
Save 5 bytes:
```
0 3 6 9 12 15 19 22
((3*!6),19 22)
```
[Answer]
# Python 2, ~~230~~ 206 bytes
```
import re
f=lambda a,b=dict(zip("0123456789*#"," 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9~\b~".split("~"))):"".join([j and b[j][(len(i)-1)%len(b[j])]or b[i]for i,j in re.findall(r"((\d)\2*|.)",a)])
```
This one creates a function **f** which takes a string of keypresses as argument and returns the corresponding string a cell phone would display. It also happens to take an optional second argument as a dictionary mapping keys to their corresponding characters, eg **{"0": " 0", "1": ".?!1", ...}**.
First, the string of keypresses is grouped by repeating characters, eg **["8", "#", "99999", "#", ...]**. Then, the first character of each group is mapped in the dictionary passed as second argument, eg **9** maps to **WXYZ9**. Finally, the length of the group is used as offset in the value from the dictionary.
Note that the offset must use modulo on the length of the group of repeating characters because keypresses might cycle. Also note that the **#** character is mapped to **\0** and only removed at the end because **99#99** is not the same as **9999**.
Here is the output of the function for each of the examples in the question:
```
>>> print f("8#99999#055#33#999#22#666#2#777#3#1")
T9 KEYBOARD.
>>> print f("4433555#55566609666666677755533*3111")
HELLO WORLD!
>>> print f("7##222#222**7#222#4")
PPCG
>>> print f("00#0#00")
0 0
```
[Answer]
# JavaScript, ~~214~~ ~~184~~ ~~168~~ 162 bytes
```
x=>(x.match(/(.)\1*/g,f='').map(a=>f=(l=a.length,v=' 0#.?!1#ABC2#DEF3#GHI4#JKL5#MNO6#PQRS7#TUV8#WXYZ9'.split`#`[a[0]])?f+v[--l%v.length]:a<'*'?f:f.slice(0,-l)),f)
```
This can probably be made a little smaller, but I'm pretty happy with the result. Splits characters into repeated groups of one or more, then steps through the array, mapping each character to it's value in the hash and adding it onto the final string. If it comes across any number of '#', it ignores it. If it comes across any '\*', it removes that number of them from the end of the final string.
[Answer]
# Python 2, 265 bytes
It's way too long. IO: stdin, stdout.
```
a=reduce(lambda q,w:q+" "+[w,""][w=="#"]if q[-1]!=w else q+w,raw_input()).split()
while "*" in a:del a[a.index("*")-1:a.index("*")+1]
print"".join([(lambda a:a[len(q)%len(a)-1])(" 0:.?!1:ABC2:DEF3:GHI4:JKL5:MNO6:PQRS7:TUV8:WXYZ9".split(":")[int(q[0])])for q in a])
```
[Answer]
# Python 2, 237 bytes
Using cr3's dictionary, but without re.
```
def f(i):
d=dict(zip("0123456789"," 0|.?!1|ABC2|DEF3|GHI4|JKL5|MNO6|PQRS7|TUV8|WXYZ9".split("|")))
s,x,j='',i[0],0
for c in i[1:]+'#':
if c==x:j+=1
else:
if x>'/':s+=d[x][j%len(d[x])]
j=0
if c=='*':s=s[:-1]
x=c
return s
```
] |
[Question]
[
>
> **Synopsis:** Find characters that are enclosed by `MYPOCKET`.
>
>
>
**Example Input**
```
MYPHEIF
YFOCKVH
MBNDEIF
TEUFTMY
ESNDUWP
KBOVUVO
CENWFKC
OPYMTEB
```
**Example Output**
```
F
BND
EUF
SNDUW
BOVUV
ENWF
```
Huh? How did we get that as an output? The "pocket" can sometimes be difficult to see. This will make it clearer:
```
**MYP**HEIF
**Y**F**OCK**VH
**M**BND**E**IF
**T**EUF**TMY**
**E**SNDUW**P**
**K**BOVUV**O**
**C**ENWF**KC**
**OPYMTE**B
```
The letters in bold indicate a ring of characters connected orthogonally to each other consisting of the string `MYPOCKET` repeated over and over again. Your program should output the characters that are within that ring.
Notes:
* There will only be one "pocket".
* Trailing new lines or spaces after lines are allowed.
* The rest of the grid may also contain characters from `MYPOCKET`, but not in a way that makes the shape of the ring ambiguous.
* The `M` is not always in the top-right corner.
* The "pocket" can move in either a clockwise or a counter-clockwise direction.
* The "pocket" won't move in diagonal directions -- that is, each letter is connected left, right, up, or down to the next.
Here's another input you can test your program with.
**Example Input**
```
EKCYMOPD
KCOPHAYM
EKNDSEST
JETHACKE
KRMYPOBN
```
**Example Output**
```
HA
NDSES
HA
```
[Answer]
## Python 2.7 ~~571~~ ~~542~~ 509
```
import sys
o,l,v,k,w="MYPOCKET",[list(e)for e in sys.stdin],[],enumerate,len
def f(z,q,t):
for r,c in(z,q+1),(z,q-1),(z+1,q),(z-1,q):
if w(l)>r>=0 and 0<=c<w(l[r])and o[t]==l[r][c]:
v.append((r,c))
if f(r,c,(t+1)%w(o)):return 1
else:v.pop()
if z==1 and(0,q)in v or z==0 and(z,q+1)in v:return 1
for i,x in k(l[0]):
v=[(0,i)]
if x==o[0]and f(0,i,1):break
for i in range(1,w(l)-1):b=[y for x,y in sorted(v)if x==i];print"".join(["".join(e)if w(e)>0 else" "for e in[l[i][b[j-1]+1:y]for j,y in k(b)][1:]])
```
Works as a program(banking on a recursive function) and accepting input from stdin.
[Demo here.](https://ideone.com/ITDSAc)
Testing it (`ex1.txt` and `ex2.txt` are the examples from the question)-
```
$ python pockets.py < ex1.txt
F
BND
EUF
SNDUW
BOVUV
ENWF
$ python pockets.py < ex2.txt
HA
NDSES
HA
```
Ungolfed version with comments -
```
s="""
EKCYMOPD
KCOPHAYM
EKNDSEST
JETHACKE
KRMYPOBN
"""
li2=[list(e.strip()) for e in s.split("\n") if e.strip()!='']
buf=[]
def find_precious(row, col, c_ind):
for r,c in[(row,col+1),(row,col-1),(row+1,col),(row-1,col)]:
if len(li2)>r>=0 and 0<=c<len(li2[r]) and seq[c_ind]==li2[r][c]:
if (r,c)in buf:return True
buf.append((r,c))
if find_precious(r,c,(c_ind+1)%len(seq)):return True
else:buf.pop()
if row==1 and (row-1,col) in buf or row==0 and (row,col+1) in buf:return True
return False
for i,x in enumerate(li2[0]):
if x==seq[0]:
buf=[(0,i)]
if find_precious(0,i,1):break
if len(buf)==1:
exit("Failed")
#Calculate the middle men
for i in range(1,len(li2)-1):
b=[y for x,y in sorted(buf)if x==i]
print "".join(["".join(e)for e in [li2[i][b[j-1]+1:y]for j,y in enumerate(b)][1:]if len(e)>0])
```
Let me know, if I did something stupid or something can be done better.
I know it's looong, but it's the best I could do :P
[Answer]
# Perl 5, 414
```
map{$y=0;push@{$h{$_}},[$-,$y++]for@$_;$-++}@l=map[/./g],<>;sub n{($a,$b,$c,$d)=@_;$a==$c&&1==abs$b-$d||$b==$d&&1==abs$a-$c}sub c{my($x,$y,$n)=@_;for(grep{($f=defined$x)?n$x,$y,@$_:1}@{$h{(MYPOCKET=~/./g)[$n%8]}}){($m,$l)=@$_ if!$f;return@r=([@$_],@r)if$n>2&&n(@$_,$m,$l)||c(@$_,$n+1)}''}c;$l[$_->[0]][$_->[1]]=$" for@r;($l[$_]=join'',@{$l[$_]})=~s/^(\w+)\s|\s(\w+)$/$"x($1||$2)=~y%%%c/eg for 0..@l;print join$/,@l
```
Usage: save as pocket.pl and run with:
```
perl pocket.pl <<< '<grid>'
```
I went for a recursive function to brute-force the path, which might not have been the best, but was the first approach I considered.
Whilst it works for both of the current test cases there are some caveats:
* it includes leading spaces (which I didn't see mentioned in the rules...); and
* it will definitely not work with a 'pocket' that contains characters in the middle (say U shaped or similar).
I want to continue working on this, but wanted to show that there is interest in the question! Happy to document my process if helpful.
] |
[Question]
[
Your task is to create the given target string. Starting with an string that is empty, you will have to add characters to it, until your string is the same as the one we want. You can either add a character to the end of you string with cost x, or you can clone you string with cost y. What we want is the cheapest way to do this.
### Test Cases
```
targetString , appendcost, clonecost -> totalcost
"bb", 1, 2 -> 2
"bbbb", 2, 3 -> 7
"xzxpcxzxpy", 10, 11 -> 71
"abababab", 3, 5 -> 16
"abababab", 3, 11 -> 23
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 25 bytes
```
φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0
```
[Try it online!](https://tio.run/##AUgAt/9odXNr///Phj/DtuKWvHorOuKBtOKInsKybeKBsMKnOmjCp860ZmDigqxvdOG5q@G4ozD///8xMP8xMf8ieHp4cHp4enhwcSI "Husk – Try It Online")
Inputs are in the order append cost, clone cost, target.
## Explanation
```
φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0 Two explicit inputs and one implicit.
Example: 2, 3, s="abab"
φ Make a recursive function and call it on s:
? 0 If s is empty, return 0.
ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ Otherwise do this.
ḣ Prefixes: ["a","ab","aba","abab"]
otṫ Suffixes except the first one: ["bab","ab","b"]
§δf`€ Keep those prefixes that have the corresponding suffix as substring: ["ab","aba"]
§:h Prepend s minus last character: ["aba","ab","aba"]
m⁰ Recurse on each: x=[6,4,6]
∞² Repeat the clone cost: [3,3,3,..
:⁴ Prepend append cost: [2,3,3,3,..
z+ Add component-wise to x: [8,7,9]
▼ Minimum: 7
```
[Answer]
# [Python 2](https://docs.python.org/2/), 112 bytes
```
f=lambda s,a,c,i=0:i<len(s)and min([a+f(s,a,c,i+1)]+[c+f(s,a,c,n)for n in range(i+1,len(s)+1)if s[i:n]in s[:i]])
```
[Try it online!](https://tio.run/##dYs7DoMwDED3nsIbifDAR11QOUmUwXzSWgJDgYFy@TSUqmKpLHt4z298LY9BMu9d2VFfNQQzEtbIZVLwrWtFzZqkgZ5FGYqd@uo41TY29Q@IdsMEAiwwkdxbFT7wyMMrO5gNF2KDnk3B1mo/TiwLOBURRQgpQqYvJ/ahGUJ@ouu2jtt@nnuRhE3PTXVMcDnC9a8JkX8D "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~123~~ 111 bytes
Takes input as `(x)(y)(s)`.
```
x=>y=>m=g=([s,...r],o='',c=0)=>s?[...r,g(r,o+s,c+x)].map(_=>s+=r.shift(~o.search(s)&&g(r,o+s,c+y)))|m:m=m<c?m:c
```
[Try it online!](https://tio.run/##Zc7bisIwEIDh@30K6YWdoTE2igri1AeRsmSzbVWMqYlIK@Krd5Mu7KEmkIvJl58c5U06ZQ/1dXI2n0VXUtdQ1lKmqSLYOcY5tzkzFMdMUYqUue0uzFgFlpnEMZU0mHMta3j3lwlZ7vaH8gpPw10hrdqDw/H4V7eI@NBrTXqjtnqtOmXOzpwKfjIVlCAQZgiRlBHi6M@aTkezt//Uu3lPB9jT1YCKFEH4dNTcm/oejkv/JFAxsL65CNmP7/2T9lYsX22fHeLw23n3BQ "JavaScript (Node.js) – Try It Online")
### Commented
```
x => y => // x = 'append' cost; y = 'clone' cost
m = // m = minimum cost, initialized to a non-numeric value
// this is what will eventually be returned
g = ( // g = recursive function taking:
[s, // - the input string split into s = next character
...r], // and r[] = array of remaining characters
o = '', // - o = output string
c = 0 // - c = current cost
) => //
s ? // if s is defined:
[ ...r, // split a copy of r
g(r, o + s, c + x) // do a recursive call with an 'append' operation
].map(_ => // iterate as many times as there are remaining characters
// in r[], + 1
s += // append to s
r.shift( // the next character picked from the beginning of r[]
~o.search(s) && // if s is found in o,
g(r, o + s, c + y) // do a recursive call with a 'clone' operation
) // (note that both s and r are updated *after* the call)
) | m // end of map(); return m
: // else:
m = m < c ? m : c // update m to min(m, c)
```
[Answer]
# [R](https://www.r-project.org/), ~~192~~ 185 bytes
```
f=function(s,a,c,k=0,x="",R=substring,N=nchar,p=R(s,1,1:N(s)))'if'(!N(s),k,{y={};for(i in c(R(s,1,1),p[mapply(grepl,p,x)]))y=min(y,f(R(s,N(i)+1),a,c,k+'if'(any(y),c,a),paste0(x,i)));y})
```
[Try it online!](https://tio.run/##XY7fasIwFMbv9xRdduE5@F00LXMwySv0wlvZRSzGBTXGtEKj@OxdGjeQnUBI@H1/ThhHo8zFtb09Oeqg0WKvSgxKCKxUd9l0fbBuh0a59lsHeLVKMgn52VDHzDNrZvQ6vbHHLarbfWlOgWxhXdHSr5bh10ft/SHSLmz9AR4DfzFHdbSOIkwWNmR5nrR5h3kO1i5S5PTXKUJ3/bakATbVLuOdR0NCa5EKKi6e5q2oXjKaYIWan9HHhIbr4K/TdU7uElJyRjLbNo8jUOOd/2xy8Z9l06OtHn8A "R – Try It Online")
Unrolled code and explanation :
```
# s is the current remaining string (at the beginning is equal to the target string)
# a is the append cost
# c is the clone cost
# k is the current cost (at the beginning is zero)
# x is the partially constructed string (at the beginning is empty)
f=function(s,a,c,k=0,x=""){
# store in p all the possible prefixes of s
p = substring(s,1,1:nchar(s))
# if s is empty return the current cost k
if(!nchar(s))
k
else{
y={}
# prepend the first letter of s (=append operation) to
# the prefixes in p that are contained in x (=clone operations)
for(i in c(substring(s,1,1),p[mapply(grepl,p,x)])){
# perform first the append then the clone operations and recurse,
# storing the cost in y if lower than previous
# (if y is NULL is an append operation otherwise is a clone, we use the right costs)
y = min(y,f(substring(s,nchar(i)+1),a,c,k+'if'(any(y),c,a),paste0(x,i)))
}
# return the current cost
y
}
}
```
] |
[Question]
[
## Introduction
Jonny wants to play Frogger. However, he's not very good. In fact, he will only try to move forward, and only after the platforms have moved.
Find out if Jonny's frog manages to reach the end of the path or if it dies on its way.
## Challenge
The program will be receiving as input a Frogger grid composed by `0`s and `1`s, with the following format:
* The grid will be of a random width and length, and at least 3x3
* `1` represents platforms
* `0` represents water
* `F` represents the starting position of the frog
* Every first and last line of the grid will be composed by only `1`s, and will not move, and the frog `F` will be placed at random on the last line
* Every intermediate layer will always be moving, and will have a `<` or `>` at the end of every line indicating if it moves left or right
Replacing these symbols with your own is allowed, as long as they're all distinct and you specify the replacements in your answer.
The input may be in any compatible format (string with line breaks, array of strings, array of characters, ...).
## Challenge Rules
* Every turn, all platforms will move one square, based on the direction indicated by the `<` or `>` sign
* Platforms reappear on the other side of the grid if they get pushed off "screen"
* If the frog is on a moving platform, it will move along with it
* After that, the frog will jump one square towards the top row. The frog will move every turn.
* The frog dies if it jumps in water (`0`) or it touches the side of the grid along with a moving platform
Your program has to output a truthy value if the frog survives and a falsy value otherwise.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win. Standard loopholes apply.
## Examples
### Example 1
### Input
```
11111
00111>
00101<
1F111
```
### Output
`1`
### Execution
Turn 1:
```
11111
10011
01010
1F111
11111
10011
0F010
11111
```
Turn 2:
```
11111
11001
F0100
11111
11111
F1001
10100
11111
```
Turn 3:
```
11111
1F100
01001
11111
1F111
11100
01001
11111
```
### Example 2
### Input
```
11111
00100<
00100<
1F111
```
### Output
`0`
### Execution
Turn 1:
```
11111
01000
01000
1F111
11111
01000
0F000
11111
```
Turn 2:
```
11111
10000
F0000
11111
11111
F0000
10000
11111
```
Turn 3:
```
11111
00001
00001
11111
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~168~~ ~~165~~ ~~152~~ ~~145~~ ~~137~~ 129 bytes
```
s=input();x=s[-1].find('F');L=len(s[0]);i=k=1
for l in s[-2:0:-1]:d=('<'in l)%-2|1;k*=l[(x-d*i)%L]>'0'>-1<x+d<L;x+=d;i+=1
print k
```
[Try it online!](https://tio.run/##jY8xb4MwEIXn@ldYqSLbSUF2RsBsYULq0g0xpGAUC2Ijh7RE6n@nRyBqo0ZRPdw925/u3mvP3d6azVDYUklCyHCU2rSnjrKwl8fME7lfaVNSkhAWprJRhh4znrNQy1oKVFmHG6wNBnQT8AD4oJSURATeGrb0Nl8irFeyyWjvlSvNlmkeE05iT0T9uozSsF/LMtRrmNU6bTpcD@ACfe51o/CbO6kAPXXuDPVJ9aqgo0@GQBeq7fD2Ndk6Z934/e7UrkZosVigZ5yqqrMfyuHK2QOuTqbotDW7BoPhg@/7aN5WUdgmxoM4hxqPjYsIiQRu8Mfuk5xH1/aYBCb@BzkPvbLQ4S157CC@tgt6ISH8kE0MecFkijQrSDWqyUSObjGwd6vuYmOYh9jPuF/gJOc8fxfHt2oKkw/f "Python 2 – Try It Online")
Input format is a list of strings; characters having meanings as given in the problem statement.
### Explanation:
`i` is the turn number (starting with Turn 1); `x` is the position of the frogger at the start of that turn.
The row the frogger is about to step onto is the string `l` (note that via the slicing, these come in bottom to top order). `d=('<'in l)%-2|1` yields `-1` or `1` depending on the direction the row is moving.
Since this is the `i`th turn, that row will have shifted from it's original position by `i` bytes; and so the character the frogger is about to jump onto is `l[(x-d*i)%L]` where `L` is the width of the row, so we want that character to be equal to `'1'`; i.e., `>'0'`.
In addition, we want to check that the frogger will not be shifted off the edge at the beginning of the *next* turn; that is the function of expression `-1<x+d<L`.
These conditions are chained (since `'0'>-1` is always `True`); and if at any time the resulting expression is false, `k` will become (and then stay) `0`.
In any case, we update the frogger's position `x+=d` and bump the row number; then lather, rinse, repeat.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~246~~ ~~245~~ ~~244~~ 242 bytes
-3 byte thanks to Mr. Xcoder
-1 byte thanks to Jonathan Frech
```
m=input()
exec"""for i,r in enumerate(m):
d=-int(min('1',r[-1]));q=r[d*2]
if m[i+1:]:r=sum([r[d+1:d-1],[[q,' '][q<'L']]][::d-~d],[])+r[-1:]
if'F'in r:j=r.index('F');r[j]='L';m[i-1][j]=min('F',m[i-1][j])
m[i]=r
"""*~-len(m)
print'F'in m[0]
```
[Try it online!](https://tio.run/##ZY9NbsMgEIX3nAJ5AyS4irPEYetVbjCaRRWISlSIPbGldJOru2NHrfqzGMHMY7736D/Gt2vZz3P2qfTTqI2I93iqqup8JZksV5GxTDnS6xh1Nk7I4OtURp1T0apRlqBu0Jh28ARhs0ch01lmSNvGoSN/m7IGVrgN/NACDFZJhTAc1FEhIjgWHoEVNNsF5laE6hRbk7t4ekklxLvmiWkJLuh5sWUHxi3dGqRT9ntixOKPngT/Y/Oo32Ph5KInjv3EZtjhPAMwyP4pzsHx7Fo/leaf8nXuVmW5db9J@Ak "Python 2 – Try It Online")
## Explanation
* `d` is the direction each layer will move
* `q` is the character that will be wrapped around
+ `[q,' '][q<'L']` will drop the frog off-screen
* `sum([r[d+1:d-1],[[q,' '][q<'L']]][::d-~d],[])+r[-1:]` will remove the last character (the direction), then remove the first character and append it or remove second last and prepend it (based on `d`), and append the direction back, effectively moving the entire row to the left/right.
* `if'F'in r:j=r.index('F');r[j]='L';m[i-1][j]=min('F',m[i-1][j])` will make the frog jump forward
* `min('F',m[i-1][j])` will make the frog fall in the water
* The characters comparison (`min` and `<`) follow the order `' ' < '0' < '1' < 'F' < 'L'`
The input will be a list of list of characters:
`' '` - water
`'F'` - frog
`'L'` - plataform
`'0'` - move the layer to the left
`'1'` - move the layer to the right
[Answer]
# Java 8, ~~293~~ 277 bytes
```
a->{for(int l=a.length-1,x=a[l].indexOf('F'),y=l,i,t=a[0].length()-1,b;y>0;y--){for(i=l;i-->1;a[i]=a[i].endsWith("<")?a[i].substring(1,t+1)+a[i].charAt(0*(x-=b))+"<":a[i].charAt(t)+a[i].substring(0*(x+=b),t)+">")b=i==y?1:0;if(x<0|x>t||a[y].charAt(x)<49)return 0>1;}return 1>0;}
```
Uses the default characters as specified in the challenge description (`01F<>`).
[Try it online.](https://tio.run/##pVPBcoIwEL33K3a4mFSgyUwvFYPTi7e2h3amB8dDwKixMXQgtDDKt9sFtPVaZYBs8t6@2X072cgvGWwWH4fUyKKAJ6nt7gZAW6fypUwVPLdbgCTLjJIWUvLqcm1XszlIGiHU4Idv4aTTKTyDBQEHGcS7ZZYTlAEjZGiUXbl1wP1KyJmZh9ouVPWyJIPpgPq1ML72HSJsfmQSitwkqmMW1UFAey1hIh0EMY/kTM9F@wuVXRTvGvne2KOT7qgok6KrkHDfDTkddqfpWuaPjrBbUgUioXSICaNzxB2Jf@ktd4hcHyEv9mgitBD1hI9YpJekGrN9Fbv9Xs7qX5GKju8faK5cmVtgWGlzjDk20hyi3qrPMjFo1dGxr0wvYIu2nxvbe353B2956db1qNu@1oVT2zArXfiJTGcssWFKrPqGU@rO4@3j@R5juMZ9wPgYAz5tkYZ2U/u3Gqqc1NhVavyk8qfXRYhMzxWx@ak0hbqw@b7K68s9icTnQVfr5Vb282jXfjC/jbdi3ZVqDj8)
**Explanation:**
```
a->{ // Method with String-array parameter & boolean return-type
for(int l=a.length-1, // Amount of rows minus 1
x=a[l].indexOf('F'), // Start x-position of the frog
y=l, // Start y-position of the frog
i, // Index-integer
t=a[0].length()-1, // Length of the rows minus 1
b; // Temp integer
y>0; // Loop as long as the frog hasn't reached the other side
y--){ // Jump forward once after every turn
for(i=l;l-->1; // Inner loop over all the moving rows
;a[i]= // After every iteration: Change the moving row to:
a[i].endsWith("<")? // If the current platform moves to the left:
a[i].substring(1,t+1)
// Last part of the platform
// i.e. "00101<" → "0101"
+a[i].charAt(0 // Appended with the first character
// i.e. "00101<" → '0'
*(x-=b)) // We are moving left, so subtract `b` from `x`
+"<" // And append the direction "<" again
// so "00101<" becomes "01010<"
: // Else (the platform moves to the right):
a[i].charAt(t) // Take the last character
// i.e. "00111>" → '1'
+a[i].substring(0 // And append the first part of the platform
// i.e. "00111>" → "0011"
*(x+=b),t) // We are moving right, so add `b` to `x`
+">") // And append the direction "<" again
// so "00111>" becomes "10011>"
b=i==y? // If the frog is on the current row:
1 // Set `b` to 1
: // Else:
0; // Set `b` to 0
if(x<0|x>t // If the Frog is out of bounds
||a[y].charAt(x)<49) // Or jumped into the water
return 0>1;} // Return false
return 1>0;} // If the loop ended the frog made it to the other side,
// so return true
```
] |
[Question]
[
### Background
Three years ago, this guy [Tom Murphy](http://www.cs.cmu.edu/~tom7/) got it into his head to extend the idea of a portmanteau to all words in a language and called this a *portmantout* (*portmanteau* plus *tout* [French for *all*]). Defining English as a list of 108,709 words, he managed to find a sequence of 611,820 letters with the following two properties:
* Every English word is contained in the string.
* Some neighborhood containing any two adjacent letters in the string is an English word.
[Here](http://www.cs.cmu.edu/~tom7/portmantout/)'s a link to a page on which this portmantout can be found (along with a video explanation).
### A portmantout
The first of the two properties of a portmantout is easy to understand. The second may require some explanation.
Basically, words must overlap. "golfcode" will never appear in a portmantout of English, as there is no word there that contains the "fc". However, you might find "codegolf" in a portmantout, for "ego" bridges the gap (and all other pairs of letters are in either "code" or "golf").
### Your task:
Write a program or function that takes a list of strings and returns any portmantout of the list.
[This Python 3 code](https://tio.run/##fVLBbsIwDD2Tr7DEoY0oB7YbEld@AG5Vhbo1pdHSuErcTXx9Z5fAmISQKqV5fn5@z@1woQ79@zQ1poUOsTnZmEcK1p8LiFQHKsD4poAfDI3eKrWwrQCwvlZhtwNnfJ7Ki0UwNAYPV4ly5myZXwlRSKyQKE@nrTeP8wDDC1OrTaIppcT@twm2vcxWTs5GJg3U02y6ZSHBwXq418Uup5lxjyQ1aRD45nFfu2hSvxVCqP3Z5JJ41uY1bHTSEYk49nl5cyyMAiw/q7dboKdGKv1sZroew2imJRwRGtOj5zXUZIC6mg2TaHxFtYSBl0N52kCZfWJjsgKyM7o2q/hFgPmiNSzh0OHoGvgwadjrfj6596WMmFQss@d4FxyBEFrrnKTcanUPCgA7KCs1YKC@9oQj/0CQZUr9m//4Bf@YWk@/) will verify a portmantout.
### Test cases
All lists are unordered; that is,
```
{"code", "ego", "golf"} -> "codegolf"
{"more", "elm", "maniac"} -> "morelmaniac" or "morelmorelmaniac" or "morelmorelmorelmaniac" or...
Would a morelmaniac be some sort of mycologist?
{"ab", "bc", "cd", "de", "ef", "fg", "gh", "hi", "ij", "jk", "kl", "lm", "mn", "no", "op", "pq", "qr", "rs", "st", "tu", "uv", "vw", "wx", "xy", "yz", "za"} -> "abcdefghijklmnopqrstuvwxyza" or "rstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef" or any 27+ letters in order
```
And why not? The massive one on Murphy's site, if your code executes within reasonable time.
### Rules
* Your code must halt.
* You need not return the same portmantout with each execution.
* You may assume all strings consist of only lowercase letters `a` through `z`.
* If no portmantout is possible, your program may do anything. Ex: `{"most", "short", "lists"}`
* Standard rules for [I/O](https://codegolf.meta.stackexchange.com/q/2447/73884) and [loopholes](https://codegolf.meta.stackexchange.com/q/1061/73884) apply.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in bytes) in each language wins! Happy golfing!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~204~~ 202 bytes
```
def f(l,s=''):
if all(w in s for w in l):return s
for i,w in enumerate(l):
a=next((s+w[i:]for i in range(len(w)-1,0,-1)if s[-i:]==w[:i]),0)if s else w;x=a and f(l[:i]+l[i+1:]+[l[i]],a)
if x:return x
```
[Try it online!](https://tio.run/##XZHdjoMgEIWv61MQb5RIk3Yv3fgkxotR0dIiWMCf9uVdBt1sujffkOFwOAPjy920@tq2lnekSyWzRZLQPCKiIyBluhChiCWdNiQsJc0Nd5PxzSh0BQt9rqaBG3A89YroBIXiq0tTmy2lyKsgRJkB1XsJV@lCz1d2Yecr9TfZ8uxVRbGUuagou4Qe4dJysnyvBRBQLabD7UyWIrvmVVb6RVUxoNHJy9ffXOs2GqGcl5dxo1seMxLzXmPpteziikZ/gkGbXSAHLAMoAc2nBGrcqRtk0yIPzw7Z9cH4hrwJpLgj7w/kQyIPb4VUIYgekeMT@TRIY5HWId2EnGbkvCCXFbm@kK838g2fKa0IAWvY3aCuhQuWjYFW8n9TwzQfY/sfCzM1sN/NJW@c2c0cDJ8Hk5s2licsGfR01BmLf72kotsP "Python 2 – Try It Online")
---
Saved
* -2 bytes, thanks to recursive
[Answer]
# Pyth, 39 bytes
```
JQW}_1mxbdQ=+J|=b*qKOQ<=T+OP._KOJlKTY)b
```
[Try it here](http://pyth.herokuapp.com/?code=JQW%7D_1mxbdQ%3D%2BJ%7C%3Db%2AqKOQ%3C%3DT%2BOP._KOJlKTY%29b&input=%5B%27code%27%2C%20%27ego%27%2C%20%27golf%27%5D&debug=0)
### Explanation
```
JQW}_1mxbdQ=+J|=b*qKOQ<=T+OP._KOJlKTY)b
JQ Get a copy of the input.
W}_1mxbdQ ) While there are words in the input
that aren't in b (initially space)...
KOQ OP._KOJ ... get a random input word, a random
prefix, and a random joined word...
=T+ ... stick them together...
q < lKT ... and check if joining them together
is valid...
=b* ... then update b accordingly...
=+J| Y ... and stick the new word into J.
b Output the final result.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~39~~ 36 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ä▬│•.k=╠lƒ☺╜00║¿~,▓╕╠7ÉΔB<e┼>☼Θ²└ô┴\
```
[Run and debug it](https://staxlang.xyz/#p=8416b3072e6b3dcc6c9f01bd3030baa87e2cb2b8cc3790ff423c65c53e0fe9fdc093c15c&i=[%22code%22,+%22ego%22,+%22golf%22]%0A[%22more%22,+%22elm%22,+%22maniac%22]%0A[%22ab%22,+%22bc%22,+%22cd%22,+%22de%22,+%22ef%22,+%22fg%22,+%22gh%22,+%22hi%22,+%22ij%22,+%22jk%22,+%22kl%22,+%22lm%22,+%22mn%22,+%22no%22,+%22op%22,+%22pq%22,+%22qr%22,+%22rs%22,+%22st%22,+%22tu%22,+%22uv%22,+%22vw%22,+%22wx%22,+%22xy%22,+%22yz%22,+%22za%22]%0A[%22sic%22,+%22bar%22,+%22rabbits%22,+%22cradle%22]%0A[%22mauve%22,+%22elated%22,+%22cast%22,+%22electric%22,+%22tame%22]&a=1&m=2)
Runs all the test cases deterministically in about a second.
This is a recursive algorithm.
* Start with each word of input as a candidate
* At each step, order the words by the number of times they occur as substrings of the candidate.
* For each word that's compatible with the end of the current candidate, join the word to form a new candidate, and make a recursive call.
Here's the program unpacked, ungolfed, and commented.
```
FG for each word in input, call target block
} unbalanced closing brace represents call target
x{[#o sort input words by their number of occurrences in the current candidate
Y store it in register Y
h[#{,}M if all of the words occur at least once, pop from input stack
input stack is empty, so this causes immediate termination,
followed by implicitly printing the top of the main stack
yF for each word in register y, do the following
[n|]_1T|[|& intersect the suffixes of the candidate with prefixes of the current word
z]+h get the first fragment in the intersection, or a blank array
Y store it in register Y
%t+ join the candidate with the current word, eliminating the duplicate fragment
y{G}M if the fragment was non-blank, recursively call to the call target
d pop the top of stack
```
[Run this one](https://staxlang.xyz/#c=FG+++++++++++++%09for+each+word+in+input,+call+target+block%0A%7D++++++++++++++%09unbalanced+closing+brace+represents+call+target%0A++x%7B[%23o++++++++%09sort+input+words+by+their+number+of+occurrences+in+the+current+candidate%0A++Y++++++++++++%09store+it+in+register+Y%0A++h[%23%7B,%7DM++++++%09if+all+of+the+words+occur+at+least+once,+pop+from+input+stack%0A+++++++++++++++%09input+stack+is+empty,+so+this+causes+immediate+termination,%0A+++++++++++++++%09followed+by+implicitly+printing+the+top+of+the+main+stack%0A++yF+++++++++++%09for+each+word+in+register+y,+do+the+following%0A++++[n%7C]_1T%7C[%7C%26%09intersect+the+suffixes+of+the+candidate+with+prefixes+of+the+current+word%0A++++z]%2Bh+++++++%09get+the+first+fragment+in+the+intersection,+or+a+blank+array%0A++++Y++++++++++%09store+it+in+register+Y%0A++++%25t%2B++++++++%09join+the+candidate+with+the+current+word,+eliminating+the+duplicate+fragment%0A++++y%7BG%7DM++++++%09if+the+fragment+was+non-blank,+recursively+call+to+the+call+target%0A++++d++++++++++%09pop+the+top+of+stack&i=[%22code%22,+%22ego%22,+%22golf%22]%0A[%22more%22,+%22elm%22,+%22maniac%22]%0A[%22ab%22,+%22bc%22,+%22cd%22,+%22de%22,+%22ef%22,+%22fg%22,+%22gh%22,+%22hi%22,+%22ij%22,+%22jk%22,+%22kl%22,+%22lm%22,+%22mn%22,+%22no%22,+%22op%22,+%22pq%22,+%22qr%22,+%22rs%22,+%22st%22,+%22tu%22,+%22uv%22,+%22vw%22,+%22wx%22,+%22xy%22,+%22yz%22,+%22za%22]%0A[%22sic%22,+%22bar%22,+%22rabbits%22,+%22cradle%22]%0A[%22mauve%22,+%22elated%22,+%22cast%22,+%22electric%22,+%22tame%22]&a=1&m=2)
**Edit:** This fails for a class of inputs that has a loop, like `["ab", "ba", "ca"]`, as do most of the other posted answers.
[Answer]
# JavaScript (ES6), ~~138~~ 130 bytes
```
f=a=>a[1]?a.map((c,i)=>a.map((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a
```
Returns an error for lists that cannot be completely portmantouted.
Ungolfed:
```
f = a =>
a[1] ? //if more than one element ...
a.map((c, i)=> // for each element
a.map((w, j, [...b])=> // for each element
i != j && // if not the same element
!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``) && // and the elements overlap
(t = f(b, // and f recursed is true when
b[i] = m, // replacing the ith element with the 2-element portmanteau
b.splice(j, 1) // and removing the jth element
)
)
)
) &&
t : //return the recursed function value
a //else return a
```
```
f=a=>a[1]?a.map((c,i)=>a.map((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a
console.log(f(["sic", "bar", "rabbits", "cradle"])+'') // "barabbitsicradle"
console.log(f(["mauve", "elated", "cast", "electric", "tame"])+'') // "mauvelectricastamelated"
console.log(f(["more", "elm", "maniac"])+'') // "morelmaniac"
console.log(f(["elm", "more", "maniac"])+'') // "morelmaniac"
console.log(f(["more", "maniac", "elm"])+'') // "morelmaniac"
console.log(f(["ego", "code", "golf"])+'') // "codegolf"
console.log(f(["code", "ego", "golf"])+'') // "codegolf"
console.log(f(["golf", "ego", "code"])+'') // "codegolf"
console.log(f(['ab', 'bc', 'cd', 'de'])+''); // "abcde"
console.log(f(['de', 'bc', 'cd', 'ab'])+''); // "abcde"
console.log(f(["ab", "ba", "ca"])+''); // "caba"
```
The code is *excruciatingly* slow on the full alphabet example (not included for that reason in the above Snippet).
That is remedied by changing the `map`s to `some`s, for the loss of 2 bytes:
```
f=a=>a[1]?a.some((c,i)=>a.((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a
```
```
f=a=>a[1]?a.some((c,i)=>a.some((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a
console.log(f(["ab", "bc", "cd", "de", "ef", "fg", "gh", "hi", "ij", "jk", "kl", "lm", "mn", "no", "op", "pq", "qr", "rs", "st", "tu", "uv", "vw", "wx", "xy", "yz", "za"])+'');
console.log(f(["ab", "ba", "ca"])+''); // "caba"
```
] |
[Question]
[
[(This challenge is very similar, but this current challenge has additional complications.)](https://codegolf.stackexchange.com/questions/48531/ascii-doodling-laser-in-a-box)
---
Imagine a 2-dimensional room, where the walls are plated with flat mirrors.
Suddenly, a beam of light strikes into the room, where a piece of wall is missing! The lightbeam dances around the room, getting reflected by the wall mirrors, and eventually leaving the room again.
## The Logic
You are given 5 variables: *W, H, X, Y* and *Z*.
*Now, what do they mean?*
W, H is the size of the room (including the walls), with W being width and H being height.
X, Y is the coordinate that the wall has the hole at. You can assume that this is always located on a wall tile. Coordinates are 0-based, with the X-axis pointing right and the Y-axis pointing down.
Z is a single character, representing the direction that the light falls into the room, either `\` or `/`.
The room has to be built up of the following characters:
* `|` for horizontal walls
* `-` for vertical walls
* `+` for corners
Example: (W=7,H=4)
```
+-----+
| |
| |
+-----+
```
---
Now that we have a room, lets destroy one of the wall tiles, so a beam of light falls into the room. Beams of light are diagonal lines, represented by `\` and `/` characters.
Let's replace the wall tile at X=2, Y=0 with a `\` beam of light.
```
+-\---+
| |
| |
+-----+
```
The incoming light travels diagonally across the room until it hits a mirror wall. If a wall is hit, the direction inverts along the axis of the wall, and the beam travels on.
```
+-\---+
|\ \/\|
| \/\/|
+-----+
```
In this example, the light beam gets to a point where a corner of the wall is hit, which inflicts that the beam gets reversed completely and travels all the way back, eventually leaving the room.
## Your Task
Write a program that prints the room and the whole path of the light beam, until it leaves the room again or repeats into an infinite loop.
## Input
Input may be received in any reasonable format, but it has to include the 4 integers W, H, X, Y and the character Z, for example `[10, 8, 0, 3, \]`.
You may assume that:
* W, H >= 3
* X, Y are always located at a wall
* Z will only be able to contain the values `\` and `/`.
## Output
You can decide if you return a string or directly output to `stdout`.
It has to include the room's wall and the light beam (defined by the ASCII characters above).
## Rules
* Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes, in any language, wins.
* All coding languages that were created prior to the publication of this challenge are allowed.
## Examples
Input: `[5, 4, 2, 0, /]`
```
+-/-+
|/ /|
|\/ |
+---+
```
Input: `[20, 3, 0, 1, \]`
```
+------------------+
\/\/\/\/\/\/\/\/\/\|
+------------------+
```
Input: `[10, 8, 0, 3, \]` (Example of an infinite loop that won't leave the room again.)
```
+--------+
|/\/\/\/\|
|\/\/\/\/|
\/\/\/\/\|
|\/\/\/\/|
|/\/\/\/\|
|\/\/\/\/|
+--------+
```
---
Good luck!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
BNNJNNPψ↷⎇⁼δ/⎇∧⁻⁻θ¹ζIε⁷I3⎇∧IζIε⁵I1W¬℅KK«¹F³¿∧κ℅KK«↷κ¶↷κ
```
[Try it online!](https://tio.run/##hY/BT8IwFMbP61/x0tNrMqIDDQdPajxIAi6GI5fCimtW2tG1KBr@9trNkQAh8dCm3/t@35fXVcntynAVwpP5wlddezfzm6WwyFI4k@yBTPymnpv/qKlXTtZWaof7KHO5M@5dfpQO58Jqbvf4svVcNVikQG9obDjOH3WBU6l909/bFLJof8fzzBuHgsXXuBd0RNlFtpuf0/dHOot0u91nKZUAnBmHb7aQmivMhaiwdeGHJHm3eBbJZG0s4IiBXENXX6VwNZKcfLFqg30JXWj6Jy/8AzmEMCZ3ZEhuySIMdmHQqF8 "Charcoal – Try It Online") Link is to verbose version of code. Edit: I don't know why but that code isn't working right now. [Here](https://tio.run/##hY87b8IwFIXn@FdcZbqWjFpKKwamturQSkCEGFkMMcSKsYNj8xS/3XVSKgGq1MGWj8/57mNRcLswXIXwZvb4qSvvRn49FxYpgxtJB@TLr6up@S@Vya1xE7kqHE6F1dwe8GPjuaoxZ5A@pBH5/X/VOQ6l9vXl3jDoRvsYzzuvHQoaX30GvTumNW9TLw3atB965WRlpXZ4iHJXSCUAR8bh2OZSc4WZEGWclFI4kSRrk92YTJbGAvYoyCW0XUoGfyLJ1YZlA16KpDOd/sg7/0zOIfTJM3kij2QWOtvQqdU3 "Charcoal – Try It Online")'s a tweaked version instead. Explanation of the original code:
```
BNN
```
Draw the outer box.
```
JNNPψ
```
Move the cursor to the entry point and make a hole in the box at this point, so this becomes the background.
```
↷⎇⁼δ/⎇∧⁻⁻θ¹ζIε⁷I3⎇∧IζIε⁵I1P
```
Rotate to the appropriate direction to print the initial line segment.
```
W¬℅KK«¹
```
While the cursor is over a hole, draw the next line segment.
```
F³¿∧κ℅KK«↷κ¶↷κ
```
Look for a hole in which to draw the next line segment. This works by repeating the same code three times. The first time, nothing happens. The second time, if the cursor is not over a hole, it rotates right 45°, then takes one step to the right, then rotates right 45°. This has the effect of reflecting it in one axis. The third time, if the cursor is still not over a hole, it rotates right 90°, then takes one step to the right, then rotates right 90°. This has the effect of changing the reflection to the other axis. If there still isn't a hole, then a corner or infinite loop has been reached, so the outer loop halts.
] |
[Question]
[
Because it's Saturday (UTC) and I'm hungry, I would like a slice of pizza. I will give you an order and I would like a nice hot [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") pizza. Up to the challenge?
## The Drive-Thru
I'll place my order wherever your drive-thru is, whether it is STDIN, a function parameter, a command-line argument, but I'm not going to put it in a variable for you. (JS function expressions must be assigned to a variable.)
## The order
My order will have 2 parts. The first will be a positive, non-zero integer from `3` to `6`. This is the size of my pizza. For instance, a size `6` pizza with no toppings would look like:
```
/=====\
/ \
| |
| |
\ /
\=====/
```
A size `5`:
```
/====\
/ \
| |
\ /
\====/
```
A size `4`:
```
/===\
| |
| |
\===/
```
A size `3`
```
/==\
| |
\==/
```
## The toppings
My toppings will be a string of UPPERCASE letters. Here are the possible values:
```
P - Pepperoni
S - Sausage
N - piNeapple
J - Jalapenos
B - Banana peppers
C - baCon
```
You must fit them on the pizza somewhere. If I order a size 4 and `PSPCJ`, then this is a valid output:
```
/===\
|PSPCJ|
| |
\===/
```
So is this:
```
/===\
|P P J|
| S C |
\===/
```
And this:
```
/===\
| |
|PSPCJ|
\===/
```
I am not really picky about where my toppings are on the pizza, as long as they aren't on the crust or on top of each other.
## The pick-up window
I will go to a lot of places to pick up my pizza, including STDOUT, a file, the return value of a function, but not a variable.
## Extra stuff
* Standard loopholes forbidden
* **This is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins!**
* Don't worry about invalid input (toppings > pizza space, etc.)
* See my answer (JS ES6) below for an example (I hope you can do better)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~202,198,190,177,162,157,~~146 bytes
```
n,t=input()
y=n+1
s=' '
l=' /'+'='*(n-1)+'\\ '+('','\n/'+s*y+'\\')[n>4]+'\n|'
print l+t[:y].center(y,s)+('','|\n|'+t[y:].center(y,s))[y%2]+l[::-1]
```
[Try it online!](https://tio.run/nexus/python2#VYuxCsIwGIT3PEUXuaRJlIo4BOKgm4MIjmkGKYUWym9p4xDoazvHFCeX4@O@u0Qq2J7Gd@CCRUuyYrNFATbk3EHCouSkKyFR1wUkBxRqymYu49pBODodfEZawMapp1AMMjgT/bZpKbQTj2oWv@OyjrKM5k8KFzd7LwdnjK58SkeF@@N2PV/woZdunk3XfgE "Python 2 – TIO Nexus")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~224~~ ~~213~~ 195 bytes
```
n,t=eval(input())
k=n+1
y=print
i=0
f,s,e,b,p="/ =\\|"
t+=s*99
y(s+f+e*~-n+b)
if n>4:y(f+t[:k]+b);i+=k
y(p+t[i:i+k]+p);i+=k
if~-n%2:y(p+t[i:i+k]+p);i+=k
if n>4:y(b+t[i:i+k]+f);i+=k
y(s+b+e*~-n+f)
```
[Try it online!](https://tio.run/nexus/python3#dY3LCsIwEEX3@YoSEJJOxAfdNDJuFfUPrAsDHRgqIZgoFMRfj1kUXbk95z6yNwn75/Wm2IdHUlqLAT2sxIjhzj4JxqUgE01vnAkoFxV23UuKBBjrthWjikDQ1@@5B6cFU@W3jR0VQTrb4VLYhgGHkguFsGUoMEyQqdRma/tHTlPu5@i7FsFNr6Rzbow8HPe7k/wA "Python 3 – TIO Nexus")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~87~~ ~~81~~ 75 bytes
74 bytes of code, +1 for `-l` flag.
```
e:'/.'=Xa-1.'\Y['/'\]Xa//5J'|X2-a%2^xPs.ePy.(b.sXa*a-a-2-#b<>a+1).RVys.RVe
```
Takes input as command-line arguments. [Try it online!](https://tio.run/nexus/pip#@59qpa6vp24bkahrqKceExmtrq8eExuRqK9v6qVeE2Gkm6hqFFcRUKyXGlCpp5GkVxyRqJWom6hrpKucZGOXqG2oqRcUVlkMJFL///@vm/Pf9L@fk58fCAdDaT8nAA "Pip – TIO Nexus")
### Approach
`e` is the top row, such as `/=====\`. If you reverse it, it's also the bottom row.
`y` is the left border, such as `["/" "|" "|" "\"]`. If you reverse it, it's also the right border.
We then construct the middle by taking `b`, the toppings, padding it with spaces to length `(a+1)*(a-2)` (where `a` is the size), and grouping it into a list of rows.
Finally, we print the top row with a leading space; concatenate the middle between `y` on the left and `RVy` on the right, and print that; and print the bottom row with a leading space.
[Answer]
# JS (ES6), 257 255 249 248 246 244 bytes
```
m=s=>t=>(r="/",k="\\",p=" ",f="\n",x="|",c=f+x,q="",t=p+t,z=(s>2?p:q)+r+"=".repeat(s-1)+k+(s>4?f+r+p.repeat(++s)+k:q)+c+p.repeat(s)+x+(!s?c+p.repeat(s)+x:q)+p+(s>5?f+k+p.repeat(s)+r:q)+f+p+k+"=".repeat(s-2)+r,i=-1,z.replace(/ /g, x=>t[++i]||p))
```
Call it like `m(4)("PS")` for 1 pepperoni and 1 sausage. Probably can be golfed more.
[Answer]
## JavaScript (ES6), ~~170~~ 161 bytes
```
(n,t,a=[1,,n%2||2,,1])=>` /=\\
/___\\
|___|
\\___/
\\=/`[r=`replace`](/.+/g,s=>s.repeat(a.pop()||n>4))[r](/=|_\b/g,`$&`.repeat(n-1))[r](/_/g,_=>t[i++]||` `,i=0)
```
Starts by taking a misshapen pizza of width 2 and height 5 and stretches it horizontally and adjusts it vertically as appropriate, then replaces the interior with toppings or spaces once they run out.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
Nθ /==×=⸿/›θ⁴⸿|‖BO↓﹪θ²‖BO⊕﹪θ²J¹¦¹⪪S⊕θ
```
[Try it online!](https://tio.run/##fY@xDoIwEIZ3n6Lp1CY1BMOkYVETA4lKhJGlwqEkpYXaYkx89woOaBwc78/33X9XXLkuFBfORbK15mCbM2jS0dUs0bU0BCMvDPE0ZnUDN4LDXHuYoZ0GbkacoYDSj5Pr56icoBJQmLU1A1SJx7EHLXhLllt1lwztVWmFGuUF/UNHstDQgDRQkh8ltk2bKeIz5E/laStqQ97PpGZILoQy9L2jGy91LpglabKJ3bwXLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the size of the pizza.
```
/==
```
Start printing the top of the pizza.
```
×=⸿/›θ⁴
```
If the pizza is one of the larger sizes, add extra to the top and side.
```
⸿|
```
Print more of the side of the pizza.
```
‖BO↓﹪θ²
```
Complete the left half of the pizza by reflection with possible overlap.
```
‖BO⊕﹪θ²
```
Complete the pizza by reflection with variable overlap.
```
J¹¦¹⪪S⊕θ
```
Input the toppings and split them into pieces so they will fit inside the pizza.
] |
[Question]
[
Problem: Slot Machine Hacker from [Facebook Hacker Cup 2011 Round 1B](http://www.facebook.com/hackercup/problems.php/?round=167482453296629)
Goal: Shortest code in your favourite language using stdin/stdout. You cannot assume `getRandomNumber` is defined, i.e. your solution has to include a potentially golfed version as a function or in some other way.
Reference solution: [on SO](https://stackoverflow.com/questions/4812640/facebook-hacker-cup-subround-1b-slot-machine-hacker/4815172#4815172) [I chose mine, because it uses stdin/stdout and I'm unsure about dave's solution.]
Problem text follows:
You recently befriended a guy who writes software for slot machines. After hanging out with him a bit, you notice that he has a penchant for showing off his knowledge of how the slot machines work. Eventually you get him to describe for you in precise detail the algorithm used on a particular brand of machine. The algorithm is as follows:
```
int getRandomNumber() {
secret = (secret * 5402147 + 54321) % 10000001;
return secret % 1000;
}
```
This function returns an integer number in [0, 999]; each digit represents one of ten symbols that appear on a wheel during a particular machine state. **secret** is initially set to some nonnegative value unknown to you.
By observing the operation of a machine long enough, you can determine value of **secret** and thus predict future outcomes. Knowing future outcomes you would be able to bet in a smart way and win lots of money.
## Input
The first line of the input contains positive number **T**, the number of test cases. This is followed by **T** test cases. Each test case consists of a positive integer **N**, the number of observations you make. Next **N** tokens are integers from 0 to 999 describing your observations.
## Output
For each test case, output the next 10 values that would be displayed by the machine separated by whitespace.
If the sequence you observed cannot be produced by the machine your friend described to you, print `"Wrong machine"` instead.
If you cannot uniquely determine the next 10 values, print `"Not enough observations"` instead.
## Constraints
* T = 20
* 1 ≤ N ≤ 100
* Tokens in the input are no more than 3 characters long and contain only digits 0-9.
Example input
```
5
1 968
3 767 308 284
5 78 880 53 698 235
7 23 786 292 615 259 635 540
9 862 452 303 558 767 105 911 846 462
```
## Example output
```
Not enough observations
577 428 402 291 252 544 735 545 771 34
762 18 98 703 456 676 621 291 488 332
38 802 434 531 725 594 86 921 607 35
Wrong machine
```
[Answer]
# Python, 293 chars
```
import sys
n=1e7+1
for s in[map(int,x.split())for x in sys.stdin][1:]:
Q=[]
for i in range(s[1],n,1e3):A=[i];R=[A.append((A[-1]*5402147+54321)%n)or A[-1]%1e3for x in[0]*8+s];Q+=[R[-10:]]*(R[:-10]==s[2:])
print Q and["%d "*10%tuple(Q[0]),"Not enough observations"][len(Q)>1]or"Wrong Machine"
```
[Answer]
# Python, 316 characters
```
C=10**7+1
G=lambda:(s*5402147+54321)%C
import sys
I=map(int,sys.stdin.read().split())[1:]
while I:
n=I[0]+1;S=range(C)
for x in I[1:n]:S=[G()for s in S if s%1000==x]
if len(S)-1:V="Not enough observations"if S else"Wrong machine"
else:
s=S[0];V=""
for i in range(10):V+="%d "%(s%1000);s=G()
print V;I=I[n:]
```
] |
[Question]
[
The majority function is a boolean function which takes three boolean inputs and returns the most common. For instance if `maj(x,y,z)` is the majority function and `T` denotes true and `F` denotes false then:
```
maj(T,T,T) = T
maj(T,T,F) = T
maj(T,F,F) = F
maj(F,F,F) = F
```
This question concerns writing boolean functions as compositions of majority functions. An example of a 5-ary composition of majority functions is `(x1,x2,x3,x4,x5) => maj(x1,x2,maj(x3,x4,x5))`. This function returns the following output on these sample input vectors:
```
(T,T,F,F,F) => maj(T,T,maj(F,F,F)) = maj(T,T,F) = T
(T,F,T,T,F) => maj(T,F,maj(T,T,F)) = maj(T,F,T) = T
(T,F,T,F,F) => maj(T,F,maj(T,F,F)) = maj(T,F,F) = F
(F,F,F,T,T) => maj(F,F,maj(F,T,T)) = maj(F,F,T) = F
```
## Task
Write a program which inputs a positive integer n and a list of length n vectors of booleans and outputs a tree of majority gates that returns true on all of the given vectors if possible. The function may return either true or false on vectors not in the list of constraints.
* The list of vectors may be input in any format you like. If you prefer, instead of inputting the vector, you may input the list of true positions in the vector. So for instance, `[TTF,TFT,FTT]` or `[[T,T,F],[T,F,T],[F,T,T]]` or `[[1,2],[1,3],[2,3]]` (list of true positions) are all fine.
* Output can be any valid tree format. For instance, `maj(maj(x1,x2,x3),x4,x5)` works. You will probably want to use single numbers as stand-ins for variables, as in `[[1,2,3],4,5]`. Reverse polish `123m45m` is also okay, for instance.
* If there is no function that works, your program should generate an error or output a falsey value.
* If there are multiple functions that work, your program can return any of them. The function does not need to be simplified. For instance, `maj(x1,x1,x2)` or `x1` are equivalent.
## Scoring
This is code golf: Shortest solution in bytes wins.
## Test cases:
Note that there are many possible outputs for each of these cases, so you should write a checker script that converts your output to a function and check that your function returns true on each of the specified input vectors.
```
Input: 3, [TFF]
Output: 1 or [1,1,2] or [1,[1,2,2],[1,1,3]] or other equivalent
Input: 3, [TFF,FTF]
Output: Falsey or error (it's not possible)
Input: 3, [TTF,TFT]
Output: [1,2,3] or 1 or other equivalent
Input: 3, [TTF,TFT,FTT]
Output: [1,2,3] or [1,3,2] or other equivalent
Input: 4, [TTFF,TFTF,FFTT]
Output: Falsey or error
Input: 4, [TTTF,TTFT,TFTT,FTTT]
Output: [1, 2, 3] or [2,3,4], or many other options
Input: 5, [TTTFF,FTTFT,TFFFT]
Output: [1,[1,[1,2,5],[2,4,5]],3] or many other options
Input: 6, [TTTFFF,FTFTTF,TFFTFT]
Output: [1, 2, 4] or [1, [1, 2, 4], [2, 3, 4]] or others
Input: 5, [TTTFF,TTFTF,TTFFT,TFTTF,TFTFT,TFFTT,FTTTF,FTTFT,FTFTT,FFTTT]
Output: [[1, [1, 3, 5], 4], [1, 2, [2, 4, 5]], [2, 3, [3, 4, 5]]] or others
Input: 7, [TTTTFFF,TTTFTFF,TTTFFTF,TTTFFFT,TTFTTFF,TTFTFTF,TTFTFFT,TTFFTTF,TTFFTFT,TTFFFTT,TFTTTFF,TFTTFTF,TFTTFFT,TFTFTTF,TFTFTFT,TFTFFTT,TFFTTTF,TFFTTFT,TFFTFTT,TFFFTTT,FTTTTFF,FTTTFTF,FTTTFFT,FTTFTTF,FTTFTFT,FTTFFTT,FTFTTTF,FTFTTFT,FTFTFTT,FTFFTTT,FFTTTTF,FFTTTFT,FFTTFTT,FFTFTTT,FFFTTTT]
Output: [[[1, [1, [1, 4, 7], 6], 5], [1, [1, 3, [3, 6, 7]], [3, 5, [5, 6, 7]]], [3, 4, [4, [4, 5, 7], 6]]], [[1, [1, [1, 4, 7], 6], 5], [1, 2, [2, [2, 5, 7], 6]], [2, [2, 4, [4, 6, 7]], [4, 5, [5, 6, 7]]]], [[2, [2, [2, 4, 7], 6], 5], [2, 3, [3, [3, 5, 7], 6]], [3, [3, 4, [4, 6, 7]], [4, 5, [5, 6, 7]]]]]
```
[Answer]
# JavaScript (ES6), 260 bytes
Takes input as an array of arrays of booleans. Returns a tree of 1-indexed majority gates or throws a recursion error (1) if no solution exists.
The main function **f()** recursively attempts to find a solution by calling the solver **F()** and incrementing the maximum nesting level **m** at each iteration.
*(1) after a **long** time, and assuming infinite memory*
```
f=(a,m)=>(F=(a,d,I=a[i=0].map(_=>++i),g=(a,b)=>b[1]?b.reduce((s,i)=>s+g(a,i),0)>1:a[b-1])=>I.find(i=>a.every(a=>g(a,i)))||d&&(I.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).some(b=>r=b.length==3&&F(a.map(a=>[...a,g(a,b)]),d-1,[...I,b]))&&r))(a,m)||f(a,-~m)
```
### Demo
```
f=(a,m)=>(F=(a,d,I=a[i=0].map(_=>++i),g=(a,b)=>b[1]?b.reduce((s,i)=>s+g(a,i),0)>1:a[b-1])=>I.find(i=>a.every(a=>g(a,i)))||d&&(I.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).some(b=>r=b.length==3&&F(a.map(a=>[...a,g(a,b)]),d-1,[...I,b]))&&r))(a,m)||f(a,-~m)
test = a => console.log(JSON.stringify(f(a.split(',').map(s => [...s].map(c => c == 'T')))))
test('TFF')
test('TTF,TFT')
test('TTF,TFT,FTT')
test('TTTF,TTFT,TFTT,FTTT')
test('TTTFF,FTTFT,TFFFT')
test('TTTFFF,FTFTTF,TFFTFT')
test('TTTFF,TTFTF,TTFFT,TFTTF,TFTFT,TFFTT,FTTTF,FTTFT,FTFTT,FFTTT')
```
### Example
Below is a validation table of the solution found for the last test case of the demo.
```
12345 | [5,[1,2,4],[3,4,[1,2,3]]]
------+-------------------------------------------------------------
TTTFF | [F,[T,T,F],[T,F,[T,T,T]]] --> [F,T,[T,F,T]] -> [F,T,T] --> T
TTFTF | [F,[T,T,T],[F,T,[T,T,F]]] --> [F,T,[F,T,T]] -> [F,T,T] --> T
TTFFT | [T,[T,T,F],[F,F,[T,T,F]]] --> [T,T,[F,F,T]] -> [T,T,F] --> T
TFTTF | [F,[T,F,T],[T,T,[T,F,T]]] --> [F,T,[T,T,T]] -> [F,T,T] --> T
TFTFT | [T,[T,F,F],[T,F,[T,F,T]]] --> [T,F,[T,F,T]] -> [T,F,T] --> T
TFFTT | [T,[T,F,T],[F,T,[T,F,F]]] --> [T,T,[F,T,F]] -> [T,T,F] --> T
FTTTF | [F,[F,T,T],[T,T,[F,T,T]]] --> [F,T,[T,T,T]] -> [F,T,T] --> T
FTTFT | [T,[F,T,F],[T,F,[F,T,T]]] --> [T,F,[T,F,T]] -> [T,F,T] --> T
FTFTT | [T,[F,T,T],[F,T,[F,T,F]]] --> [T,T,[F,T,F]] -> [T,T,F] --> T
FFTTT | [T,[F,F,T],[T,T,[F,F,T]]] --> [T,F,[T,T,F]] -> [T,F,T] --> T
```
[Answer]
# Mathematica, 121 bytes
An anonymous function which takes its second argument as a list of the lists of true positions in the vector of booleans.
```
f[n_][s_]:=If[n<3,(Intersection@@s)[[1]],{#/. 2->1,#2/.{2->1,3->2},#3}&@@(1+f[n-1]/@(s-1/.{{0->1},{1->2,0->1},{0->2}}))]
```
Formatted slightly nicer:
```
f[n_][s_] := If[n < 3, (Intersection @@s)[[1]],
{# /. 2 -> 1, #2 /. {2 -> 1, 3 -> 2}, #3} & @@
(1 + f[n - 1] /@ (s - 1 /. {{0 -> 1}, {1 -> 2, 0 -> 1}, {0 -> 2}}))]
```
\$\def\maj{\mathrm{maj}}\def\T{\mathrm{True}}\def\F{\mathrm{False}}\$
If there are fewer than three variables, intersect the constraint vectors to see if there is a common "True" in all of the constraints. If there is one, then the constant function (x\_1,x\_2) --> x\_i works, otherwise it is impossible (and will throw an error by trying to take the first element of an empty list).
Otherwise, substitute \$f\_1=f(x\_1,x\_1,x\_2,x\_3,\ldots,x\_{n-1})\$, \$f\_2=f(x\_1,x\_2,x\_2,x\_3,\ldots,x\_{n-1})\$, and \$f\_3=f(x\_1,x\_2,x\_1,x\_3,\ldots,x\_{n-1}))\$, recursively solve each of these, then set \$f=\maj(f\_1(x\_1,x\_3,x\_4,\ldots,x\_n), f\_2(x\_1,x\_2,x\_4,\ldots,x\_n),f\_2(x\_2,x\_3,x\_4,\ldots,x\_n))\$.
### Explanation:
This is a recursive algorithm that reduces the problem of finding a solution of an \$n\$ variable problem to finding three solutions to \$n-1\$ variable problems. The key observation that makes this work is that for \$f\$ one of the functions we are looking for we have:
\$f(x\_1,\ldots,x\_n)=\maj(f(x\_1,x\_1,x\_3,x\_4,\ldots,x\_n),f(x\_1,x\_2,x\_2,\ldots),f(x\_3,x\_2,x\_3,\ldots))\$
In the first position, we replaced \$x\_2\$ with \$x\_1\$, in the second position \$x\_3\$ with \$x\_2\$ and in the third position \$x\_1\$ with \$x\_3\$.
Once you know this identity, the algorithm is clear: when there are two or fewer variables, the problem is trivial. Otherwise, recursively solve the three problems of representing \$f(x\_1,x\_1,x\_3,x\_4,\ldots,x\_n)\$, \$f(x\_1,x\_2,x\_2,x\_4,\ldots,x\_n)\$, and \$f(x\_3,x\_2,x\_3,x\_4,\ldots,x\_n))\$ and take the majority of them.
Why is this true? Well the majority function satisfies two properties:
1. It is "complementary". That is, if \$!x\$ is the negation of \$x\$, then \$\maj(!x,!y,!z)=!\maj(x,y,z)\$. As a consequence, every function we can build out of the majority function is complementary.
2. It is monotonic. That is, \$\maj(x,y,\F)\leq \maj(x,y,\T)\$. In general, if we say that \$\F\leq \T\$ and say \$(x\_1,\ldots,x\_n)\leq (y\_1,\ldots, y\_n)\$ if \$x\_i\leq y\_i\$ for all \$i\$, then I say a function \$f\$ is monotonic if \$(x\_1,\ldots x\_n)\leq(y\_1,\ldots, y\_n)\$ implies \$f(x\_1,\ldots x\_n)\leq f(y\_1,\ldots, y\_n)\$. The composition of monotonic functions is monotonic so every function we can build out of the majority function is monotonic.
It turns out that complementary monotonic functions are exactly the class of functions that can be built out of majority gates.
Now, we show that for \$f\$ a complementary monotonic function, our identity holds:
\$f(x\_1,\ldots,x\_n)=\maj(f(x\_1,x\_1,x\_3,x\_4,\ldots,x\_n),f(x\_1,x\_2,x\_2,x\_4,\ldots,x\_n),f(x\_3,x\_2,x\_3,x\_4,\ldots,x\_n))\$
Let's set \$f\_1(x\_1,x\_2,x\_3,\ldots,x\_n)=f(x\_1,x\_1,x\_3,x\_4,\ldots,x\_n)\$, \$f\_2(x\_1,\ldots,x\_n)=f(x\_1,x\_2,x\_2,x\_4,\ldots,x\_n)\$ and \$f\_3(x\_1,\ldots,x\_n)=f(x\_3,x\_2,x\_3,x\_4,\ldots,x\_n)\$. To show that \$f=\maj(f\_1,f\_2,f\_3)\$, we need to show that for any input, at least two of \$f\_1\$, \$f\_2\$, and \$f\_3\$ are equal to \$f\$. We divide up into cases based on the values of \$x\_1\$, \$x\_2\$ and \$x\_3\$. If \$x\_1=x\_2=x\_3\$ then \$f\_1=f\_2=f\_3=f\$.
Suppose not all of \$x\_1\$, \$x\_2\$, and \$x\_3\$ are the same. By permuting the variables of \$f\$, we can assume that \$x\_1=x\_2\$ and \$x\_3\$ is different and because \$f\$ is complementary, it suffices to deal with the case \$x\_1=x\_2=\F\$ and \$x\_3=\T\$. In this case, \$(x\_1,x\_1,x\_3)=(\F,\F,\T)=(x\_1,x\_2,x\_3)\$, \$(x\_1,x\_2,x\_2)=(\F,\F,\F)\leq (x\_1,x\_2,x\_3)\$ and \$(x\_3,x\_2,x\_3)=(\T, \F, \T) \geq (x\_1,x\_2,x\_3)\$. By monotonicity we deduce that \$f\_2\leq f\_1=f\leq f\_3\$. If \$f=\F\$ then \$f\_2\leq \F\$ implies \$f\_2=\F=f\$ and if \$f=\T\$ then \$f\_3\geq \T\$ implies \$f\_3=\T\$. Thus, at least two of \$f\_1\$, \$f\_2\$, and \$f\_3\$ are equal to \$f\$ in all cases so \$f=\maj(f\_1,f\_2,f\_3)\$.
] |
[Question]
[
A loop is a pretty simple algebraic structure. It is a tuple **(G,+)** where **G** is a set and **+** is a binary operator **G × G → G**. That is **+** takes two elements from **G** and returns a new element. The operator is also required to fulfill two properties
* Cancellation: For every **a** and **b** in **G** there exists unique **x** and **y** in **G** such that
```
a + x = b
y + a = b
```
* Identity: There is an **e** in **G** such that for every **a** in **G**
```
e + a = a
a + e = a
```
If you are familiar with the concept of a group you might notice that a loop is just a group that doesn't have an associative property.
Loops are pretty simple so people like to add more rules to make new structures that are more interesting. One such structure is a [Moufang loop](https://en.wikipedia.org/wiki/Moufang_loop) which is a loop that also satisfies the following four identities forall **x**, **y** and **z** in **G**
```
z + (x + (z + y)) = ((z + x) + z) + y
((y + z) + x) + z = y + (z + (x + z))
(z + x) + (y + z) = (z + (x + y)) + z
(z + x) + (y + z) = z + ((x + y) + z)
```
For example the following Cayley table represents a Moufang loop:
```
0 1 2 3
1 0 3 2
2 3 0 1
3 2 1 0
```
*(If you are not familiar a Cayley table is a square matrix **M** where **Mi,j** is equal to **i + j**. It is a handy way for representing binary operators on a set.)*
We can show that there is an identity rather easily it is `0`. Cancellation is a little harder to show but a brute force approach yields this table
```
b a → 0 1 2 3
↓
0 0 1 2 3
1 1 0 3 2
2 2 3 0 1
3 3 2 1 0
```
Where our elements are the solutions to
```
a + x = b = x + a
```
*(You may notice that this table is identical to our Cayley table. I'll leave it as an exercise to the reader to figure out why this is the case for this Moufang loop)*
Now we need to verify the Moufang identities for our structure. There are two ways to do this for the particular structure the first way is to realize that it is associative and thus automatically fulfills the criteria, however this will not work in general so we would rather brute force the result. There are 3 free variables each with a potential of 4 values in every expression here. This means we have to perform 7\*43 or 448 computations. I'll leave out the raw computations but [here is some Haskell you can use to verify this](https://tio.run/##lY8xb8IwEIX3/IoLYrAlGyVhK2VlohOdGkWVaUxjATYKjhRH/e/pOa0jGFoUD0/n5/N97ypxPcrTqe85h1IelJZgKwkvpjkI/QlbYy5A3t4zaAGVAueRgBj2sAYSx4LOUfc0jyCcPGEpy9iyYDdeyhK2ZNmdhz3opnce9uDvpCiis1AaGaWJ4NLYna23GmYbVV8tqFJqq6x7mq3wsVbawhyELiHvMBlpvfjKUQprjDlcWorSeXFf3TPPk8UCI7Zj5UJVrG6JO/lhcPLfSEJcGPyD8EgXIgxhOkqnIF8rVf9LHNcJaL/kSPNbozuFuDFNbaupyIH4ixzMR8i@/wY "Haskell – Try It Online").
# Task
Given a positive integer **n** as input output the number of Moufang loops that have order **n**. (the order of a group is the size of the set)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
# Test cases
Here is the number of Moufang loops for the first **71** inputs
```
1,1,1,2,1,2,1,5,2,2,1,6,1,2,1,19,1,5,1,6,2,2,1,20,2,2,5,5,1,4,1,122,1,2,1,18,1,2,2,19,1,7,1,5,2,2,1,103,2,5,1,6,1,17,2,17,2,2,1,18,1,2,4,4529,1,4,1,6,1,4,1
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~475~~ 410 bytes
Thanks to Mr.Xcoder for saving some bytes!
Use the symmetry of the formula to save 65 bytes. Yes, that's a lot.
```
from itertools import*
n=int(input())
P=permutations
R=[*range(n)]
u=[]
A=all
S=sorted
for T in P(P(R),n):u+=[T]*(A(A(R==S(x)for x in
t)and any([*x]==S(x)for x in t)and
A(t[z][t[x][t[z][y]]]==t[t[t[z][x]][z]][y]and
t[t[z][x]][t[y][z]]==t[t[z][t[x][y]]][z]for x in R
for y in R for z in R)for t
in(T,[*zip(*T)]))and A(A(1-A(p[T[i][j]]==U[p[i]][p[j]]for i in R
for j in R)for p in P(R))for U in u))
print(len(u))
```
[Try it online!](https://tio.run/##VVBNa8MwDL37V/goZ@1hbKeBD/kHIU1PwodA080lkY2jQNI/n8kuWzcM8nvS02fc@CvQ275fU5i05yFxCOOs/RRD4kqR9cTgKS4MxqjGxiFNC/fsA82qtVilnj4HIOPUYtGp2vbjqE52lvThoq4h6U570g000JoDmY/lxWLnKqjltdaeYDVZtYpKsenponvaAKvV/Q/qElQ1MN4dMq7ZCNqcEyUjP@jqnHzZndV/nCyuHHlof0rkbCG/Tdoy8lagzvBeYJmClSfoDljdfYSqM86UcfMir8caInboHd5yizNGwU6s0Jzrn8Vvz4rxcZrWFHbObJEzx5SvPg4Ewvb9/Rs "Python 3 – Try It Online")
---
Some `and` can be replaced by `*`, results in lower bytecount but at the cost of significantly slower execution time:
# [Python 3](https://docs.python.org/3/), ??? bytes
[TODO put code here]
(of course not all `*` makes the program significantly slower, only some of them are critical)
---
Ungolfed:
```
from itertools import *
n = 4 # int(input())
rangeN = list(range(n))
def is_moufang_loop(T):
A = tuple(zip(*T))
return all(
all(sorted(x) == rangeN for x in t)
and any(list(x) == sorted(x) for x in t)
and all(
T[z][T[x][T[z][y]]] == T[T[T[z][x]][z]][y]
and T[T[z][x]][T[y][z]] == T[T[z][T[x][y]]][z]
for x in rangeN for y in rangeN for z in rangeN)
for t in (T, A)
)
def isomorphic(loop1, loop2):
for p in permutations(rangeN):
if all(
p[loop1[i][j]] == loop2[p[i]][p[j]]
for i in rangeN
for j in rangeN
): return True
return False
unique_moufang_loops = []
for x in [
cayley_table
for cayley_table in permutations(permutations(rangeN), n)
if is_moufang_loop(cayley_table)
]:
if all(not isomorphic(x, y) for y in unique_moufang_loops):
unique_moufang_loops.append(x)
print(len(unique_moufang_loops))
```
[Try it online!](https://tio.run/##dVNNb8MgDL3zKyztAlM1aR@nSj3ssuNO3BCqspVsTAQYIVLSP9/ZSZuPNkNKiP3sB352Ype/g38@ncoUKrDZpByCq8FWMaQM98zDDl7gDqzP3PrYZC4ES4X/Mu@IOFtn3lvco58dTAm23lehKdG5dyFELsWWAa5XjM9NdIYfbeT3EuPJnUxukofCOd7btMio8Xxz4K2A3Q7OB5YhQYtXgSymWH/Ap@P9VYboKfXfhPlplyXVUSupWnrhV6e1Jjap5OBotcaNgEUq8c0iJOIUdkm9cBIdGovU8Xqz@ror@zjZUw0EZAK43MDr4B/lD1VI8dt@cpL/cQO0PZ2bQImREqNJVZOLbIOv@Zl@O/Lb8laiqHo@ZbX6GcrriVVEj8Y3Om@Ks9Plb7CfFUxsL/MgU2Pm8/FWuNow1nj725jFgNU4V0qzUUs1sn0WnTPdPhcfzsBCuwVyrcaaNBvwYq7O9ZDPCQXTg5JnFX3I8660G@jE1Oq1imadWIMfihiNpwFnLCb6M53xfJVInE4vfw "Python 3 – Try It Online")
No scroll bars...
---
Explanation:
The program is pretty simple.
* Each possible "binary operator" is represented by a Cayley table (0-indexing).
* The "identity" property implies that there exists `e` such that both the `e`'th row and the `e`'th column are equal to `[0, 1, 2, ..., n-1]`, which is the same condition as
>
> both the array `T` and its transpose has a row equal to `[0, 1, 2, ..., n-1]`.
>
>
>
* The "cancellation" property is equivalent to
>
> Every row and every column are a permutation of `[0, 1, 2, ..., n-1]`.
>
>
>
So, the part
```
all(
all(sorted(x) == rangeN for x in t)
and any(list(x) == sorted(x) for x in t)
for t in (T, A))
```
of the code checks that. (for all row in the array `T` and its transpose `A`, it being sorted is equal to `rangeN`, and there exists a row in both `T` and `A` that equals to itself being sorted)
The four conditions of a Moufang loops are checked manually.
```
z + (x + (z + y)) = ((z + x) + z) + y
((y + z) + x) + z = y + (z + (x + z))
(z + x) + (y + z) = (z + (x + y)) + z
(z + x) + (y + z) = z + ((x + y) + z)
```
In the code, `(a + b)` is represented as `T[a][b]`. (because of the representation as Cayley table). Use Python chaining equality comparison to avoid duplication of `(z + x) + (y + z)`.
However, because the formula is symmetric:
If we switch the operands of `+` in the first formula, we get the second formula; and if we switch the operands of `+` in the third formula, we get the fourth formula with `x` and `y` swapped place.
Note that the transposition of the Cayley table is equivalent to the binary operators having operands swapped. (`x + y -> y + x`)
Finally, all the candidates Cayley table are picked from
```
permutations(permutations(rangeN), n)
```
so that each row is a permutation of `rangeN` (which is `[0, 1, 2, ..., n-1]`) and there are `n` distinct rows.
] |
[Question]
[
A lawn is defined as a rectangular field with of one character surrounded by two layers of **visible** whitespace. This means two lines above and twos lines below, and a two space padding on the left (the right has visible whitespace, so you do not need to include it).
```
|||||
|||||
|||||
```
A mowed lawn is a similar structure, except that the main character is a shortened version of the first character.
```
.....
.....
.....
```
A mower is two different characters, different than the two lawn characters. Here is an example, with `=` as the back of the mower and `o` as the front:
```
=o
```
A mower will move around the lawn vertically, and can also rotate on its front. The above mower may look like any of the below during some point in the animation:
```
=o
o=
o
=
=
o
```
The mower can start on any set of the below positions on the below lawn. Mowers with `o` would drive around the lawn clockwise. Mowers with `0` would drive around the lawn counterclockwise.
```
= =
0 o
=o|||||0=
|||||
=0|||||o=
o 0
= =
```
The animation starts at second 0. Each second, the mower moves forward one space, and cut the grass on its front. When the mower vacates a spot, it appears cut. When the mower front reaches the last uncut item on a line (and there is still uncut grass), the mower back rotates once so as to continue the current mow (staying in clockwise/counterclockwise based on original position) When the mower is finished, it continues straight (mowing already cut grass) until it is completely off the lawn.
With a mower starting in the left top, this shows the basic progression for a 5x3 lawn:
```
Second 0 Second 1 Second 2 Second 3 Second 4 Second 5 Second 6 Second 7 Second 8 Second 9 Second 10 Second 11 Second 12 Second 13 Second 14 Second 15 Second 16 Second 17 Second 18 Second 19 Second 20 Second 21 Second 22
=
=o||||| =o|||| =o||| .=o|| ..=o| ...=o ....o ....= ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... .....
||||| ||||| ||||| ||||| ||||| ||||| ||||| ||||o ||||= ||||. ||||. ||||. ||||. ||||. ||||. o|||. =o|||. =o||. .=o|. ..=o. ...=o ....=o .....=o
||||| ||||| ||||| ||||| ||||| ||||| ||||| ||||| ||||o ||||o= |||o= ||o=. |o=.. o=... o.... =.... ..... ..... ..... ..... ..... ..... .....
=
```
# Input
Your input will be the dimensions of the lawn (two integers).
# Output
Print the lawn and the mower in your chosen position. You may chose the four characters for grass, cut grass, mower front, and mower back. You only to need enough whitespace to show the current second's content to specs, but extra whitespace is completely allowed, as long as it looks the same.
Since this is an [animation](/questions/tagged/animation "show questions tagged 'animation'"), you may either clear the output each second, or print enough newlines to appear to animate in the viewing frame (you may assume the viewing frame is the size needed to appear to animate).
A consistent time interval other than one second is allowed (i.e. 999 millis to save a byte, or two seconds for some reason), but it should be such that the lawn mower still appears to be moving naturally.
If possible, provide a visual (TIO, Snippet, GIF, etc.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
## JavaScript (ES6/Node.js), ~~664~~ ~~525~~ 523 chars
```
f=(w,h)=>{Z=require('sleep');c=a=>console.log(a);X=1;Y=2;D='e';N='|';O={'|':[0,-1],'e':[1,0],'s':[0,1],'w':[-1,0]};S=[N,D,'s','w'];q=d=>F[Y+O[d][1]][X+O[d][0]];b=' '.repeat(w+4),U=' ';F=[b,b].concat([...Array(h)].map(x=>U+N.repeat(w)+U)).concat([b,b]).map(x=>x.split``);for(;;){f=F.map(a=>a.concat());f[Y][X]='@';d=O[D];f[Y-d[1]][X-d[0]]='=';c(f.map(x=>x.join``).join`\n`);if(F[Y][X]==N)F[Y][X]='.';d=O[D],f=q(D),R=S[(S.indexOf(D)+1)%4],r=q(R);(r==N)&&((f==' ')||(f=='.'))?D=R:(X+=d[0],Y+=d[1])
Z.msleep(1E3);c('\033[2J')}}
```
Unminified with comments:
```
f=(w,h)=>{
Z = require('sleep');
c=a=>console.log(a);
//mower coordinates
X = 1;
Y = 2;
//mower direction
D='e'; //n/e/s/w
N='|';
//directions with amount of change in [x,y] coordinates
O = {'|':[0,-1],'e':[1,0],'s':[0,1],'w':[-1,0]};
//direction short names
S=[N,D,'s','w'];
//query for item in specified direction relative to mower
q=d=>F[Y+O[d][1]][X+O[d][0]];
//generate field + whitespace
b=' '.repeat(w+4),U=' ';
F=[b,b].concat([...Array(h)].map(x=>U+N.repeat(w)+U)).concat([b,b]).map(x=>x.split``);
for(;;){
//print the field:
//make a copy of the field, so we can paste the mower on top of it
f=F.map(a=>a.concat());
//print mower head
f[Y][X]='@';
//print mower tail
d = O[D];
f[Y-d[1]][X-d[0]]='=';
c(f.map(x=>x.join``).join`\n`);
//-----
//move the mower
if(F[Y][X]==N)F[Y][X]='.';//cut the grass if we stand on some
d=O[D],//how many fields to move forward
f=q(D),//item in front of mower
R=S[(S.indexOf(D)+1)%4],//name of direction if we rotate to the right
r=q(R);//item to right of mower
//if there is wall in front of me OR cut grass in front of me and uncut on the right, turn right, else go ahead
(r==N) && ((f==' ') || (f=='.'))?D=R:(X+=d[0],Y+=d[1])
Z.msleep(1E3);
c('\033[2J');
};
}
//test script
f(3,3);
```
note: I suppose I should get of the 'sleep' package and rewrite with setTimeout to be nodejs independent
] |
[Question]
[
Given the state of a square Game of Life grid, determine whether it could have evolved from any previous state, or could only have been created. That is, identify whether the state is a ["Garden of Eden" state](https://en.wikipedia.org/wiki/Garden_of_Eden_%28cellular_automaton%29).
# Input
A square grid of states, with 1 indicating "alive" and 0 indicating "dead". You may choose any two distinguishable symbols instead of 0 and 1 if you wish.
The side length of the grid will not be zero, but may be any natural number 1 <= N <= 20.
Any or all of the cells outside the input grid may be alive at this generation, and any or all of them may have been alive in the previous generation. The universe to be considered is infinite, so there are no boundary conditions. The edges of the input are not the edges of the universe. Specifically, the grid does not wrap.
The input may be in the form of a row delimited string, or a single string. If you wish, you may take the side length or the area of the grid as an additional input (before or after the grid).
Acceptable input formats:
```
010,101,010
010101010
010
101
010
3 010101010
```
# Output
"Created" if there is no possible previous state (including states larger than the input grid) that would lead to the input state on the next generation.
"Evolved" if there exists at least one possible previous state (including states larger than the input grid) that would lead to the input state on the next generation.
You may use any two distinguishable strings or numbers instead of "Created" and "Evolved" if you wish.
Note that the possible previous state need not be distinct from the input. If a state has itself as the next generation, then it should be considered evolved.
### Test cases
```
010
101
010 Evolved
0101110100
0010101001
1011100110
0101111101
1001001111
1111001001
1011111010
0110011101
1001010100
0010111010 Created
```
The created test case is taken from [Achim Flammenkamp's Game of Life Page](http://wwwhomes.uni-bielefeld.de/achim/orphan.html).
### Note
Thanks to trichoplax for writing this challenge and I adopted it from [here](https://codegolf.meta.stackexchange.com/questions/7804/secret-santas-sandbox/10061#10061)
[Answer]
# Java- 1254 bytes- a very poor solution
```
import java.util.Arrays;
public class z{
static boolean u=1>0,v=0<1;
public static void main(String[] a){
int y=a.length,x=a[0].length();Boolean[][] l=new Boolean[x][y];for(int i=0;i<a.length;i++){l[i]=m(a[i]);}
Boolean[] n=new Boolean[x*y];for(int i=0;i<n.length;i++){n[i]=v;}
while(n.length==x*y){Boolean[][] o=new Boolean[x][y];for(int i=0; i<n.length;i++){o[i%x][i/x]=n[i];}
n=p(n);o=q(o,x,y);int r=0;for(int i=0;i<x*y;i++){if(o[i%x][i/x]&&l[i%x][i/x])r++;}
if(r==x*y){System.out.println("evolved");return;}}System.out.println("created");}
public static Boolean[][] q(Boolean[][] o,int bx,int by){Boolean[][] s=new Boolean[bx][by];for(int x=0; x<bx; x++){for(int y=0;y<by;y++){
int t=0;for(int tx=-1;tx<2;tx++){for(int ty=-1;ty<2;ty++){if(ty+y<0||ty+y>by-1||tx+x<0||tx+x>bx-1)continue;if(o[tx+x][ty+y]){t++;}}}
if(t>1&&t<4){s[x][y]=u;}else{s[x][y]=v;}}}return s;}
public static Boolean[] p(Boolean[] b){boolean w=u;Boolean[] x=new Boolean[b.length];for(int i=0;i<b.length;i++){if(w&&b[i]){x[i]=u;w=u;}else if(b[i]||w){x[i]=u;w=v;}else{x[i]=v;w=v;}
}if(w){x=Arrays.copyOf(x,x.length+1);x[x.length]=u;}return x;}
public static Boolean[] m(String s){Boolean[] x=new Boolean[s.length()];for(int i=0;i<s.length();i++){x[i]=s.charAt(i)=='1';}return x;}}
```
It takes input via command line.
## What it does
No fancy tricks here, simply a brute force solution. It goes through every possible beginning board of size X,Y and iterates it once thru the Game of Life algorithm and checks it against the input board. This takes a VERY long time, as each board of size x by y has 2^(x\*y) possible combinations. It took almost 10 minutes to run a 4x5 board. Stupidly silly for something that is simpler than it is.
If it is possible that it was an evolved board, it prints "evolved.", and if it couldn't have been evolved, it prints "created.".
] |
[Question]
[
[Roll cakes](https://en.wikipedia.org/wiki/Swiss_roll) are delicious sweets made with a layer of sponge cake, a layer of cream (or icecream), rolled as a spiral, see [Wikipedia](https://en.wikipedia.org/wiki/Swiss_roll).
Your task is to get a non-empty phrase string from standard input, strip the spaces out, and roll it as a roll cake starting from the center in right to left in a counterclockwise direction, while the spaces starts at the bottom of the first phrase character, from the center left to right, as in the following example.
Please note that the phrase will be the layer of sponge cake and the cream layer will be represented as empty spaces.
```
Input: Lorem ipsum dolor sit amet, consectetu adipiscing elit, sed do eiusmod
Output with spaces ' ' represented as _
ilegnicsip
t________i
,_srolod_d
s_i____m_a
e_t_oL_u_u
d_a_r__s_t
d_m_emip_e
o_e______t
e_t,consec
i____
usmod
```
**Test cases**
```
Input: Lorem ipsum dolor sit amet, consectetu adipiscing elit, sed do eiusmod
Output:
ilegnicsip
t i
, srolod d
s i m a
e t oL u u
d a r s t
d m emip e
o e t
e t,consec
i
usmod
Input: Sandbox for Proposed Challenges
Output:
soporp
e r
d aS o
c n f
h dbox
a
llenges
Input: Cake
Output:
aC
k
e
Input: it
Output:
ti
```
**Rules:**
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
[Answer]
## Python 2, ~~202~~ 200 bytes
-2 bytes thanks to LevitatingLion
```
c=[];s=n=0
a=input().replace(' ','')
#Calculate the ammount of rotations
l=len(a)
while s<l:s=n*(1+n)/2;n+=1
#Add trailing spaces to not break the rolling
a+=' '*(s-l)
#Add a cream layer on top and a cake layer on bottom of the cake and roll 90 degrees
for i in range(1,n):c=[' '*i]+zip(*c[::-1])+[a[:i]];a=a[i:]
#Finish the rolling to match the pattern
exec~i%4*'c=zip(*c[::-1]);'
#Serve the cake
for i in c:print''.join(i)
```
[Answer]
# Befunge, ~~260~~ 250 bytes
```
"'"::00p09p19p35*::10p29pv
v`*84:~<0p041p031p020p93<
v_0`!#v_^*!p04+g04:p03%4+g03:p02%4+g02:!%g04:+1pp01+%2-1g03p\3+<
>00g:: :09g\`8+0\p::19g`8+1\p20g1-2%+00p10g:::29g\`8+2\p::39g`8^
9g\-\v>29g:39g\->\:50p09g:1
$$1+\:!#@_1-55+,^>
,gg05<:+1\-1_:$#\^#
```
[Try it online!](http://befunge.tryitonline.net/#code=IiciOjowMHAwOXAxOXAzNSo6OjEwcDI5cHYKIHZgKjg0On48MHAwNDFwMDMxcDAyMHA5MzwKdl8wYCEjdl9eKiFwMDQrZzA0OnAwMyU0K2cwMzpwMDIlNCtnMDI6ISVnMDQ6KzFwcDAxKyUyLTFnMDNwXDMrPAo-MDBnOjogOjA5Z1xgOCswXHA6OjE5Z2A4KzFccDIwZzEtMiUrMDBwMTBnOjo6MjlnXGA4KzJccDo6MzlnYDheCjlnXC1cdj4yOWc6MzlnXC0-XDo1MHAwOWc6MQokJDErXDohI0BfMS01NSssXj4KLGdnMDU8OisxXC0xXzokI1xeIw&input=TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHUgYWRpcGlzY2luZyBlbGl0LCBzZWQgZG8gZWl1c21vZA)
The basic idea is that we build up the spiral in the lower half of the playfield, keeping tracking of the min and max coordinates as we go along. Once all the input has been processed, we iterate over the range of coordinates and write out the content that was saved.
**Detailed Explanation**
Note that the *dx* and *dy* values are in the range 0 to 3, corresponding to the relative offsets -1, 0, 1, 0. Updating the direction is thus done by adding 1, modulo 4. Converting to a relative offset is done by subtracting 1, modulo 2.
```
"'"::00p09p19p Set x, minx, and maxx to 39.
35*::10p29p39p Set y, miny, and maxy to 15.
020p130p Set dx to 0 (relative offset -1) and dy to 1 (relative offset 0).
140p Set the segment length to 1.
0 Set the index to 0 (on the stack).
-- The main input loop start here --
~ Read a character from stdin.
:48*`_ If it's greater than 32 (i.e. not whitespace or EOL)...
00g: Get the current value of x and make a duplicate.
::09g\`8+0\p If it's less than minx, update minx.
::19g`8+1\p If it's greater than maxx, update maxx.
20g1-2% Calculate (dx-1)%2, which converts dx into the range -1 to 1.
+00p Add that to x and save (leaving the original x on the stack).
10g: Get the currrent value of y and make a duplicate.
::29g\`8+2\p If it's less than miny, update miny.
::39g`8+3\p If it's greater than maxy, update maxy.
30g1-2% Calculate (dy-1)%2, which converts dy into the range -1 to 1.
+10p Add that to y and save (leaving the original y on the stack).
p Store the character we read at the original x,y coordinates.
1+ Increment the index by 1.
:40g%! Mod that with the current segment len; if zero it's time to turn.
:20g+4%20p Add the turn condition to the dx value, thus turning if needed.
:30g+4%30p Similarly add the turn condition to the dy value.
:40g+40p Also add it to the segment length, so it gets longer every turn.
!* Multiply the index by !turn, so it's reset to zero on every turn.
^ Repeat the loop, reading another character.
0`!#v_^ If the char <= 32, we test for EOF and repeat the loop if not.
> If it is EOF, we start the output routine.
29g Initialise the y coordinate with miny.
:39g\- Calculate maxy - miny to use as the height countdown.
-- The outer output loop starts here --
\:50p Swap y to the top and save in a temporary variable.
09g Initialise the x coordinate with minx.
:19g\- Calculate maxx - miny to use as our width countdown.
\ Swap x to the top of the stack.
-- The inner output loop starts here --
:50g Take a copy of x and the y save in the temporary variable.
g, Read the character at those coordinate and write to stdout.
\:_ Swap the width countdown to the top of the stack and break if zero.
1- Otherwise decrement the width countdown.
\1+ Swap the x value back to the top and increment it.
< Repeat the inner loop.
$$ Clear the width countdown and x value from the stack.
1+ Increment the y value.
\ Swap the height countdown to the top of the stack.
:¬#@_ If it's zero, exit.
1- Otherwise decrement it.
55+, Output a line break.
^ Repeat the outer loop.
```
] |
[Question]
[
### Challenge
You will be given a positive integer `n` as input. Output should be a pyramid-like sandpile built on the rules specified below:
* Each integer "falls" downward from the same initial starting point, like sand falling into a conal-shape.
* Numbers greater than the number directly below it when it hits the sandpile will fall to the right, if able.
* Numbers less than the number directly below it when it hits the sandpile will fall to the left, if able.
* Numbers equal to the number directly below it when it hits the sandpile will stay in place.
* Numbers are able to fall to the left/right if they can move down and to the left/right respectively. That is, if there is already a number below and to the left/right, depending on the direction, the currently falling number does not move.
* A number will continue to tumble down the sandpile until it cannot be moved into its next position, or hits the floor.
### Notes
The initial comparison check only applies to the first encountered integer, not for each successive encounter as it tumbles down the sandpile.
Trailing spaces are okay but trailing new lines are not.
No leading spaces or new lines except where needed to preserve the structure of the sandpile.
You may write a full program or function.
You may assume input will only contain some combination `[0-9]`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes will be marked winner by the [Ides of March](https://en.wikipedia.org/wiki/Ides_of_March)
**Examples**
1
```
1
```
12345
```
35
124
```
54321
```
13
245
```
555444333222111
```
2
2
2
135
1345
13445
```
111222333444555
```
4
4
4
135
1235
12235
```
7313623030872935273465247457435345345350
```
3
3
3
3
34
355
3644
239475
201277445
020373685575
```
[Answer]
## JavaScript (ES6), ~~260~~ 208 bytes
```
s=>[...s].map(c=>a[g(n,(c>(l=a[n].slice(-1)))-(c<l))]+=c,n=s.length,a=Array(n+n).fill(''),g=(i,d)=>a[i].length>a[i+d].length?g(i+d,d):n)&&[...a[n]].map((_,i)=>a.map(c=>c?c[i]||' ':c).join``).reverse().join`\n`
```
Edit: Saved 25 bytes by realising that the first character isn't a special case. Saved 15 bytes by using an array of strings instead of an array of arrays of chars. Saved 12 bytes in miscellaneous fixes, including using a literal `\n` (not shown). That makes this whole 20% shorter! I wanted to get rid of `reverse` but that costs more than I can then save by replacing `map` with `replace`.
Ungolfed:
```
function sandpile(str) {
var arr = new Array(str.length * 2); // max width of sandpile is approx. 2√n but this is close enough
for (i = 0; i < arr.length; i++) arr[i] = '';
for (i = 0; i < str.length; i++) {
var digit = str[i];
var pos = str.length; // start dropping here
if (digit < str[pos][str[pos].length - 1]) {
while (str[pos - 1].length < str[pos].length) pos--;
} else if (digit > str[pos][str[pos].length - 1]) {
while (str[pos + 1].length < str[pos].length) pos++;
}
str[pos] += digit; // drop the digit
}
var len = arr[str.length].length; // final height
// remove the unused columns, and then pad the columns with spaces for the transpose
for (i = 0; i < arr.length; ) {
if (!arr[i]) arr.splice(i, 1);
else arr[i++] += ' '.repeat(len);
}
ans = '';
for (i = len; i-- > 0; ) {
for (j = 0; j < arr.length; j++) ans += arr[j][i];
ans += '\n';
}
return ans;
}
```
] |
[Question]
[
# Introduction
There is a plantation defined by one big *square-board* like this one:
[](https://i.stack.imgur.com/UY6cv.png)
The numbers inside each small square represents its area's value/cash/...
The farmer needs help to find the *N* squares that connected *(it means all N squares should have at least one shared border)* give him the greatest value.
For example:
If `N=1`, then the output must be `140`.
If `N=6`, then..
[](https://i.stack.imgur.com/gR1q6.png)
..the output must be `315`.
# Challenge
Your program/function must take the the **matrix's values** and the number **N** as input/arguments and must output **the powerful connection**'s value.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins!
# Examples
Input:
```
10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20
6
```
Output: `315`
---
Input:
```
35 -7
-8 36
2
```
Output: `29`
[Answer]
# JavaScript (ES6), 190 bytes
```
(m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o
```
## Explanation
Takes the matrix as an array of arrays.
Starts from each square then uses a recursive function to test every possible combination. This is a brute-force approach, but it finishes almost instantly for the first test case on my machine.
```
(m,n)=>
m.map((a,r)=> // for each row
a.map((_,c)=> // for each column
f(r,c,[0],0) // start checking paths from the coordinate of the square
),
o= // o = output number (max total)
f=(x,y,s,t)=> // recursive function f, x & y = current square, t = total
// s = array of used squares (starts as [0] so length = +1)
s[n]? // if we have used n squares
o>t?0:o=t // set o to max of o and t
:s.indexOf(w=x+","+y)<0&& // if the square has not been used yet
m[y]&&(v=m[y][x])<1/0&& // and the square is not out of bounds
// ( if value of square is less than Infinity )
// Check each adjacent square
f(x+1,y,
s=[...s,w], // clone and add this square to s
t+=v // add the value of this square to the total
)
+f(x,y+1,s,t)
+f(x-1,y,s,t)
+f(x,y-1,s,t)
)
|o // return output
```
## Test
```
var solution = (m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o
```
```
<textarea rows="7" cols="40" id="Matrix">10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20</textarea><br />
N = <input type="number" id="N" value="6" /><br />
<button onclick="result.textContent=solution(Matrix.value.split('\n').map(x=>x.split(' ').map(z=>+z)),N.value)">Go</button>
<pre id="result"></pre>
```
] |
[Question]
[
I just had a lesson in school about alkanes and figured it would probably make for a great code golf challenge! Don't worry, it isn't as complicated as it may look!
# A Quick Rehash
(Please Note: To keep this brief, not all information is 100% accurate.)
Alkanes are strings of carbon and hydrogen. Every carbon atom has 4 bonds, and every hydrogen atom 1 bond. All the carbon atoms of the alkane form a string where each C-atom is connected to 2 other C-atoms (left and right in the Lewis structure) and 2 H-atoms (up and down), except for the ends of the string, where the C-atom is connected to only 1 other C but 3 Hs. Here's a basic example for pentane (an alkane with 5 C-atoms and 12 H-atoms):
```
H H H H H
| | | | |
H-C-C-C-C-C-H
| | | | |
H H H H H
```
Alkanes also can have branches. But don't worry, all alkanes in this challenge can be expressed with only 1 level of branching. Example:
```
H
|
H-C-H
H H H | H
| | | | |
H-C-C-C-C-C-H
| | | | |
H H H H H
```
For completing this challenge you also must understand the IUPAC naming convention for branched alkanes. First of there's the root alkane. In our previous example, this would be the "C-C-C-C-C" part. Depending on how long this chain is, it has a different name. 1 C is called methane, 2 C ethane, 3 C propane, then butane, pentane, hexane, heptane, octane, nonane and decane (10 C). Then, for each branch, there's a certain prefix to that: First of, there's the index (offset) of the C-atom the branch is appended to (count from the left). In the example, this would be 4 (aka it's the 4th C-atom from the left). Then there's a hyphen (this symbol: "-") and after that another name indicating the size of the branch. The naming of the size of the branch is almost same like the naming of the size of the root, just that instead of "ane" you append "yl". With that the full name of the example would be
```
4-methylpentane
```
If you have multiple branches, then they are prepended as well, separated by another hyphen. Example:
```
2-butyl-5-methylhexane
```
One last thing: if you have multiple branches of the same size, they get grouped; their offsets are separated by comma and they share the same size-name, which gets prepended by an extra syllable depending on how many branches are grouped: "di" for 2 branches, "tri" for 3, "tetra" for 4 (you don't need more for this challenge). Example:
```
2-ethyl-2,4,6-trimethyldecane
```
FYI, this *could* look somewhat like this: (Omitted H-atoms)
```
|
-C-
| |
-C- -C-
| | | | | | | | | |
-C-C-C-C-C-C-C-C-C-C-
| | | | | | | | | |
-C- -C-
| |
```
# Nomenclature Cheatsheet
```
Prefixes indicating numbers:
| Num | Prefix |
|------|--------|
| 1 | meth |
| 2 | eth |
| 3 | prop |
| 4 | but |
| 5 | pent |
| 6 | hex |
| 7 | hept |
| 8 | oct |
| 9 | non |
| 10 | dec |
Suffix root: ane
Suffix branch: yl
Prefixes grouping: di, tri, tetra
```
# The Rules
Write a program that reads in such an IUPAC name from STDIN, program arguments or equivalent and draws it as an ASCII-art lewis structure to STDOUT (or equivalent).
* For simplicity, you DO NOT have to draw the H-atoms (Else you will run into spacing issues)
* You are NOT allowed to print any empty leading or trailing horizontal lines
* The chains you have to parse won't be any longer than 10, and the maximum of branches in a "group" is limited to 4.
* The maximum "offset" of a branch is 9 (meaning that you don't have to parse more than 1 digit)
* Your branches have to alternate between going up and down after every new branch. In case this space is already taken by another branch at the same offset, you have to draw it on the other side of the root. (up->down, down->up)
* On corrupt, not-correctly-formatted or otherwise not-drawable input, your program may behave unspecified.
This is code golf, shortest code in bytes wins!
Happy golfing! :)
[Answer]
# Python 2, 620 bytes
```
import re
i=input()
s='m|e|pr|b|p|hex|h|o|n|de';d=dict(zip(s.split('|'),range(1,11)))
z=[[eval('['+a+']'),d[b]]for a,b in re.findall('(?:(\d[,\d]*).*?[\-ia]|l)('+s+')',i[:-3])]
v=z[-1][1]
l=[[0,0]for _ in range(v)]
c=0
for a,b in sorted([(i,b)for a,b in z[:-1]for i in a]):l[a-1][c]=b;c=~c
m=[max(x) for x in zip(*l)]
L,R=[[[' 'for _ in '_'*2*i]for _ in '_'*(2*v+1)]for i in m]
c=[' |'*v+' ']
C=c+['-C'*v+'-']+c
for i in range(len(l)):
X=L;q=2*i+1
for a in l[i]:
if a>0:
for j in range(0,2*a,2):
X[q][j]='C'
X[q-1][j]=X[q+1][j]='-'
X[q][j+1]='|'
X=R
for l in zip(*L)[::-1]+C+zip(*R):print ''.join(l)
```
---
### Explanation
Input:
`'2-ethyl-2,4,6-trimethyldecane'`
First parses to string with regex (last group is root):
`[[[2], 2], [[2, 4, 6], 1], [[], 10]]`
Each branch is written in an array of length `len(root)` (Alternating up/down is handled here):
`[[0, 0], [1, 2], [0, 0], [1, 0], [0, 0], [0, 1], [0, 0], [0, 0], [0, 0], [0, 0]]`
'Left' and 'Right'(`L,R`) and 'root' (`C`) string branches are initialized.
Each branch is then added to the corresponding 'string' branch (big loop).
The two sides and center are printed at the end:
```
| |
-C- -C-
| | | | | | | | | |
-C-C-C-C-C-C-C-C-C-C-
| | | | | | | | | |
-C- -C-
| |
-C-
|
```
] |
[Question]
[
Your task is simple: Write a program that can be run in two languages. It should be a normal quine (prints its own source code) in language 1, and should be an error quine (generates an error message identical to its own source code) in language 2.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (in bytes) wins.
Rules:
* The languages may be arbitrarily similar. Supersets/similar versions/similar dialects are not disallowed.
* The error quine rules are the same as those in [Make an Error Quine!](https://codegolf.stackexchange.com/q/36260/61384).
[Answer]
# [Befunge-93 (FBBI)](https://github.com/catseye/FBBI) / [C (tcc)](http://savannah.nongnu.org/projects/tinycc), 93 + 62 = 155 bytes
```
^"
>#001p#"<>:#,_@#1-8*3:-1*57+55-1*79*57:-1:*77**278\-1:*57$p:1: error: declaration expected
```
Try it online!: [Befunge-93](https://tio.run/##FchBCoMwEEDRfU8RjKupAaOE0aEED1IqRkcJiIZgobdP4@o/vuP1e2ys@latzvmUPsXDyrrWQRYvS7IaB6lVBy0pDQafxuRin5kHASJAg937tsEykCbBMZ6RxMLzPsXp8uch@Bd4vnhJ6Q8 "Befunge-93 (FBBI) – Try It Online"), [C](https://tio.run/##S9YtSU7@/z9OictO2cDAsEBZycbOSlkn3kHZUNdCy9hK11DL1Fzb1BRIm1sCmUABKy1zcy0tI3OLGBDb1FylwMrQSiG1qCi/yEohJTU5J7EosSQzP08htaIgNbkkNeX/fwA "C (tcc) – Try It Online")
*Thanks to randomdude999 for noting that the filename requires matching quotes to work.*
Must be saved under the filename `^"\n>#001p#"<>:#,_@#1-8*3:-1*57+55-1*79*57:-1:*77**278\-1:*57$p`, where `\n` is a newline. Because of this, the TIO for C doesn't run exactly as intended. Tested to work on Lubuntu.
### Explanation (C):
The program fails to compile, and tcc happily outputs the name of the file as part of its error message. There are multiple compilation errors you can get, based on the beginning of the code. `^` at the start gives us a `declaration expected`, which is short and doesn't contain any problematic characters like `"`. On the other hand, the gcc and clang developers are very pessimistic and they chose to output multiple errors at once, which is not very nice, so we aren't using their compilers.
### Explanation (Befunge-93):
Befunge is convenient for quines in that its code can also be utilised as character data, thanks to the `"` command, which toggles string mode. At the beginning, we perform some useless stack operations, then issue a `p` (put command) which places a NUL character at (0, 1). Then we reflect the instruction pointer to the left and begin reading everything as a string. This has to be done to the left, because of the stack's LIFO nature. After wrapping around and reaching the `"` character again, the string ends. Note that the NUL character replaced the `$` character, creating a delimiter midway through the string. We then push 3 numbers onto the stack and jump over the NUL (because it unfortunately hangs the interpreter when run as an instruction). The static part of the error message has to be executed here. Most of its characters are no-ops, but the `p` command consumes three arguments (hence why we pushed 3 numbers, otherwise part of the string would be eaten here), and `:` & `1` characters push a total of 4 values to the stack, which we counteract with a `p` and a `$` (pop and discard) instruction. Then, some arithmetic is performed to push the ASCII codes for `^"\n>#001p#"` and finally a loop prints out all the values on the stack as characters until it finds a NUL character and terminates.
[Answer]
# [Applesoft BASIC](https://www.scullinsteel.com/apple2/) / [Commodore LCD BASIC](http://commodore-lcd.lgb.hu/jsemu/), 13 bytes
```
?SYNTAX ERROR
```
In the Apple ][ emulator, hit the `RESET` key to enter BASIC mode.
In the Commodore LCD emulator, hit `RightArrow``Enter` to get into the BASIC application.
In both of them, don't type `?SYNTAX ERROR` in all caps, because they automatically capitalize.
] |
[Question]
[
**UPDATE: Added a Python framework to get started.**
The space-station has been overtaken by crusher-bots. You must direct as many of
our expensive and fragile tech-bots called "rabbits" to an exit teleporter
before the station self-destructs, but the crusher-bots are patrolling the
corridors.
Your program is given an ASCII map, and each turn is told where the crusher-bots
are and your current rabbits are. Your program should then move your rabbits
toward the exit teleporter while avoiding the crusher-bots.

## Execution
Run the Python 2 controller with:
```
python controller.py <mapfile> <turns> <seed> <runs> <prog>...
<prog> can be <interpreter> <yourprog> or similar.
```
The seed is a small integer used for the crusher and your program PRNG so that runs are
repeatable. Your program should perform consistently regardless of the actual
seed used. If seed is zero, the controller will use a random seed for each run.
The controller will run your program with the name of the map text file and seed
as arguments. Eg:
```
perl wandomwabbits.pl large.map 322
```
If your program uses a PRNG, you should initialise it with the
given seed. The controller then sends your program updates through STDIN and
reads your rabbit movements through STDOUT.
Each turn the controller will output 3 lines:
```
turnsleft <INT>
crusher <x,y> <movesto|crushes> <x,y>; ...
rabbits <x,y> <x,y> ...
```
then waits for the program to output one line:
```
move <x,y> to <x,y>; ...
```
**UPDATE: Your program will have 2 seconds to initialise before the first lines are sent by the controller.**
If your program takes longer than 0.5 seconds to respond with moves after the
controller rabbit location input, the controller will exit.
If there are no rabbits on the grid, the rabbits line will have no values, and your program should output a bare "move" string line.
Remember to flush your program output stream each turn or the controller may
hang.
## Example
prog input:
```
turnsleft 35
crusher 22,3 crushes 21,3; 45,5 movesto 45,4
rabbits 6,4 8,7 7,3 14,1 14,2 14,3
```
prog output:
```
move 14,3 to 14,4; 14,2 to 14,3; 6,4 to 7,4
```
## Controller logic
The logic for each turn:
* if turns left is zero, print score and exit.
* for each empty start cell, add a rabbit if no crusher in sight.
* for each crusher, decide move direction (see below).
* for each crusher, move if possible.
* if crusher is at a rabbit location, remove rabbit.
* output turnsleft, crusher actions, and rabbit locations to program.
* read rabbit move requests from program.
* if a rabbit not exist or move not possible, skip.
* plot each new location of rabbits.
* if rabbit hits a crusher, rabbit is destroyed.
* if rabbit is in exit teleporter, rabbit is removed and score increased.
* if rabbits collide, they are both destroyed.
Each crusher always has a heading direction (one of NSEW). A crusher follows this
navigation logic each turn:
* If one or more rabbits are visible in any of 4 orthogonal directions, change
direction to one of the closest rabbits. Note that crushers cannot see past
another crusher.
* else choose randomly between open forward,left,right options if possible.
* else if obstacles (wall or other crusher) in front, left, *and* right, set direction
to behind.
Then for each crusher:
* If there is no obstacle in new crusher direction, move (and possibly crush).
## The map symbols
The map is a rectangular grid of ASCII characters. The map is made up of walls
`#`, corridor spaces , rabbit start positions `s`, exit teleporters `e`, and
crusher starting locations `c`. The top left corner is location (0,0).
## Small map
```
###################
# c #
# # ######## # # ##
# ###s # ####e#
# # # # ## ## #
### # ### # ## # #
# ## #
###################
```
## Test map
```
#################################################################
#s ############################ s#
## ## ### ############ # ####### ##### ####### ###
## ## ### # # ####### ########## # # #### ###### ###
## ## ### # ############ ####### ########## ##### ####### ###
## ## ## # ####### ########## # # ##### #### #
## ### #### #### ######## ########## ##### #### ## ###
######### #### ######## ################ ####### #### ###
######### ################# ################ c ####### ###
######### ################## ####### ####### ###########
######### ################## ######## ####### ###########
##### ### c ###### ###################
# #### ### # # # # # # # # # # ###### ############## #
# ####### #### ### #### ##### ## #
# #### ### # # # # # # # # # # ### # ### ######### #
##### ### #### ### ##### ### # ######## ####
############## ### # # # # # # # # # # ####### ## ####### ####
#### #### #### ### ### # # ### ###### ####
## ### # # # # # # # # # # ### ### # ### ##### ####
##### ######## ### # # # ##### # # # # ### ### # ##### #### ####
##### ##### ###### c # ### ### ###### ### ####
## c ######################### ### ##### ####### ### ####
##### # ### ####### ######## ### ##### c ## ## ####
##### # ####### ########## ## ######## # ######## ## ####
######### # ####### ## # ## # # # ##### # ####
### ##### # ### # ############## # ### # ### ## # ####
# ## # ### ### # ############## # ### ##### ##### ## ####
### ## ## # ### # ######## #
#s ## ###################################################e#
#################################################################
```
## Example large map run

## Score
To evaluate your program, run the controller with the test map, 500 turns,
5 runs, and seed of 0. Your score is the total number of rabbits successfully
teleported off the station to safety. In the event of a tie, the answer with the
most votes will win.
Your answer should include a title with entry name, language used, and score. In
the answer body, please include the controller score output complete with seed
numbers so that others can repeat your runs. For example:
```
Running: controller.py small.map 100 0 5 python bunny.py
Run Seed Score
1 965 0
2 843 6
3 749 11
4 509 10
5 463 3
Total Score: 30
```
You can use standard and freely available libraries but the standard loopholes
are forbidden. You must not optimise your program for a given seed, turn count,
map feature set, or other parameters. I reserve the right to change the map,
turn count, and seed if I suspect a violation of this rule.
## Controller code
```
#!/usr/bin/env python
# Control Program for the Rabbit Runner on PPCG.
# Usage: controller.py <mapfile> <turns> <seed> <runs> <prog>...
# Tested on Python 2.7 on Ubuntu Linux. May need edits for other platforms.
# v1.0 First release.
# v1.1 Fixed crusher reporting bug.
# v1.2 Control for animation image production.
# v1.3 Added time delay for program to initialise
import sys, subprocess, time, re, os
from random import *
# Suggest installing Pillow if you don't have PIL already
try:
from PIL import Image, ImageDraw
except:
Image, ImageDraw = None, None
GRIDLOG = True # copy grid to run.log each turn (off for speed)
MKIMAGE = False # animation image creation (much faster when off)
IMGWIDTH = 600 # animation image width estimate
INITTIME = 2 # Allow 2 seconds for the program to initialise
point = complex # use complex numbers as 2d integer points
ORTH = [1, -1, 1j, -1j] # all 4 orthogonal directions
def send(proc, msg):
proc.stdin.write((msg+'\n').encode('utf-8'))
proc.stdin.flush()
def read(proc):
return proc.stdout.readline().decode('utf-8')
def cansee(cell):
# return a dict of visible cells containing robots with distances
see = {} # see[cell] = dist
robots = rabbits | set(crushers)
if cell in robots:
see[cell] = 0
for direc in ORTH:
for dist in xrange(1,1000):
test = cell + direc*dist
if test in walls:
break
if test in robots:
see[test] = dist
if test in crushers:
break # can't see past them
return see
def bestdir(cr, direc):
# Decide in best direction for this crusher-bot
seen = cansee(cr)
prey = set(seen) & rabbits
if prey:
target = min(prey, key=seen.get) # Find closest
vector = target - cr
return vector / abs(vector)
obst = set(crushers) | walls
options = [d for d in ORTH if d != -direc and cr+d not in obst]
if options:
return choice(options)
return -direc
def features(fname):
# Extract the map features
walls, crusherstarts, rabbitstarts, exits = set(), set(), set(), set()
grid = [line.strip() for line in open(fname, 'rt')]
grid = [line for line in grid if line and line[0] != ';']
for y,line in enumerate(grid):
for x,ch in enumerate(line):
if ch == ' ': continue
cell = point(x,y)
if ch == '#': walls.add(cell)
elif ch == 's': rabbitstarts.add(cell)
elif ch == 'e': exits.add(cell)
elif ch == 'c': crusherstarts.add(cell)
return grid, walls, crusherstarts, rabbitstarts, exits
def drawrect(draw, cell, scale, color, size=1):
x, y = int(cell.real)*scale, int(cell.imag)*scale
edge = int((1-size)*scale/2.0 + 0.5)
draw.rectangle([x+edge, y+edge, x+scale-edge, y+scale-edge], fill=color)
def drawframe(runno, turn):
if Image == None:
return
scale = IMGWIDTH/len(grid[0])
W, H = scale*len(grid[0]), scale*len(grid)
img = Image.new('RGB', (W,H), (255,255,255))
draw = ImageDraw.Draw(img)
for cell in rabbitstarts:
drawrect(draw, cell, scale, (190,190,255))
for cell in exits:
drawrect(draw, cell, scale, (190,255,190))
for cell in walls:
drawrect(draw, cell, scale, (190,190,190))
for cell in crushers:
drawrect(draw, cell, scale, (255,0,0), 0.8)
for cell in rabbits:
drawrect(draw, cell, scale, (0,0,255), 0.4)
img.save('anim/run%02uframe%04u.gif' % (runno, turn))
def text2point(textpoint):
# convert text like "22,6" to point object
return point( *map(int, textpoint.split(',')) )
def point2text(cell):
return '%i,%i' % (int(cell.real), int(cell.imag))
def run(number, nseed):
score = 0
turnsleft = turns
turn = 0
seed(nseed)
calltext = program + [mapfile, str(nseed)]
process = subprocess.Popen(calltext,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errorlog)
time.sleep(INITTIME)
rabbits.clear()
crushers.clear()
crushers.update( dict((cr, choice(ORTH)) for cr in crusherstarts) )
while turnsleft > 0:
# for each empty start cell, add a rabbit if no crusher in sight.
for cell in rabbitstarts:
if cell in rabbits or set(cansee(cell)) & set(crushers):
continue
rabbits.add(cell)
# write the grid to the runlog and create image frames
if GRIDLOG:
for y,line in enumerate(grid):
for x,ch in enumerate(line):
cell = point(x,y)
if cell in crushers: ch = 'X'
elif cell in rabbits: ch = 'o'
runlog.write(ch)
runlog.write('\n')
runlog.write('\n\n')
if MKIMAGE:
drawframe(number, turn)
# for each crusher, decide move direction.
for cr, direc in crushers.items():
crushers[cr] = bestdir(cr, direc)
# for each crusher, move if possible.
actions = []
for cr, direc in crushers.items():
newcr = cr + direc
if newcr in walls or newcr in crushers:
continue
crushers[newcr] = crushers.pop(cr)
action = ' movesto '
# if crusher is at a rabbit location, remove rabbit.
if newcr in rabbits:
rabbits.discard(newcr)
action = ' crushes '
actions.append(point2text(cr)+action+point2text(newcr))
# output turnsleft, crusher actions, and rabbit locations to program.
send(process, 'turnsleft %u' % turnsleft)
send(process, 'crusher ' + '; '.join(actions))
rabbitlocs = [point2text(r) for r in rabbits]
send(process, ' '.join(['rabbits'] + rabbitlocs))
# read rabbit move requests from program.
start = time.time()
inline = read(process)
if time.time() - start > 0.5:
print 'Move timeout'
break
# if a rabbit not exist or move not possible, no action.
# if rabbit hits a crusher, rabbit is destroyed.
# if rabbit is in exit teleporter, rabbit is removed and score increased.
# if two rabbits collide, they are both destroyed.
newrabbits = set()
for p1,p2 in re.findall(r'(\d+,\d+)\s+to\s+(\d+,\d+)', inline):
p1, p2 = map(text2point, [p1,p2])
if p1 in rabbits and p2 not in walls:
if p2-p1 in ORTH:
rabbits.discard(p1)
if p2 in crushers:
pass # wabbit squished
elif p2 in exits:
score += 1 # rabbit saved
elif p2 in newrabbits:
newrabbits.discard(p2) # moving rabbit collision
else:
newrabbits.add(p2)
# plot each new location of rabbits.
for rabbit in newrabbits:
if rabbit in rabbits:
rabbits.discard(rabbit) # still rabbit collision
else:
rabbits.add(rabbit)
turnsleft -= 1
turn += 1
process.terminate()
return score
mapfile = sys.argv[1]
turns = int(sys.argv[2])
argseed = int(sys.argv[3])
runs = int(sys.argv[4])
program = sys.argv[5:]
errorlog = open('error.log', 'wt')
runlog = open('run.log', 'wt')
grid, walls, crusherstarts, rabbitstarts, exits = features(mapfile)
rabbits = set()
crushers = dict()
if 'anim' not in os.listdir('.'):
os.mkdir('anim')
for fname in os.listdir('anim'):
os.remove(os.path.join('anim', fname))
total = 0
print 'Running:', ' '.join(sys.argv)
print >> runlog, 'Running:', ' '.join(sys.argv)
fmt = '%10s %20s %10s'
print fmt % ('Run', 'Seed', 'Score')
for n in range(runs):
nseed = argseed if argseed else randint(1,1000)
score = run(n, nseed)
total += score
print fmt % (n+1, nseed, score)
print 'Total Score:', total
print >> runlog, 'Total Score:', total
```
The controller makes a text log of the runs in `run.log` and a series of images
in the `anim` directory. If your Python installation can't find the PIL image
library (download as Pillow), no images will be generated. I have been animating
the image series with ImageMagick. Eg:
```
convert -delay 100 -loop 0 anim/run01* run1anim.gif
```
You are welcome to post interesting animations or images with your answer.
You can turn these features off and speed up the controller by setting `GRIDLOG
= False` and/or `MKIMAGE = False` in the first few lines of the controller program.
## Suggested Python framework
To help get started, here is a framework in Python. The first step is to read in the map file and find paths to the exits. In each turn there should be some code to store where the crushers are, and code that decides where to move our rabbits. The simplest strategy to start with is moving the rabbits towards an exit ignoring the crushers -- some rabbits might get through.
```
import sys, re
from random import *
mapfile = sys.argv[1]
argseed = int(sys.argv[2])
seed(argseed)
grid = [line.strip() for line in open(mapfile, 'rt')]
#
# Process grid to find teleporters and paths to get there
#
while 1:
msg = sys.stdin.readline()
if msg.startswith('turnsleft'):
turnsleft = int(msg.split()[1])
elif msg.startswith('crusher'):
actions = re.findall(r'(\d+),(\d+) (movesto|crushes) (\d+),(\d+)', msg)
#
# Store crusher locations and movement so we can avoid them
#
elif msg.startswith('rabbits'):
moves = []
places = re.findall(r'(\d+),(\d+)', msg)
for rabbit in [map(int, xy) for xy in places]:
#
# Compute the best move for this rabbit
newpos = nextmoveforrabbit(rabbit)
#
moves.append('%u,%u to %u,%u' % tuple(rabbit + newpos))
print 'move ' + '; '.join(moves)
sys.stdout.flush()
```
[Answer]
# Crazy, Python 45
I did 25 runs with random seed, my computer isn't fast enough to go for 1000 (if someone want to correct the score)
First program in python, it was a pain to debug for me. Also I don't know if I used it well.
It uses a breadth-first algorithm from the exit, one taking into account the crushers, the other without. I had a lot of timeout so I didn't go for something more complex (one crusher removal, etc.). The rabbits also go crazy if there is a crusher nearby in the hope to make it go to a wrong path.
```
import sys, re
from random import *
mapfile = sys.argv[1]
argseed = int(sys.argv[2])
seed(argseed)
grid = [line.strip() for line in open(mapfile, 'rt')]
width = len(grid[0])
height = len(grid)
starts = set([])
end = ()
walkables = set([])
crushers = set([])
#
# Process grid to find teleporters and paths to get there
#
for a in range(height):
for b in range(width):
if grid[a][b] == 'e':
end = (b,a)
walkables.add((b,a))
elif grid[a][b] == 's':
starts.add((b,a))
walkables.add((b,a))
elif grid[a][b] == 'c':
crushers.add((b,a))
walkables.add((b,a))
elif grid[a][b] == ' ':
walkables.add((b,a))
toSearch = [ (end, 0) ]
inSearch = [ end ]
visited = set([])
gradient = [[0]*height for x in range(width)]
while len(toSearch) > 0 :
current = toSearch.pop(0)
(row, col) = current[0]
length = current[1]
visited.add(current[0])
neighbors = {(row+1,col),(row-1,col),(row,col+1),(row,col-1)}
neighborSpaces = walkables & neighbors
unvisited = neighborSpaces - visited
for node in unvisited:
if not node in inSearch:
gradient[node[0]][node[1]]=[current[0][0],current[0][1]]
inSearch.append(node)
toSearch.append((node, length+1))
toSearch.sort(key=lambda node: node[1])
while 1:
msg = sys.stdin.readline()
if msg.startswith('turnsleft'):
turnsleft = int(msg.split()[1])
elif msg.startswith('crusher'):
# Update crushers
actions = re.findall(r'(\d+),(\d+) (movesto|crushes) (\d+),(\d+)', msg)
for one_action in actions:
crushers.discard((int(one_action[0]),int(one_action[1])))
crushers.add((int(one_action[3]),int(one_action[4])))
elif msg.startswith('rabbits'):
toSearch = [ (end, 0) ]
inSearch = [ end ]
visited = set([])
gradient2 = [[0]*height for x in range(width)]
while len(toSearch) > 0 :
current = toSearch.pop(0)
(row, col) = current[0]
length = current[1]
visited.add(current[0])
neighbors = {(row+1,col),(row-1,col),(row,col+1),(row,col-1)}
neighborSpaces = (walkables - crushers) & neighbors
unvisited = neighborSpaces - visited
for node in unvisited:
if not node in inSearch:
gradient2[node[0]][node[1]]=[current[0][0],current[0][1]]
inSearch.append(node)
toSearch.append((node, length+1))
toSearch.sort(key=lambda node: node[1])
moves = []
places = re.findall(r'(\d+),(\d+)', msg)
for rabbit in [map(int, xy) for xy in places]:
# If any crushers insight, go crazy to lose him
directions = [(1,0),(-1,0),(0,1),(0,-1)]
crazy = False
newpos = 0
for direction in directions:
(row, col) = rabbit
sight = 0
while len({(row,col)} & walkables)>0 and sight<5 and crazy == False:
sight+=1
if (row,col) in crushers:
directions.remove(direction)
crazy = True
(row,col) = (row+direction[0],col+direction[1])
for direction in directions:
if not (rabbit[0]+direction[0],rabbit[1]+direction[1]) in walkables:
directions.remove(direction)
if len(directions)==0:
directions = [(1,0),(-1,0),(0,1),(0,-1)]
direction = choice(directions)
newpos = [rabbit[0]+direction[0],rabbit[1]+direction[1]]
# Else use gradients
if crazy == False:
newpos = gradient2[rabbit[0]][rabbit[1]]
if newpos == 0:
newpos = gradient[rabbit[0]][rabbit[1]]
moves.append('%u,%u to %u,%u' % tuple(rabbit + newpos))
print 'move ' + '; '.join(moves)
sys.stdout.flush()
```

[Answer]
# Bunny, Java, 26.385
I averaged the scores of runs 1 to 1000 and multiplied by 5 to get my score. I'm pretty sure this is equivalent to the average score over all possible games with the standard options.
[Scores](http://pastebin.com/svNffZBQ)
```
import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
private static final char WALL = '#';
private static final char CRUSHER = 'c';
private static final char ESCAPE = 'e';
private static final char HUTCH = 's';
private int height;
private int width;
private char[][] map;
private List<Point> escapes = new ArrayList<>();
private List<Point> crushers = new ArrayList<>();
private List<Point> rabbits = new ArrayList<>();
private List<Point> hutches = new ArrayList<>();
private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private PrintStream out = System.out;
private int[][] distances;
public Main(String[] args) throws Exception {
loadMap(args[0]);
}
private void loadMap(String mapFileName) throws Exception {
char[][] preMap = new BufferedReader(new FileReader(mapFileName))
.lines()
.map(String::toCharArray)
.toArray(char[][]::new);
width = preMap[0].length;
height = preMap.length;
map = new char[width][height]; //tranpose
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
map[x][y] = preMap[y][x];
}
}
processMap();
distances = dijkstra();
}
private void processMap() {
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
char c = map[x][y];
Point p = new Point(x, y);
if (c == CRUSHER){
crushers.add(p);
}
if (c == ESCAPE){
escapes.add(p);
}
if (c == HUTCH){
hutches.add(p);
}
}
}
}
public static void main(String[] args) throws Exception {
new Main(args).run();
}
private void run() throws Exception{
while (true) {
in.readLine();
readCrushers();
readRabbits();
makeDecision();
}
}
private void makeDecision() {
Map<Point, Point> moves = new HashMap<>();
for (Point rabbit : rabbits){
Point bestDirection = null;
for (Point p : pointsAroundInclusive(rabbit)){
if (
(bestDirection == null ||
distances[p.x][p.y] < distances[bestDirection.x][bestDirection.y]
) && !moves.entrySet().contains(p)){
bestDirection = p;
}
}
if (bestDirection != null) {
moves.put(rabbit, bestDirection);
}
}
out.println("move" +
moves.entrySet().stream().map(a -> {
Point l0 = a.getKey();
Point l1 = a.getValue();
return " " + l0.x + "," + l0.y + " to " + l1.x + "," + l1.y;
}).collect(Collectors.joining(";")));
}
private List<Point> pointsAroundInclusive(Point point) {
List<Point> result = pointsAroundExclusive(point);
result.add(point);
return result;
}
private int[][] dijkstra() {
Queue<Point> queue = new LinkedList<>();
Set<Point> scanned = new HashSet<>();
queue.addAll(escapes);
scanned.addAll(escapes);
int[][] distances = new int[width][height];
while (!queue.isEmpty()) {
Point next = queue.remove();
int distance = distances[next.x][next.y];
pointsAroundExclusive(next).stream()
.filter(p -> !scanned.contains(p))
.forEach(p -> {
distances[p.x][p.y] = distance + 1;
scanned.add(p);
queue.add(p);
});
}
return distances;
}
private List<Point> pointsAroundExclusive(Point p) {
Point[] around = new Point[]{
new Point(p.x - 1, p.y),
new Point(p.x + 1, p.y),
new Point(p.x, p.y - 1),
new Point(p.x, p.y + 1)
};
List<Point> result = new ArrayList<>(Arrays.asList(around));
result.removeIf(a -> {
if (a.x < 0 || a.x >= width){
return true;
}
if (a.y < 0 || a.y >= height){
return true;
}
char c = map[a.x][a.y];
return c == WALL;
});
return result;
}
private void readRabbits() throws Exception {
String[] locations = in.readLine().substring("rabbits".length()).trim().split("\\s");
rabbits.clear();
for (String location : locations){
if (location.equals("")){
continue;
}
String[] decomposed = location.split(",");
int x = Integer.parseInt(decomposed[0]);
int y = Integer.parseInt(decomposed[1]);
rabbits.add(new Point(x, y));
}
}
private void readCrushers() throws Exception {
String[] locations = in.readLine().substring("crusher".length()).trim().split("(; )?\\d+,\\d+ (movesto|crushes) ");
crushers.clear();
for (String location : locations){
if (location.equals("")){
continue;
}
String[] decomposed = location.split(",");
int x = Integer.parseInt(decomposed[0]);
int y = Integer.parseInt(decomposed[1]);
crushers.add(new Point(x, y));
}
}
}
```
The best run tested has seed 1000. Here's a GIF of it:

] |
[Question]
[
What general tips do you have for golfing in [Starry](https://esolangs.org/wiki/Starry)? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Starry (e.g. "remove comments" is not an answer).
Please post one tip per answer.
[Answer]
# Use `dup` and `add` for large numbers
If you need to produce a big but reasonable number which is a multiple of 2 (and in some cases, even not a multiple), you can push half the number and end with `+*` (dup and add) instead of pushing the whole number. The threshold for this is **8** and above.
As mentioned, sometimes you can double, then subtract one (threshold **27**), and with multiples of higher 2 powers it can be repeated to gain greater numbers.
[Try it online!](https://tio.run/##Ky5JLCqq/P9fAQa0FbS19LgUkIG2HheqAEIljIWuBZtyZFPAerVx6dLW@/8fAA "Starry – Try It Online")
] |
[Question]
[
Alphys, the Underground's Royal Scientist, has finished a prototype for a new puzzle. However, she can't seem to find anyone willing to test it.
### The rules of her puzzle are as follows:
The goal is to get to the right side, starting from the centermost tile on the left side. For puzzles with even-numbered heights, start on the lower of the two center tiles. (Examples: In a zero-indexed 4x4 array, the starting position would be [2,0] - row 2, column 0. In a zero-indexed 5x5 array the starting position would be [2,0] - row 2, column 0.)
Each colored tile has its own "sadistic" function:
* Pink and green tiles (represented as "P" and "G") do nothing
* Red and yellow tiles ("R", "Y") are impassable.
* Orange tiles ("O") make the player smell like oranges
* Purple tiles ("U") force the player to the next tile in the direction they are facing and make them smell like lemons
* Blue tiles ("B") are passable as long as the player does *not* smell like oranges.
To clarify the flavor mechanic, a player's smell will persist indefinitely or until overridden by a different-smelling tile, i.e. if a player steps on an orange tile they will smell like oranges until they step on a purple tile.
Additionally, a yellow tile placed vertically or horizontally adjacent to a blue tile will cause the blue tile to become impassable as well.
Your task is to write a program or function that accepts a 2-dimensional character array (or 1D string array, or some other valid format) representing the puzzle's layout as input and outputs both the original puzzle and the solved puzzle, with asterisks or some other character showing the correct path. Assume that the given puzzle is solveable.
Use this puzzle as an example:
```
BGYBG
PGPBG
PUBPB
OUGYB
PPOPP
```
Your program would output:
```
BGYBG
PGPBG
PUBPB
OUGYB
PPOPP
BGYBG
PGPBG
*****
OUGYB
PPOPP
```
Any puzzle used must be generated using [this](https://putnam3145.github.io/tilemaze).
Standard code golf rules apply. Best answers will be the shortest for each language. Answers must contain the language, number of bytes, and three test cases. The first two can be any layout you choose, but the third must be:
```
RRRR
RPPR
PUOR
RPBP
```
[Answer]
## C 529 bytes
```
#define M m[y][x]
char**m,*l,i;main(Y,X){for(;scanf("%ms",&l)>0;)(m=realloc(m,Y*8))[Y-1]=l,X=puts(m[Y++-1])-2;puts("");int s(x,y,c,d){(x<0|y<0|y/Y)?:({if(M^'R'&&M^'Y')if(M^'B'||c^2&&!((y&&m[y-1][x]=='Y')|(x&&m[y][x-1]=='Y')|(y<Y-1&&m[y+1][x]=='Y')|(x<X-1&&m[y][x+1]=='Y'))){x^X?:({M='#';return 1;});c=M^'O'?c:2;M^'U'?:({return s(x+(d<4?d-2:0),y+(d>3?d-5:0),1,d)?({M='#';1;}):0;});if(d^1&&s(x+1,y,c,3)||d^4&&s(x,y+1,c,6)||d^6&&s(x,y-1,c,4)||d^3&&s(x-1,y,c,1)){M='#';return 1;}}});return 0;}s(0,--Y/2,0,3);for(;i<Y;)puts(m[i++]);}
```
We approach the puzzle by stepping first to the right, provided we are not blocked, then trying up, then down and finally back to the left. The search is recursive and once we identify a successful path, we mark the spaces in our matrix and return.
## [Try it Online](http://ideone.com/3uDkHU)
### Ungolfed
```
#include <stdio.h>
#include <malloc.h>
char**m,*l,i;
main(Y,X) {
for(Y=1;scanf("%ms",&l)>0;Y++)
m=realloc(m,Y*8),
m[Y-1]=l,
X=puts(m[Y-1])-2;
puts("");
int step(x,y,c,d,i){
if(x<0||y<0||y>=Y)return 0;
if(m[y][x]=='R'||m[y][x]=='Y')return 0;
if(m[y][x]=='B'&&(c==2||(y&&m[y-1][x]=='Y')||(x&&m[y][x-1]=='Y')
||(y<Y-1&&m[y+1][x]=='Y')||(x<X-1&&m[y][x+1]=='Y')))return 0;
if(x==X){m[y][x]='#';return 1;}
if(m[y][x]=='O')c=2;
if(m[y][x]=='U')return step(x+(d<4?d-2:0),y+(d>3?d-5:0),1,d,i+1)?({m[y][x]='#';1;}):0;
else if((d!=1&&step(x+1,y,c,3,i+1)) ||
(d!=4&&step(x,y+1,c,6,i+1)) || (d!=6&&step(x,y-1,c,4,i+1)) ||
(d!=3&&step(x-1,y,c,1,i+1))) {m[y][x]='#';return 1;}
return 0;
}
step(0,--Y/2,0,3,0);
for(;i<Y;)puts(m[i++]);
}
```
---
### Example Output 1
```
PYYOPPPP
YRGGRYRG
PGPBYPUR
PYRBOYOG
OBPGYYPP
PRGPOYPO
YPYOUGPP
YGROBRYY
RGRYBBOG
PYY#####
YR##RYRG
###BYPUR
#YRBOYOG
#BPGYYPP
PRGPOYPO
YPYOUGPP
YGROBRYY
RGRYBBOG
```
### Example Output 2
```
PBYRYPGP
OBRGOOBG
PGPGUROO
PUGORBUG
PUPUUURO
BGGUYPRG
GBOPGGRG
PUPUBUYB
GYOPRPOG
PBYRYPGP
OBRGOOBG
PGPGUROO
PUGORBUG
###UUURO
BG#UYPRG
GB####RG
PUPUB#YB
GYOPR###
```
### Example Output 3
```
RRRR
RPPR
PUOR
RPBP
RRRR
R##R
###R
R###
```
[Answer]
# Python3, 640 bytes
```
M=[(1,0),(-1,0),(0,-1),(0,1)]
E=enumerate
def f(b):
D=eval(str(b))
C=[(j,k)for j,r in E(b)for k,_ in E(r)]
q=[(len(b)//2,0,b,0,{})]
while q:
x,y,b,s,m=q.pop(0)
b[x][y]='#'
if y==len(b[0])-1:return b
for X,Y in M:
if(K:=(x+X,y+Y))in C and K not in m.get((x,y),[])and(B:=D[x+X][y+Y])not in['R','Y']and(B!='B'or(s!=1 and[]==[1 for Q,W in M if(x+X+Q,y+Y+W)in C and'Y'==D[x+X+Q][y+Y+W]])):
I=eval(str(b));P={**m,(x,y):m.get((x,y),[])+[K]}
if'U'==B:
T=2;I[x+X][y+Y]='#';Z,G=x+X+X,y+Y+Y;J,K=[K,(Z,G)][(Z,G)in C]
if D[J][K]not in['R','Y']:q+=[(J,K,I,[T,1]['O'==D[J][K]],P)]
else:q+=[(*K,I,[s,1]['O'==B],P)]
```
[Try it online!](https://tio.run/##pVNfT9swEH@eP4XHHmI3hjUFpKnILx6TBRWzsRYxz7OmVqQj0CYlCRvVtM/Ozk5gGk@TsBQ75/v9uXOczba7qqv9d5vm4eGMO5KxMWVkt1/GbDeLS0Y9@sCL6m5dNPOuQJfFEi/Jgk4RPubFj/mKtF0DMUX4PYhcsxu6rBt8zRpcVvgDZEJ4w771YQNy@BaAq6KC3Nu3EzZmC3h@/Q6Zn1flqsC3II7v2RYSLVvz271NvSFjcMALd@/d1vPkTQJRucRbzqOSG3u6m02bortrKryAZLD9zGywPQt6gCazKSf36We2TS2lkHiP59UlnuGq7gJuvfe96AgBZ8qcp5AjYsqPHVDANbWe9kCXmIQlNvER8ZonIqkb0r7mWdBznnOXRf9zdhH9gzeIpOfBOb14sgYN3uun59EhvfCe0lguxif/nO@R5r9GozWL5U2flZq6mf/ds8plkoOqGETwJz45OvnbQji6oy9M8mAaTyK1R6dsxt2MEdin3sUllOgHCTjnY3fqweNZ/9PbFD4lsNkJc59Y5l2iYkcR7Jmmg0SxaosePIrY9gkrIuqhzTDHOzs7SEgrJNJShzkXWiCVwxbSWmmNAqKdDFADAxmtDQBVeBMDYH8AaGuBBDRrpDQwRV2rc2BYI5RVEimhpbWA0UZqZbVCVluwDCxplDDWIgNkIQAc1Q8e1YU1FgRBwkil@qplbpSCeqQyIg8d6DyHLWhL5hYskBRKQzF9SuTQmYQijR7UUXs4yEsYBuYcZqWkFE87YQ6I8Ct29bdFPW8uSQu35tVw/Z0blT5ewDJcv2W56oqGfKyrguF2r92syo4kX6uEwudBaNOUVR/vXddlRdbzDUn6d7Ykfw0yGsYjfDcZTcb0v8mTl5D3X0I@eAn5MJIf/gA)
] |
[Question]
[
Write a function or program that outputs [Quater-imaginary base](https://en.wikipedia.org/wiki/Quater-imaginary_base) displayed as binary digits. The number base is 2*i*, where *i* is the square root of -1. See [Complex Number](https://en.wikipedia.org/wiki/Complex_number) for more details on *i*. Each digit position can go from 0 to 3 (quaternary), as each real and imaginary part is -4 times as large as the previous real and imaginary part. The quaternary digits in binary are as follows: `0: 00`, `1: 01`, `2: 10` & `3: 11`.
Breakdown of digit positions:
```
re im 16 -8i -4 2i 1 -0.5i, etc.
4 0 1 0 3 0 0 (quaternary representation)
01 00 11 00 00 (binary representation)
```
The number `100110000` is 1x16 + 3x-4 = 16 + -12 = 4.
```
re im 16 -8i -4 2i 1 -0.5i, etc.
0 5 0 0 0 3 0 2 (quaternary representation)
00 00 00 11 00 .10 (binary representation)
```
The number `1100.1` is 3x2*i* + 2x-0.5*i* = 6*i* + -*i* = 5*i*.
Your code will take a pair of numbers, which could be integer or floating point, and will output the complex number as a string of binary digits. The first number will be real, the second input number will be the imaginary value. A binary point must only be printed if there are non-zero number positions below 1 (i.e. if any of the positions for -0.5*i*, -0.25, 0.125*i*, etc. have a non-zero digit). Leading and trailing zeros are not allowed, except for a single zero digit immediately before the binary point if there are no other digits. The output must not start with a binary point (\*`00.1` - wrong, `0.1` - right, \*`.1` - wrong, \*`0.10` - wrong). You may assume that all input numbers will have finite binary representations.
Test numbers:
```
re im output
0 0 0
1 0 1
2 0 10
3 0 11
4 0 100110000
-1 0 10011
-2 0 10010
-3 0 10001
0 1 100.1
0 2 100
0 3 1000.1
0 4 1000
0 -1 0.1
0 -2 1001100
0 -3 1001100.1
3 4 1011
4 3 100111000.1
6 -9 101110010.1
-6 9 10011100110.1
-9 -6 1110111
0.5 14.125 10011001101.001001
```
Note: The output of all integer values will end in `.1` if the imaginary part is odd.
Standard code-golf.
[Answer]
## JavaScript (ES6), 340 bytes
```
f=x=>[0,...x.toString(16)].reverse().map(d=>s=d<'.'?s:d<`0`?d+s.slice(0,-1):`${(c=+`0x${d}`+(c>>4)+m^m)>>2&3}${c&3}`+s,c=s='.',m=x<0?3:12)&&s
g=(s,t,n=s.indexOf`.`,m=t.indexOf`.`)=>n<m?g(0+s,t):n>m?g(s,0+t):t[s.length]?g(s+0,t):s.replace(/\d/g,(c,i)=>`${t[i]>>1}${t[i]&1}${c>>1}${c&1}`).replace(/^0+(\d)|\.?0*$/g,'$1')
(r,i)=>g(f(r),f(i/2))
```
`f` converts a number into base `-4` (with trailing `.` if the number is an integer). `g` takes two base `-4` numbers, pads them at both ends to the same length and `.` position, shuffles the digits together, converts everything from base `4` to base `2`, then finally strips leading and trailing zeros.
Explanation: To represent the given complex number in modified-base `2i` we need to represent the real part and half of the complex part (i.e. dividing the imaginary part by `2i`) in base `2i²` (i.e. `-4`), shuffle the digits together, and then convert them from base `4` to base `2`. To represent a real number in base `-4` we start with the base `4` conversion. Alternate digits have the correct sign (in the case of a positive number, these are the digits in the even positions; in the case of a negative number, these are the digits in the odd positions) but the remaining digits have the wrong sign and a correction needs to be applied. Examples:
```
0 -> 000 -> 000 (no correction needed)
4 -> 010 -> 130 }
8 -> 020 -> 120 } (correction includes carry)
12 -> 030 -> 110 }
```
As you can see, the correction is `8` minus the original digit, mod `8`. However a slightly more convenient calculation is the original digit, plus 3, xor 3 (indeed in 32-bit integer arithmetic we could simply write `+0xCCCCCCCC^0xCCCCCCCC` to convert the entire number in one go). Finally as the correction applies to alternate digits it is simpler to do an initial conversion to base `16` which automatically picks up pairs of base `4` digits, then correct using a factor of either `3` or `0xC` as appropriate. It just remains to ignore the `-` sign.
[Answer]
## Perl - 313 bytes
Since no-one has posted an answer yet I thought I'd kick it off myself.
```
$r=$ARGV[0];$i=$ARGV[1]/2;$m=1;while($r!=int($r)||$i!=int($i)){$c++;$m*=-1;$i*=4;$r*=4}while($r||$i){$r-=($d[$n++]=$r/$m%4)*$m;$i-=($d[$n++]=$i/$m%4)*$m;$m*=-4}$_=join("",map({sprintf"%02b",$_}reverse splice(@d,$c*2)))||"0";@d and$_.=".".join("",map({sprintf"%02b",$_}reverse@d));s/^0+1/1/;s/(\.\d*1)0+$/$1/;print
```
I'm sure there are lots of opportunities to golf this further.
] |
[Question]
[
In the game [Terraria](https://en.wikipedia.org/wiki/Terraria), one of the game mechanics involves building houses so that an NPC can move in. There is a strict set of rules for what counts as a valid house or not. Here is the list of rules:
1. The total area in the house must be at least 60 square tiles, but less than 750. Also, the size of the house including the outer frame must be at least one of these:
```
5x12
6x10
7x9
8x8
9x7
10x6
12x5
15x4
```
for simplicity's sake, you can safely assume that: a) All input houses will be rectangles, and b) no solid tile `#` will be inside of the house. Here is our 12x6 frame (drawn in beautiful ASCII):
```
############
# #
# #
# #
# #
############
```
2. The house must be covered in background walls. These are not solid tiles, but rather a wall *behind* the house in the third dimension. Holes are allowed, but no holes can be larger than 4x4. If there is a row or column of 5 or more space characters in a row, this is a hole larger than 4x4, and the house is invalid. Multiple holes are also allowed, but there must be at least a single wall apart.
```
############
#**********#
#**********#
#**********#
#**********#
############
############
#* * #
#* * #
#* * #
#****** #
############ (Still acceptable since neither hole is larger than 4x4 and there is a separator)
############
# ******#
#*** ***#
# ******#
#*** ***#
############ (Also still valid. No row or column of blank spaces is longer or taller than 4.)
```
3. There must be an entrance. This can be a door `|` on the sides or a platform `-` on the floor or ceiling. If the only entrance is on a corner, the NPC is unable to enter. Also, if you have a platform as the floor, you must have at least a single solid block for the NPC to stand on. This solid block cannot be directly adjacent to the **side walls** on the left or the right. These are all valid houses with entrances:
```
############
#**********#
|**********#
#**********#
#**********|
############ (Multiple doors, or doors up high are okay)
############
#**********#
#**********#
#**********#
#**********#
#######----#
#----#######
#**********#
#**********#
#**********#
#**********#
############
```
4. There must be at least one light source `$`, table `T` and chair `C`, although more is allowed. The light source can be in the air or on the ground, but the table and chair both must be on the ground, e.g on the lowest row.
```
############
#**********#
#**********#
#***$******|
#****TC****|
############
```
Also, you can assume that there is a wall behind any furniture, so a torch, chair or table can count as a separator between two holes.
```
############
#* * #
#* * #
#* $ #
#**TC******|
############
```
# The challenge
You must write the shortest function that takes a house as an ASCII string, and returns true/false whether or not it is valid housing. You can take this as a newline delimited string, a list of strings, or any other way as long as it is reasonable. For my sake, please include a short program so I can test if it works right or not.
For reference, these are all invalid inputs:
```
############
-**********#
-****$*****#
-**********#
-******TC**#
############ (You can't have platforms on the sidewalls)
###########-
#**********#
#**********#
#****$*****#
#**T***C***#
###########| (NPC can't enter because the only entrances are on the corner)
############
#**********#
#******$***#
#**********#
#T****C****#
##--------## (NPC has nowhere to stand)
############
#**********#
#**********#
#**********#
#**$**TC***#
##########|# (Door cannot be in the floor or ceiling)
############
#**********#
#**********#
#**********#
|** T C #
############ (Since table and chair do not count as a background wall, the hole in background is too wide)
####### ####
#**********#
#**********#
#****$*****#
#**T***C***|
############ (There's a hole in the frame.)
###########################################################################
# #
# #
# #
# #
# #
# #
# #
# #
# #
########################################################################### (House is 75x11, which is too big.)
```
### Leaderboard
```
var QUESTION_ID=68237,OVERRIDE_USER=31716;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Python 2, ~~503~~ 439 bytes
Not super short, but it's a solution. Let me know if you see something to golf. I'd recommend looking at my ungolfed version as well, since it's actually readable.
Edit: All the `if`s outside a loop have been combined at the bottom.
```
def f(s):
s=s.split("\n");e=l=0;h=len(s);w=len(s[0])
for c in s[0][1:-1]+s[-1][1:-1]:
if(c in"#-")<1:return 0
if"-"==c:e=1
for r in s[1:-1]:
if(r[0]in"#|")*(r[-1]in"#|")<1or" "*5in r:return 0
if"$"in r:l=1
for r in zip(*s):
if" "*5in`r`[2::5]:return 0
if(h*w<60)+(h*w>749)+(w<5)+(h<4)or" "in s[0][0]+s[0][-1]+s[-1][0]+s[-1][-1]or("T"in s[-2])*("C"in s[-2])*l<1or("#"in s[-1][2:-2])<1or"|"in"".join(s[1:-1])<1>e:return 0
return 1
```
[**Try it online**](http://ideone.com/oGVu3W)
### Ungolfed:
Also outputs the reason the result is `False`, for debugging purposes.
```
def f(s):
# check dimensions
s=s.split("\n")
h=len(s)
w=len(s[0])
if h*w < 60 or h*w > 749 or w<5 or h<4: return False,"Size"
# top / bottom
e=0
for c in s[0][1:-1]+s[-1][1:-1]:
if(c in"#-")<1:return False,"T/B"
# entrance
if"-"==c:e=1
# no spaces in corners -_-
if" "in s[0][0]+s[0][-1]+s[-1][0]+s[-1][-1]: return False,"Corner"
# light, table, chair
l=t=c=0
# left / right
for r in s[1:-1]:
if(r[0]in"#|")*(r[-1]in"#|")<1: return False,"L/R"
# walls, put above
if" "*5in r: return False,"Walls"
# light
if"$"in r:l=1
# table, chair
if"T"in s[-2]:t=1
if"C"in s[-2]:c=1
if l*t*c<1: return False,"L/T/C"
# wall columns
for r in zip(*s): # Transpose
if" "*5in`r`[2::5]: # Tuple to string
return False,"Walls"
# entrance
if"|"in"".join(s[1:-1])<1>e: return False,"Entrance"
# place to stand
if("#"in s[-1][2:-2])<1: return False,"Stand"
return True
```
[**Ungolfed version online**](http://ideone.com/MctzTz)
] |
[Question]
[
In a few British newspapers there is a game known as [Hidato](https://en.wikipedia.org/wiki/Hidato). It is somewhat similar to [Sudoku](https://en.wikipedia.org/wiki/Sudoku), albeit instead of having 1-9 in a line and block, it's about placing numbers such that they connect in order from `01` all the way up to the highest one, so they are all touching **horizontally, diagonally or vertically**.
Inputs will contain multiple lines separated by `\n`, containing blocks separated by a space, which you can assume to be two characters wide. Each block will be a number, a blank space to be filled (indicated by `--`), or a wall that cannot have numbers in (`XX`).
Your output should match the provided one albeit with empty blocks provided with numbers. **Note that there may not be a unique, or even the existence of, a solution** – some may yield multiple due to their ambiguity, much like Sudoku, and some may be literally unsolvable, in which case you should give a [falsey](http://meta.codegolf.stackexchange.com/q/2190) output, but you can assume inputs are formatted as below.
Use a standard header `Language: XX bytes`. Happy golfing!
## Examples
Inputs `01 XX 03`, `01 -- 04`, `01 --`, etc should all return something [falsey](http://meta.codegolf.stackexchange.com/q/2190).
Input:
```
01 -- --
-- XX 05
```
Output:
```
01 03 04
02 XX 05
```
Input:
```
-- 33 35 -- -- XX XX XX
-- -- 24 22 -- XX XX XX
-- -- -- 21 -- -- XX XX
-- 26 -- 13 40 11 XX XX
27 -- -- -- 09 -- 01 XX
XX XX -- -- 18 -- -- XX
XX XX XX XX -- 07 -- --
XX XX XX XX XX XX 05 --
```
Output:
```
32 33 35 36 37 XX XX XX
31 34 24 22 38 XX XX XX
30 25 23 21 12 39 XX XX
29 26 20 13 40 11 XX XX
27 28 14 19 09 10 01 XX
XX XX 15 16 18 08 02 XX
XX XX XX XX 17 07 06 03
XX XX XX XX XX XX 05 04
```
Input:
```
XX XX XX XX -- 53 XX XX XX XX
XX XX XX XX -- -- XX XX XX XX
XX XX 56 -- -- -- 30 -- XX XX
XX XX -- -- -- -- -- -- XX XX
XX -- -- 20 22 -- -- -- -- XX
XX 13 -- 23 47 -- 41 -- 34 XX
-- -- 11 18 -- -- -- 42 35 37
-- -- -- -- 05 03 01 -- -- --
XX XX XX XX -- -- XX XX XX XX
XX XX XX XX 07 -- XX XX XX XX
```
Output:
```
XX XX XX XX 52 53 XX XX XX XX
XX XX XX XX 54 51 XX XX XX XX
XX XX 56 55 28 50 30 31 XX XX
XX XX 26 27 21 29 49 32 XX XX
XX 25 24 20 22 48 45 44 33 XX
XX 13 19 23 47 46 41 43 34 XX
14 12 11 18 04 02 40 42 35 37
15 16 17 10 05 03 01 39 38 36
XX XX XX XX 09 06 XX XX XX XX
XX XX XX XX 07 08 XX XX XX XX
```
[Answer]
## [JavaScript (Node.js)](https://nodejs.org), 482 bytes
This is a brute-force solution, it starts at `01` and checks every neighbouring cell checking for empty cells (`--`) or the desired number and following the path to completion or impossibility. If the desired number exists and isn't a neighbour it shortcuts this solution. Takes a few seconds for the largest grid.
This probably isn't particularly interesting, but I thought I'd try my hand at making a solution before looking at the answers linked on Rosetta Code and I enjoyed tackling a slightly more difficult challenge!
Finds all [solutions when many exist](https://tio.run/##VZJRb9owEMff@RRU2rCtOE4CY1qbXXgorVSp6lqeqkbR8BIHwlwnjcMIEPbVmUOBqZLl/H33u3Puzgv@h@u4zIrKVnki9vsUOATbW8BjquiCQBC@QBixOFcxrzBjbEzoBl5YphJR/0jxwhwD2@v1who2n1d0DRtn1bjRyRrWtkfXthfRsD59rbOl9Z0sp7N1ZK0za1QUhSryr@ENgjf2ygv8BMET0zKLBSbEXwEP3Si8BySFmlVzFPkSbjGnLmFpJitR4hiC@ALQ8zMi4X3kT0xVfglY08QUuZWi6iqYup@2lra83fSY2u4T/8EkSmifKuKrQI4mrFjqOb7GCSFXf1uXRzUZ4eKADYymxenORwgeAR4sdLhzVGJF3@MujoGKjIpDOXfmH9qiI7ijuP7uNk0drGyvadatXgeJibc90jRJuI7COgJAto16PTyGNiMt8fjoUHRMyI5cuWbt/BIj10OUE78U1bJU3clu7zjdeVUV@spxYjPzWS5Tpise/xZ1POdqJsy0X503Z/ilP/Scy8HXYadTlHkstDZckimmRXWjTGymZhgtq/QbIv5HIlcYlYIn/JcUiP5sO2welmn5ap5JYYbxEW9RM8dtluKYSAvinc9BMl3IrJp2pocWlRCUR0t3SnzzInUuBZP5DKeYkwPTDvk/vMgz1bLvonMWRu3I3vW6tm1W57B33cFJXP4D). The body is a function that accepts a two dimensional array and the footer processes the input to the desired format, and returns the result to the desired format too. Happy to provide more information (and a less golfed implementation if there's interest).
```
f=a=>{F=(D,n,j)=>[Z=[].concat(...D),z=Z.indexOf(j),z>-1&&[x=z%w,y=z/w|0],z>-1&&[[x-1,y-1],[x,y-1],[x+1,y-1],[x-1,y],[x+1,y],[x-1,y+1],[x,y+1],[x+1,y+1]]][n];C=q=>q.map(Q=>Q.slice());w=a[0][L='length'];l=F(a,0).filter(c=>c!='XX')[L];R=[];r=(s,d)=>{let n=`0${+s+1}`.slice(-2);N=F(d,2,n);n>l?R.push(C(d)):~F(d,1,s)?(p=F(d,3,s),p.filter(P=>P==N+'')[L]?r(n,C(d)):!~F(d,1,n)?p.map(I=>{[x,y]=I,(x<0||x>w-1||y<0||y>d[L]-1)||d[y][x]=='--'&&(D=C(d),r(D[y][x]=n,D))}):0):0};r('01',a);return R}
```
[Try it online!](https://tio.run/##fVJrb5swFP3Or6DSFmxhHiZNX@ySD00rVaq6tp@iIrQwMAmZayjQhTRkfz0zeXXt1klX5viec665vp6GP8MyKtK8MkQWs9UqgRC8xSWgARFkisHzH8APzCgTUVgh0zQHmLzAg5mKmNVfEzSVW8@gnY5fw8vnGZnDizVr7GCX9WuDkrlBA@LXu6@@z7TcLrPb61utvtdKFAS@CNxzeALvyXwMc3QH3p1Z8jRiCGN3BqFvB/41aJyJcTXRApfDJQqJjc0k5RUrUARedADacKhh/zpw72VXbgGoJLFscsFZpQoY2Z8WeqnT5Whb2nCweyMLxcQhArvC4/17M38uJ@gcxRif/WopSkrcR/la1pWY5Lszb8G7BbjRtfWZ/QIJsvEdbI0C9/N1O1fyH9qmA7giqP5iN03tzQzaNPMWz71Y@g2Kmyb254FfBwCaYWidDhpAW5EUaLAlBBlgvMRntoylWyDNphoJsVuw6rkQ6v1yZVnqpKry8syyIjnzccYTs6zC6Aero0koxkxO@9F6snqHTo9ap92jnqLkRRaxspS6OBVmyaoLIb2pGCPtuUpONOy@VWQCaQUL4/A7Zxr51t6wfFjyymeTlDM5jLfyVirnuEgTFGGuQ7R0Q@BmmfO0Gimj9RUV4BXbjDrCrnyRZcaZybMxSlCI15p2yK/iaZaKVrsByh5ItMSr4VD9OBS5Goba7ardXgtk/M3KcA5Vx/mQbQX0nX3LOkftSrvqoa1S@oZ1jl/t9ul6pa/sJjYsPfmzuPKui9Z4vBco/@zU7v2P3cVv "JavaScript (Node.js) – Try It Online")
[Answer]
# Python3, 860 bytes:
```
R=range
S=lambda x,y:[(X,Y)for X in R(x)for Y in R(y)]
def O(b,x,y,X,Y):
for A,B in[(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]:
if-1<(j:=x+A)<X and-1<(k:=y+B)<Y and b[j][k]!='XX':yield(j,k,b[j][k])
def f(b):
b=[[int(j)if j.isdigit()else j for j in i.split()]for i in b.split('\n')]
k=S(*(I:=(len(b),len(b[0]))))
if len(d:=[(x,y)for x,y in k if type(b[x][y])==int])==1:return
s,e=min(d,key=(_:=lambda x:b[x[0]][x[1]])),max(d,key=_)
q,a=[(s,{(x,y)for x,y in k if b[x][y]=='--'},b)],[]
D=[b[x][y]for x,y in d]
while q:
(X,Y),W,B=q.pop(0)
if(X,Y)==e and W==set():return'\n'.join(' '.join(str(j).zfill(2)for j in i)for i in B)
T=[]
for x,y,C in O(B,X,Y,*I):
if C==B[X][Y]+1:q+=[((x,y),W,B)];T=[];break
if'--'==C and B[X][Y]+1 not in D:
U=eval(str(B));U[x][y]=B[X][Y]+1
if U not in a:T+=[((x,y),W-{(x,y)},U)];a+=[U]
q+=T
```
[Try it online!](https://tio.run/##bVJNc5swEL3zK9RckGLhATtpUxIdQnLJKTNJPMFDNRkYRMJHMAbamnby291diVKnrYeRrPfe7r5dqRn6l029PGva/f5OtHH9rKx7UcWvSRqTHR/8iIZ8zbJNS0KS1@SO7vRhbQ4Dk1aqMnJLEw5qjlrfIqi45AFoIupyj3FYHdw87sLqmM3jBtKMY06OPkrIQfLM8S5o4Yvd7JJdhCSuUwRKXwyzgF2sESBJVMiolB@EHYa2P@SqSmnBSz7iTLvLaIKuEhFFed3TguUZKeZ5l@bPeU@ZqjpFCm26wLbyeddUSEiEcoSSEbK/1Da0TEpxT4/pjS9opWrIzvUWuZLBzwLrBIHUFxGFseiJwY6ZSiT7oVEg38lokEwIMIWb57eq/9rWFum4Eq85JOClGgR98qcb8SEKykhYPQnV@Gu8G2VPUHjLYyjZ8Z//LTtWFMJ2HPuNJ0zyCJq5FtHIHASkQHx/yStFtngZ@hXwRx6I7bzZNNRl@oY0LITSd/EoRKdgbGMbOKt5sYE2bDL@6foWpj//keVVRRfsz8TZNOkAEz8I9EVGO/wKiVsa4PPixzd4l1icXAkRRKGM1nLm@dsZdK7bRptMnmOS86RVcWnk2LQQV9rqFEbqTY/Zr3VOshLqW1xpnwFj56txYJNci6Dy6ndc7D8c1HXM3N/4CurHQKywDXD2sG9afHoZtV2PhCFxlzY8lEPQcYh78i94iBwdHRmh41iwYppTwN4rgFguyfLU6FBkPvhZBlqckMXib25iUeAdBiO@@IhHb0lOXOJ5I774RKYQ97NekbJMToN7Z1MqaypnWHcMf4ebz0X3urP9Lw)
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.