text
stringlengths 180
608k
|
---|
[Question]
[
In today's episode of AAOD, we are going to construct a Chinese Shrine of varying heights.
Consider the following examples for height (`N`) `1` to `6`
`N = 1`:
```
.
|
. ]#[ .
\_______/
. ]###[ .
\__]#.-.#[__/
|___| |___|
|___|_|___|
####/_\####
|___|
/_____\
```
`N = 2`:
```
.
|
. ]#[ .
\_______/
. ]###[ .
\___________/
. ]#####[ .
\___]#.---.#[___/
|__|_| |_|__|
|__|_|___|_|__|
#####/___\#####
|_____|
/_______\
```
`N = 3`:
```
.
|
. ]#[ .
\_______/
. ]###[ .
\___________/
. ]#####[ .
\_______________/
. ]#######[ .
\____]#.-----.#[____/
|__|__| |__|__|
|__|__|_____|__|__|
######/_____\######
|_______|
/_________\
```
`N = 4`:
```
.
|
. ]#[ .
\_______/
. ]###[ .
\___________/
. ]#####[ .
\_______________/
. ]#######[ .
\___________________/
. ]#########[ .
\_____]##.-----.##[_____/
|__|__|_| |_|__|__|
|__|__|_|_____|_|__|__|
########/_____\########
|_______|
/_________\
```
`N = 5`:
```
.
|
. ]#[ .
\_______/
. ]###[ .
\___________/
. ]#####[ .
\_______________/
. ]#######[ .
\___________________/
. ]#########[ .
\_______________________/
. ]###########[ .
\______]###.-----.###[______/
|__|__|___| |___|__|__|
|__|__|___|_____|___|__|__|
##########/_____\##########
|_______|
/_________\
```
`N = 6`:
```
.
|
. ]#[ .
\_______/
. ]###[ .
\___________/
. ]#####[ .
\_______________/
. ]#######[ .
\___________________/
. ]#########[ .
\_______________________/
. ]###########[ .
\___________________________/
. ]#############[ .
\_______]####.-----.####[_______/
|__|__|__|__| |__|__|__|__|
|__|__|__|__|_____|__|__|__|__|
############/_____\############
|_______|
/_________\
```
and so on.
# Construction Details
I am sure most of the details about the pattern are clear. Here are some finer details:
* The door at the bottom of the shrine can at minimum be of `1` `_` width and at maximum be of `5` `_` width.
* There will always be two `.` directly above the pillars around the door (two vertical `|`).
* The stairs start with the same width as the door and increase like show in the pattern
* The `]##..##[` blocks above each roof level increase in size of `2` from top to bottom.
* The `\__...__/` roofs levels increase in size of `4` from top to bottom.
* The walls blocks around the door should at minimum contain `1` `_` and at maximum, `3` `_` between the two `|`. Priority goes to the outer wall blocks so that the one closest to the door gets a varying size for each level.
* The space between the `.` and the `]` (or `[`) is filled by `#` in the roof just above the doors.
# Challenge Details
* Write a function or full program that reads a positive integer greater than `0` via STDIN/ARGV/function argument or closest equivalent and outputs (to STDOUT or closest equivalent) the `N`th Chinese Shrine
* Trailing newline is optional.
* There should either be no trailing spaces or enough trailing spaces to pad the output in the minimum bounding rectangle.
* There should not be any leading spaces that are not part of the pattern.
# Leaderboard
**[The first post of the series generates a leaderboard.](https://codegolf.stackexchange.com/q/50484/31414)**
To make sure that your answers show up, please start every 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
```
[Answer]
# Perl, ~~332 316~~ 294
```
$:=($w=<>)*2+6;$r=2x($m=$w>3?3:$w);$k=1x($w-3).b.4x$m;
y!a-f1-4!/.|\\[,#_ -!,/,/,s/(.*),(.*).{@{-}}/$2$1/,printf"%$:s%s
",y!/\\[!\\/]!r,(reverse=~s/.//r)for@x=(b,c,
(map{b33.3x$_.e.1x$_,"[#$k,"x/$w/.a__.22x$_}1..++$w),
_c.3x$m.f.($z=substr"|__"x$:,0,2*++$w),"_|$r,$z","d$r,".11x$w,c_.$r,d__.$r)
```
Try [me](http://ideone.com/I6833m).
# C, 371
```
d,i,w;char s[1<<24];m(){v(w,13);}p(){puts(s+1);}
v(i,j){s[w-i]=".|]\\#/"[j%7];s[w+i]=".|[/#\\"[j%7];
while(i--)s[w-i]=s[w+i]="# _-"[j/7];}
main(l){scanf("%d",&l);d=l>3?3:l;m(w=l*2+6);p(v(0,0));
for(v(0,1);i++<=l;v(i*2+2,17))p(),v(i*2+3,7),m(p(v(i,2)));v(l+2,2);p(v(d,21));
for(m(i=w-3);i>d+1;i-=3)v(i,15);p(v(d,8));p(v(d,15));
v(w-3,4);m(p(v(d,19)));p(v(d+1,15));p(v(d+2,19));}
```
Try [me](http://ideone.com/sZ0W6q).
# JavaScript, 365
The above can be translated almost 1 to 1 into JavaScript:
```
s=[];r="";i=0;m=()=>v(w,13);p=()=>r+=s.join('')+"\n";
v=(i,j)=>{s[w-i]=".|]\\#/"[j%7];s[w+i]=".|[/#\\"[j%7];
while(i--)s[w-i]=s[w+i]="# _-"[j/7|0];};
f=l=>{d=l>3?3:l;m(w=l*2+6);p(v(0,0));
for(v(0,1);i++<=l;v(i*2+2,17))p(),v(i*2+3,7),m(p(v(i,2)));v(l+2,2);p(v(d,21));
for(m(i=w-3);i>d+1;i-=3)v(i,15);p(v(d,8));p(v(d,15));
v(w-3,4);m(p(v(d,19)));p(v(d+1,15));p(v(d+2,19));}
```
Use:
```
f(2);console.log(r)
```
[Answer]
# Python 2, ~~356~~ ~~352~~ ~~347~~ 344 bytes
```
n=input()
A,B,C,D,E,F,G,H,I='_ |\/#.]['
def p(*S):
for s in S:print(5+2*n-len(s)/2)*B+s
p(G,C,'. ]#[ .')
for i in range(n):b=B*(4+i);p(D+A*(7+4*i)+E,G+b+H+F*(3+2*i)+I+b+G)
d=2*min(3,n)-1
a=A*(2+i)
f=F*(1+i-d/2)
j=4+2*i-d/2
w=('|__'*n)[:j-1]+A+C
v=w[::-1]
p(D+a+H+f+G+'-'*d+G+f+I+a+E,w+B*d+v,w+A*d+v,F*j+E+A*d+D+F*j,C+A*(d+2)+C,E+A*(d+4)+D)
```
This basically builds the shrine line by line. The function `p` prints a string with the spaces needed to center it.
I used *python 2* to save lots of bytes, because the *python 3* map object doesn't trigger. I guess I should always golf in *python 2*, just saves a few more bytes (even if it's just to not have to parse the input to int).
Hehehe, it's not like code's pretty for golfing in the first place.
Edit: and of course, I now don't need the map anymore...
Here's the code in ungolfed form:
```
n = int(input())
# A function to print strings centered
half_width = 5 + 2*n
def p(string):
spaces = ' ' * (half_width - len(string) // 2)
print(spaces + string)
# The rooftops
p('.')
p('|')
p('. ]#[ .')
for i in range(n):
p('\\' + '_'*(7 + 4*i) + '/')
p('.{0}]{1}[{0}.'.format(' '*(i + 4), '#'*(3 + 2*i)))
# The bottom rooftop
door_width = 2 * min(3, n) - 1
# (11+4i - (3+2i) - 4) / 2 = (4 + 2i) / 2 = 2 + i
p('\{0}]{1}.{2}.{1}[{0}/'.format('_'*(2 + i), '#'*(1 + i - door_width // 2), '-'*door_width))
# The windows
w = '|__'*n
w = w[:4 + 2*i - door_width // 2]
if w[-1] == '|':
w = w[:-1] + '_'
w += '|'
p(w + ' '*door_width + w[::-1])
p(w + '_'*door_width + w[::-1])
# The foundation and the stairs
w = '#'*(4 + 2*i - door_width // 2)
p(w + '/' + '_'*(door_width) + '\\' + w)
# The remaining stairs
p('|' + '_'*(door_width + 2) + '|')
p('/' + '_'*(door_width + 4) + '\\')
```
[Answer]
# JavaScript (*ES6*), 440
**Edit** Fixed lintel bug
A function whith height as a parameter, output to console.
Using template string *a lot*, all newlines are significant and counted.
Run snippet to test in Firefox (with console output)
```
f=x=>{R=(n,s=0)=>' #_-'[s][Z='repeat'](n),M=c=>R(2)+'|__'[Z](z+1).slice(0,z-1)+'_|'+R(y,c)+'|_'+'__|'[Z](z+1).slice(1-z)
for(z=x+x+(x<2)+(x<3),y=x>2?5:x>1?3:1,l=-1,o=`${t=R(x+x+5)}.
${t}|
`;l++<x;)o+=`${t=R(x+x-l-l)}.${u=R(l+3)}]${R(l*2+1,1)}[${u}.
${t}\\${l-x?R(7+l*4,2):`${t=R(x+1,2)}]${u=R(x<3||x-2,1)}.${R(y,3)}.${u}[${t}`}/
`;console.log(`${o+M(0)}
${M(2)}
${R(2)}${t=R(z,1)}/${u=R(y,2)}\\${t}
${R(1+z)}|__${u}|
${R(z)}/____${u}\\`)}
// TEST
f(1),f(2),f(3),f(4),f(5),f(6)
```
```
Output 1 to 6 in console
```
**Ungolfed** version for interactive test:
```
// Not so golfed
f=x=>{
R=(n,s=0)=>' #_-'[s].repeat(n); // base building blocks
M=c=>R(2)+'|__'.repeat(z+1).slice(0,z-1)+'_|'+R(y,c)+'|_'+'__|'.repeat(z+1).slice(1-z); // manage door level
z=x+x+(x<2)+(x<3); // door and stairs surroundings
y=x>2?5:x>1?3:1; // door and stairs width
o = `${R(x+x+5)}.\n${R(x+x+5)}|\n`; // top
for(l=-1;l++<x;)
o += `${ // even row
t=R(x+x-l-l) // left padding
}.${
u=R(l+3)
}]${
R(l*2+1,1)
}[${
u
}.\n ${ // end even row, start odd row
t // left padding
}\\${
l-x?R(7+l*4,2)
:`${t=R(x+1,2)}]${u=R(x<3||x-2,1)}.${R(y,3)}.${u}[${t}` // if last row before the door, insert lintel
}/\n`;
o += `${
M(0) // door level row 1
}\n${
M(2) // door level row 2
}\n${
R(2)}${t=R(z,1)}/${u=R(y,2)}\\${t // stairs row 1
}\n${
R(1+z)}|__${u // stairs row 2
}|\n${
R(z)}/____${u // stairs row 3
}\\`;
out(o)
}
out=x=>O.innerHTML=x
f(3)
```
```
<input id=I value=3><button onclick='f(+I.value)'>-></button><br>
<pre id=O></pre>
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 280 bytes
```
d5+\.꘍,d5+\|꘍,(n-d:£\.꘍3n+\]꘍\#nd›*\[3n+\.꘍Ṡ,¥›\\꘍ndd7+\_*\/Ṡ,)\.?3+꘍\]\#?d›*\[?3+\.꘍Ṡ,ð\\?›\_*\]?2-1∴\#*\.?d‹5∵-\.?2-1∴\#*\[?›\_*\/Ṡ,3<[⟨0|⟨3⟩|⟨2|1⟩⟩$i|3/⌊d2w$ẋf`013`?3%iIJ';]\_*Ṅðpð+ð\|Vðdp:£3?∵꘍øm,¥3?∵\_*+øm,4<[3+|d]\#*:£ðdp\/\_?d‹5∵*\\¥Ṡ,¥L›\|꘍\_?d‹5∵⇧*\|Ṡ,¥L\/꘍\_?d‹5∵4+*\\Ṡ,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=d5%2B%5C.%EA%98%8D%2Cd5%2B%5C%7C%EA%98%8D%2C%28n-d%3A%C2%A3%5C.%EA%98%8D3n%2B%5C%5D%EA%98%8D%5C%23nd%E2%80%BA*%5C%5B3n%2B%5C.%EA%98%8D%E1%B9%A0%2C%C2%A5%E2%80%BA%5C%5C%EA%98%8Dndd7%2B%5C_*%5C%2F%E1%B9%A0%2C%29%5C.%3F3%2B%EA%98%8D%5C%5D%5C%23%3Fd%E2%80%BA*%5C%5B%3F3%2B%5C.%EA%98%8D%E1%B9%A0%2C%C3%B0%5C%5C%3F%E2%80%BA%5C_*%5C%5D%3F2-1%E2%88%B4%5C%23*%5C.%3Fd%E2%80%B95%E2%88%B5-%5C.%3F2-1%E2%88%B4%5C%23*%5C%5B%3F%E2%80%BA%5C_*%5C%2F%E1%B9%A0%2C3%3C%5B%E2%9F%A80%7C%E2%9F%A83%E2%9F%A9%7C%E2%9F%A82%7C1%E2%9F%A9%E2%9F%A9%24i%7C3%2F%E2%8C%8Ad2w%24%E1%BA%8Bf%60013%60%3F3%25iIJ%27%3B%5D%5C_*%E1%B9%84%C3%B0p%C3%B0%2B%C3%B0%5C%7CV%C3%B0dp%3A%C2%A33%3F%E2%88%B5%EA%98%8D%C3%B8m%2C%C2%A53%3F%E2%88%B5%5C_*%2B%C3%B8m%2C4%3C%5B3%2B%7Cd%5D%5C%23*%3A%C2%A3%C3%B0dp%5C%2F%5C_%3Fd%E2%80%B95%E2%88%B5*%5C%5C%C2%A5%E1%B9%A0%2C%C2%A5L%E2%80%BA%5C%7C%EA%98%8D%5C_%3Fd%E2%80%B95%E2%88%B5%E2%87%A7*%5C%7C%E1%B9%A0%2C%C2%A5L%5C%2F%EA%98%8D%5C_%3Fd%E2%80%B95%E2%88%B54%2B*%5C%5C%E1%B9%A0%2C&inputs=5&header=&footer=)
No, I'm not explaining this.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 404 bytes
```
≔Nν≔⁺⁵ײνη≔× ⁻η⁻∕¹¦²¦¹τ⁺⁺⁺⁺⁺τ.¶τ|¶× ⁻η⁻∕¹²¦²¦¹“±∨N"G:W⮌+”Fν«≔⁺⁺\×_⁺⁷×⁴ι/ε≔× ⁻η⁻∕L岦¹τ⁺⁺τε¶≔⁺⁺⁺⁺.× ⁺ι⁴]×#⁺³×²ι⁺⁺[× ⁺ι⁴.ε≔× ⁻η⁻∕L岦¹τ⁺⁺τε¶»≔⁻ײ⌊⟦³ν⟧¹δ≔∕δ²ζ≔×#⁺¹⁻νζσ≔⁺⁺⁺⁺⁺\×_⁺ν¹]σ.⁺×-δ⁺.⁺σ⁺[⁺×_⁺ν¹/ε≔× ⁻η⁻∕L岦¹τ⁺⁺τε¶≔×|__νε≔⁻⁻⁺⁴ײνζ¹τ≔✂ε⁰τ¦¦ε≔Lεα≔⁻Lε¹β¿⁼✂εβᦦ|«≔⁺✂ε⁰⦦_ε»≔⁺✂ε⁰ᦦ|ε≔⁺⁺ε× δ⮌εα≔⁺⁺ε×_δ⮌εβM⁼ν¹¦⁰⁺⁺⁺⁺ ᶦ βM±⁼ν¹¦⁰M±Lα⁰≔×#⁻⁺⁴ײ⁻ν·⁵ζε⁺¶⁺⁺ε⁺/⁺⁺×_δ\ε¶≔⁻⁻⁺⁴ײ⁻ν·⁵ζ¹ψ⁺× ψ⁺|⁺×_⁺δ²|¶⁺× ⁻ψ¹⁺/⁺×_⁺δ⁴\
```
[Try it online!](https://tio.run/##lVLNSsNAEH6VRY/Sir8HX8CbL2BLKL0oCILnHBqbQ5QeLblUeouCWmzapGx@EDb3yTvsC@QR4uzkp7HFQ2GTXWa/@b5vZrZ/03vo3/fu8lw@vWTRDGLcpRFIw0ts4UIMKwwkNpNGiEcjlNZYcOEIFz@emgRdr9RsCz81deFvpbhVkhxMxFxa71d7lxdZtJKz0YEcvGaRA7H4qNSDTmJrdFoltjSWwA/B23KSRZ/g/bWSmhjxa5pitSktAI5M3cTex7NYUH28AFw3AO1dhERIUqEik6NnOXXEAns4fRMclurKGsMSdXyiJGGueGPw0@GGy3XV2AneTYdtPCZ2C4mwBCU5VFYpWKF27Upi65qG6l5hmxYCluWwfUrBq8kjQozv1EQWh9DECvMir5Dg4IofaUSEBhfmCqzXQyw5QDlxNMSHGxcFvvSibAI@Ooblzka1VBXWqrCbRV@oqYoXDrI028cYcvrCwV3B8Jk1gBRQxucqqxxHo3wai8AeeuArfwE2rJTH32FxJiOd@omF/zJgIy3CM9r19dTwOehEXUwttdSLIP4KgHSdPD9nZ@yUnbBjdpS3bn8B)
[Answer]
# CJam, 200 bytes
```
-4'.-4'|]2/ri:M),{2af.-~[W'.I3+~']'#I)*][-2'\'_I2*4+*]]}fI~[~M)<']
M2m1e>'#*'.'-M3e<:D*][-3"|__"M*M2+M2*(e>:L<"_|"D~][_~~'_*][-3'#L)*
'/'_D*][L2+~'|'_D)*][L)~'/'_D2+*]]{{_0<{~S*}&}%s_W%1>"\/]""/\["erN}%
```
Newlines added to avoid scrolling. [Try it online](http://cjam.aditsu.net/#code=-4'.-4'%7C%5D2%2Fri%3AM)%2C%7B2af.-~%5BW'.I3%2B~'%5D'%23I)*%5D%5B-2'%5C'_I2*4%2B*%5D%5D%7DfI~%5B~M)%3C'%5DM2m1e%3E'%23*'.'-M3e%3C%3AD*%5D%5B-3%22%7C__%22M*M2%2BM2*(e%3E%3AL%3C%22_%7C%22D~%5D%5B_~~'_*%5D%5B-3'%23L)*'%2F'_D*%5D%5BL2%2B~'%7C'_D)*%5D%5BL)~'%2F'_D2%2B*%5D%5D%7B%7B_0%3C%7B~S*%7D%26%7D%25s_W%251%3E%22%5C%2F%5D%22%22%2F%5C%5B%22erN%7D%25&input=5)
**Brief explanation:**
The program builds the left half of the shrine (including the middle), then reverses it and replaces some characters to get the right half. A series of n spaces is represented as the number ~n (bitwise "not") during construction, and replaced with the actual spaces at the end.
The program starts with the top 2 lines, then for each roof level, it prepends all the previous lines with 2 spaces and adds the new roof (2 lines). The last roof is modified to add the "above door" part.
Next, the upper wall is built by repeating "|\_\_" and truncating at the right length, followed by a fixed "\_|" and spaces. The wall is then duplicated and the door spaces are replaced with underscores. Finally, the lower part is constructed line by line.
[Answer]
# Haskell, 473 bytes
```
g '\\'='/'
g '/'='\\'
g '['=']'
g ']'='['
g x=x
z=reverse
d=min 3
m n s=putStrLn$(6+2*n+1-length s)#' '++map g(z s)++tail s
n#c=replicate n c
t 0=".";t n=n#'#'++"["++(2+n)#' '++"."
r 0="|";r n=(2+2*n)#'_'++"/"
q n=d n#'-'++"."++max(n-2)1#'#'++"["++(n+1)#'_'++"/"
e i n=d n#i++"|_"++z(take(max(n+2)(2*n-1))(cycle"|__"))
b n=d n#'_'++"\\"++max(2*n)(3+n)#'#'
w i n=(d n+1+i)#'_'++["|","\\"]!!i
f n=mapM_(m n)$[u k|k<-[0..n],u<-[t,r]]++(t(n+1):map($n)[q,e ' ',e '_',b,w 0,w 1])
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~120~~ 113 bytes
```
3∵£\.\|?›ƛ⇧\.$꘍\[+\#n*+\\\_n›d*+";f÷?⇧Ẏ\]+?⇩1∴\#*+\.+¥-`|__`?:3>[d‹|⇧]Ẏ‛_|+¥꘍:ð\_VȮȧL‹\#*\/+‛|/fJ2ʀ¥+\_*+÷WvøMøĊ⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIz4oi1wqNcXC5cXHw/4oC6xpvih6dcXC4k6piNXFxbK1xcI24qK1xcXFxcXF9u4oC6ZCorXCI7ZsO3P+KHp+G6jlxcXSs/4oepMeKItFxcIyorXFwuK8KlLWB8X19gPzozPltk4oC5fOKHp13huo7igJtffCvCpeqYjTrDsFxcX1bIrsinTOKAuVxcIypcXC8r4oCbfC9mSjLKgMKlK1xcXyorw7dXdsO4TcO4xIrigYsiLCIiLCI1Il0=)
Posting this as a separate answer because it's so golfed, and uses the latest version of Vyxal.
## Explanation
```
----------------- TOP ------------
3∵£ # Store min(input, 3) into the register for later use
\.\| # Push a . and a |
?›ƛ ; # Map 1...input+1 to
⇧\.$꘍ # That+2 spaces after a dot
\[+ # Append a [
\#n*+ # Append that many #
\_n›d* # That+1 underscores
\\ +" # Appended to a \ and paired with the previous
f÷ # All of that flattened and each pushed to the stack
------------------- Doorway ------------------
?⇧Ẏ # To the last of what was pushed in the previous, take the first input+2 characters
\]+ # Append a ]
?⇩1∴\#*+ # Append min(input-2,1) hashes
\.+ # Append a .
¥- # Append min(input,3) -
?:3>[d‹|⇧] # Input*2-1 if input>3 else input+2
`|__` Ẏ # Repeat '|__' to that length
‛_|+ # Append '_|'
¥꘍ # Append min(input,3) spaces
:ð\_V # Make a copy, and replace spaces with underscores
---------- Entrance ------------
ȮȧL‹\#*\/+
ȮȧL # Length of top part of doorway with whitespace removed
‹\#*\/+ # That-1 #, plus a /
‛|/fJ # Append ['|','/']
2ʀ¥+ # [a,a+a,a+2] where a = min(3,input)
\_*+ # That many underscores appended to each of previous
÷ # Iterate out those on the stack
- Final magic bit -
W # Get the stack
vøM # Palindromise each, mirroring brackets
øĊ # Center each
⁋ # Join on newlines
```
[Answer]
## C, 660 bytes
The pattern just seemed to be too irregular to come up with anything fancy, particularly in a language without string processing. So here is my brute force approach:
```
m,d,w,k,j;r(n,c){for(j=0;j++<n;)putchar(c);}c(char*s){for(;*s;)putchar(*s++);}f(n){m=n*2;d=n<3?m-1:5;w=m-d/2+2;r(m+5,32);c(".\n");r(m+5,32);c("|\n");for(;;){r(m-k*2,32);c(".");r(k+3,32);c("]");r(k*2+1,35);c("[");r(k+3,32);c(".\n");if(k==n)break;r(m-k*2+1,32);c("\\");r(k++*4+7,95);c("/\n");}c(" \\");r(n+1,95);c("]");r(n-d/2,35);c(".");r(d,45);c(".");r(n-d/2,35);c("[");r(n+1,95);c("/\n");for(k=0;k<2;){c(" ");for(j=0;j<w/3;++j)c("|__");c("|_|"-w%3+2);r(d,k++?95:32);c(!w%3?"|":w%3<2?"|_":"|_|");for(j=0;j<w/3;++j)c("__|");c("\n");}c(" ");r(w,35);c("/");r(d,95);c("\\");r(w,35);c("\n");r(w+1,32);c("|");r(d+2,95);c("|\n");r(w,32);c("/");r(d+4,95);c("\\\n");}
```
Before golfing:
```
#include <stdio.h>
void r(int n, int c) {
for (int i = 0; i++ < n; )
putchar(c);
}
void c(char* s) {
for (; *s; ++s) putchar(*s);
}
int f(int n) {
int m = n * 2;
int d = n < 3 ? m - 1 : 5;
int w = m - d / 2 + 2;
r(m + 5, 32);
c(".\n");
r(m + 5, 32);
c("|\n");
for (int k = 0; ; ++k) {
r(m - k * 2, 32);
c(".");
r(k + 3, 32);
c("]");
r(k * 2 + 1, 35);
c("[");
r(k + 3, 32);
c(".\n");
if (k == n) break;
r(m - k * 2 + 1, 32);
c("\\");
r(k * 4 + 7, 95);
c("/\n");
}
c(" \\");
r(n + 1, 95);
c("]");
r(n - d / 2 , 35);
c(".");
r(d, 45);
c(".");
r(n - d / 2 , 35);
c("[");
r(n + 1, 95);
c("/\n");
for (int k = 0; k < 2; ++k) {
c(" ");
for (int j = 0; j < w / 3; ++j)
c("|__");
c("|_|" - w % 3 + 2);
r(d, k ? 95 : 32);
c(!w % 3 ? "|" : w % 3 < 2 ? "|_" : "|_|");
for (int j = 0; j < w / 3; ++j)
c("__|");
c("\n");
}
c(" ");
r(w, 35);
c("/");
r(d, 95);
c("\\");
r(w, 35);
c("\n");
r(w + 1, 32);
c("|");
r(d + 2, 95);
c("|\n");
r(w, 32);
c("/");
r(d + 4, 95);
c("\\\n");
return 0;
}
```
Not much to explain here. It just goes line by line, and generates the necessary count of each character. I tried to keep the code itself compact, but it still adds up. `d` is the width of the door, `w` the width of each brick wall.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/48428/edit)
## The Background
So, we all know the classic proof that goes like this:
a = b
a² = ab
a² - b² = ab - b²
(a-b)(a+b) = b(a-b)
(a+b) = b
b+b = b
2b = b
2 = 1 (Ha ha!)
Of course, the mistake is that you can't divide by 0. Since a = b, a - b = 0, so there was a hidden division by 0.
## The Challenge
You have to replicate this proof. First, declare two integers a and b (it doesn't matter what you call them) that equal. Then declare aMod and bMod to be modifiable versions of a and b and initially equal to a and b, respectively. You must multiply them both by a, then subtract b\*b from both of them. You must then divide by a - b and then divide them by b (or a) to get. Then, print out aMod and bMod with an equal sign between them.
## The Underhanded
Of course, since you declared a and b to equal, a - b = 0, and dividing by 0 causes an error. So you must creatively fake it. Also, because you are trying to replicate the proof, the result on all the operations on aMod and bMod must not equal when printed. They don't have to equal exactly 2 and 1, just two numbers that don't equal.
Here is an example:
```
#include <iostream>
#define subtract(a, b) a - b
using namespace std;
int main()
{
int a = 4, b = 4;
int a_2 = a, b_2 = b;
a_2 *= a;
b_2 *= b;
a_2 -= b * b;
b_2 -= b * b;
a_2 = a_2 / subtract(a, b);
b_2 = b_2 / subtract(-b, -a); // a - b == (-b) - (-a)
a_2 /= a;
b_2 /= a;
cout << a_2 << " = " << b_2 << " because I did the same operations on both of them.";
return 0;
}
```
Maybe not the best one, but it illustrates the point.
## Bonus Underhanded
Instead of printing the equals sign, you can print out just the two variables (aMod and bMod), and then have code that appears to compare the two variables for equality but in actuality lies that they equal (and prints some form of `true`).
Remember, this is a popularity contest, so highest number of upvotes wins.
Also, a new version of mathematics called Mathematics 2.0 has made use of standard loopholes automatically invalidate a proof.
[Answer]
# JavaScript
```
var a=3,b=3,a2=3,b2=3
[a2,b2]=[a2*a,b2*a]
[a2,b2]=[a2-b*b,b2-b*b]
[a2,b2]=[a2/(a-b),b2/(a-b)]
console.log([a2/a,b2/a])
```
Output:
```
[1, NaN]
```
Note that 0/0 = NaN
### Hint
>
> Try add some semicolons.
>
> This program is actually `var a=3,b=3,a2=3,b2=3[a2,b2]=...=[a2/(a-b),b2/(a-b)];console.log([a2/a,b2/a])`.
>
> And the NaN is `[3/0,undefined/0]/3`.
>
>
>
[Answer]
# Python 2
I'm pretty sure it's obvious since everyone knows Python, but here's my attempt:
```
a=b=1
x,y=a*a,a*b
x,y=x-b*b,y-b*b
x,y=a+b/a-b,b
x,y=x/a,y/a
print(x==y)
```
It outputs `True`.
Hint:
>
> Check my division.
>
>
>
[Answer]
# Ruby
```
def calculate a,
b = a
left, right = a, b
left, right = [left, right].map { |x| x * a }
left, right = [left, right].map { |x| x - b*b }
left, right = [left, right].map { |x| x / a - b }
left, right = [left, right].map { |x| x / b }
puts $/=[left, right].join(' = ')
end
calculate 3,
STDOUT.write($/)
```
[ideone](https://ideone.com/vQGVAD)
Hint:
>
> ,
>
>
>
Explanation:
>
> The two lines that end in commas cause the program to behave differently than it would. Without the commas, the method takes a single argument `a`, sets `b` equal to `a`, performs the transformations from the proof on each one (except due to some missing parentheses, it doesn't divide by 0), and outputs the result (With input of 3, it'd output "-1 = -1". With the trailing comma, however, the `b = a` line becomes part of the method signature, meaning that it's declaring a second argument with a default value. The method invocation at the end passes in the result of `STDOUT.write($/)`, which is 1 (the number of bytes it wrote to STDOUT, since `$/` is predefined to a newline character.) So a is 3 and b is 1, resulting in the equation starting off as "3 = 1". Garbage in, garbage out.
>
>
>
[Answer]
# GolfScript
Warning: this program is cheating a bit, in that it doesn't print aMod and bMod
```
1nt main(){
int a = 2, b = 2;
int aMod,bMod;
//The next line should throw and error, but why doesn't it??/
aMod = (a*a - b*b) / (a-b);
//The next line should throw and error, but why doesn't it??/
bMod = (b*a - b*b) / (a-b);
//The if should fail, but it works??/
if(aMod == bMod)
printf("1");
return 0;
};
```
Try it [here](http://golfscript.apphb.com/?c=MW50IG1haW4oKXsKICBpbnQgYSA9IDIsIGIgPSAyOwogIGludCBhTW9kLGJNb2Q7Ci8vVGhlIG5leHQgbGluZSBzaG91bGQgdGhyb3cgYW5kIGVycm9yLCBidXQgd2h5IGRvZXNuJ3QgaXQ%2FPy8KICBhTW9kID0gKGEqYSAtIGIqYikgLyAoYS1iKTsKLy9UaGUgbmV4dCBsaW5lIHNob3VsZCB0aHJvdyBhbmQgZXJyb3IsIGJ1dCB3aHkgZG9lc24ndCBpdD8%2FLwogIGJNb2QgPSAoYiphIC0gYipiKSAvIChhLWIpOwovL1RoZSBpZiBzaG91bGQgZmFpbCwgYnV0IGl0IHdvcmtzPz8vCiAgaWYoYU1vZCA9PSBiTW9kKQogICAgcHJpbnRmKCIxIik7CiAgcmV0dXJuIDA7Cn07)!
So what's going on?
>
> The first thing you may have noticed are the "forbidden trigraphs". But remember, this is GolfScript, not C! Also, probably noticed that it doesn't actually say "int main()", it says "1nt main()". In GolfScript, the "1" means push 1 onto the stack, and the "nt main" gets processed as two uninitialized variables, which do nothing. The two parentheses first add 1 to the top number of the stack, and then subtract one, essentially cancelling themselves out. The brackets denote a block that gets pushed onto the stack, and then the semicolon pops it off right away. So, at the end, we just have the original "1" that was pushed on, and at the end of a GolfScript program, the stack gets printed. This answer was inspired by [this](https://codegolf.stackexchange.com/a/30034/52152) one.
>
>
>
[Answer]
# Prolog
```
areEqual(A, B) :-
Amod = A,
Bmod = B,
Amod = Amod * A,
Bmod = Bmod * B,
Amod = Amod - B*B,
Bmod = Bmod - B*B,
Amod = Amod / (A-B),
Bmod = Bmod / (A-B),
Amod = Amod / A,
Bmod = Bmod / A,
Amod == Bmod.
```
The output when `areEqual(4,4)` is called (or any other couple of numbers really):
```
false
```
Why?
>
> In Prolog, the operator "=" is not affectation ; it's "Unification". Therefore `Amod = Amod * A` fails because `Amod`has already been unified with `A`, and thus cannot possibly be unified with `Amod * A`. Prolog then immediatly stops executing the current rule and returns `false`.
>
>
>
[Answer]
## JavaScript
```
//Very badly written code!
//No! It is "poetic" code!
while(true){break;}{
let scrollMaxX = 3, screenX = 3;
var scrollBarWithBeerMax = scrollMaxX, Yscroll = screenX; for(var i = 0; i<1; i++){}}
scrollBarWithBeerMax *= scrollMaxX;
Yscroll *= screenX;
scrollBarWithBeerMax -= screenX * screenX;
Yscroll -= screenX * screenX;
scrollBarWithBeerMax /= (scrollMaxX - screenX);
Yscroll /= (scrollMaxX - screenX);
alert(scrollBarWithBeerMax + ' = ' + Yscroll);
```
Output:
<http://jsbin.com/furino/2/edit?js,output>
JsBin doesn't seem to be able to execute this code. Use the browser console instead.
Why?
>
> scrollMaxX and screenX are already existing variables. They are built in in the browser. Thus, the result may vary. The let keyword only temporarily changes their value.
>
>
>
Another JavaScript one:
It doesn't exactly follow the rules, it only outputs if the variables are equal or not.
```
var a = 2;
var b = 2;
var a_duplicate = a;
var b_duplicate = b;
a_duplicate*=a
b_duplicate*=b;
a_duplicate-=b*b;
b_duplicate-=b*b;
a_duplicate/=(a-b);
b_duplicate/=(a-b);
alert(a_duplicate==b_duplicate);
```
Why?
>
> NaN is not equal to NaN by IEEE float specifications. Thanks to Alex Van Liew for pointing out that this doesn't just apply to Javascript.
>
>
>
[Answer]
## Fantom
```
a := 3
b := 3
duplicates := [a:b]
duplicates = duplicates.map {it * a}
duplicates = duplicates.map {it - b*b}
duplicates = duplicates.map {it / a-b}
echo(duplicates.join("") |Int a_2, Int b_2 ->Str| {"" + a_2 + " = " + b_2})
```
Output:
```
-3 = 3
```
Why?
>
> [a:b] is a map, not a list. Not so sneaky, I know :(
>
>
>
[Answer]
# C
Classic proof fallacy requires classic C syntax misunderstanding. Sadly I have met some "high-level-only" developers who are convinced C is broken because of results similar to this code. If you know how C works it becomes fairly obvious, but if you saw the code and assumed it was a different language, it might not be.
```
a,b,LHS,RHS;
main(){
a=2; b=2;
LHS=a; RHS=b;
//multiply both sides by a
LHS,RHS *= a;
//subtract b squared from both sides
LHS,RHS -= b*b;
//assert that it factors correctly
if (LHS,RHS != (a+b)*(a-b), b*(a-b)) printf("ERROR!\n");
//'hard' division, just to be sure the compiler doesn't remove it
LHS,RHS /=! (a-b);
//assert that a+a really is b+b
if (a+a != b+b) printf("ERROR!\n");
//now just divide them by b
printf("%d = %d ? ", LHS/b, RHS/b);
if (RHS = LHS)
printf("true!");
else
printf("false!");
}
```
Of course it doesn't work quite as well when written more idiomatically with `#include <stdio.h>` and int's thrown in front of the declarations.
] |
[Question]
[
Write a program that generates a winning sequence of moves to the deterministic variant of the game 2048. The sequence should be in the form of a string of numbers 0-3, with 0: up, 1: right, 2: down, 3: left.
For example, the string "1132" means right right left down. The winning program is the shortest source code that gets to 2048!
The rules to deterministic 2048:
The game is played on a 4x4 grid initially containing 1 tile, in the upper left-hand corner. Each move consists of the command "left", "right", "up" or "down". The command left slides all the tiles on the grid to the left, then combines and sums like tiles starting from the left. Likewise, the command right slides tiles to the right, then combines starting from the right.
Each tile can only participate in one combination per move.
After a move, a new 2 tile is created in the first column from the left with an available space, in the first available space from the top in that column.
For example, the sequence "right right left down" leads to the states
```
2___
____
____
____
2__2
____
____
____
2__4
____
____
____
24__
2___
____
____
2___
____
____
44__
```
The command right applied to the row \_ 2 2 2 results in \_ \_ 2 4
The command right applied to the row 2 2 2 2 results in \_ \_ 4 4
This question inspired by <http://jmfork.github.io/2048/>
[Answer]
# Python, 740 characters (665 characters compressed)
**Code**:
```
R=range
G=lambda:[[0]*4for _ in R(4)]
J=[(0,4,1),(2,-1,-1),(1,4,1)]
H=[0,-1,1]
def M(P,d):
C=G();g,z=[(0,-1),(1,0),(0,1),(-1,0)][d];Q=H[g];W=H[z]
while 1:
N=[r[:]for r in P]
for x in R(*J[g]):
for y in R(*J[z]):
s=N[y][x];q,w=y-W,x-Q;d=N[q][w];a,b,c=(((0,s,d),(1,0,s+d))[s==d],(0,0,s or d))[s<1 or d<1];
if 2-a-(C[y][x]+C[q][w]>0):N[y][x]=b;N[q][w]=c;C[q][w]+=a
if N==P:break
P=N
return N
def F(N):
for x in R(4):
for y in R(4):
if N[y][x]==0:N[y][x]=2;return N
def Z(P,i):
X=[d for d in R(4)if M(P,d)!=P]
return i==0and(sum((256,c)[c>0] for v in P for c in v)+P[3][3]*10+P[3][2]*9,-1)or max((Z(F(M(P,d)),i-1)[0],d)for d in X)if X else(-1,-1)
B=G()
B[0][0]=2
h=''
while B[3][3]!=2048:_,X=Z(B,4);h+=`X`;B=F(M(B,X))
print h
```
(Mixes tabs with spaces for indentation to save a few bytes)
I must have sucked at golfing it because if I just compress the above code, base-64 encode it, and `exec` it, it's only 665 characters. The following is exactly equivalent to the above, no hard-coded solution or anything:
```
exec"""eJxVUl1vozAQfMa/wn2qnRjJcNzpDnf7QKS2qlRE+1IUy2oJkARdwl2hbT5+/a0NiXqSZXYH78zY
u0/QFe2qJrewKbaLqoi1lmYSLf909IU2LX1iETfkHjSTIhIBFywUfoALo8AhhtyBlhYMDKnqJX1g
mah4TOgMbhlXK3F01WOJxF06It8mRldGPcKdXhn1jJ+jIXS3bjY1DWLipaA7HRvrprNuMkM8m+wH
a5N7LEMlj1rwcAaPDvR6SPXB6L1Rb2IHB/9Z7P1HVSH6ZvTOqEIsRAmMoZ8eHTt3op9WnOseoDLW
KAIUuR12FbjwKjAK2ZslDf3CZ7NBYzobWK8lj0dZWKhRCko1/p5CQWxpCpDFi64ufhMvg5TQrn7/
6Fqauie8Yal9wC9XjeyNvtzS5dQSjVogz7Kh+o9sjv1oLF0OunKc1YmjOXXrAvBpTx4aJCvaivUf
W8bC7z9EyXV5LY2r/XR9cGFpw08+zfQ3g2sSyCEMzeSXbTce2RZ7xubshg0yXDSI44RhfDaSWxs5
rTd9zYbRIomdHJLgQVwQkjVcXpJhLJJB7AJCGf2MX0QOc5aIiKv1FF7zV5WAFUtEzjn52zXtO13/
AwRvylc=""".decode('base64').decode('zip')
```
**Answer**:
Takes ~47 seconds (17 seconds ungolfed) to find the 1111-move sequence:
>
> 2221230232213120120232222222221221203211012312310123123101223113322222123230210302321222323223212322101202323123322032132021233212312332023123312111123231223113312312322312232123222021221332111332221012222312222302232021233212312332023212222222123221202332023120312123223221232232222222122122323222222212212232222222221322233231222322200232122312232313132022322212312332121332312320212211332312323223212320232322322133223213212323202123123321231313332122232310112113322212323222220130231233211313332122232312312223232231231232312222220232212312220212232312232123222021221332111332221012222312222302232021233212312332023212222222123221202332023120312123223221322323223312230230323312232313133232223233212312323123323222332222222132221321320323233223232121323212232013221323233032021223320231233220322203132123202123321231233202131321221111231213232131210212312232332132103123130213133213232213321323212332332212222123323322202302333121220222323232113123323221223032131201123212133123131222323313133313300123231332011222221223232331313313112312113230231121232332122323232321312323213212232313212323211330231231012
>
>
>
With the following final board position and move:
```
4 2 16 4
2 8 128 8
2 . . 1024
. . . 1024
Best move: s, with EV=25654
```
Trivia: the solution is 309 bytes gzipped and 418 bytes if gzipped and base64-encoded. Thus it would be a shorter program to just decode that and print it out, but that is [no fun at all](http://meta.codegolf.stackexchange.com/a/1063/4800).
**Explanation**:
Here's a [pastebin of the ungolfed version](http://pastebin.com/y96uRGPN) which prints out the board after each move, very fun to watch!
It's a very simple brute-force AI. It assigns an EV for each board position:
```
ev = 256 * number of spaces
+ sum_of_values
+ 10 * board_bottom_right
+ 9 * board_bottom_2nd_right
```
It does a depth-first search four moves ahead and picks the path that leads to the highest EV in four moves. The ev function encourages it to clean up the board and to keep the highest-valued pieces in the corner, which ends up being pretty optimal. It's enough to get it there!
If you modify the EV function to place a higher value on other board spots, something like:
```
1 1 1 1
1 1 1 1
1 1 9 10
1 9 10 11
```
That function gets it as far as:
```
2 8 4 2
16 32 64 16
64 128 512 1024
2 256 2048 8192
```
**16k**:
Eureka! With a 5-step lookahead instead of a 4, and the following weights:
```
1 1 4 4
1 1 4 10
1 1 14 16
1 16 18 20
```
It almost almost gets 32k, ending on:
```
2 128 4 2
64 256 512 4
4 128 1024 4096
16 2048 8192 16384
```
The sequence is [here](http://pastebin.com/WuaeJQqJ).
**32k**:
Yes ladies and gentlemen, we have hit the 32k mark. The EV function, instead of multiplying squares by a constant, raises each square to the following powers and adds them. `x` means the square isn't involved:
```
x x x 3
x x x 4
x x 5 6
x 6 7 8
```
It still sums all the values once and adds 256 for each empty square. Lookahead was 4 all the way up to 32k, and then it bumped up to 5, but it doesn't really seem to do much. End board:
```
2 128 8 2
64 256 512 4
4 128 1024 2048
16 4096 8192 32768
```
[Pastebin of the 24,625-move sequence](http://pastebin.com/LrVzF0yL).
] |
[Question]
[
The Hamming distance between two strings of *equal* length is the number of positions at which the corresponding characters are different. If the strings are not of equal length, the Hamming distance is not defined.
### Challenge
Write a program or function that finds the largest Hamming distance from among all pairs of strings from a list of strings, padded as required according to the rules described below.
The characters will be from within `a-zA-Z0-9`.
The strings may not be equal in length, so for each comparison the shorter string has to be padded as follows:
* wrap the string from the beginning as many times as needed to match the required length
* change the cases of the letters each *odd time* wrapping (1st, 3rd, 5th, etc.)
* leave things outside `a-zA-Z` unchanged when wrapping
For example, let's say you need to pad the 5 character string `ab9Cd` so that it ends up with 18 characters. You would end up with:
```
ab9CdAB9cDab9CdAB9
^^^^^ ^^^
```
with `^` added underneath the 1st and 3rd wraps to highlight to case changes.
### Input/Output
Input/output format is flexible. You can assume the input has at least two strings, and that all strings will have at least one character.
The output is an integer.
### Rules
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Standard rules apply.
### Test cases
```
[ "a", "b" ] => 1
[ "a", "b", "c" ] => 1
[ "a", "a", "c" ] => 1
[ "abc", "abcd" ] => 1
[ "abc12D5", "abC34d3", "ABC14dabc23DAbC89d"] => 17
[ "a", "Aaa", "AaaA", "aAaAa", "aaaaaaaaaaaaaa", "AAaAA", "aAa" ] => 8
["AacaAc", "Aab"] => 2
```
### Reference implementation
I tested the examples with (completely ungolfed) R code that you can [try here](https://tio.run/##fVJNT@MwFLznV5icHClFJAVpkeghFDhx2wsCoci1TRvJcSzbFYEVv72M7RYtIiV5ip1543lftjvDBLmakZet5r4bNB0L8i8jRLeuCrjmG2bp@FQ9Fwmt/0friMK6F5pOLCInaRDieqZUOOC8dUZ1PiqVJM@LJ2yeI0kxu5aBFPQiotsvLKgB@yBSOfmLav2LajWlWgXVlPwgRPtqmQmeUJi3NGez92b2mEMUC36wi2H39Qa6kbFzhjkvz6iVhnIaOeWXYlESJfXab06HrSeLQwqA@aAUMyhpEdKGIqd7zTKlXmQfWbZhfd/p9dSA0niO9zUN6niHYFb6rdXUbXsKtZMFzhQxLO6EkKI9En0PU7DwW2RZz8bWbCZvUQBTBwABeAiAHA3T4nRtOwiUBIY0oegad8e4H6xDV@6a@7@3@24jAO0ZOCNFi9QbfShJVZLvaaKpGhYq2KWMMA@SszDDVU6A/0Tx4ZMuNu1a8ehccTHhquqbi@Rezs/FPN6d62V1LuCr5zfNavnnUkxGa9hhaaJAgzduvj2RAteBE6R2u08) to compare any other examples you might try out with your code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
Not really happy with it. Should be golfable, even to ~15 bytes perhaps.
```
LÞŒcµṁ/sḢL$ŒsÐeFn)§Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8/9/n8Lyjk5IPbX24s1G/@OGORT4qRycVH56Q6paneWj5w50N////j1ZKTEo2NHIxVdJRADKdjU1SjEFMRydnQ5MUoJyRsYtjkrOFZYpSLAA "Jelly – Try It Online")
or [Check out a test suite!](https://tio.run/##y0rNyan8/9/n8Lyjk5IPbX24s1G/@OGORT4qRycVH56Q6paneWj5w50N/w@3P2pa4/7/f3S0UqKSjoJSklKsDpcCnAMkkpFFElFEkpLBYknJKQgRQyMXU4ios7FJijGI6ejkbGiSApQzMnZxTHK2sExBNtIxEUY5gvU5AiGYgQLASoBSMDVKsbEA "Jelly – Try It Online")
### Explanation
```
LÞŒcµṁ/sḢL$ŒsÐeFn)§Ṁ Full program or monadic link. N = input. | Example: ["abc12D5", "abC34d3", "ABC14dabc23DAbC89d"]
LÞ Sort N by length. | [['a', 'b', 'c', '1', '2', 'D', '5'], ['a', 'b', 'C', '3', '4', 'd', '3'], ['A', 'B', 'C', '1', '4', 'd', 'a', 'b', 'c', '2', '3', 'D', 'A', 'b', 'C', '8', '9', 'd']] (in Jelly, strings are list of characters)
Œc Unordered pairs: [x, y] for all distinct x, y in N. | [[['a', 'b', 'c', '1', '2', 'D', '5'], ['a', 'b', 'C', '3', '4', 'd', '3']], [['a', 'b', 'c', '1', '2', 'D', '5'], ['A', 'B', 'C', '1', '4', 'd', 'a', 'b', 'c', '2', '3', 'D', 'A', 'b', 'C', '8', '9', 'd']], [['a', 'b', 'C', '3', '4', 'd', '3'], ['A', 'B', 'C', '1', '4', 'd', 'a', 'b', 'c', '2', '3', 'D', 'A', 'b', 'C', '8', '9', 'd']]]
Here, by distinct, I mean at different positions. |
µ ) Map with a monadic link. |
ṁ/ Mold x like y. That is, cycle x until it reaches length y. | [['a', 'b', 'c', '1', '2', 'D', '5'], ['a', 'b', 'c', '1', '2', 'D', '5', 'a', 'b', 'c', '1', '2', 'D', '5', 'a', 'b', 'c', '1'], ['a', 'b', 'C', '3', '4', 'd', '3', 'a', 'b', 'C', '3', '4', 'd', '3', 'a', 'b', 'C', '3']]
sḢL$ Split into chunks of x's length. | [[['a', 'b', 'c', '1', '2', 'D', '5']], [['a', 'b', 'c', '1', '2', 'D', '5'], ['a', 'b', 'c', '1', '2', 'D', '5'], ['a', 'b', 'c', '1']], [['a', 'b', 'C', '3', '4', 'd', '3'], ['a', 'b', 'C', '3', '4', 'd', '3'], ['a', 'b', 'C', '3']]]
ŒsÐe Swap the case of even-indexed chunks (1-indexed). | [[['a', 'b', 'c', '1', '2', 'D', '5']], [['a', 'b', 'c', '1', '2', 'D', '5'], ['A', 'B', 'C', '1', '2', 'd', '5'], ['a', 'b', 'c', '1']], [['a', 'b', 'C', '3', '4', 'd', '3'], ['A', 'B', 'c', '3', '4', 'D', '3'], ['a', 'b', 'C', '3']]]
F Flatten. | [['a', 'b', 'c', '1', '2', 'D', '5'], ['a', 'b', 'c', '1', '2', 'D', '5', 'A', 'B', 'C', '1', '2', 'd', '5', 'a', 'b', 'c', '1'], ['a', 'b', 'C', '3', '4', 'd', '3', 'A', 'B', 'c', '3', '4', 'D', '3', 'a', 'b', 'C', '3']]
n Vectorized inequality with y. | [[[0, 0, 1, 1, 1, 1, 1]], [[1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1]]]
§ After ending the map, sum each bool (0 or 1) array. | [[5], [17], [14]]
Ṁ Maximum. | 17
```
[Answer]
# [Python 2](https://docs.python.org/2/), 86 bytes
```
lambda a:max(sum(x!=y for x,y in zip((s+s.swapcase())*len(t),t))for s in a for t in a)
```
[Try it online!](https://tio.run/##VY9dC4IwFIav61esq201ArWgBIOl/8K8OPODBL9wi7Q/b9tCsR3YHp7znsHpRvVsG3cqgsdUQS0yQODXMBD5qsmwC0ZUtD0a2IjKBn3KjhB5kEf5hi4FmRNK91XeEEWZotQkpcmBHVIW6WQYDMcxBswQFjhhaGF9pSsBayFSq0QKi3Dc6PyToXfKPIP8HjqnTPdcL@IivFyz1X8c5ofbMa7Lwt@xEd2aMzhJ/O2m68tGIWA4uGFWEL3L9AU "Python 2 – Try It Online")
Given two strings, `s,t`, `zip((s+s.swapcase())*len(t),t))` will be a list of tuples of length `len(t)` since `zip` truncates to the shortest iterable. If `len(s)<len(t)`, then this "pads out" `s` with the desired case swapping and we calculate the `sum` of differing characters.
If `len(t)<=len(s)`, then the resulting `sum` will be less than or equal to the `sum` if we were evaluating `t,s`; so it has no effect on the resulting `max` in that case.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 111 bytes
```
a=>a.map(m=S=>a.map(s=>B(S).map((c,k)=>m=(c^(c=B(s)[k%(l=s.length)])^(k/l&c>9)<<5&&++x)<m?m:x,x=0)),B=Buffer)|m
```
[Try it online!](https://tio.run/##rdBBa8IwFAfw@z5FCKzkYW1Xq0xH05HWb@BRKqRJ61yTVowbPey7d1mkhx30IL5A8of3@IXkk39zI06H43nadrIaajpwmvJA8yPRdDNGQ9OMbMBlIvwGaKopETsiaEYMbJtnoqgJVNXuzx9QwI40ofJEuoIkWXjeZNJDot/1W@/39AXAz2j2VdfVCX70ILrWdKoKVLcnNdkizLGPcIlRge4pABSGKHq6xtpN3GHfZvnj2VI4uBTywWw0Wy8udB7PZfwXWZZHc2l7s3jNyny5kri4wb5e@QXGx4O5C5hdLvwrN2Jb44x93sVdDr8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
WṁŒsÐeF=ċ0
LÞŒcç/€Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8/z/84c7Go5OKD09IdbM90m3A5XN43tFJyYeX6z9qWvNwZ8P///@jlRKTkg2NXEyVdBSATGdjkxRjENPRydnQJAUoZ2Ts4pjkbGGZohQLAA "Jelly – Try It Online")
```
LÞŒcç/€Ṁ
LÞ Sort by length
Œc unordered pairs
€ to each of the pairs
ç/ find the hamming distance with molding and swapping case (helper link)
Ṁ maximum
WṁŒsÐeF=ċ0
W wrap the shorter string
ṁ repeat this string once for each character in the second string
Ðe for every other repeated string
Œs swap case
F flatten
= characterwise equality check between the two strings. If the first
string is longer, the leftover characters are appended to the result.
e.g. 'abABab' and 'xbA' give [0,1,1,'B','a','b']
ċ0 count the number of 0s, giving the Hamming distance.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~89~~ 82 bytes
Creates the cross-product of the input list against itself before calculating the Hamming distance of each pair, using a duplication method similar to [Chas Brown's answer](https://codegolf.stackexchange.com/a/170586/52194). Ruby can't zip strings together or add booleans without additional overhead, though, so it becomes necessary to iterate through the pair of strings manually instead.
-7 bytes from GB.
```
->a{a.product(a).map{|s,t|(0...w=t.size).count{|i|(s+s.swapcase)[i%w]!=t[i]}}.max}
```
[Try it online!](https://tio.run/##JcxPC4IwGIDxu5@iDoFSvaQW1MHA9NKlS91M4t2cOPDPcBMrt8@@hK4P/J5@IB9bRk@7PeOEIPquGKhy0YMGxaTlRml3BwBjpEDyL/OAdkOrJs21K9cS5IiComRexldjvoxUxnNjZvw2VizK7P5IrzdgSKtXzVv2v9a6Blp1jTC5RUL9ID04SJJwX4ROfEn8fTHXIExjkhxPxQ8 "Ruby – Try It Online")
[Answer]
# [Java 10](http://jdk.java.net/), ~~748~~ ~~740~~ ~~667~~ ~~666~~ 616 bytes
This has to be the most dense and unreadable, yet the longest golf I ever came up with.
Call method `h(String[])` with an explicit array (no var args): eg,
```
h(new String[] {"a", "b", "c"});
```
returns `1`.
```
char e(boolean w,char c){return(char)(w&(64<c&c<91|96<c&c<123)?c^32:c);}String p(String s,int l){var p="";int m=s.length(),n=l/m,r=l%m,i=0,j=0;var w=1<0;for(;i<n;++i,w=!w)for(char c:s.toCharArray())p+=e(w,c);for(;j<r;)p+=e(w,s.charAt(j++));return p;}int d(String s,String t){int l=s.length(),n=0,i=0;for(;i<l;)if(s.charAt(i)!=t.charAt(i++))++n;return n;}int h(String s,String t){int l=s.length(),m=t.length();return l>m?d(s,p(t,l)):l<m?d(p(s,m),t):d(s,t);}int h(String[]s){int l=s.length,i=0,j;int[]n=new int[l*l];for(;i<l;++i)for(j=i;++j<l;)n[i*l+j]=h(s[i],s[j]);return java.util.Arrays.stream(n).max().getAsInt();}
```
You can [Try It Online](https://tio.run/##nVJdb9owFH0uv8KNtMq3yTK@Vg2CV2X0oXvuIzDJcVLizDFRbEorxm9ndj5ArNrEcKT43Ot7zznXSUZf6Mcs/rlngiqFHtG2s2cpLVGCo9VKJFSijVclGGzLRK9LiW0IeHOD74YTdsMmo96v0V2Fev0B3LMfg/6YQbB70iWXS1TgBiiPS40EbF8MXUEcJ7BxTpQvErnUKQZPEvEp90oiPuQeJ10vI93AVm9Ib9INnlclDvhEBq7LvQ253oDN1O7GyterqYFhWdI3DFC4JMHGO9Rt2aQM2pzybU@ocea6AEE9FiqCnfUTH@02QMO2Mn5qtGsNtpZEAPwZH3g5XBN9CKyI68pWR9Y66Vk6ueFpg5ZAfM3vY6y8AmtPAIzFxMaFyeTgaRjbMw2nKrOF@pO9vmD7DWYLSWSyQRaKW7E4TmUuurrjjHCDMzunnPFb4WYLkmI14wtPzbLFwVpmfid/rbnwq8@gfKXLhOZYgp/TVwz@MtGh@i61mWa371wV60hwhpSm2mwvKx6jnHJ5MI1ouVRgfsqrq0eUIoKszUfTbBJPb0onub9aa78w1VpI7KQ0z03jAzeMkiV47tC546G5E80dMO0OclHqp9jSHDS2DjU1TuTs4CJiu7Fz@M2LXSRCzxahl4hErJGJWPxviYhVIqbuvyV6/YfPrcx0MIwHdRB@m/aGsTnvDx7CaPpl1Dow3Oj9@psty15bq7gtfM980d2H9AjCZoDQPA08WU2hOT5WXjBO5Z62W1jNZSUrcLKqEivX1DQT7jq7zv43)!
### Ungolfed and commented:
```
// Encode the character (swap case)
char e(boolean w, char c) {
return (char) (w & (64 < c & c < 91 | 96 < c & c < 123) ? c ^ 32 : c);
}
// Pad the string to desired length
String p(String s, int l) {
var p = "";
int m = s.length(), n = l / m, r = l % m, i = 0, j = 0;
var w = 1 < 0;
for (; i < n; ++i, w = !w)
for (char c : s.toCharArray())
p += e(w, c);
for (; j < r;)
p += e(w, s.charAt(j++));
return p;
}
// Calculate the actual hamming distance between two same-length strings
int d(String s, String t) {
int l = s.length(), n = 0, i = 0;
for (; i < l;)
if (s.charAt(i) != t.charAt(i++))
++n;
return n;
}
// Pad the strings as needed and return their hamming distance
int h(String s, String t) {
int l = s.length(), m = t.length();
return l > m ? d(s, p(t, l)) : l < m ? d(p(s, m), t) : d(s, t);
}
// Dispatch the strings and gather their hamming distances, return the max
int h(String[] s) {
int l = s.length, i = 0, j;
int[] n = new int[l * l];
for (; i < l; ++i)
for (j = i; ++j < l;)
n[i * l + j] = h(s[i], s[j]);
return java.util.Arrays.stream(n).max().getAsInt();
}
```
I *know* a better solution can be achieved, especially for the string pairing part.
**EDIT**: shave off 8 bytes by changing the size of the int array in `hammingDistance()` to the square of the numbe of strings given. It also fixes an `ArrayIndexOutOfBounds` thrown in one of the test cases.
**EDIT 2**: Saved 33 bytes thanks to [Kevin Cruijssen's comments](https://codegolf.stackexchange.com/questions/170581/maximum-hamming-distance-among-a-list-of-padded-strings#comment411969_170612): class declaration removed, names shortened to 1 char, operators changed, etc.
**EDIT 3**: Save 1 byte and reach Satan-approved score by changing method with var-arg to array.
**EDIT 4**: Save another 50 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/questions/170581/maximum-hamming-distance-among-a-list-of-padded-strings#comment411976_170612), again: update Java version from 8 to 10 to use `var` keyword, removed `StringBuilder` instance, etc.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~33~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ćü)€é©εćDš«s`g∍}®€¤‚ø€ζ€€Ë_Oà
```
[Try it online](https://tio.run/##MzBNTDJM/f//SNvhPZqPmtYcXnlo5bmtR9pdji48tLo4If1RR2/toXVAiUNLHjXMOrwDpAREgOjueP/DC/7/j1ZKTEo2NHIxVdIBspyNTVKMgSxHJ2dDkxSgjJGxi2OSs4VlilIsAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/yNth/doPmpac3jloZXnth5pdzm68NDq4oT0Rx29tYfWASUOLXnUMOvwDiDr3DYgAVLaHe9/eMF/nf/RSolKOkpJSrFcMJaOUjKcl4jgJSWD@EnJKTCuoZGLKVjI2dgkxRjIcnRyNjRJAcoYGbs4JjlbWKbAzXFMhJKOIB2OQAiiUQBIHigBVQDWCTIQYqkLxKIUY6NUpVgA).
Can most likely be halved in byte-count, but it works..
**Explanation:**
```
Ć # Enclose the input-list (adding the first item to the end of the list)
# i.e. ['ABC1','abcD','abCd32e'] → ['ABC1','abcD','abCd32e','ABC1']
ü) # Pair-vectorize each of them
# i.e. ['ABC1','abcD','abCd32e','ABC1']
# → [['ABC1','abcD'],['abcD','abCd32e'],['abCd32e','ABC1']]
ێ # Sort each pair by length
# i.e. [['ABC1','abcD'],['abcD','abCd32e'],['abCd32e','ABC1']]
# → [['ABC1','abcD'],['abcD','abCd32e'],['ABC1','abCd32e']]
© # Store this list in the register to re-use later on
ε } # Map each inner list in this list to:
ć # Head extracted
# i.e. ['abcD','abCd32e'] → 'abcD' and ['abCd32e']
Dš # Duplicate it, and swap the capitalization of the copy
# i.e. 'abcD' → 'ABCd'
« # Then merge it together
# i.e. 'abcD' and 'ABCd' → 'abcDABCd'
s` # Swap so the tail-list is at the top of the stack, and get it's single item
# i.e. ['abCd32e'] → 'abCd32e'
g # Get the length of that
# i.e. 'abCd32e' → 7
∍ # Extend/shorten the string to that length
# i.e. 'abcDABCd' and 7 → 'abcDABC'
® # Get the saved list from the register again
€¤ # Get the tail from each
# i.e. [['ABC1','abcD'],['abcD','abCd32e'],['abCd32e','ABC1']]
# → ['abcD','abCd32e','abCd32e']
‚ # Pair it with the other list
# i.e. ['ABC1','abcDABC','ABC1abc'] and ['abcD','abCd32e','abCd32e']
# → [['ABC1','abcDABC','ABC1abc'],['abcD','abCd32e','abCd32e']]
ø # Zip it, swapping rows / columns
# i.e. [['ABC1','abcDABC','ABC1abc'],['abcD','abCd32e','abCd32e']]
# → [['ABC1','abcD'],['abcDABC','abCd32e'],['ABC1abc','abCd32e']]
€ζ # And then zip each pair again
# i.e. [['ABC1','abcD'],['abcDABC','abCd32e'],['ABC1abc','abCd32e']]
# → [['Aa','Bb','Cc','1D'],['aa','bb','cC','Dd','A3','B2','Ce'],['Aa','Bb','CC','1d','a3','b2','ce']]
€ # Then for each inner list
€ # And for each inner string
Ë # Check if all characters are the same
# i.e. 'aa' → 1
# i.e. 'cC' → 0
_ # And inverse the booleans
# i.e. [['Aa','Bb','Cc','1D'],['aa','bb','cC','Dd','A3','B2','Ce'],['Aa','Bb','CC','1d','a3','b2','ce']]
# → [[1,1,1,1],[0,0,1,1,1,1,1],[1,1,0,1,1,1,1]]
O # Then sum each inner list
# i.e. [[1,1,1,1],[0,0,1,1,1,1,1],[1,1,0,1,1,1,1]] → [4,5,6]
à # And take the max as result
# i.e. [4,5,6] → 6
```
[Answer]
# Java 11, 387 bytes
```
a->{int l=a.length,i=l,t,j=0,C[]=new int[l];var p=new String[l][2];for(;i-->0;p[i][0]=a[t>0?i:j],p[i][1]=a[t>0?j:i])t=a[i].length()<a[j=-~i%l].length()?1:0;i=0;for(var P:p){var s="";for(var x:P[0].getBytes())s+=(char)(x>64&x<91|x>96&x<123?x^32:x);for(P[0]=repeat(P[0]+s,t=P[1].length()).substring(0,t);t-->0;)if(P[0].charAt(t)!=P[1].charAt(t))C[i]++;i++;}for(int c:C)j=c>j?c:j;return j;}
```
[Try it online.](https://tio.run/##bVNRb9MwEH7nV5hIMFtNvaQdE0vmVlnHA0iMSeMtBMlxvM0hTav4MlqN8sgP4CfyR4rtZC1TSRTn7ru773y@c8kf@LAsvm1FxbVGH7mqH18gpGqQzS0XEl1Z1QFI4BtoVH2XZoiT2MCbF2bRwEEJdIVqxNCWDyeP1rdinFayvoN7X7HKB79kgT9LM1bL75YsrbL4gTdo6YCet8rSURbfLhocq@FwEsTLVGVpkDGewiSYqqjMfAeFT1AZqYyAUVTWp8PknKclG/5Ur6o9Ng2jIFYscOQ273W0JI9W0Mzzdugqujbp6J2EizVIjQnRA4bFPW8IXk1OT16vzs/CH6vJ2amRwtF4uvo6HkUr4ghsKGvkUnJw8kD7wK7NXne7IFS3uXa14sAHEoOrkqhbF0BtogQwkJdd3E4nM1PgYBAr821sLteOaEZKJiblVERl3EhomxqV8WYb27Ys27wybem787BQBZqb5v7bwq6zpk7AHvd8L/dcV59DvicOYf4fOBfWkIviAA9Hl2@cbTY@KcZGSi5m4UlhLKPxZZLP3p4VhykS3q@JDU3Ma//PHms3ht7hOYVN0e3nsktdjEfSO5hady4uojsXSunuYG7WGuScLlqgS2ODqsaluS20BVXRpGn4WlNYdHGYk4GH/vz6jbxBTYVR96mOj9G7eVtxkAX6YAhQGB7pfuRpPy@Gnvgol4K3Wj55IaXrI0CLGn1@/wmtJSCs@Vyi3MzmUCxaE7OvpONDPV@vmVnz3dXlc@feFdaPyv7iYSvaYUs7v4zYfVXm@mPvS@D5hqYvZ7P9Cw) (NOTE: Since Java 11 isn't on TIO yet, `String.repeat(int)` has been emulated as `repeat(String,int)` for the same byte-count.)
**Explanation:**
```
a->{ // Method with String-array parameter and integer return-type
int l=a.length, // Length of the input-array
i=l, // Index-integer, starting at the length
t,j=0, // Temp-integers
C[]=new int[l]; // Count-array the same size as the input
var p=new String[l][2]; // String-pairs array the same size as the input
for(;i-->0 // Loop `i` in the range [`l`, 0)
; // After every iteration:
p[i][0]= // Set the first String of the pair at index `i` to:
a[t>0?i:j],// The smallest of the `i`'th or `j`'th Strings of the input-array
p[i][1]= // And set the second String of the pair at index `i` to:
a[t>0?j:i])// The largest of the `i`'th or `j`'th Strings of the input-array
t=a[i].length()< // If the length of the `i`'th item is smaller than
a[j=-~i%l].length()?// the length of the `i+1`'th item
// (and set `j` to this `i+1` with wrap-around to 0 for the last item
1 // Set `t` to 1 as flag
: // Else:
0; // Set `t` to 0 as flag
// We've now created the String pairs, where each pair is sorted by length
i=0; // Reset `i` to 0
for(var P:p){ // Loop over the pairs
var s=""; // Temp-String starting empty
for(var x:P[0].getBytes())
// Loop over the characters of the first String of the pair
s+= // Append the temp-String with:
(char)(x>64&x<91|x>96&x<123?
// If the current character is a letter:
x^32 // Swap it's case before appending it to `s`
: // Else (not a letter):
x); // Append it to `s` as is
for(P[0]= // Now replace the first String with:
repeat(P[0]+s, // The first String appended with the case-swapped first String
t=P[1].length())
// Repeated `t` amount of times,
// where `t` is the length of the second String of the pair
.substring(0,t); // And then shorten it to length `t`
t-->0;) // Inner loop over the character of the now same-length Pairs
if(P[0].charAt(t)!=P[1].charAt(t))
// If the characters at the same indices in the pair are not equal
C[i]++; // Increase the counter for this pair by 1
i++;} // After every iteration of the outer loop,
// increase `i` by 1 for the next iteration
for(int c:C) // Now loop over the calculated counts
j=c>j?c:j; // And set `j` to the maximum
return j;} // And finally return this maximum `j` as result
```
[Answer]
# [R](https://www.r-project.org/), 173 bytes
```
function(x,U=utf8ToInt,N=nchar)max(combn(x,2,function(z,v=z[order(N(z))])sum(U(substr(Reduce(paste0,rep(c(v[1],chartr('A-Za-z','a-zA-Z',v[1])),n<-N(v[2]))),1,n))!=U(v[2]))))
```
[Try it online!](https://tio.run/##bY7NaoQwFIX3fQrrxly4QtUpTKEuUmfTjYtSNx2GIT8O04VRohkGX97eOLXQ1gRuDuc7OYmdGnE9dud8Ojmjhs/WsCtWuRtO2/f21QxY5kadhQWKMdU20vMUf8IjXvJx31pdW1ayEeAAvWtYxXon@8Gyt1o7VbNO9EP9gLbumGKXfXJAX0o84vGHiMcII5qkI/QUAM1zXFIyJQ2YoAG4z6vFgO9fU1kQihCDUIYBwN1/l4ZaRWIdSTVDqfQKStLd4w0X2UZnXvKXItloYmm247LYPunV17hYDj4XcNqz@LXmCKEl87eK325z709f "R – Try It Online")
@ngm : I tried my best to golf your code (with my *heavy* customizations of course) but, as you well know, R is not very golfy in manipulating strings :P
] |
[Question]
[
In this challenge you will be asked to implement any function (or full program) that fulfills two properties. Those properties are:
* Your function must be an injective (reversible) function from the polynomials with non-negative integer coeffecients to the non-negative integers. This means no two unequal inputs can map to an equal output.
* Your function must preserve the total number of "on bits" from its input to its output. This means if you count the 1 bits of each coefficient of the polynomial, their sum should be the same as the number of 1 bits in the binary representation of the output. For example `9` is `1001` in binary so it has 2 `1` bits.
---
# IO
A non-negative integer polynomial is the same as a infinite list of non-negative integers such that after a certain point all the integers are zero. Thus, polynomials may be represented either by infinite lists (although this is probably undesirable) or by finite lists with implicit zeros after the end of the list.
The key distinction between polynomials and finite lists is that adding a zero to the end of a list will change the list:

While adding a zero to the end of a polynomial does not change its value:

Thus if your function takes a finite list representing a polynomial as input, adding a zero must not change its result.
When representing polynomials as lists, you may represent them either with the first or last entry representing the constant term. For example you could have either of the following possibilities:

In the first case, adding zeros to the end of the list should not change the result; in the second case, adding zeros to the *front* of the list should not change the result.
Of course if your language supports polynomials you may take those as inputs.
Output should be a non-negative integer output via any standard methods.
---
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.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
BFṢḄæ«ÆẸ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//QkbhuaLhuITDpsKrw4bhurj///8xLCAyLCAz "Jelly – Try It Online")
### Left inverse, 5 bytes
```
Bċ0ÆE
```
[Try it online!](https://tio.run/##HZLLEVVBCERTAprv1ipDcWOZgAm4MSzN63nGxb01H2AO3Xz/9uPHz8/ny9/f9ufX18/nI/farTq/ClnlqSdXZRbWmZtjHcs2o3M6z9pzljSOrizT1pvEYn0bbRvexEZauLrDxzUzOlXFsqhNtxyKVPaWbzubaL5sgsNyx66jYq7OjuJrXIMYvXE3ao/p2hpzbjz9VmPjTWrnS22Nl1weGZf8afQE2qRlmzgFYlPA3MzllqSUSjR8ztJb4eFuT6KoDIPTLrV6QhgtedjqOk1DEJ2XEISGepCGBEI8D5XAHb06wIapXs5lN8pneNEjiwZ4Mu/BW0EK50jIVbw6TZOpi/8VULLNqp4YExyOL05NgLB7Jv8vKsjKu20MsRYXae53TwJ0sHiYcY2LgKB1YwhxnhuxK@HKPDXnTcK47zIUi0/YiNFSY8uV82cyBvEAoU@eGJRjgAqBwHTMS27LYiF@No0jvAP52qk@BorkNwNMmVEQ85lI@wc "Jelly – Try It Online")
### How it works
```
BFṢḄæ«ÆẸ Main link. Argument: A (array)
B Binary; convert each integer in A to base 2.
F Flatten; concatenate the resulting binary arrays.
Ṣ Sort the resulting bit array.
Ḅ Convert from base 2 to integer, yielding an integer x with as much set
bits as there are set bits in A.
ÆẸ Unexponents; convert A = [a1, a2, ...] to y = (p1**a1 + p2**a2 + ...),
where pn is the n-th prime number.
By the fundamental theorem of arithmetic, the resulting integer is unique
for each array A without trailing zeroes.
æ« Bitshift left; compute x * 2**y.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~36~~ 20 bytes
```
x#/.x->2^(#/.x->2)!&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/b9CWV@vQtfOKE4DytBUVPuv76BQzaWgYKwDJCq0DSEUhBdnpG3IVRv7HwA "Wolfram Language (Mathematica) – Try It Online")
Takes a polynomial f(x) as input. Evaluates y\*f(y), where y = 2^(f(2)!). Regrettably, this means that the outputs get pretty large.
Evaluating y\*f(y) will preserve the number of 1-bits whenever y is a power of 2 bigger than any coefficient, which is true for the value chosen above. We choose y = 2^(f(2)!) to make the result injective:
* Two different inputs with the same value of y will give different outputs because we're essentially reading two different numbers in base y.
* If we fix k=f(2) and therefore y, the smallest value of y\*f(y) is achieved when the input is a constant polynomial equal to k and the largest value is achieved when the input is the polynomial giving the base-2 expansion of k. In the first case, y\*f(y) = 2^(k!)\*k, and in the second case, y\*f(y) < 2^(k!\*ceil(lg k)), which is less than 2^((k+1)!)\*(k+1).
* As a result, for two polynomials f and g with f(2) < g(2), the integer we get from f will be less than the integer we get from g.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 61 bytes
```
Tr[2^((2#2-1)2^#)&@@@Position[Reverse/@#~IntegerDigits~2,1]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T@kKNooTkPDSNlI11DTKE5ZU83BwSEgvzizJDM/LzootSy1qDhV30G5zjOvJDU9tcglMz2zpLjOSMcwNlbtv6Y1V0BRZl6Jg1aavkM1FxdXtaGOkY5xrQ6UoWMAYhroIIkaoCow0TGt5eKq/Q8A "Wolfram Language (Mathematica) – Try It Online")
Two positive integers can be mapped to a single positive integer. Let `a, b` be two positive integers. Then `a, b -> (2a - 1) 2^(b-1)` is a bijection from NxN to N.
This function finds the position of all `1` bits in the input (from the 1s place), and applies an injective-only variant of the above map to each position. Then, each resulting number is raised to the power of two, and all numbers are added together (which is okay since we applied an injective NxN -> N map).
For example:
```
{1, 2, 3}
{{1}, {1, 0}, {1, 1}} (* Convert to binary *)
{{1}, {0, 1}, {1, 1}} (* Reverse each *)
{{1, 1}, {2, 2}, {3, 1}, {3, 2}} (* Position of 1s *)
{2, 12, 8, 24} (* Inject to N *)
{4, 4096, 256, 16777216} (* Raise to the power of 2 *)
16781572 (* Add *)
```
### Inverse function (124 bytes)
```
##+#&~Fold~#&@*Reverse/@Normal@SparseArray[{Log2[j=#~BitAnd~-#],(#/j+1)/2}->1&@@@(Reverse[#~IntegerDigits~2]~Position~1-1)]&
```
Here's an inverse function to test for injectivity.
[Try it online!](https://tio.run/##XYxBS8MwGIbv@RuB0m4rzfclTRNkkokIgsjQY@khuKxmrK2kQZCx/PW6gyeP78PzvIONn26w0X/Y5bjNF0rXNEtP0/mQaGZWb@7bhdlV5nUKgz2b9y97m7sQ7E97eZl6bE9bmh583I2HVNJuk9PqtIaiwmt5D5kxJv@7aGl6HqPrXXj0vY9zwi7tp9lHP40JSii6bCnuyD74MZrVsTIXQkA2CuoGNwQViEZozeuaCxT/ANwMEBJqBpI3nDPNUINCxqWSTIAUCAzlrVRagNJaMWSEXJdf "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~118~~ ~~117~~ ~~114~~ ~~103~~ 100 bytes
100 bytes by Jonathan Frech:
```
a=input()
while a[0]<1:a.pop(0)
y="".join("2"+bin(v)[2:]for v in a)
print~-2**y.count("1")<<int(y,3)
```
[Try it online!](https://tio.run/##JY2xCsMgFEV3v0LepGkaEgsdjJn8DHGwISWW8pRg0rr0162l0@EeLpyY0xpQFD0BQHGTx7gnxslr9c@FOtNbNUjXxRBZz0mur@4RPDIQcLpVHtwIae9howf1SB0ncfOYPmfRNLmbw46JwQBcqWpZbi@81NC4vJcZ/g0tf4NqKOZqienbwX4B "Python 2 – Try It Online")
103 bytes with a golfing possibility1
```
a=input()
while a[0]<1:a.pop(0)
x="".join(map(bin,a))
print~-(1<<x.count("1"))<<int(x.replace(*"b2"),3)
```
[Try it online!](https://tio.run/##JY1BCoMwEADveYXsabfYYCz0oPHkM4KHKAFTbLJIpOmlX08tPc4wMPxOawxtGQcAKHbwgY@EJF6r31xlTTNp1VnJkbEhkc9KPqIP@LSMsw@1JRK8@5A@V1RaZ7nEIyQEBURanx6z3B1vdnF4gbkFqm9Uzlfvslvgvxm7H1QjFHOfhGlqNX0B "Python 2 – Try It Online")
*-15 bytes thanks to Jonathan Frech*
It creates a number that first contains the "on bits" and then the unary representation of the array interpreted as a trinary number.
The trinary number is created by converting the numbers to binary strings (`0bNNN`), then replacing `b` with `2`.
1I could have saved 14 bytes by converting it to a base-12 number instead, but TIO ran out of memory so I decided to use this.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
gÅpImPoIbS{2β*
```
[Try it online!](https://tio.run/##MzBNTDJM/f8//XBrgWduQL5nUnC10blNWv//RxvqGOkYxwIA "05AB1E – Try It Online")
Yields the same results as Dennis' Jelly solution, yet the technique is *slightly* different.
## How?
Let's try the input `[1, 2, 3]`:
```
gÅpImPoIbS{2β* | Full program.
| STACK: [[1, 2, 3]]
|
g | Push the length.
| STACK: [3]
Åp | Generate the first N primes.
| STACK: [[2, 3, 5]]
Im | Push the input, and apply pairwise exponentiation.
| STACK: [2, 9, 125]
P | Push the product.
| STACK: 2250
o | Push 2 ** N.
| STACK: 2 ** 2250 (way too large)
Ib | Push the input and convert to binary.
| STACK: [2 ** 2250, ['1', '10', '11']].
S{ | Sort all the characters.
| STACK: [2 ** 2250, ['0', '1', '1', '1', '1']]
2β | Convert from binary.
| STACK: [2 ** 2250, 15]
* | Multiplication.
| STACK: [2 ** 2250 * 15]
| Implicitly print the top of the stack (2 ** 2250 * 15).
```
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
```
r='print 0';s='<<'
for n in input():r+=oct(n)[:0:-1];s+='0'+'1'*n
exec r+s
```
[Try it online!](https://tio.run/##FcIxDoAgDADA3Vd0q4gmwIjyEuJEMLIUUjDR16NerjztzGR6Z4eFEzVQuFaH24bDkRkI0r9cbRSWpcuhjSS8VXbR@1qlQ4USNU40xDsGYFl792qGr57B7C8 "Python 2 – Try It Online")
[Answer]
# JavaScript 6, ~~96~~ 83 Bytes
```
x=>(t=x.map(k=>(x[0]+=k)&&2+k.toString(2)).join``).replace(/0|2/g,'')+'0'.repeat(t)
```
outputs a binary expression
```
([1,2]) => 3*2^21210(Decimal)
([0,1,2]) => 3*2^21210
([1,2,0]) => 3*2^2121020
([1,2,3,4]) => 31*2^212102112100(Threotically)
```
] |
[Question]
[
**Task:** Given the area of a triangle, find a [Heronian triangle](https://en.wikipedia.org/wiki/Heronian_triangle) with that area. Any Heronian triangle with the specified area is allowed.
A Heronian triangle is a triangle with **integer sides and integer area**. By Heron's formula, a triangle with sides lengths `a,b,c` has area
```
sqrt(s*(s-a)*(s-b)*(s-c))
```
where `s=(a+b+c)/2` is half the perimeter of the triangle. This can also be written as
```
sqrt((a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c)) / 4
```
If no such triangle exists, output with a consistent falsey value.
**Input:** A single, positive integer representing the area of the triangle.
**Output:** Any three side lengths for such a triangle OR a falsely value.
Examples:
```
Input -> Output
6 -> 3 4 5
24 -> 4 15 13
114 -> 37 20 19
7 -> error
```
[Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?answertab=votes#tab-top)
This is code golf, shortest answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to Erik the outgolfer (make use of the quick, `¥`)
```
SHð;_P
ṗ3Ç⁼¥Ðf²Ḣ
```
Brute force application of Heron's formula.
**[Try it online!](https://tio.run/nexus/jelly#ASEA3v//U0jDsDtfUArhuZczw4figbzCpcOQZsKy4bii////MjQ)** (reaches the 60s time out for the 114 tests case. Takes 3m 30s locally - it does check 1143 = 1,481,544 triples)
### How?
A true golf solution - given an area `a` it finds **all** tuples of three integers between `1` and `a` (even with repeated triangles and ones of no area), gets their area and filters for those with the desired area (it doesn't even stop as soon as one is found, it ploughs through them all and pops the first result afterwards). Yields `0` if none exists.
```
SHð;_P - Link 1, get the square of the area of a triangle: list of sides
S - sum the sides (get the perimeter)
H - halve
ð - dyadic chain separation (call that p)
_ - subtraction (vectorises) = [p-side1, p-side2, p-side3]
; - concatenate = [p, p-side1, p-side2, p-side3]
P - product = p*(p-side1)*(p-side2)*(p-side3)
= the square of Heron's formula = area squared
ṗ3Ç⁼¥Ðf²Ḣ - Main link: number a (area)
ṗ3 - third Cartesian power (all triples of [1,area] : [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2], ... ,[a,a,a]]
² - square a
Ðf - filter keep if:
¥ - last two links as a dyad:
Ç - call last link (1) as a monad f(list of sides)
⁼ - left (that result) equals right (square of a)?
Ḣ - head - get the first one (an empty list yields 0, perfect for the falsey case)
```
[Answer]
## JavaScript (ES7), ~~109~~ ~~102~~ ~~100~~ 98 bytes
Returns either an array of 3 integers or `false`. Like the [Jelly answer](https://codegolf.stackexchange.com/a/121816/58563), this is brute forcing Heron's formula.
```
A=>[...Array(A**3)].some((_,a)=>A*A/(r=[b=a/A%A|0,c=a/A/A|0,a%=A],p=a+b+c>>1)/(p-a)/(p-b)==p-c)&&r
```
### Test cases
```
let f =
A=>[...Array(A**3)].some((_,a)=>A*A/(r=[b=a/A%A|0,c=a/A/A|0,a%=A],p=a+b+c>>1)/(p-a)/(p-b)==p-c)&&r
console.log(JSON.stringify(f(6)))
console.log(JSON.stringify(f(24)))
console.log(JSON.stringify(f(114)))
console.log(JSON.stringify(f(7)))
```
---
## Recursive version, 83 bytes
Returns an array of 3 integers or throws a recursion error. Sadly, it only works for small inputs.
```
f=(A,n)=>A*A/(r=[a=n%A,b=n/A%A|0,c=n/A/A|0],p=a+b+c>>1)/(p-a)/(p-b)==p-c?r:f(A,-~n)
```
### Demo
```
f=(A,n)=>A*A/(r=[a=n%A,b=n/A%A|0,c=n/A/A|0],p=a+b+c>>1)/(p-a)/(p-b)==p-c?r:f(A,-~n)
console.log(JSON.stringify(f(6)))
console.log(JSON.stringify(f(24)))
```
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
```
f a=take 1[t|t<-mapM(\_->[1..a])":-)",a*a==product[sum t/2-x|x<-0:t]]
```
[Try it online!](https://tio.run/nexus/haskell#@5@mkGhbkpidqmAYXVJTYqObm1jgqxETr2sXbainlxirqWSlq6mkk6iVaGtbUJSfUppcEl1cmqtQom@kW1FTYaNrYFUSG/s/NzEzT8FWAaRZQaOgKDOvRC9NUyHaTMfIRMfQRMc89j8A "Haskell – TIO Nexus")
Outputs a singleton of a list of three triangle sides like `[[3.0,4.0,5.0]]`. Impossible inputs give `[]`. Technically only `False` is Falsey for Haskell, but because Haskell requires all possible outputs to be of the same type, it can't be used. If an error could be used as Falsey, `[...]!!0` would save 3 bytes over `take 1[..]`.
Tries all triples `t` of possible side lengths each ranging from `1` to the area `a`. Heron's formula is used to check if the area matches via `(s-0)(s-x)(s-y)(s-z)==a*a` where `s=(x+y+z)/2` is `sum t/2`. The product `(s-0)(s-x)(s-y)(s-z)` is expressed as a `product` with elements taken from `0:t`, i.e. the triple as well as 0.
[Answer]
# F#, ~~170~~ ~~156~~ 152 bytes
```
let f(a,b,c)=
let s=(a+b+c)/2.0
s*(s-a)*(s-b)*(s-c)
let g A=[for a in 1.0..A do for b in a..A do for c in b..A do yield a,b,c]|>List.find(f>>(=)(A*A))
```
[Try it online!](https://tio.run/##Tc3LCsMgFATQfb7iEih487A2dKvgvn9QuvARg5BoiW4K@XeLoYtuBuYwMC6NWwyxlHXO4Iga9GCQN1Br4kT1ujd4nShrIHUkjQpr6jMNNnW2gORPF3dQ4APcKKNUgo1QSVdSf2Aq6B98/LxaOD9fh3j4lKnzwRInBOFIZCcRywLTnbJDvHcfsmsvsi1f "F# (Mono) – Try It Online")
# "Ungolfed"
```
let calculateArea (a, b, c) =
let s = (a+b+c)/2.0
s*(s-a)*(s-b)*(s-c)
let getTriangle A =
[ for a in 1.0..A do
for b in a..A do
for c in b..A do yield a,b,c
]
|> List.find(calculateArea>>(=)(A * A))
```
If there are no results found, the program will fault. If this is not desired, I have to replace `List.find` with either `List.filter` (+2 bytes) which will produce an empty list in case nothing is found or `List.tryFind` (+3 bytes), returning None in case no triangle was found.
I always find that a golfed F# version is still reasonable legible.
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), ~~131~~ ~~123~~ 118 bytes
```
n=input()
t=n*3;r=i=c=0
while c<t:
i+=1;a,b,c=i%t,i/t%t,i/t/t;s=a+b+c>>1
if(s-a)*s*(s-b)*(s-c)==n**2:r=a,b,c
print r
```
[Try it online!](https://tio.run/nexus/python2-pypy#JYxLDgIhEAX3nIKNyfAxI@pq8M1doKOxE0Mm0BOPj6ibept61Qu4bLtMRgmKvcQKBuGk3k9@3TXdZFGaHUJMPnsCH8TzLH/OEhuSy47WNQztMbVjMrbZsdl8SQajas9Lxe@vtspFdO09hOsH "Python 2 (PyPy) – TIO Nexus")
While this also works on CPython, PyPy is a lot faster and is able to compute the triangle for 114 in the time limit on TIO.
Timings from my machine:
```
$ echo 114 | time pypy2 d.py
0.55 real 0.52 user 0.02 sys
$ echo 114 | time python2 d.py
52.46 real 51.76 user 0.27 sys
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes
```
Solve[Area@SSSTriangle[a,b,c]==#>c>b>a>0,{a,b,c},Integers]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg/pyw12rEoNdEhODg4pCgzMS89JzU6USdJJznW1lbZLtkuyS7RzkCnGixUq@OZV5KanlpUHKv2P6AoM69EwUEhDYjNuJB5Rib/AQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Pyth - 23 bytes
```
/mu*G-/sd2Hd/sd2^UQ3^Q2
```
Which prints a truthy/falsy value, or
```
fq^Q2u*G-/sT2HT/sT2^UQ3
```
which prints out all possible solutions, and is horribly slow for large inputs. Put 'h' at the beginning to only print one.
Explanation:
```
fq^Q2u*G-/sT2HT/sT2^UQ3
UQ # List of numbers from 0 to input-1
^ 3 # All triples of these numbers
f # Filter this by the following test (on variable T, based on Hero's formula)
u*G-/sT2HT/sT2 # s*(s-a)*(s-b)*(s-c), where s is the sum of the triple over 2 (calclated as /sT2 )
q^Q2 # Test if equal to input ^2
```
[Try it](https://pyth.herokuapp.com/?code=%2Fmu%2aG-%2Fsd2Hd%2Fsd2%5EUQ3%5EQ2&input=6&test_suite=1&test_suite_input=6%0A7%0A24&debug=0)
[Answer]
## Mathematica, 77 bytes
with mathematica's **Solve**
```
s=(a+b+c)/2;d=Sqrt[s(s-a)(s-b)(s-c)];Solve[d==#&&0<a<b<c<#,{a,b,c},Integers]&
```
---
## Mathematica, 117 bytes
brute force
```
s=(a+b+c)/2;l="error";(For[a=1,a<#,a++,For[b=1,b<a,b++,For[c=1,c<b,c++,If[Sqrt[s(s-a)(s-b)(s-c)]==#,l={a,b,c}]]]];l)&
```
[Answer]
# [Perl 6](http://perl6.org/), 54 bytes
```
->\a{first {a*a==[*] .sum/2 «-«(0,|$_)},[X] ^a xx 3}
```
Brute force search of all possibles sides up to one less than `a`, the input area.
* `^a` is the range of numbers from 0 to `a - 1`.
* `[X] ^a xx 3` reduces, by cross product, three copies of that range, producing all triplets from `(0, 0, 0)` to `(a - 1, a - 1, a - 1)`.
* We look for the `first` triplet such that the area of the triangle with those sides equals `a`, using [Heron's formula](https://en.wikipedia.org/wiki/Heron%27s_formula).
Within the code block given to `first`:
* `$_` is the triplet. Call it `(x, y, z)` here.
* `(0,|$_)` is the same triplet but with `0` prepended: `(0, x, y, z)`.
* `.sum / 2` is half the perimeter (a quantity which is named `s` in the usual expression of Heron's formula).
* `.sum / 2 «-« (0, |$_)` is the subtraction hyperoperator with `s` on the left and the `(0, x, y, z)` on the right, giving `(s - 0, s - x, s - y, s - z)`.
* `[*]` then reduces that quadruplet with multiplication, giving the square of the area.
* `a * a ==` looks for a squared area equal to the square of the given area.
If no triplet is found, `Nil` (which is falsey) is returned.
[Answer]
# [Haskell](https://www.haskell.org/documentation), 76 bytes
```
f s=[[a,b,c]|a<-[1..s],b<-[1..a],c<-[1..b],a*a*c*c-(a*a+c*c-b*b)^2/4==4*s*s]
```
This outputs a list of lists containing all possible integral sizes that generate the correct area via brute force (outputting the empty list if there are none). The caveat being it outputs them as doubles because of that division in the middle but their fractional part is always 0.
If you for some reason can't take that,
```
f s=[[a,b,c]|a<-[1..s],b<-[1..a],c<-[1..b],4*a*a*c*c-(a*a+c*c-b*b)^2==16*s*s]
```
This will output the answers as a list of integer lists for ~~89~~ 77 bytes total or ~~13~~ 1 extra bytes. (Thanks to Neil)
If you need / want only the first element just putting `!!0` at the end will give you only the first element if there are numbers that apply and an error if there's none for 3 more bytes and `take 1` at the beginning will take the first element without erroring out for 6 more bytes.
[Try it online!](https://tio.run/nexus/haskell#JcYxDsIwDADAva/wwADGKQrKRvMDfhAZyU5TlIGAmg4d@Hso6nDStQmqD0FIKfJXBhNs31cm3SdMcZ8yCQpGjOa45fyPop4e14vz3mHFyl33klzAw/iGFQYDz7Tcc0k3@My5LHCAaTMnGWFtzVr3Aw)
[Answer]
# TI-Basic, ~~70~~ 69 bytes
```
Prompt A
For(B,1,A
For(C,1,B
For(D,1,C
(B+C+D)/2
If A2=Ansprod(Ans-{B,C,D
Then
Disp B,C,D
Return
End
End
End
End
/
```
Displays the three side lengths if there is a triangle, throws a syntax error if there isn't (thanks to the `/` at the end).
-1 byte thanks to [Sean's comment](https://codegolf.stackexchange.com/questions/121811/what-are-my-dimensions/121836#comment298798_121824) on a different answer
[Answer]
# [Actually](https://github.com/Mego/Seriously), 22 bytes
```
;╗R3@∙⌠;Σ½;)♀-π*╜²=⌡░F
```
[Try it online!](https://tio.run/nexus/actually#ASwA0///O@KVl1IzQOKImeKMoDvOo8K9OynimYAtz4Aq4pWcwrI94oyh4paRRv//Ng "Actually – TIO Nexus")
Explanation:
```
;╗R3@∙⌠;Σ½;)♀-π*╜²=⌡░F (implicit input: A)
;╗ store a copy of A in register 0
R range(1, A+1)
3@∙ ternary Cartesian product (all triples with values in [1, A])
⌠;Σ½;)♀-π*╜²=⌡░ filter: take triples where function returns truthy
;Σ½ make a copy of the triple, compute s = (a+b+c)/2
;) make a copy of s, move it to the bottom of the stack
♀- subtract each value in the triple from s
π* product of those values and s (s*(s-a)*(s-b)*(s-c))
╜² A*A
= compare equality (does area of triangle with given dimensions equal input?)
F take first triple that satisfies the filter (or empty list if none)
```
[Answer]
# Casio Basic, 123 bytes
```
For 1⇒a To n
For 1⇒b To n
For 1⇒c To n
If(s*(s-a)*(s-b)*(s-c)|s=(a+b+c)/2)=n^2
Then
Print{a,b,c}
Stop
IfEnd
Next:Next:Next
```
Standard brute force solution. 122 bytes for the code, 1 byte to specify `n` as a parameter.
[Answer]
# [Perl 5](https://www.perl.org/), 119 + 2 `-pa` = 121 bytes
```
for$a(1..$_){for$b(1..$_){map{($t=($s=($a+$b+$_)/2)*($s-$a)*($s-$b)*($s-$_))>0&&"@F"==sqrt$t&&($\="$a $b $_")}1..$_}}}{
```
[Try it online!](https://tio.run/##NYzBCgIhFEV/ZZCHaIOm0SyNVu36g2B4QkFQ6ag78dd7WUyLy@GcxY3X9JiIbiEBCqs1zLJ@xf/libEKKE5A7sMR/Njzdic3vSjAlX7lLOXBcM6OJ@ZcXlKBwrmAi2OAA/gBZibb77q1Voms3b9DLPfwyqTOkzbWkIr4AQ "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 90 bytes
```
S=>(g=(a,b,c,r=(a+b+c)/2)=>r*(r-a)*(r-b)*(r-c)^S*S?!c&&g(S,a,b)||--a&&g(a,b,c):[a,b,c])(S)
```
[Try it online!](https://tio.run/##bYxNCsIwFIT33sJNedMmSosoCKmHyFIUkmcblNJIKq5695hmKd3MzwczL/M1E4fn@yNH/@hir6JWLTlFRljBIqRQ2Yqxb6DaUFKQBovarIy7LvVly0XhSIu0wTxLaZaaD3C@Zr@BNCL7cfJDtxu8I@rpCGDzx5rDCqzrNXpKLP4A "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 92 bytes
```
S=>(g=(a,b,c,r=(a+b+c)/2)=>(c?r*(r-a)*(r-b)*(r-c)==S*S&&[a,b,c]:g(S,a,b))||--a&&g(a,b,c))(S)
```
[Try it online!](https://tio.run/##bcxBCsIwFATQvQcJf9pEaRGFQvQQWYqL5NsGpTSSlq569xjrTroZhgczLzvbkePzPakhPNrU6WT0hbwmK51kGXMpXck41MjO11hQVBbfdGsytDaFEeK2Lu6NJyNzBZZFKSuE/10BZJA4DGPo230fPFFHJwC7P6uPG1hVW3rOlj4 "JavaScript (Node.js) – Try It Online")
Usual search
Where's the proof every length <= area?
[Answer]
# Uiua, 54 Bytes
Standard bruteforce solution. Returns all possible results.
```
▽=⊙:≡(√/×⊂-:⊙:.÷2/+.).☇1+1⇡⊂⊂...
```
[Try It](https://uiua.org/pad?src=0_8_0__4pa9PeKKmTriiaEo4oiaL8OX4oqCLTriipk6LsO3Mi8rLiku4piHMSsx4oeh4oqC4oqCLi4uMTIK)
Explanation:
```
▽=⊙:≡(√/×⊂-:⊙:.÷2/+.).☇1+1⇡⊂⊂...
☇1+1⇡⊂⊂... # generate tuples [1, a]^3
. # save a copy to output
≡(√/×⊂-:⊙:.÷2/+.) # for each side length tuple calculate the area
. # save a copy of the current tuple so we can do s-a,s-b,s-c later
÷2/+ # calculate s by summing and dividing by 2
. # copy s so we can multiply by it later
:⊙: # bring the saved tuple to the top of the stack
- # calculate s-a,s-b,s-c
⊂ # join s to the array containing [s-a,s-b,s-c]
/× # reduce multiply to get the product of all of the elements
√ # final square root to calculate area
⊙: # bring area we are looking for up to the second position in the stack
= # create a boolean mask which selects all areas which matched
▽ # keep the tuples that had the correct area
```
] |
[Question]
[
How well do you know the site? Let's find out.
This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. [Cop's thread](https://codegolf.stackexchange.com/questions/100357/ppcg-jeopardy-cops).
As a robber, you need to:
1. Find a non-deleted, non-closed challenge that matches a cop's submission. The challenge cannot have the following tags: [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'"), [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'"), [underhanded](/questions/tagged/underhanded "show questions tagged 'underhanded'"), [busy-beaver](/questions/tagged/busy-beaver "show questions tagged 'busy-beaver'"), [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'"), [tips](/questions/tagged/tips "show questions tagged 'tips'"), [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'"). The challenge must have restrictions on valid output.
2. Post the challenge here, and link to the cop you are cracking
3. Add a "Cracked" comment to the cops' post, with a link back to this answer
You will receive 1 point, plus 1 point for each 24-hour period the submission had remained uncracked (max 7). Tiebreaker is the total number of cracked submisisons.
Notes:
* If a challenge requires an output of `X`, and you output `XY` or `YX` where `Y` is anything besides whitespace, the submission is not valid for that challenge.
* A challenge newer than 2016-11-17 is not allowed.
* I reserve the right to ban certain challenges if they are widely applicable (could be applied to the majority of all submissions).
* Make sure you add a sentence or two as an explanation (it also helps your submission from being converted to a comment)
* Thanks to [Daniel](https://codegolf.stackexchange.com/users/56477/daniel) for the initial idea!
[Answer]
## Calculate probability of getting half as many heads as coin tosses.
Cops entry (posted by Conor O'Brien): <https://codegolf.stackexchange.com/a/100521/8927>
Original question: [Calculate probability of getting half as many heads as coin tosses.](https://codegolf.stackexchange.com/questions/1209/calculate-probability-of-getting-half-as-many-heads-as-coin-tosses)
---
The posted solution had a couple of obfuscation techniques applied, followed by multiple layers of the same obfuscation technique. Once past the first few tricks, it became a simple (if tedious!) task to extract the actual function:
```
nCr(a,b) = a! / ((a-b)! * b!)
result = nCr(x, x/2) / 2^x
```
Took a while to realise what I was looking at (for a while I suspected something to do with entropy), but once it twigged, I managed to find the question easily by searching for "probability of coin toss".
---
Since Conor O'Brien challenged an in-depth explanation of his code, here's a rundown of the more interesting bits:
It starts by obfuscating some built-in function calls. This is achieved by base-32 encoding the function names, then assigning them to new global-namespace names of a single character. Only 'atob' is actually used; the other 2 are just red-herrings (eval takes the same shorthand as atob, only to be overridden, and btoa simply isn't used).
```
_=this;
[
490837, // eval -> U="undefined" -> u(x) = eval(x) (but overwritten below), y = eval
358155, // atob -> U="function (M,..." -> u(x) = atob(x)
390922 // btoa -> U="function (M,..." -> n(x) = btoa(x), U[10] = 'M'
].map(
y=function(M,i){
return _[(U=y+"")[i]] = _[M.toString(2<<2<<2)]
}
);
```
Next there are a couple of trivial string mix-ups to hide the code. These are easily reversed:
```
u(["","GQ9ZygiYTwyPzE6YSpk","C0tYSki","SkoYSkvZChhLWIpL2QoYikg"].join("K"))
// becomes
'(d=g("a<2?1:a*d(--a)"))(a)/d(a-b)/d(b) '
u("KScpKWIsYShFLCliLGEoQyhEJyhnLGM9RSxiPUQsYT1D").split("").reverse().join("")
// becomes
"C=a,D=b,E=c,g('D(C(a,b),E(a,b))')"
```
The bulk of the obfuscation is the use of the `g` function, which simply defines new functions. This is applied recursively, with functions returning new functions, or requiring functions as parameters, but eventually simplifies right down. The most interesting function to come out of this is:
```
function e(a,b){ // a! / ((a-b)! * b!) = nCr
d=function(a){return a<2?1:a*d(--a)} // Factorial
return d(a)/d(a-b)/d(b)
}
```
There's also a final trick with this line:
```
U[10]+[![]+[]][+[]][++[+[]][+[]]]+[!+[]+[]][+[]][+[]]+17..toString(2<<2<<2)
// U = "function (M,i"..., so U[10] = 'M'. The rest just evaluates to "ath", so this just reads "Math"
```
Although since the next bit is ".pow(T,a)", it was always pretty likely that it would have to be "Math"!
The steps I took along the route of expanding functions were:
```
// Minimal substitutions:
function g(s){return Function("a","b","c","return "+s)};
function e(a,b,c){return (d=g("a<2?1:a*d(--a)"))(a)/d(a-b)/d(b)}
function h(a,b,c){return A=a,B=b,g('A(a,B(a))')}
function j(a,b,c){return a/b}
function L(a,b,c){return Z=a,Y=b,g('Z(a,Y)')}
k=L(j,T=2);
function F(a,b,c){return C=a,D=b,E=c,g('D(C(a,b),E(a,b))')}
RESULT=F(
h(e,k),
j,
function(a,b,c){return _['Math'].pow(T,a)}
);
// First pass
function e(a,b){
d=function(a){return a<2?1:a*d(--a)}
return d(a)/d(a-b)/d(b)
}
function h(a,b){
A=a
B=b
return function(a){
return A(a,B(a))
}
}
function j(a,b){ // ratio function
return a/b
}
function L(a,b){ // binding function (binds param b)
Z=a
Y=b
return function(a){
return Z(a,Y)
}
}
T=2; // Number of states the coin can take
k=L(j,T); // function to calculate number of heads required for fairness
function F(a,b,c){
C=a
D=b
E=c
return function(a,b,c){return D(C(a,b),E(a,b))}
}
RESULT=F(
h(e,k),
j,
function(a){return Math.pow(T,a)}
);
// Second pass
function e(a,b){...}
function k(a){
return a/2
}
function F(a,b,c){
C=a
D=b
E=c
return function(a,b,c){return D(C(a,b),E(a,b))}
}
RESULT=F(
function(a){
return e(a,k(a))
},
function(a,b){
return a/b
},
function(a){return Math.pow(2,a)}
);
// Third pass
function e(a,b) {...}
C=function(a){ // nCr(x,x/2) function
return e(a,a/2)
}
D=function(a,b){ // ratio function
return a/b
}
E=function(a){return Math.pow(2,a)} // 2^x function
RESULT=function(a,b,c){
return D(C(a,b),E(a,b))
}
```
The structure of the function nesting is based around utility; the outer-most "D" / "j" function calculates a ratio, then the inner "C" / "h" and "E" (inline) functions calculate the necessary coin flip counts. The "F" function, removed in the third pass, is responsible for connecting these together into a usable whole. Similarly the "k" function is responsible for choosing the number of heads which need to be observed; a task which it delegates to the ratio function "D"/"j" via the parameter binding function "L"; used here to fix parameter `b` to `T` (here always 2, being the number of states the coin can take).
In the end, we get:
```
function e(a,b){ // a! / ((a-b)! * b!)
d=function(a){return a<2?1:a*d(--a)} // Factorial
return d(a)/d(a-b)/d(b)
}
RESULT=function(a){
return e(a, a/2) / Math.pow(2,a)
}
```
[Answer]
## MATL, [Luis Mendo](https://codegolf.stackexchange.com/a/100362/42545), [Count number of hefty decimals between 2 numbers](https://codegolf.stackexchange.com/q/2952/42545)
```
&:"@FYAYm7>vs
```
I figured out what it does by playing with the inputs, but I couldn't figure out for what challenge you'd have to calculate the number of integers in a range whose sum was greater than 7 times the number of digits. After reading the MATL docs, I put together an rough explanation of what this does:
```
& % Change default input format
: % Implictly input two integers, create inclusive range
" % For each item in this range:
@ % Push the item
F % Push false
YA % Convert to base N digits; N is false, so this produces base-10 digits
Ym % Calculate arithmetic mean
7> % Push 1 if this is greater than 7, 0 otherwise
v % Concatenate result into array with previous result
s % Sum
% Implicitly end loop and output
```
I then switched from searching "digit sum greater than 7 times length" to "average digit greater than 7", which yielded the challenge I was looking for.
[Answer]
# 아희(Aheui), [JHM](https://codegolf.stackexchange.com/a/100407/58106), [Shortest infinite loop producing no output](https://codegolf.stackexchange.com/questions/59347/shortest-infinite-loop-producing-no-output?page=1&tab=active#tab-top)
Tried it online, code just keeps running and there's no output.
[Answer]
# [Reverse a 1-dimensional array](https://codegolf.stackexchange.com/questions/79155/reverse-a-1-dimensional-array)
I think this is it, its hows up as the first answer for it.
<https://codegolf.stackexchange.com/a/100368/31343>
[Answer]
# C#, [Yodle](https://codegolf.stackexchange.com/a/100373/58106), [Given an input, move it along the keyboard by N characters](https://codegolf.stackexchange.com/questions/50336/given-an-input-move-it-along-the-keyboard-by-n-characters)
Input a `string` and `int` and changes each `char` of the `string` to the `char` that's `N` keys away on the keyboard (wrapping around).
[Answer]
## Perl, [Gabriel Benamy](https://codegolf.stackexchange.com/a/100372/16766), [Convenient palindrome checker](https://codegolf.stackexchange.com/q/28190/16766)
The code was obviously some kind of palindrome. Once I picked out the `y- - -` structure and noticed what was being transliterated, I knew what challenge it was.
[Answer]
# Pyth - <https://codegolf.stackexchange.com/a/100391/31343>
I quickly found out what the program did, but finding the challenge took pretty long.
[Different Way Forward](https://codegolf.stackexchange.com/questions/47005/different-way-forward)
this is my buffer.
[Answer]
# 05AB1E, 27 bytes, [Adnan](https://codegolf.stackexchange.com/a/100361/31343)
[Evaluating the score based from a chess FEN string](https://codegolf.stackexchange.com/questions/61510/evaluating-the-score-based-from-a-chess-fen-string)
I decompressed the string and searched, and came up with this challenge.
[Answer]
# MATL, [Luis Mendo](https://codegolf.stackexchange.com/questions/100357/ppcg-jeopardy-cops/100377#100377), [Calculate hamming weight with low hamming weight](https://codegolf.stackexchange.com/questions/6239/calculate-hamming-weight-with-low-hamming-weight)
```
dP7EGn:q^1J2/h)ts_hX=Gs[BE]Wd=~>~GBz*
```
I tested putting in numbers, and found the hamming weight thing on [OEIS](https://oeis.org/A000120).
Then I searched on PPCG, tried putting in strings and it worked.
[Answer]
## C++, [Karl Napf](https://codegolf.stackexchange.com/a/100453/194), [Substring Sum Set](https://codegolf.stackexchange.com/q/86229/194)
[Online demo](http://ideone.com/HGYvoR) showing the first test case from the question.
[Answer]
## Ruby, [histocrat](https://codegolf.stackexchange.com/a/100501/16766), [Implement a Truth-Machine](https://codegolf.stackexchange.com/q/62732/16766)
The code defines an iterated function system `f(n) = n*(3*n-1)/2` that runs until `n` mod 7 is 0. Input of `0` therefore terminates right away (after printing `0` once). Input of `1` gives `1`, leading to an infinite loop of printing `1`. Other input terminates after 1-3 steps if the initial `n` is congruent to 0, 2, 3, 5, or 6 mod 7, or grows forever if it is congruent to 1 or 4 mod 7. But that's irrelevant.
[Answer]
# Hexagony, [548 bytes, Martin Ender](https://codegolf.stackexchange.com/a/100508/31516)
This is the "[Print every character your program doesn't have](https://codegolf.stackexchange.com/questions/12368/print-every-character-your-program-doesnt-have)" challenge!
Prints:
```
Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look
```
Which is very similar to the output in [this one](https://codegolf.stackexchange.com/questions/47342/keep-the-unique-characters-down). The clue here was that the last `.` wasn't printed. Also, the code itself had no letters, and we all know that the phrases in the output contains all letters in the alphabet.
[Answer]
## Python, 935 Bytes, [Mega Man](https://codegolf.stackexchange.com/a/100447/25180), [What is the smallest positive base 10 integer that can be printed by a program shorter (in characters) than itself?](https://codegolf.stackexchange.com/q/67921/25180)
I didn't actually try it. But I guess it prints a number longer than the program.
[Answer]
# Python 3, <https://codegolf.stackexchange.com/a/100381/31343>
[Use xkcd's formula to approximate the world population](https://codegolf.stackexchange.com/questions/57802/use-xkcds-formula-to-approximate-the-world-population/57806#57806)
I just searched for challenges that involved leap years (because of the decoded divisibility by four checker) and that took no input.
[Answer]
# Brainfuck, [FinW](https://codegolf.stackexchange.com/a/100464/56258), [Print the ASCII table](https://codegolf.stackexchange.com/questions/40490/print-the-ascii-table/)
That was easy, since he posted his answer on that challenge.
[Link to his answer](https://codegolf.stackexchange.com/a/98746/56258)
[Answer]
## Mathematica, [JHM](https://codegolf.stackexchange.com/a/100420/8478), [Natural construction](https://codegolf.stackexchange.com/q/95035/8478)
The unary operator `±` computes a set-theory based representation of the natural numbers.
[Answer]
## Ruby, [wat](https://codegolf.stackexchange.com/a/100593/8478), [400th Question Celebration/Challenge](https://codegolf.stackexchange.com/q/3420/8478)
That was the first thing I found when searching for "400". That said, the challenge seems to be mistagged and should be a popcon and should probably also be closed for not having objective requirements.
] |
[Question]
[
The first [Letters, Get Moving!](https://codegolf.stackexchange.com/questions/66556/letters-get-moving) was very popular, but had limited participation. This one will be easier to solve, but hopefully involve some tricks in golfing.
You are given a string of only lowercase letters. For each letter, with position in the alphabet *m*, move it so it becomes the *m*th letter from the end. If the value of *m* is longer than the length of the string, move it to the very front. Output only the fully transformed string.
**Examples:**
**"giraffe"**
* 'g' is the 7th letter in the alphabet, it is already the 7th letter from the back, so leave it.
* 'i' is the 9th letter, since 9 is bigger than the length of the word, it goes to the front, so the string becomes `igraffe`
* 'r' is the 18th letter, like 'i' it goes to the front: `rigaffe`
* 'a' is the 1st letter, it goes to the very end: `rigffea`
* 'f' is the 6th letter, it becomes the 6th from the back: `rfigfea`
* the next 'f' is also the 6th letter, so it also goes to 6th from the back : `rffigea`
* 'e' is the 5th letters, it goes to 5th from the back: `rfefiga`
**"flower"**
* 'f' (6) => `flower`
* 'l' (12) => `lfower`
* 'o' (15) => `olfwer`
* 'w' (23) => `wolfer`
* 'e' (5) => `weolfr`
* 'r' (18) => `rweolf`
**"pineapple"**
* 'p' (16) => `pineapple`
* 'i' (9) => `ipneapple`
* 'n' (14) => `nipeapple`
* 'e' (5) => `nipaepple`
* 'a' (1) => `nipepplea`
* 'p' (16) => `pnipeplea`
* 'p' (16) => `ppnipelea`
* 'l' (12) => `lppnipeea`
* 'e' (5) => `lppneipea` (make sure you move the *e* that hasn't been moved already! Here it doesn't matter, but below it does.)
*Thanks to @Neil for improving the test cases with these 3 additions:*
**"pizza"**
* 'p' (16) => `pizza`
* 'i' (9) => `ipzza`
* 'z' (26) => `zipza`
* 'z' (26) => `zzipa` (moving the second z!)
* 'a' (1) => `zzipa`
**"abracadabra"**
* 'a' (1) => `bracadabraa`
* 'b' (2) => `racadabraba`
* 'r' (18) => `racadabraba`
* 'a' (1) => `rcadabrabaa`
* 'c' (3) => `radabrabcaa`
* 'a' (1) => `rdabrabcaaa`
* 'd' (4) => `rabrabcdaaa`
* 'a' (1) => `rbrabcdaaaa`
* 'b' (2) => `rrabcdaaaba`
* 'r' (18) => `rrabcdaaaba`
* 'a' (1) => `rrbcdaaabaa`
**"characters"**
* 'c' (3) => `haractecrs`
* 'h' (8) => `arhactecrs`
* 'a' (1) => `rhactecrsa`
* 'r' (18) => `rhactecrsa`
* 'a' (1) => `rhctecrsaa`
* 'c' (3) => `rhtecrscaa`
* 't' (20) => `trhecrscaa`
* 'e' (5) => `trhcrescaa`
* 'r' (18) => `rtrhcescaa`
* 's' (19) => `srtrhcecaa`
[Answer]
## CJam, ~~41~~ 38 bytes
```
lee_S+W%\{Xa-X1='`-/(Xa+\L*+}fX1>W%1f=
```
[Test it here.](http://cjam.aditsu.net/#code=lee_S%2BW%25%5C%7BXa-X1%3D'%60-%2F(Xa%2B%5CL*%2B%7DfX1%3EW%251f%3D&input=pineapple)
[Answer]
# Python 3, 78 bytes.
Saved 2 bytes thanks to orlp.
Saved 7 bytes thanks to DSM.
```
x=input()
y=[]
for z in x:m=max(len(x)-ord(z)+96,0);y[m:m]=z
print(''.join(y))
```
Builds the word as a list then joins it.
[Answer]
# Python 2, 86 bytes
```
a=input();k=list(a)
for i in a:k.remove(i);k.insert(ord(i)-97,i)
print"".join(k)[::-1]
```
---
# Python 3, 88 bytes
```
a=input();k=list(a)
for i in a:k.remove(i);k.insert(ord(i)-97,i)
print("".join(k)[::-1])
```
---
### Examples
Python 2:
```
$ python2 test.py
"flower"
rweolf
```
Python 3:
```
$ python3 test.py
flower
rweolf
```
[Answer]
## Javascript ES6, ~~136~~ ~~134~~ 131 bytes
```
s=>([...s].map(c=>{s=s.replace(c,'');p=s.length+97-c.charCodeAt();s=s.substr(0,p)+c.toUpperCase()+s.substring(p)}),s.toLowerCase())
```
Note that I take great care not to move the same character twice, otherwise `pizza` turns into `zipza` when it should be `zzipa`. There's also an edge case dealing with not removing characters prematurely; `characters` becomes maybe `srtrchaeac` or `srtrheccaa` if you do it wrongly but it should be `srtrhcecaa`. Another tricky word is `abracadabra` for which the output `rrabaaadcba` would be incorrect; `rrbcdaaabaa` would be correct.
Edit: Shaved off two bytes by using substring which automatically coerces its arguments to the range 0..length.
Edit: Shaved off three bytes by changing the first substring to substr as suggested by user81665.
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang) (v2), 58 bytes
```
;=i~!=sP;W<=i+1iLs=sI>0=l-L=tSs iT@-A=cGs iT95+c tSt lFcOs
```
[Try it online!](https://knight-lang.netlify.app/#WyI7PWl+IT1zUDtXPD1pKzFpTHM9c0k+MD1sLUw9dFNzIGlUQC1BPWNHcyBpVDk1K2MgdFN0IGxGY09zIiwiZmxvd2VyIiwiMi4wIl0=)
expanded:
```
; = idx ~1 # ie -1
; = str PROMPT
; WHILE < (= idx + idx 1) (LENGTH str)
; = chr GET str idx 1 # ie get the char at index `idx`
; = tmp SET str idx 1 "" # delete that chr
; = index - (LENGTH str) (- (ASCII chr) 95)
: = str
IF (> 0 index)
: + chr tmp
# ELSE:
: SET tmp index 0 chr # insert the char there
: OUTPUT str
```
[Answer]
# Pyth, ~~18~~ 17 bytes
```
uXeS,Z-lzhx;HGHzk
```
[Test Suite](http://pyth.herokuapp.com/?code=uXeS%2CZ-lzhx%3BHGHzk&test_suite=1&test_suite_input=giraffe%0Aflower%0Apineapple%0Abaa&debug=1).
Iterates using reduce over the input string, inserting into a string, base case empty string, at the correct position.
[Answer]
# ùîºùïäùïÑùïöùïü, 23 chars / 40 bytes
```
ᴉⓜΞăМƲ ïꝈ-ᶛą$,0),0,$;Ξ⨝
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=flower&code=%E1%B4%89%E2%93%9C%CE%9E%C4%83%D0%9C%C6%B2%20%C3%AF%EA%9D%88-%E1%B6%9B%C4%85%24%2C0%29%2C0%2C%24%3B%CE%9E%E2%A8%9D)`
# Explanation
```
ᴉⓜΞăМƲ ïꝈ-ᶛą$,0),0,$;Ξ⨝ // implicit: ï=input, ᴉ=input split into chars, Ξ=empty array, ᶛ=lowercase alphabet
ᴉⓜ // map over input chars
ΞăМƲ ïꝈ-ᶛą$,0),0,$; // use splice to insert map item into Ξ at requested index
Ξ⨝ // join Ξ
// implicit output
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 56 bytes
Port of [Morgan Thrapp's Python answer](https://codegolf.stackexchange.com/a/68830/11261).
```
->x{y=[]
x.chars{y[[x.size-_1.ord+96,0].max,0]=_1}
y*""}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3LXTtKqorbaNjuSr0kjMSi4qrK6OjK_SKM6tSdeMN9fKLUrQtzXQMYvVyEyuAlG28YS1XpZaSUi1Uv1FBaUmxglu0UnpmUWJaWqpSLBdMJC0nvzy1CEmgILOqKlEpFqJzwQIIDQA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.āDvyUΣNsXQiIgAXнk2t+-]€н
```
Outputs as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f9f70ijS1ll6LnFfsURgZme6Y4RF/ZmG5Vo68Y@alpzYe///@mZRYlpaakA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVLmNJ/vSONLmWVoecW@xVHBGZGpjtGXNibbVSirRv7qGnNhb3/lfTCXOy9lBQ0Du/XVNL5H62UnlmUmJaWqqSjlJaTX55aBGQUZOalJhYU5KSC2VVViUA6MakoMTkxBUQBeckZiUBuSWpRsVIsAA).
**Explanation:**
Unfortunately 05AB1E lacks a builtin to insert a character at a certain index without removing the current character at that index. So instead I'm using a sort-by, where I only modify the index of the current character.
```
.ā # Enumerate the (implicit) input-string, pairing each character with
# its (0-based) index (to make them all unique)
D # Duplicate it
v # Loop over each pair `y` in this list:
yU # Put pair `y` in variable `X`
Σ # Sort the list of pairs by:
N # Push the current sort-index
s # Swap so the current pair is at the top of the stack
XQi # If it's equal to pair `X`:
Ig # Push the input-length
A # Push the lowercase alphabet
X–Ω # Push the character of pair `X`
k # Get the (0-based) index of this character in the alphabet
2t+ # Add sqrt(2) to it (+1 to make it 1-based, and +0.414 so it'll
# come before the actual integer-index)
- # Subtract this index from the input-length
] # Close both the sort-by and loop
€ # Map over each pair
–Ω # And only leave its character
# (after which the list of characters is output implicitly)
```
] |
[Question]
[
**Challenge**: write a single script file `foo.cmd` which can be invoked from the vanilla Windows `cmd.exe` prompt (not PowerShell, not in administrator mode), to execute arbitrary Windows-specific code...
```
> .\foo.cmd
Hello Windows!
```
...but also be invoked unaltered from a typical POSIX-compliant (Linux/OSX) shell prompt (`bash`, `tcsh`, or `zsh`), to execute arbitrary POSIX-specific code:
```
$ chmod a+x foo.cmd
$ ./foo.cmd
Hello POSIX!
```
...without requiring installation or creation of third-party interpreters/tools.
I know this is possible, but with cruft (i.e. on Windows, one or two lines of garbage/error-message are printed to stderr or stdout before "Hello Windows!").
The winning criterion is minimization of (first) the number of cruft lines, and (second) the number of cruft characters.
Cruft can be defined as any console output (stdout or stderr) that is not produced by the (arbitrary) payload code. Blank lines are counted in the line count. Newlines are not counted in the character count. Cruft scores should be summed across both platforms. Let's disregard mechanisms like `cls` that sweep away the cruft but at the cost of also blanking out previous terminal output. If Windows echos your commands because you haven't turned `@echo off` yet, let's exclude the characters it spends in printing the current directory and prompt.
A secondary criterion is the simplicity/elegance of the solution inside `foo.cmd`: if "infrastructure" is defined as any character not directly involved in the arbitrary payload code, then minimize first the number of lines that contain infrastructure characters, and second the total number of infrastructure characters.
Extra kudos if the POSIX part will work despite the file having CRLF line-endings! (Am not sure that last part is even possible.)
My existing solution, which I will post here once others have had a chance, uses 6 lines of infrastructure code (52 chars excluding newlines). It produces 5 lines of cruft, two of which are blank, all of which occur on Windows (30 chars excluding newlines and excluding the current directory/prompt string that appears on two of those lines).
[Answer]
# 0 cruft lines, 0 cruft chars, 2 infra. lines, 21 infra. chars, CRLF ok
```
:<<@goto:eof
@echo Hello Windows!
@goto:eof
echo "Hello POSIX!" #
```
Removed the other solution.
17 characters using `exit /b` from Digital Trauma's answer:
```
:<<@exit/b
@echo Hello Windows!
@exit/b
echo "Hello POSIX!" #
```
[Answer]
# Score 0 cruft + 4 infra lines + 32 infra chars. LF & CRLF OK.
This is based off what I found at [this blog](http://stardot.org.uk/forums/viewtopic.php?t=2564), with the Amiga bits and other unnecessary lines taken out. I hid the DOS lines in commented quotes instead of using `\` line continues, so that this can work with both CRLF and LF.
```
@REM ()(:) #
@REM "
@ECHO Hello Windows!
@EXIT /B
@REM "
echo Hello POSIX!
```
With either DOS CRLF or \*nix LF line endings, it works on Ubuntu, OSX and wine:
```
ubuntu@ubuntu:~$ ./dosix.bat
Hello POSIX!
ubuntu@ubuntu:~$ wine cmd.exe
Wine CMD Version 5.1.2600 (1.6.2)
Z:\home\ubuntu>dosix.bat
Hello Windows!
Z:\home\ubuntu>exit
ubuntu@ubuntu:~$
```
To create this exactly (with CRLFs) on a \*nix machine (including OSX), paste the following to a terminal:
```
[ $(uname) = Darwin ] && decode=-D || decode=-d
ubuntu@ubuntu:~$ base64 $decode > dosix.bat << EOF
QFJFTSAoKSg6KSAjDQpAUkVNICINCkBFQ0hPIEhlbGxvIFdpbmRvd3MhDQpARVhJVCAvQg0KQFJF
TSAiDQplY2hvIEhlbGxvIFBPU0lYIQ0K
EOF
```
[Answer]
I'll already post the solution I had been using, since it has already been beaten. It's courtesy of a colleague of mine who I think must have read the same blog entry as [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma).
```
#!/bin/sh # >NUL 2>&1
echo \
@goto c \
>/dev/null
echo "Hello Posix!"
exit
:c
@echo Hello Windows!
```
* Windows cruft: 5 lines (of which two are blank) / 30 chars
* OSX cruft: 0
* Infrastucture: 6 lines / 52 chars
* CRLF compatibility: only if the interpreter named on the `#!` line doesn't care (so for standard interpreters like `sh` and friends, it fails)
[Answer]
# Summary/synthesis of answers and discussion
This was fun, and I learned a lot.
Some Windows-specific cruft is inevitable if, on your POSIX system, you need to start your script with a `#!` line. If you have no alternative but to do this, then this line:
```
#!/bin/sh # 2>NUL
```
is probably the best it can get. It causes one blank line and one line of cruft to be output on the Windows console. However, you *may* be able to get away without a `#!` line: on most systems, one of the usual shell interpreters will end up executing the script (the problem is that it's not universally predictable which interpreter that will be - it depends on, but will not necessarily be identical to, the shell you use to invoke the command).
Beyond that tricky first line, there were some really ingenious cruftless solutions. The winning submission by [jimmy23013](https://codegolf.stackexchange.com/users/25180/jimmy23013) consisted of only two short infrastructure lines, and made use of the dual role of the `:` character to implement a "silent" line on both platforms (as a *de-facto* no-op in `sh` and friends, and as a label marker in `cmd.exe`):
```
:<<@exit/b
:: Arbitrary Windows code goes here
@exit/b
#
# Arbitrary POSIX code goes here
```
It *is* possible to make such a script run on POSIX systems even despite CRLF line-endings, but to do this for most interpreters you have to end *every* line of your POSIX section (even blank lines) with a comment or comment character.
Finally, here are two variants on a solution I have developed based on everybody's input. They might be *almost* the best of all worlds, in that they minimize the damage from the lack of `#!` and make CRLF-compatibility even smoother. Two extra infrastructure lines are needed. Only one (standardized) line has to be interpreted by the unpredictable POSIX shell, and that line allows you to select the shell for the rest of the script (`bash` in the following example):
```
:<<@GOTO:Z
@echo Hello Windows!
@GOTO:Z
bash "$@"<<:Z
#
echo "Hello POSIX!" #
ps # let's throw this into the payload to keep track of which shell is being used
#
:Z
```
Part of the beauty of these heredoc solutions is that they are still CRLF-robust: as long as `<<:Z` comes at the *end* of the line, the heredoc processor will actually be looking for, and will find, the token `:Z\r`
As a final twist, you can get rid of those pesky end-of-line comments and still retain CRLF-robustness, by stripping the `\r` characters out before passing the lines to the shell. This places slightly more faith in the unpredictable shell (it would be nice to use `{ tr -d \\r|bash;}` instead of `(tr -d \\r|bash)` but curly brackets are bash-only syntax):
```
:<<@GOTO:Z
@echo Hello Windows!
@GOTO:Z
(tr -d \\r|bash "$@")<<:Z
echo "Hello POSIX!"
ps
:Z
```
Of course, this approach sacrifices the ability to pipe stdin input into the script.
] |
[Question]
[
# The Interview: The Front Nine
*This is the first of a series of challenges inspired by programming job interview questions.*
You walk into the office where your potential future boss sits. "Come on in and sit down", he says. You nervously sit down, making sure your snappy yet professional attire is free of wrinkles. He asks you many questions, about your education, previous work experiences, and so on. You answer them mostly honestly, adding a little embellishment here and there to make yourself sound better. He leans forward and begins to speak again.
"Have you ever heard of code golfing?" Why, yes, you love to golf code, and do it frequently in your free time. "Great. The last part of the interview is a technical examination. You will be tasked with writing code to solve a series of problems..." He hands you a sheet of paper. You quickly glance over it. Easy peasy. Now why did he ask about code golfing?
"You will be graded based on the total size of your solutions to these problems. If you can score lower than all the other candidates, the job is yours." Oh. "Like golf, there are 18 problems, broken up into two sets of 9. Feel free to use any language you like to solve them; we have compilers and interpreters for every language you've heard of, and certainly a few that you haven't. Good luck!"
## The Tasks
### Task 1: Multiplication Table
Given a number `n` as input, output a multiplication table for positive integers in the range `[1, n]`. `n` will be in the range `[1, 12]`. All numbers should be left-aligned in the table. Use the character `x` for the top-left corner.
Examples:
```
n=4
x 1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
n=10
x 1 2 3 4 5 6 7 8 9 10
1 1 2 3 4 5 6 7 8 9 10
2 2 4 6 8 10 12 14 16 18 20
3 3 6 9 12 15 18 21 24 27 30
4 4 8 12 16 20 24 28 32 36 40
5 5 10 15 20 25 30 35 40 45 50
6 6 12 18 24 30 36 42 48 54 60
7 7 14 21 28 35 42 49 56 63 70
8 8 16 24 32 40 48 56 64 72 80
9 9 18 27 36 45 54 63 72 81 90
10 10 20 30 40 50 60 70 80 90 100
```
### Task 2: Ordinal RMS
Given a string of ASCII characters, output the [root-mean-square](https://en.wikipedia.org/wiki/Root_mean_square) average of their ASCII ordinals. The string will never contain a NULL byte (ordinal 0).
Examples:
```
Input: The Interview: The Front Nine
Output: 95.08290393488019
Input: `1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./
Output: 91.38101204135423
```
### Task 3: Projectile Motion
Given the initial velocity and angle with the horizon of a projectile fired from ground level, output the horizontal distance it will travel before landing. The initial velocity will be given in meters per second, the angle will be given in degrees, and the distance shall in meters. Assume Earth gravity (`g=9.81 m/s/s`), and ignore relativistic effects. For the sake of this problem, you may assume the Earth is flat (you will not need to consider the curvature of the Earth when making your calculations). The given angle will be in the range `[0, 90]`. Your answer should be accurate to at least two decimal places (rounding is allowed).
Examples:
```
velocity=50, angle=45
Result: 254.84 (rounded)
velocity=10, angle=60
Result: 8.82798576742547
```
### Task 4: etaoin shrdlu
Given a string of non-null printable ASCII characters (ordinals in the range `[32,127]`), output the string, with its characters sorted by their frequencies in descending order. In the case of a tie, order by ASCII ordinal, ascending.
Examples:
```
Input: "Hello, World!"
Output: "llloo !,HWder"
Input: "Programming Puzzles and Code Golf"
Output: " oooPPaaddeeggllmmnnrrzzCGfisu"
```
### Task 5: Fibonacci Index
Given a number, determine if it is a Fibonacci number, and if it is, output its index (starting from 1) in the sequence. If it is not a Fibonacci number, output 0. In the case of 1, which is in the sequence twice, output the earliest occurrence (index 1).
Examples:
```
Input: 1
Output: 1
Input: 144
Output: 12
Input: 4
Output: 0
```
### Task 6: Anagrams
Given three strings of lowercase English letters (`[a-z]`), output a string that uses all the letters in the first string, begins with the second string, and ends with the third string. If such a string cannot be constructed, output an empty string. The input strings will always be at least one letter long. The "middle" of the output string (between the prefix and postfix string) may be empty, if the prefix and postfix strings together use all of the letters in the source string.
Examples:
```
Input: geobits bi es
Possible output: bigtoes
Input: mariatidaltug digital trauma
Output: digitaltrauma
Input: mego go lf
Output: (empty string)
```
### Task 7: Filling In The Blanks
Given a list of strings and a fill character, output the result of padding all of the strings to the length of the longest string with the fill character, sorted in ascending order by the original lengths of the strings, preserving the original order in the case of a tie. You should be able to handle lists of any finite length, containing strings of any finite length, bounded only by memory constraints.
Examples:
```
Input: ["hello","world","this","is","a","test"], 'x'
Output: ["axxxx","isxxx","thisx","testx","hello","world"]
Input: ["I'm","a","lumberjack","and","I'm","okay"], '!'
Output: ["a!!!!!!!!!","I'm!!!!!!!","and!!!!!!!","I'm!!!!!!!","okay!!!!!!","lumberjack"]
```
### Task 8: Making Change
Given a number in the range `[0.01,0.99]`, output the number of each of the 4 standard US coins that should be used to represent this value such that the total number of coins is minimized. The input will always have exactly 2 places behind the decimal.
Coin value reference:
`Penny: 0.01, Nickel: 0.05, Dime: 0.10, Quarter: 0.25`
Examples:
```
Input: 0.75
Output: [0,0,0,3]
Input: 0.23
Output: 3 pennies, 0 nickels, 2 dimes, 0 quarters
```
### Task 9: Merging Ranges
Given a finite list of 2-tuples containing integers that represent ranges, output the result of merging all overlapping or adjacent ranges. All ranges will be at least of length 1, and the starting value will always be less than the ending value. The order of the output does not matter.
Examples:
```
Input: (2,3), (4,5), (6,9), (0,7)
Output: (0,9)
Input: (-3,4), (2,5), (-10,-4)
Output (-10,-4), (-3,5)
Input: (2,3), (5,6), (6,8)
Output: (5,8), (2,3)
```
---
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) wins.
* Your score will be the sum of the byte counts for all of your solutions.
* Standard loopholes are forbidden.
* Input and output may be performed in whatever manner is considered standard for your language.
* You may write full programs or functions for each challenge, and may interchange between the two across challenges.
* You must use the same language for all the challenges. If version differences are significant enough for them to be usually considered separate entries in challenges, you must use the same version throughout. For example, if you use Python, you must use either Python 2 or Python 3 for all challenges.
* You must solve all of the challenges. Answers that only solve some of the challenges will be considered non-competitive.
* You may use language builtins or standard libraries.
### 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 = 63014; 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 "//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 "//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(42), 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]
# CJam, 162
1. [25 bytes](http://cjam.aditsu.net/#code=qi)%2C0Xt_ff%7B*s4Se%5D%7DN*s0'xt&input=10) • `qi),0Xt_ff{*s4Se]}N*s0'xt`
2. [12 bytes](http://cjam.aditsu.net/#code=q_%3Ai%3Amh%5C%2Cmq%2F&input=%601234567890-%3Dqwertyuiop%5B%5D%5Casdfghjkl%3B'zxcvbnm%2C.%2F) • `q_:i:mh\,mq/` (© Dennis)
3. [18 bytes](http://cjam.aditsu.net/#code=q~P*90%2Fms%5C_**9.81%2F&input=50%2045) • `q~P*90/ms\_**9.81/`
4. [12 bytes](http://cjam.aditsu.net/#code=q%24e%60%7B0%3D~%7D%24e~&input=Hello%2C%20World!) • `q$e`{0=~}$e~` (© Dennis)
5. [16 bytes](http://cjam.aditsu.net/#code=1_%7B_2%24%2B%7D99*%5Dqi%23)&input=144) • `1_{_2$+}99*]qi#)`
6. [22 bytes](http://cjam.aditsu.net/#code=qS%2F(1%2B1%24s%7B1%24%23Lt%7D%2F)%40%40**&input=geobits%20bi%20oes) • `qS/(1+1$s{1$#Lt}/)@@**`
7. [18 bytes](http://cjam.aditsu.net/#code=q~%7B%2C%7D%24_z%2Cf%7BW%24e%5D%7Dp%3B&input='x%5B%22hello%22%22world%22%22this%22%22is%22%22a%22%22test%22%5D) • `q~{,}$_z,f{W$e]}p;`
8. [16 bytes](http://cjam.aditsu.net/#code=q2%3Ei25A5%5D%3Amd%5DW%25p&input=0.75) • `q2>i25A5]:md]W%p`
9. [23 bytes](http://cjam.aditsu.net/#code=q~%24%7B_0%3D2%241%3D%3E%7B%2B%243%25%7D%7C%7D*%5Dp&input=%5B%5B2%203%5D%5B4%205%5D%5B6%209%5D%5B0%207%5D%5D) • `q~${_0=2$1=>{+$3%}|}*]p`
[Dennis agreed to join forces :)](http://chat.stackexchange.com/transcript/message/25187715#25187715)
[Answer]
# Pyth, ~~155~~ ~~153~~ ~~149~~ ~~142~~ ~~141~~ ~~131~~ 130 bytes
*4 bytes thanks to @FryAmTheEggman*
*1, 5 and 4 bytes thanks to @Jakube*
1. [24 bytes](https://pyth.herokuapp.com/?code=J%2B1SQp%5Cxtjmsm.%5B%60%2adk%5C+4JJ&input=12&debug=0): `J+1SQp\xtjmsm.[`*dk\ 4JJ`
Construct the multiplication table from the list `[1, 1, 2, 3, ...]`, which is `+1SQ`, then print a `x` and remove its first character.
2. [10 bytes](https://pyth.herokuapp.com/?code=%40.Om%5ECd2z2&input=%601234567890-%3Dqwertyuiop%5B%5D%5Casdfghjkl%3B%27zxcvbnm%2C.%2F&debug=0): `@.Om^Cd2z2`
Straightforward.
3. [18 bytes](https://pyth.herokuapp.com/?code=c%2a.t.tyvw7Z%2aQQ9.81&input=10%0A60&debug=0): `c*.t.tyvw7Z*QQ9.81`
Uses the formula `sin(2 theta) * v^2/a`, where `theta` is the angle, `v` is the initial velocity and `a` is `9.81`
4. [7 bytes](https://pyth.herokuapp.com/?code=o_%2FzNSz&input=Hello%2C+World%21&debug=0): `o_/zNSz`
Straightforward.
5. [15 bytes](https://pyth.herokuapp.com/?code=hxeM.u%2CeNsNQU2Q&input=144&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A144&debug=0): `hxeM.u,eNsNQU2Q`
Generate fibonacci pairs, find the index of the input in them, add one.
6. [14 bytes](https://pyth.herokuapp.com/?code=IqSzSJj.-zsQQJ&input=geobits%0A%22bi%22%2C+%22es%22&test_suite_input=geobits%0A%22bi%22%2C+%22es%22%0Amariatidaltug%0A%22digital%22%2C+%22trauma%22%0Amego%0A%22go%22%2C+%22lf%22&debug=0&input_size=2): `IqSzSJj.-zsQQJ`
Use bagwise subtraction to remove the prefix and suffix from the word, then put the remainder of the word in the middle. If the result of this is not a permutation of the input, don't print it.
7. [8 bytes](https://pyth.herokuapp.com/?code=C.tolNQz&input=x%0A%5B%22hello%22%2C%22world%22%2C%22this%22%2C%22is%22%2C%22a%22%2C%22test%22%5D&debug=0): `C.tolNQz`
Sort by length. Filled transpose. Transpose again.
8. [18 bytes](https://pyth.herokuapp.com/?code=Jsttz%2FL~%25Jd%5B25T5+1&input=0.23&debug=0): `Jsttz/L~%Jd[25T5 1`
Output coin counts are in the order `[quarters, dimes, nickels, pennies]`.
Remove first 2 characters of input and cast to int to get cents. Save to `J`. For each number `d` in the list `[25, 10, 5, 1]`, post-assign `J%d` to `J`, then generate the value `/Jd` with the original value of `J`. Print.
9. [16 bytes](https://pyth.herokuapp.com/?code=C-M.p%2CJS%7BsrMQhMJ&input=%28-3%2C4%29%2C+%282%2C5%29%2C+%28-10%2C-4%29&debug=0): `C-M.p,JS{srMQhMJ`
Turn the tuples into ranges, combine into one list, deduplicate and sort. Save this to `J`. Form `J, hMJ` and `hMJ, J`, where `hMJ` is `J` with every element increased by 1. Perform subtraction in both cases. The former is the lower ends of the ranges, the latter is the higher ends. Transpose them into pairs and print.
[Answer]
# CJam, 223 bytes
### Task 1, 35 bytes
```
ri_)_,0Xt2m*::*0'xt:s@s,2+f{Se]}/N*
```
[Try it online.](http://cjam.aditsu.net/#code=ri_)_%2C0Xt2m*%3A%3A*0'xt%3As%40s%2C2%2Bf%7BSe%5D%7D%2FN*&input=10)
### Task 2, 12 bytes
```
q_:i:mh\,mq/
```
[Try it online.](http://cjam.aditsu.net/#code=q_%3Ai%3Amh%5C%2Cmq%2F&input=The%20Interview%3A%20The%20Front%20Nine)
### Task 3, 27 bytes
```
rd180/P*_mc\ms]rdf*~4.905/*
```
[Try it online.](http://cjam.aditsu.net/#code=rd180%2FP*_mc%5Cms%5Drdf*~4.905%2F*&input=45%2050)
### Task 4, 12 bytes
```
q$e`{0=~}$e~
```
[Try it online.](http://cjam.aditsu.net/#code=q%24e%60%7B0%3D~%7D%24e~&input=Hello%2C%20World!)
### Task 5, 17 bytes
```
XXri:R{_2$+}*]R#)
```
[Try it online.](http://cjam.aditsu.net/#code=XXri%3AR%7B_2%24%2B%7D*%5DR%23)&input=144)
### Task 6, 25 bytes
```
re!_rf#:!.*r:S;{N+SN+#)}=
```
[Try it online.](http://cjam.aditsu.net/#code=re!_rf%23%3A!.*r%3AS%3B%7BN%2BSN%2B%23)%7D%3D&input=geobits%20bi%20es)
### Task 7, 19 bytes
```
{:C;{,}$_W=,f{Ce]}}
```
[Try it online.](http://cjam.aditsu.net/#code=q~%0A%20%20%7B%3AC%3B%7B%2C%7D%24_W%3D%2Cf%7BCe%5D%7D%7D%0A~p&input=%5B%22hello%22%20%22world%22%20%22this%22%20%22is%22%20%22a%22%20%22test%22%5D%20'x)
### Task 8, 33 bytes
```
A4m*{:+}$r2>i:R;{[X5A25].*:+R=}=p
```
[Try it online.](http://cjam.aditsu.net/#code=A4m*%7B%3A%2B%7D%24r2%3Ei%3AR%3B%7B%5BX5A25%5D.*%3A%2BR%3D%7D%3Dp&input=0.23)
### Task 9, 43 bytes
```
{{~1$-,f+}%:|$__,(%a\2ew{:-W<},+e_$2/2,f.+}
```
[Try it online.](http://cjam.aditsu.net/#code=qN%2F%3A~%0A%20%20%7B%7B~1%24-%2Cf%2B%7D%25%3A%7C%24__%2C(%25a%5C2ew%7B%3A-W%3C%7D%2C%2Be_%242%2F2%2Cf.%2B%7D%0A%25%3Ap&input=%5B%5B2%203%5D%20%5B4%205%5D%20%5B6%209%5D%20%5B0%207%5D%5D%0A%5B%5B-3%204%5D%20%5B2%205%5D%20%5B-10%20-4%5D%5D%0A%5B%5B2%203%5D%20%5B5%206%5D%20%5B6%208%5D%5D)
[Answer]
## Haskell, 650 bytes
Task 1, 88 bytes:
```
f n="x "++unlines(map(take 4.(++" ").show=<<)$[1..n]:map(\a->a:map(a*)[1..n])[1..n])
```
Task 2, 76 bytes:
```
g s=sqrt(sum(map(fromIntegral.(^2).fromEnum)s)/sum(s>>[1]))
```
Task 3, 28 bytes
```
v?a=v*v/9.81*sin(2*a*pi/180)
```
Task 4, 60 bytes:
```
import Data.List
i x=concat$sortOn((0-).length)$group$sort x
```
Task 5, 64 bytes
```
j=(%zip[0..]z);x%((i,h):t)|x<h=0|x==h=i|1<2=x%t;z=scanl(+)0(1:z)
```
Task 6, 93 bytes
```
import Data.List
k a b c|q b a&&q c a=b++((a\\b)\\c)++c|1<2="";q=(.sort).isSubsequenceOf.sort
```
Task 7, 81 bytes
```
import Data.List
s!f=map(take(maximum$map r s).(++cycle[f]))(sortOn r s);r=length
```
Task 8, 73 bytes
```
m x=floor(x*100)#[25,10,5,1];x#[]=[];x#(h:t)|(d,m)<-divMod x h=(m#t)++[d]
```
Task 9, 87 bytes (a shameless copy of @MtnViewMark's [answer](https://codegolf.stackexchange.com/a/2154/34531) from a similar challenge)
```
n i=foldr(&)[]i;p@(a,b)&(q@(c,d):r)|b<c=p:q&r|a>d=q:p&r|1<3=(min a c,max b d)&r;p&_=[p]
```
[Answer]
# Mathematica 10.3, 465 bytes
All of these are anonymous functions. Also, thanks to Martin for help golfing, since I'm a noob at Mathematica.
### Task 1, 69 bytes
```
Grid@Join[{Join[{"x"},r=Range@#]},Flatten/@({r,Outer[1##&,r,r]}\[Transpose])]&
```
`\[Transpose]` is the 3 byte "transpose" symbol.
### Task 2, 13 bytes
```
Mean[#^2]^.5&
```
or
```
√Mean[#^2]&
```
(√ is 3 bytes). The `RootMeanSquare` built-in isn't quite short enough...
### Task 3, 18 bytes
```
Sin[2#2°]#/9.81#&
```
### Task 4, 57 bytes
```
""<>SortBy[c=Characters@#,{-c~Count~#&,ToCharacterCode}]&
```
### Task 5, 33 bytes
```
Tr@Position[Fibonacci@Range@#,#]&
```
or
```
Tr[Fibonacci@Range@#~Position~#]&
```
or
```
Tr[Fibonacci~Array~#~Position~#]&
```
### Task 6, 178 bytes ~~(currently has a bug)~~
```
({s,a,b}=Characters@{##};q=If[#2~SubsetQ~#,List@@(Plus@@#-Plus@@#2),{}]&;i=If[#!={},##]&;x=i[q[s,a],{}];y=If[x!={},i[q[x,b],{},Null],Null];Echo[If[y!=Null,""<>Join@{a,y,b},""]])&
```
Less golfed:
```
({s,a,b}=Characters@{##};
q=If[#2~SubsetQ~#,List@@(Plus@@#-Plus@@#2),{}]&;
i=If[#!={},##]&;
x=i[q[s,a],{}];
y=If[x!={},i[q[x,b],{},Null],Null];
Echo[If[y!=Null,""<>Join@{a,y,b},""]])&
```
String manipulation is horrid...
### Task 7, 39 bytes
```
#~SortBy~StringLength~StringPadRight~#1
```
### Task 8, 46 bytes
```
FrobeniusSolve[{1,5,10,25},100#]~MinimalBy~Tr&
```
or
```
{.1,.5,.10,.25}~FrobeniusSolve~#~MinimalBy~Tr&
```
### Task 9, 12 bytes
```
Interval@##&
```
Intervals passed to the constructor are automatically union-ed. Beat that.
] |
[Question]
[
Finding a treasure hidden by pirates is really easy. Everything you need for this is a map. It is widely known that pirates draw maps by hand and describe the algorithm to find a place in the following way: "Stand near a lone palm tree, do 30 steps towards the forest, 15 towards the lake, ..."
A journey through such route is usually a great opportunity to see the scenery... However, nowadays nobody has time for that. That's why treasure seekers have asked you to write a program that would determine the exact location of a treasure using a given map.
---
# Input
The input consists of multiple instructions `<Direction> <Distance>`, separated with commas (that are followed by one whitespace each).
**Direction** is one of the following:
**`N`** - North, **`S`** - South, **`E`** - East, **`W`** - West,
**`NE`** - Northeast, **`NW`** - Northwest, **`SE`** - Southeast, **`SW`** - Southwest.
**Distance** is an integer (1 to 1000).
# Output
The result is the coordinates where you end up after finishing the instructions, with three decimal places, separated with a comma and a whitespace. Start location has zero coordinates (0, 0).
The first coordinate is **X** (East means coordinates larger than zero, West means less than zero).
The second coordinate is **Y** (North means *more* than zero, South means *less* than zero).
---
# Examples
**1.** `N 3, E 1, N 1, E 3, S 2, W 1`
`3.000, 2.000`
**2.** `NW 10`
`-7.071, 7.071`
**3.** `NE 42, NW 42, SE 42, SW 42`
`0.000, 0.000`
---
[Source](http://acm.lviv.ua/fusion/viewpage.php?page_id=9&id=1016) (in Ukrainian). Input format is different there.
[Answer]
## Ruby 1.9, 175 171 162 153 130 120 117
```
l=0
gets.scan(/(\w+) (\d+)/){|d,n|l+=n.to_i*?i.to_c**%w[E NE N NW W SW S SE].index(d).quo(2)}
puts'%.3f, %.3f'%l.rect
```
[Answer]
## Haskell (291)
```
import Text.Printf
d=sqrt(0.5)
f"N"n(x,y)=(x,y+n)
f"S"n(x,y)=(x,y-n)
f"E"n(x,y)=(x+n,y)
f"W"n(x,y)=(x-n,y)
f[a,b]n(x,y)=(s,t)where(s,_)=f[b](d*n)(x,y);(_,t)=f[a](d*n)(x,y)
p[]=(0,0)
p(a:b:c)=f a(read b::Float)$p c
s(a,b)=printf"%.3f, %.3f"a b
main=getLine>>=putStrLn.s.p.words.filter(/=',')
```
[Answer]
## C99 (319 chars)
```
#define B ;break;
#include<math.h>
#include<stdio.h>
float x,y,w,z,j;int
main(void){int
k;char
c[3];while(scanf("%s%d,",c,&k)==2){j=k;w=1;switch(c[1]){case'E':w=3;default:w-=2;j=sqrt(k*k/2)B
case
0:w=z=0;}switch(*c){case'N':z=1
B
case'S':z=-1
B
case'E':w=1
B
default:w=-1;}x+=w*j;y+=z*j;}printf("%5.3f, %5.3f\n",x,y);}
```
input in `stdin`, [test run](http://ideone.com/HNj3d) at ideone :)
[Answer]
## Python, 158 154 150 chars
```
p=0j
for s in raw_input().split(','):c,d=s.split();v=sum(dict(N=1j,E=1,S=-1j,W=-1)[x]for x in c);p+=v*int(d)/abs(v)
print'%.3f, %.3f'%(p.real,p.imag)
```
[Answer]
## JavaScript, ~~179~~ ~~164~~ ~~170~~ ~~168~~ ~~158~~ ~~156~~ 153 chars
```
prompt(X=Y=0).replace(/(N|S)?(.)? (\d+)/g,
function(m,y,x,n){
n/=x&&y?Math.SQRT2:1
Y+=y?y<'S'?n:-n:0
X+=x?x<'W'?n:-n:0
})
alert(X.toFixed(3)+', '+Y.toFixed(3))
```
* 170: fixed accuracy issue
* 168: replaced `(E|W)` in regex with `(.)`
* 158: replaced repetitive logic in function with variable `d`
* 156: reused `n` instead of a new variable `d`
* 153: Personally, I think this edit makes it ten times uglier, but it's three characters shorter. It's based on the non-standard behavior that you can call RegExp objects as functions: `/./g('string')` is the same as `/./g.exec('string')`:
`for(p=prompt(X=Y=0),R=/(N|S)?(.)? (\d+)/g;[,y,x,n]=R(p)||0;X+=x?x<'W'?n:-n:0)n/=x&&y?Math.SQRT2:1,Y+=y?y<'S'?n:-n:0;alert(X.toFixed(3)+', '+Y.toFixed(3))`
[Answer]
# Haskell, 199 characters
```
import Text.Printf
import Complex
i=0:+(1::Float)
e 'S'= -i
e d=i^mod(fromEnum d-1)4
g p(d:s:t)=g(p+(signum.sum.map e)d*(fst(reads s!!0):+0))t
g(x:+y)[]=printf"%.3f, %.3f"x y
main=interact$g 0.words
```
[Answer]
**Scala (367, 332)**
```
var (x,y,s)=(.0,.0,.7071);args.mkString(" ").split(",").foreach{m=>val a=m.trim.split(" ");var (n,u,v)=(a(1).toInt,.0,.0);a(0) match{case "N"=>v=1;case "S"=>v= -1;case "E"=>u=1;case "W"=>u= -1;case "NW"=>{u= -s;v=s};case "NE"=>{u=s;v=s};case "SW"=>{u= -s;v= -s};case "SE"=>{u=s;v= -s}};x += n*u;y += n*v};printf("%1.3f %1.3f\n",x,y)
```
[Answer]
## Java ~~(459) (445) (402) (382) (363)~~ (352)
```
import java.util.*;class
M{public
static void main(String[]a){double
x=0,y=0;Scanner
s=new
Scanner(System.in);s.useDelimiter("\\W+");while(s.hasNext()){String
d=s.next();double
z=Math.sqrt(d.length());int
w=s.nextInt();y+=(d.contains("N")?w:d.contains("S")?-w:0)/z;x+=(d.contains("E")?w:d.contains("W")?-w:0)/z;}System.out.format("%1.3f %1.3f",x,y);}}
```
stdin input
[Answer]
## PowerShell, 178
```
$input-split','|%{,@{N=0,1
NE=($s=.707106781186548),$s
E=1,0
SE=$s,-$s
S=0,-1
SW=-$s,-$s
W=-1,0
NW=-$s,$s}[($a=-split$_)[0]]*$a[1]}|%{$x+=$_[0]
$y+=$_[1]}
'{0:N3}, {1:N3}'-f$x,$y
```
This can probably lose up to 10 characters by reducing the accuracy of √2/2.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~155~~ 152 bytes
-3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
float x,y,l;D;main(d){for(;scanf("%s%f,",&d,&l)>0;y+=d^78?d^83?0:-l:l)D=d,l/=D>99?D/=256,d&=255,sqrt(2):1,x+=D^87?D^69?0:l:-l;printf("%.3f, %.3f",x,y);}
```
[Try it online!](https://tio.run/##FY5NC4JAFEX/ykNIHHpmKubHMLqZtm1atBOGGSaEl5W6UKK/3qSbc7mLw706vGvtnKWnmmDGBYlL/lBdHxj2sc8h4KNWvQ283biz6KFv0CdWH/myF6bNi8a0Rdocq5AqYlIYpEjIuiwbGYkkO6Hx18hwfA9TkLAqxnkvZFvkjWxP5erRavLX0PXTtnFILcJGD9cvjH@du0CKcIYY4bLhvNUrJAg3iH/akrqPLqTHHw "C (gcc) – Try It Online")
[Answer]
## Groovy (215)
```
x=0.0;y=0.0;args.join(' ').split(', ').each{d=it.split(' ');c=d[0]==~/../?Math.sqrt(2):1;s=d[1] as int;a=['N':1,'S':-1,'E':1,'W':-1];m=d[0]=~/N|S/;y+=m?a[m[0]]*(s/c):0;m=d[0]=~/E|W/;x+=m?s/c*a[m[0]]:0};print "$x,$y"
```
reads input as program arguments. Example:
```
groovy golf.groovy NW 10, SW 10, W 10
```
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 122 bytes
```
s,(N|S)?(E|W)? (\d+),$d=$3/($1&$2?2**.5:1);$x+=$2&&$d*(-1)**($2gt F);$y+=$1&&$d*(-1)**($1gt O),ge;printf"%.3f, %.3f",$x,$y
```
[Try it online!](https://tio.run/##VckxDoMgFADQqxDzawCB@jEuNYap3WqHDl06osbEIFEGTTx7qR27vOX5dh7LGBdBm/3JDL3uL2YIfduMCbA1FGcKmII2mnNVXpBVsGY16DQFy6lExjkF3QdyO2Y7Bv8Gj3kw0beVnwcXuuSkik6Qn4mAVcAWY0Mw/0w@DJNboryXKsc8SvcF "Perl 5 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 93 bytes
```
[:0j3&":@+.@(1#.".@>@{:*(0j1^2%~i.8){~<;._1@' E NE N NW W SW S SE'i.{.)@|:[:(<;._1);._1', ',]
```
[Try it online!](https://tio.run/##VU3BqsJADLz3K4aKptU1ZFtBWX2y8Kgn8eAePIh6EEV78QMq/npftvoePEgmGTKTqduU6YovB4KBwGmPGd/b9ardO6nLQer8iH1me5yyX/rGDTOp7bHov@48y5vXYs4n6wkVNlrY7LBD0EKo6M4N5/7p9i7rZHkEMiBzaPPkcr49QKcpy9SiQ8LY4QrSJ1boIyhZRFBE/LujNBpojQbauCkNKIxG21@bdDb5Z6swUZF@jyO8WYiMkqT9AQ "J – Try It Online")
] |
[Question]
[
Your job is to create the longest period [iterating quine](https://esolangs.org/wiki/Iterating_quine), where the length of each program in the sequence is bounded by 500 bytes.
That is, if you repeat the following steps:
1. Start with your initial program
2. Run the current program
3. Go back to step 2
You will eventually get back to your original program. The number of programs in the cycle is your score, which you are trying to maximize.
None of the programs may raise any errors. Each program must be run the same way as well (e.g. no different versions, implementations, compiler options, platforms, etc...) (EDIT: Yes, any external state such as that of a pseudo random number generator was included in the last statement. The external state must be "reset" after each run. If you use true random numbers, worst case is assumed.)
What separates this challenge from [The longest period iterating quine](https://codegolf.stackexchange.com/questions/91332/the-longest-period-iterating-quine) (other than 100 v.s. 500) is that every program in the cycle must also be 500 bytes or less. This means that the longest possible cycle is (256^501 - 1)/255 or less. That of course is a big number, but not that big in terms of how much code it takes to calculate. So the challenge is about using as many of the (256^501 - 1)/255 possibilities as you can, not a busy beaver challenge.
The programs are not permitted to access its own source code. However an empty program *is* permitted if you want (as long as you follow the other rules).
Since checking the programs manually would be hard, you may figure out the score using theoretical methods. You must include an explanation of the score and correctness with your program. If you can not figure out the score, you may instead use a lower bound of the number of programs in the cycle as a defacto score. You are allowed to update this as you find better lower bounds, or if you find the exact actual score.
This is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), so highest score wins!
EDIT: It is recommended that you write what your score is in scientific notation, so that answers are more easily comparable. It is perfectly fine to have other forms of the score as well, especially if they are connected to your program more clearly. Also, readers are encouraged to edit previous answers to comply with this.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), \$126^{398} \approx 8.86 \times 10^{835}\$ iterations
```
$!=Q~~;<say "\$!=Q~{chrs(my@a=[R,] polymod :126[$!.ords]+1: 126 xx*)x?(@a-399)}~;<$_>~~.EVAL">~~.EVAL
```
[Try it online!](https://tio.run/##TY/NqsIwEIXXN08xllBaq@VWQdAYfxZ3dzeKuFHRaoMW2kYSxZTSvHqNtYKrOWeYmfPNlYlkUKU54BOPGFBYHCrcogutyViGOVjb2hWni5BOms9Cull2dnDlSZ7yCEZBb7DBLZ@LSO68YATGg1JtV02dWdjtD4duaS7h/URr/289/7c@AlUHX96P8iacoNPuBi5B6IXBRXyOszAxKDXSu22/WCgUH0q819Y2swisxJ2Vzaqiv0Y9LnHCwLmJ5qc6zQXbbl7M2FdIgX7eQ@Y@MVp5HkElQl9NrOpaPQE "Perl 6 – Try It Online")
This iterates through all the possible combinations of the first 126 bytes of length 398 and under (excluding strings with leading NUL bytes). If you want to see that it actually returns to the first iteration, you can reduce the length to 1 by changing the limit [like so](https://tio.run/##TY8/D4IwEMVn@ylO0hAQJeLgYK1/BjcXjXFRoyiNkgA1rcYSQr86VsTE6d673N373Z2JZFilOeALjxhQWJ0q3KYrrclYhjlY@9oVl5uQTprPQrpbdw9w50me8ghGwWC4w22fi0gevGAExoNSHVdNnVnYG7iluYOPE639xXa@tH4CVSdfPs/yIZyg2@kFLkHoA8FFfI2zMDEgNdC3bX9IKBQ/RnzU1j6zCGzEk5XNqqJ9o163OGHgPETzUZ3mgm03D2bsL6RAre@QuU@MVp5HUInQXxOrulZv).
### Explanation:
Each iteration increments the string, stored in base 126 form, and then converts it back to base 126. It does this until it reaches a string with length 399, and then resets the string back to empty again. If you're having trouble conceptualising the number, imagine it with ten bytes instead. Starting from `0`, increment up to 4 digits, `1000` and reset. This is \$10^{4-1}\$ iterations (including `0` or empty string in my program's case).
```
$!=Q~~; # Start with an empty string
< ... >~~.EVAL # Set a string to $_ and EVAL it
say "\$!=Q~{...}~;<$_>~~.EVAL" # Print the program with the string replaced by
:126[$!.ords] # The string converted from base 126
+1 # Incremented
[R,] polymod : 126 xx* # Back to base 126
chrs( ) # Back to a string
my@a= x?(@a-399) # Only if it isn't 399 characters
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), ~~64654106~~; 122387-1 ≈ 2.638 × 10807 iterations
```
"3X4+kSq'ƃZ,r{1?{1[:1Z%1+:a=+:d=+:3X4+=+:6X2+=+:'€(c*?~1-1kq}͍f1+0Bl1=6*?S1-Skql͗2=4*?{͍]}B͍l1=6*?kS1-Sq]}@
```
[Try it online!](https://tio.run/##KyrNy0z@/1/JOMJEOzu4UP1Yc5ROUbWhfbVhtJVhlKqhtlWirbZVChCDVAApswgjEKV@qEEjWcu@zlDXMLuw9mxvmqG2gVOOoa2Zln2woW5wdmHO2elGtiZa9tVne2Nrnc72QuSyQZKFsbUOjKNggAHT//8A "Runic Enchantments – Try It Online")
*Alert: The `€` is incorrectly displayed, it should be `` (0x80).*
Rather than the stack, use a string and the stack operators modified with `͍` to modify a string rather than the stack (see prior revision). As such, each char is limited to 1 byte (0-127 range, minus the problematic characters), but with over 3 times as many of them (due to there being less processing boilerplate due to not having to skip Unicode combining characters, as well as some other byte savings) it achieves a higher number of iterations.
If encoding as a true big endian is allowed (that is, having byte values above 127 without interjecting `0x00` bytes) this can achieve 251387-1 ≈ 4.717 × 10928 iterations. However, TIO's Latin encoding prevents this as noted by Erik the Outgolfer in his Python 2 answer. I would need to check if it works locally before claiming this score.
Should be able to replace `f1+0B` with `'0B` (there's an unprinting `0x16` there), but it was fighting me (things didn't want to branch/skip/return correctly), so I left it alone. This would raise the big-endian structure from 387 to 388.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), flags: `/u:System.Numerics.BigInteger` and `/r:System.Numerics`
# Score: 10332
Thanks to JoKing who increased my score from 10255 \* 2 - 1 to now!
```
var i=Parse("0");var s="var i=Parse({0}{2}{0});var s={0}{1}{0};Write(s,(char)34,s,(++i).ToString().Length<333?i:0);";Write(s,(char)34,s,(++i).ToString().Length<333?i:0);
```
[Try it online!](https://tio.run/##ncsxC8IwEAXgvyKZElpjNU6tRXATRIQKziUc6Q1N5S4VpPSvG9tBEEeXx@N7PMtLyxjjo6YFlpeaGKTIhCpm4FJ8@5CNw2ac8rPOsJ6huBEGkJxK29SkzDadapKg0teuCoTeSaVP4F1odsaYPeaZKsRfrxhf3T1g5zmuKK@eHKDV574FQjtR/0v6gO7oAzigNw "C# (Visual C# Interactive Compiler) – Try It Online")
# Explanation
Increments a BigInteger every iteration, until it's length becomes too large, which in that case we instantly revert back to the original quine.
```
//The BigInteger that will be incremented
var i=Parse("0");
//The string that encodes the quine
var s="var i=Parse({0}{2}{0});var s={0}{1}{0};Write(s,(char)34,s,(++i).ToString().Length<333?i:0);";
//Print out the string, with every {0} replaced with quotes and the {1} replaced with the original string
Write(s,(char)34,s,
//And the {2} is replaced to the BigInteger+1 if the BigInteger wouldn't be too long, else 0
(++i).ToString().Length<333?i:0);
```
[Answer]
# DOS COM, 49 bytes, period 2^3608
```
00000000 be 31 01 89 f7 b9 f4 02 f9 ac 14 00 aa 39 ce 72 |.1...........9.r|
00000010 f8 31 c9 b4 3c ba 2b 01 cd 21 89 c3 b4 40 b9 f4 |.1..<.+..!...@..|
00000020 01 ba 00 01 cd 21 b4 3e cd 21 c3 71 2e 63 6f 6d |.....!.>.!.q.com|
00000030 00 |.|
```
Original assembly to create:
```
BITS 16
ORG 0100h
mov si, l
mov di, si
mov cx, 500 + 0100h
stc
n: lodsb
adc al, 0
stosb
cmp si, cx
jb n
xor cx, cx
mov ah, 3ch
mov dx, f
int 21h
mov bx, ax
mov ah, 40h
mov cx, 500
mov dx, 0100h
int 21h
mov ah, 3eh
int 21h
ret
f: db "q.com", 0
l: db 0
```
This little jewel writes the next phase to q.com rather than standard output because of nulls and other stuff the terminal cannot handle. The root quine technique is [equivalent to stringification](https://codegolf.stackexchange.com/a/115635/14306) and the payload room is used as a 3608 bit counter. Due to the way DOS works, the initial state of the counter contains debris from whatever was in memory prior to its first execution.
The original 49 byte input is unreachable, so if you want to score this as 500 bytes go ahead.
[Answer]
# [Python 2](https://docs.python.org/2/), 500 bytes, \$252^{219}\$
```
#coding=L1
s=""""""
for i in range(220-len(s.lstrip("ÿ")))[:219]:s=s[:i]+chr(ord(s[i])%255-~(s[i]in"!$&"))+s[i+1:]
S='#coding=L1\ns="""%s"""\nfor i in range(220-len(s.lstrip("\xff")))[:219]:s=s[:i]+chr(ord(s[i])%%%%255-~(s[i]in"!$&"))+s[i+1:]\nS=%%r;print S%%%%s%%%%S';print S%s%S
```
Note that there is a trailing newline. It might get removed above if the syntax highlighter forces its way in.
Unfortunately, you can't execute this program in TIO, as it's encoded in Latin-1.
Above, `s` contains 219 0x01 bytes. After the program runs, its source is printed, except for one difference: `s` has been incremented like a base-252 big-endian number, so its leftmost character has been "incremented" to 0x02. The bytes 0x00, 0x22, 0x25 and 0x5C are avoided, so, if any character of the string becomes one of those after the incrementation, the character itself is incremented again.
* 0x00 (null): A Python source file can't contain null characters.
* 0x22 (`"`): There's a danger of three 0x22 bytes forming in a row, that is, `"""`, or the last character of the string becoming `"`, so the string would be closed prematurely.
* 0x25 (`%`): printf-like string formatting is used before completion of the quine skeleton, so a `%` not adjacent to another `%` in `s` will cause trouble. Unfortunately, it's not possible to reorder the formatting to avoid this caveat.
* 0x5C (`\`): There's a possibility that the `\` is used as an escape mark in the string, instead of verbatim, so it's avoided.
Therefore, 252 out of 256 bytes are usable. If `s` contains 219 0xFF (`ÿ`) bytes, it's simply reverted to 219 0x01 bytes, hence completing the cycle.
Given the above, we have \$252^{219}\$ possible strings, hence as many programs overall.
\$252^{219}=8067118401622543607173815381864126969021321378412714150085501148172\\081568355283332551767558738710128769977220628694979838777041634307806013053\\042518663967641130129748108465109552157004184441957823830340121790768004370\\530578658229253323149648902557120331892465175873053680188287802536817909195\\292338112618632542000472094347226540339409672851252596442228662174845397731\\175044304251123874046626291460659909127172435776359148724655575878680270692\\451120531744950544969860952702932354413767504109600742385916705785109741289\\800204288\$
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), \$251^{226} \approx 2.1 \times 10^{542}\$
* ~~25139~~ removed dependency on `Text`
* ~~251122~~ golfed incrementing function
* ~~251128~~ combined prefix and suffix source strings
* ~~251188~~ removed dependency on `Gast.GenLibTest`
Presented in xxd format due to nonprintables / invalid UTF-8:
```
00000000: 6d6f 6475 6c65 2071 3b69 6d70 6f72 7420 module q;import
00000010: 5374 6445 6e76 3b53 7461 7274 3d28 7325 StdEnv;Start=(s%
00000020: 2830 2c34 3129 2c3f 5b27 0101 0101 0101 (0,41),?['......
00000030: 0101 0101 0101 0101 0101 0101 0101 0101 ................
00000040: 0101 0101 0101 0101 0101 0101 0101 0101 ................
00000050: 0101 0101 0101 0101 0101 0101 0101 0101 ................
00000060: 0101 0101 0101 0101 0101 0101 0101 0101 ................
00000070: 0101 0101 0101 0101 0101 0101 0101 0101 ................
00000080: 0101 0101 0101 0101 0101 0101 0101 0101 ................
00000090: 0101 0101 0101 0101 0101 0101 0101 0101 ................
000000a0: 0101 0101 0101 0101 0101 0101 0101 0101 ................
000000b0: 0101 0101 0101 0101 0101 0101 0101 0101 ................
000000c0: 0101 0101 0101 0101 0101 0101 0101 0101 ................
000000d0: 0101 0101 0101 0101 0101 0101 0101 0101 ................
000000e0: 0101 0101 0101 0101 0101 0101 0101 0101 ................
000000f0: 0101 0101 0101 0101 0101 0101 0101 0101 ................
00000100: 0101 0101 0101 0101 0101 0101 275d 2c73 ............'],s
00000110: 2528 3432 2c39 3939 292c 712c 732c 7129 %(42,999),q,s,q)
00000120: 3b71 3d69 6e63 2721 273b 3f5b 683a 745d ;q=inc'!';?[h:t]
00000130: 2363 3d68 2b69 6628 616e 7928 283d 3d29 #c=h+if(any((==)
00000140: 6829 5b27 ff09 0c26 5b27 5d29 2702 2727 h)['...&['])'.''
00000150: 0127 3d5b 633a 6966 2863 3e68 2969 643f .'=[c:if(c>h)id?
00000160: 745d 3b3f 653d 653b 733d 226d 6f64 756c t];?e=e;s="modul
00000170: 6520 713b 696d 706f 7274 2053 7464 456e e q;import StdEn
00000180: 763b 5374 6172 743d 2873 2528 302c 3431 v;Start=(s%(0,41
00000190: 292c 3f5b 2727 5d2c 7325 2834 322c 3939 ),?[''],s%(42,99
000001a0: 3929 2c71 2c73 2c71 293b 713d 696e 6327 9),q,s,q);q=inc'
000001b0: 2127 3b3f 5b68 3a74 5d23 633d 682b 6966 !';?[h:t]#c=h+if
000001c0: 2861 6e79 2828 3d3d 2968 295b 27ff 090c (any((==)h)['...
000001d0: 265b 275d 2927 0227 2701 273d 5b63 3a69 &['])'.''.'=[c:i
000001e0: 6628 633e 6829 6964 3f74 5d3b 3f65 3d65 f(c>h)id?t];?e=e
000001f0: 3b73 3d22 ;s="
```
[Try it online!](https://tio.run/##tZZdb9MwFIbv@ysOIEgLbZccJ3a9KkwIJkDiS@JymlA@1Yh@0CVDgz8/3uN4ZUxCuyDkwnJl@/Gxz@v3NM/a1fX11VVJswt6TvtwVF1921109PLd6YsPX958fH@aHu2@dUfFusq2o/WWZjVm0X7eFOvR75GjvNmit6HZ23f06sc22zRF6358WmddvbvoR15nbUeznGYbDG472o/mR9l8d9nJ3tENPvoveL7B83/Bq1Fbf6V1I1Pa5mdF@6fX16H/jkmXuiYdm4R0oRPi0ESkcm0xYELStWEyMYdEm115ucbqZbNxiRj1hAiMRJkYjBiMymgsTxQW6YgMY0CVvCCjOCH63JWn2@/Lz1120aXj9rFnMBi8UCFxoTA/Yiu9mpKcDWGH6FZD43AaR5PpyVkwd59nKDDuTP1rQ/M7n2fEAzCSARh6AIYZgLEYgGEHYGQDMPIBGMUAjHIARjUAo/53RhTey2CTlHjLRv3JCM6nrWeIf3ACh1CxYnn2lpRFw5YLMpE0qu9ZosfjmKfW2sl0P22n@4lniH@oXIyrFOOqtMLGLLurnFSd5KQXKoMlIRha7tNmWwQPguXJ2eq4O/cM8Q9WWAnGgtg5oEZYOtIVGYseHKoUM0Mcj4p09aypx9n2x3icpjdxiH/oBSY446rr0FJYsO5/JrKSTcgSmyFaTZyDPTkLzifBPAg8o/cPTFClxK0Qt7ZaY3eJrZLYrMQWwx9pHqRnxTECKZ6vJk154hniH@6wKscsnSBuNDluEj1mjZ@1jskkuiDqzpcnVVot2/Shs3jPEP/QCYzfRFiJEEoyIUqFs3QOe4ePKU5wPXSrLDiL9wzxD6OxvC8QkaslEsICguiTHiK3yDw0dqssOIv3DPEPpwWXR3d1uMmiLyhICeoFy6hohlxZEHF5oXiG@IeyrqpAJE6Ofc/KpURyPRbH0ErychCXF4pniH@wy0vuKhMSoTKcCsEoSVMpmc/7XNFBXF4onlG4Ooe6iDKJYBZyAaXch3Vpdeera4JnIi8HcXmheIb4B2s3VZ6WlQrJaKAsJ/hSYoNSMoiEDuLyQvEM8Y9e3EpVvWIRN26ydgdyjwb/BfASULMP4vJC8Yy6f3PyXpjpnk/E9Qs "Bash – Try It Online")
Increments a 226-byte string through all byte values excluding `\0`, `\n`, `\r`, `'` and `\`.
The reason we avoid these characters is:
* `\0` makes the compiler angry
* `\n` and `\r` can't appear in charlists
* `'` would end the charlist
* `\` could cause problems if it comes before an escapable character
Once the string is all `\377`s it wraps around to all `\001`s, giving the original program.
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes, 16444 ≈ 4.258 \$\times\$ 10534 iterations
-1 byte and \$\times\$16 iterations thanks to [@AndersKaseorg](https://codegolf.stackexchange.com/questions/179752/write-the-longest-period-iterating-quine-bounded-by-500-bytes/198561#comment472128_198561)
```
b=0x0;s="print'b=%#x;s=%r;exec s'%(-~b%4**888,s)";exec s
```
Increments a hexadecimal counter on each iteration and when it reaches \$16^{444}\$ it resets to \$0\$
[Try it online!](https://tio.run/##K6gsycjPM/r/P8nWoMLAuthWqaAoM69EPclWVbkCyFUtsk6tSE1WKFZX1dCtS1I10dKysLDQKdZUgopz/f8PAA "Python 2 – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 70 bytes, 39039000 iterations
```
":1=l8:*6+=S&Q~:'~'=Q~~'H#'||lPaa*5*=?1:1=Q$~$~|:1)lPaa*5*(Q?:|r2ssH##
```
Wow, that is a lot lower than I thought it would be... Next step! Making it have more iterations!!!
[Try it online!](https://tio.run/##S8/PScsszvj/X8nK0DbHwkrLTNs2WC2wzkq9Tt02sK5O3UNZvaYmJyAxUctUy9beEKgqUKVOpa7GylATKqoRaG9VU2RUXOyhrPz/PwA "Gol><> – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 500 bytes, 221290 ≈ 7.477 \$\times\$ 10679
```
#coding=L1
c=r"##################################################################################################################################################################################################################################################################################################|";exec(s:='from itertools import*;print("#coding=L1\\nc=r\\"%s|\\";exec(s:=%r)"%([*filter(c[:-1].__lt__,map("".join,combinations_with_replacement(map(chr,range(35,256)),290))),"#"*290][0],s))')
```
[Try it online!](https://tio.run/##7VBLasMwFNznFOEZE8koIR9S8sE36A1sI1xFiV@x9MSTIAnk7q66aZe9QGcxM4thBiY800B@dwg8TYWhC/pb/b6ZmZqh@McfeMHZPqwR8VQvrkxujslyIhrjHF0gTtU5MPok4PfatvX53LaFMr4y/xSULKEUTXXFMZcI05yWm26l9Zi0Vq4PAmD1SeiVIfeBvk9IPuo7pkGzDWNvrLN56TtpBlbc@5sVu73a7t@kVNvjWmaBAqpsu2bdqSjlQs6m6Qs "Python 3.8 (pre-release) – Try It Online")
[Try a smaller version online!](https://tio.run/##RY1BbsIwEEX3nAKNFWFHLipEVAiUG/QGSWSlxpCpYo81tkQrcffU3cDmrf57P/7miUJzjLwswtIFw6393K1syyCEeMDZ/Tgr06ndXJn8GrPjTDSnNfpInOtzZAxZwsvt@1DsvocqPQqfgYoVVLKrrziXiLTd6W03bI2ZszHaj1ECbL8Jg7bkvzCMGSkkc8c8GXZxHq3zrjz9L@3Emsdwc7I56P3hQyndqAIQUDdD9z7opNRGrZblDw "Python 3.8 (pre-release) – Try It Online")
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 500 bytes, 93314 ≈ 1.269 \$\times\$ 10618
```
c=r"##########################################################################################################################################################################################################################################################################################################################|";exec(s:='from itertools import*;print("c=r\\"%s|\\";exec(s:=%r)"%([*filter(c[:-1].__lt__,map("".join,combinations_with_replacement(map(chr,range(35,128)),314))),"#"*314][0],s))')
```
Ascii version
[Try it online!](https://tio.run/##7VDNCsIwGLv7FOMbw3ZUcU5hbOxJtlFmqa6y/vC1oMLefdaLD@DZHJIckhziXmGypqwcrqtoEdI/fsQCjXxKQXzdbq9odaKCxGDt7BOlncWQNw6VCQTiz30PmV8ifzsZUshIl1/VHHtEdPWuGPacz4FzpkdHAPZ3qwwTVl@UGYOyxvOHChNH6eZRSC3j@CcpJmQ4mpsk5ZkVx4pSVhYnGgVSyKMdusPAPKVbulnXNw "Python 3.8 (pre-release) – Try It Online")
[Try a smaller version online!](https://tio.run/##PcxLCoMwFIXheVchV8REUqmVgiiuRCXYEGuKeXATaAvu3aaTTv7R@Y77hNWaunF4HKJHSNN0h06@pSC@7fMFrU5UkBis3XyitLMYis6hMoFABOMImd9j/yZDChkZikVt0RExtOdqKjnfAudMz44AlE@rDBNW35WZg7LG85cKK0fptllILeP5bylWZDibhyT1jVXXhlJW0xhIoain4TIxT2lOT8fxBQ "Python 3.8 (pre-release) – Try It Online")
# Explanation
The value assigned to `c` iterates through all possible strings of length 290 (314 in the ascii version) formed from the characters in the range `\x23` to `\xff` (`\x23` to `\x7f` in the ascii version)
Since the string assigned to `c` is prefixed with a `r` backslashes in the string are not treated as the beginning of escape sequences, this allows the use of backslashes inside the string assigned to `c` without causing problems.
Since a string like `r'\'` still cause problems a `|` is added to the end of the string assigned to `c`.
] |
[Question]
[
# Challenge
You are given two distinct bit strings of the same length. (For example, `000` and `111`.) Your goal is to find a path from one to the other such that:
* At each step, you change only one bit (you can go from `000` to any of `001`, `010`, `100`).
* You cannot visit the same bit string twice.
* The path is as long as possible, under these constraints.
For example, going from `000` to `111`, we can take the path
```
000, 001, 011, 010, 110, 100, 101, 111
```
which visits all 8 bit strings of length 3, so it has to be the longest possible.
# Rules
* Standard loopholes apply.
* You may take the input as two strings of zeroes and ones, or as two arrays of zeroes and ones, or as two arrays of boolean values.
* You may **not** take the input as two integers with the right binary representation (writing `000` and `111` as `0` and `7` is not valid).
* If you want, you may take the length of the bit strings as input.
* Your program is allowed to output the path by printing the bit strings visited one at a time, or by returning an array of the bit strings visited (each in the same format as the input).
* Your output should include the start and end of the path (which are your inputs).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins.
# Examples
```
0 1 -> 0, 1
10 01 -> 10, 00, 01 or 10, 11, 01
000 111 -> any of the following:
000, 100, 110, 010, 011, 001, 101, 111
000, 100, 101, 001, 011, 010, 110, 111
000, 010, 110, 100, 101, 001, 011, 111
000, 010, 011, 001, 101, 100, 110, 111
000, 001, 101, 100, 110, 010, 011, 111
000, 001, 011, 010, 110, 100, 101, 111
1001 1100 -> 1001, 0001, 0000, 0010, 0011, 0111, 0101, 0100, 0110, 1110, 1010, 1011, 1111, 1101, 1100 (other paths exist)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~27 26~~ 24 bytes
```
→foΛεẊδṁ≠ÖLm↓≠⁰←ġ→PΠmṠe¬
```
Brute force, so very slow.
[Try it online!](https://tio.run/##yygtzv7//1HbpLT8c7PPbX24q@vcloc7Gx91Ljg8zSf3UdtkIOtR44ZHbROOLASqCji3IPfhzgWph9b8//8/2lDHQMcgFkQDWbEA "Husk – Try It Online")
## Explanation
Husk reads naturally from right to left.
```
←ġ→PΠmṠe¬ Hypercube sequences ending in second input, say y=[1,1,0]
mṠe¬ Pair each element with its negation: [[0,1],[0,1],[1,0]]
Π Cartesian product: [[0,0,1],[1,0,1],..,[1,1,0]]
P Permutations.
ġ→ Group by last element
← and take first group.
The permutations are ordered so that those with last element y come first,
so they are grouped together and returned here.
ÖLm↓≠⁰ Find first input.
m For each permutation,
↓≠⁰ drop all elements before the first input.
ÖL Sort by length.
foΛεẊδṁ≠ Check path condition.
fo Keep those lists that satisfy:
Ẋ For each adjacent pair (e.g. [0,1,0] and [1,1,0]),
ṁ take sum of
≠ absolute differences
δ of corresponding elements: 1+0+0 gives 1.
Λε Each value is at most 1.
→ Finally, return last element (which has greatest length).
```
[Answer]
# Mathematica, 108 bytes
```
a=#~FromDigits~2+1&;Last@PadLeft[IntegerDigits[#-1,2]&/@FindPath[HypercubeGraph@Length@#,a@#,a@#2,∞,All]]&
```
Input:
```
[{0, 0, 0, 0}, {1, 1, 1, 1}]
```
Output:
```
{{0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 1}, {0, 0, 1, 0}, {0, 1, 1, 0},
{0, 1, 0, 0}, {0, 1, 0, 1}, {1, 1, 0, 1}, {1, 0, 0, 1}, {1, 0, 0, 0},
{1, 1, 0, 0}, {1, 1, 1, 0}, {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 1, 1}}
```
[Answer]
# Mathematica, 175 bytes
Nice first question!
```
(m=#;n=#2;Last@SortBy[(S=Select)[S[Rest@Flatten[Permutations/@Subsets[Tuples[{0,1},(L=Length)@m]],1],First@#==m&&Last@#==n&],Union[EditDistance@@@Partition[#,2,1]]=={1}&],L])&
```
**Input**
>
> [{0, 0, 0}, {1, 1, 1}]
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), ~~212~~ 207 bytes
This is probably way too long, but it finally works now. (Thanks to @Lynn for the [cartesian product trick](https://codegolf.stackexchange.com/a/52945/24877)!) Thansk @nimi for -5 bytes!
```
import Data.List
b%l=[l++[x|b/=last l,x`notElem`l,1==sum[1|(u,v)<-x`zip`last l,u/=v]]|x<-mapM id$[0>1..]<$b]
b!a|f<-nub.concat.((b%)<$>)=snd$maximum$map(length>>=(,))$filter((==b).last)$until(f>>=(==))f[[a]]
```
[Try it online!](https://tio.run/##dZBBb4QgEIXv/oppwkbIqrvexVPb0/bU3gyJsIuVFNAIbG3jf7eYbrOnHpiX8M2bx9Bz9yG1XldlxmHy8Mg9L07K@UTsNG30ft/MizhQzZ0Hnc2tHfyTlqbVWUmpC6YpFxyyK6nyuf1WY3trDAd6ZWyZq9zw8QXUBTXHuiwKViHBEvHAl67KbRDFebBn7guMxY5UqCbU2QsyfFYmmKgj1tK@@76uKc4IQZ3SXk4YUypIsWURFKxXGndbB6WEdE3DGVs5UGjepiAzeOba/UnMvoN7Zck4Se@/YI5UdVF8Ly2kZQoyuiA9ponhykY6Bv/qp5MFBK4fPqNsr4wHfkeQeBP3S/Ic/nVEDpHHvwQ33HzrDw "Haskell – Try It Online")
Explanation:
```
b%l -- helper function:
-- given a path l (that should end in b) this generates all possible extensions
-- of l (if not possible also l itself)
x<-mapM id$[0>1..]<$b -- generate all possible vertices of the hypercube
-- and check the criteria
b/=last l,x`notElem`l,1==sum[1|(u,v)<-x`zip`last l,u/=v]
-- extend if possible
[l++[x| ... ]| ... ]
b!a| -- actual function:
-- first define a helper function:
f<-nub.concat.((b%)<$>)
-- begin with the vertex a and apply the function from above repeatedly
-- until you cannot make the path any longer without violating the
-- criteria
until(f>>=(==))f[[a]]
-- only take the paths that actually end in b
filter((==b).last)$
-- and find the one with the maximum length
=snd$maximum$map(length>>=(,))$
```
[Answer]
# Mathematica ~~116~~ 114 bytes
With several bytes saved thanks to Misha Lavrov.
```
Last@FindPath[Graph[Rule@@@Cases[Tuples[Tuples[{0,1},{l=Length@#}],{2}],x_/;Count[Plus@@x,1]==1]],##,{1,2^l},Alll]&
```
Input (8 dimensions)
```
[{1,0,0,1,0,0,0,1},{1,1,0,0,0,0,1,1}]//AbsoluteTiming
```
Output (length = 254, after 1.82 seconds)
```
{1.82393, {{1, 0, 0, 1, 0, 0, 0, 1}, {0, 0, 0, 1, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 0}, {0, 0,0, 0, 0, 0, 1, 1}, {0, 0, 0, 0, 0, 1, 1, 1}, {0, 0, 0, 0, 0, 1, 0, 1}, {0, 0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 1, 1, 0}, {0, 0, 0, 0,1, 1, 1,0}, {0, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 1}, {0, 0, 0, 0, 1, 0, 1, 1}, {0, 0, 0, 0,1, 1, 1, 1}, {0, 0, 0, 0, 1, 1, 0, 1}, {0, 0, 0, 0, 1, 1, 0, 0}, {0, 0, 0, 1, 1, 1, 0, 0}, {0, 0, 0, 1, 0, 1, 0, 0}, {0, 0, 0, 1,0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 1, 1}, {0, 0, 0, 1, 0, 1, 1, 1}, {0, 0, 0, 1, 0, 1, 0, 1}, {0, 0, 0, 1, 1, 1, 0, 1}, {0, 0, 0, 1, 1, 0, 0, 1}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 1, 0}, {0, 0, 0, 1, 1, 0, 1, 1}, {0, 0, 0, 1,1, 1, 1, 1}, {0, 0, 0, 1, 1, 1, 1, 0}, {0, 0, 0, 1, 0, 1, 1, 0}, {0, 0, 1, 1, 0, 1, 1, 0}, {0, 0, 1, 0, 0, 1, 1, 0}, {0, 0, 1, 0,0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 1, 1}, {0, 0, 1, 0, 0, 1, 1, 1}, {0, 0, 1, 0,0, 1, 0, 1}, {0, 0, 1, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 1, 1, 0, 0}, {0, 0, 1, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 1, 0, 0, 1}, {0, 0, 1, 0,1, 0, 1, 1}, {0, 0, 1, 0, 1, 0, 1, 0}, {0, 0, 1, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 1, 1, 1, 1}, {0, 0, 1, 0, 1, 1, 0, 1}, {0, 0, 1, 1,1, 1, 0, 1}, {0, 0, 1, 1, 0, 1, 0, 1}, {0, 0, 1, 1, 0, 0, 0, 1}, {0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 1, 1, 0, 0, 1, 0}, {0, 0, 1, 1,0, 0, 1, 1}, {0, 0, 1, 1, 0, 1, 1,1}, {0, 0, 1, 1, 1, 1, 1, 1}, {0, 0, 1, 1, 1, 0, 1, 1}, {0, 0, 1, 1, 1, 0, 0, 1}, {0, 0, 1, 1,1, 0, 0, 0}, {0, 0, 1, 1, 1, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 0, 1, 0, 0}, {0, 1, 1, 1,0, 1, 0, 0}, {0, 1, 0, 1, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 1}, {0, 1, 0, 0,0, 0, 1, 1}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 1, 0, 0, 0, 1, 1, 0}, {0, 1, 0, 0, 0, 1, 1, 1}, {0, 1, 0, 0, 0, 1, 0, 1}, {0, 1, 0, 0,1, 1, 0, 1}, {0, 1, 0, 0, 1, 0, 0, 1}, {0, 1, 0, 0, 1, 0, 0, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 1}, {0, 1, 0, 0,1, 1, 1, 1}, {0, 1, 0, 0, 1, 1, 1, 0}, {0, 1, 0, 0, 1, 1, 0,0}, {0, 1, 0, 1, 1, 1, 0, 0}, {0, 1, 0, 1, 1, 0, 0, 0}, {0, 1, 0, 1,0, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 0, 1}, {0, 1, 0, 1, 0, 0, 1, 1}, {0, 1, 0, 1, 0, 0, 1, 0}, {0, 1, 0, 1, 0, 1, 1, 0}, {0, 1, 0, 1,0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1}, {0, 1, 0, 1, 1, 1, 0, 1}, {0, 1, 0, 1, 1, 0, 0, 1}, {0, 1, 0, 1, 1, 0, 1, 1}, {0, 1, 0, 1,1, 0, 1, 0}, {0, 1, 0, 1, 1, 1, 1, 0}, {0, 1, 0, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 1}, {0, 1, 1, 0,0, 1, 1, 1}, {0, 1, 1, 0, 0, 0, 1, 1}, {0, 1, 1, 0, 0, 0, 0, 1}, {0, 1, 1, 0, 0, 0, 0, 0}, {0, 1, 1, 0, 0, 0, 1, 0}, {0, 1, 1, 0,0, 1, 1, 0}, {0, 1, 1, 0, 0, 1, 0, 0}, {0, 1, 1, 0, 0, 1, 0, 1}, {0, 1, 1, 0, 1, 1, 0, 1}, {0, 1, 1, 0, 1, 0, 0, 1}, {0, 1, 1, 0,1, 0, 0, 0}, {0, 1, 1, 0, 1, 0, 1, 0}, {0, 1, 1, 0, 1, 0, 1, 1}, {0, 1, 1, 1, 1, 0, 1, 1}, {0, 1, 1, 1, 0, 0, 1, 1}, {0, 1, 1, 1,0, 0, 0, 1}, {0, 1, 1, 1, 0, 0, 0, 0}, {0, 1, 1, 1, 0, 0, 1, 0}, {0, 1, 1, 1, 0, 1, 1, 0}, {0, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 1, 1,0, 1, 0, 1}, {0, 1, 1, 1, 1, 1, 0, 1}, {0, 1, 1, 1, 1, 0, 0, 1}, {0, 1, 1, 1, 1, 0, 0, 0}, {0, 1, 1, 1, 1, 0, 1, 0}, {0, 1, 1, 1,1, 1, 1, 0}, {0, 1, 1, 0, 1, 1, 1, 0}, {0, 1, 1, 0, 1, 1, 0, 0}, {0, 1, 1, 1, 1, 1, 0, 0}, {1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 1, 1,1, 1, 0, 0}, {1, 0, 0, 1, 1, 1, 0, 0}, {1, 0, 0, 0, 1, 1, 0, 0}, {1, 0, 0, 0, 0, 1, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0,0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 1, 1}, {1, 0, 0, 0, 0, 0, 1, 0}, {1, 0, 0, 0, 0, 1, 1, 0}, {1, 0, 0, 0, 0, 1, 1, 1}, {1, 0, 0, 0,0, 1, 0, 1}, {1, 0, 0, 0, 1, 1, 0, 1}, {1, 0, 0, 0, 1, 0, 0, 1}, {1, 0, 0, 0, 1, 0, 0, 0}, {1, 0, 0, 0, 1, 0, 1, 0}, {1, 0, 0, 0,1, 0, 1, 1}, {1, 0, 0, 0, 1, 1, 1, 1}, {1, 0, 0, 0, 1, 1, 1, 0}, {1, 0, 0, 1, 1, 1, 1, 0}, {1, 0, 0, 1, 0, 1, 1, 0}, {1, 0, 0, 1,0, 0, 1, 0}, {1, 0, 0, 1, 0, 0, 0, 0}, {1, 0, 0, 1, 0, 1, 0, 0}, {1, 0, 0, 1, 0, 1, 0, 1}, {1, 0, 0, 1, 0, 1, 1, 1}, {1, 0, 0, 1,0, 0, 1, 1}, {1, 0, 0, 1, 1, 0, 1, 1}, {1, 0, 0, 1, 1, 0, 0, 1}, {1, 0, 0, 1, 1, 0, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 0}, {1, 0, 1, 1,1, 0, 1, 0}, {1, 0, 1, 0, 1, 0, 1, 0}, {1, 0, 1, 0, 0, 0, 1, 0}, {1, 0, 1, 0, 0, 0, 0, 0}, {1, 0, 1, 0, 0, 0, 0, 1}, {1, 0, 1, 0,0, 0, 1, 1}, {1, 0, 1, 0, 0, 1, 1, 1}, {1, 0, 1, 0, 0, 1, 0, 1}, {1, 0, 1, 0, 0, 1, 0, 0}, {1, 0, 1, 0, 0, 1, 1, 0}, {1, 0, 1, 0,1, 1, 1, 0}, {1, 0, 1, 0, 1, 1, 0, 0}, {1, 0, 1, 0, 1, 0, 0, 0}, {1, 0, 1, 0, 1, 0, 0, 1}, {1, 0, 1, 0, 1, 0, 1, 1}, {1, 0, 1, 0,1, 1, 1, 1}, {1, 0, 1, 0, 1, 1, 0, 1}, {1, 0, 1, 1, 1, 1, 0, 1}, {1, 0, 0, 1, 1, 1, 0, 1}, {1, 0, 0, 1, 1, 1, 1, 1}, {1, 0, 1, 1,1, 1, 1, 1}, {1, 0, 1, 1, 0, 1, 1, 1}, {1, 0, 1, 1, 0, 0, 1, 1}, {1, 0, 1, 1, 0, 0, 0, 1}, {1, 0, 1, 1, 0, 0, 0, 0}, {1, 0, 1, 1,0, 0, 1, 0}, {1, 0, 1, 1, 0, 1, 1, 0}, {1, 0, 1, 1, 0, 1, 0, 0}, {1, 0, 1, 1, 0, 1, 0, 1}, {1, 1, 1, 1, 0, 1, 0, 1}, {1, 1, 0, 1,0, 1, 0, 1}, {1, 1, 0, 0, 0, 1, 0,1}, {1, 1, 0, 0, 0, 0, 0, 1}, {1, 1, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 1, 0}, {1, 1, 0, 0,0, 1, 1, 0}, {1, 1, 0, 0, 0, 1, 0, 0}, {1, 1, 0, 0, 1, 1, 0, 0}, {1, 1, 0, 0, 1, 0, 0, 0}, {1, 1, 0, 0, 1, 0, 0, 1}, {1, 1, 0, 0,1, 0, 1, 1}, {1, 1, 0, 0, 1, 0, 1, 0}, {1, 1, 0, 0, 1, 1, 1, 0}, {1, 1, 0, 0, 1, 1, 1, 1}, {1, 1, 0, 0, 0, 1, 1, 1}, {1, 1, 0, 1,0, 1, 1, 1}, {1, 1, 0, 1, 0, 0, 1, 1}, {1, 1, 0, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 0, 0, 0, 0}, {1, 1, 0, 1, 0, 0, 1, 0}, {1, 1, 0, 1,0, 1, 1, 0}, {1, 1, 0, 1, 0, 1, 0, 0}, {1, 1, 0, 1, 1, 1, 0, 0}, {1, 1, 0, 1, 1, 0, 0, 0}, {1, 1, 0, 1, 1, 0, 0, 1}, {1, 1, 0, 1,1, 0, 1, 1}, {1, 1, 0, 1, 1, 0, 1, 0}, {1, 1, 0, 1, 1, 1, 1, 0}, {1, 1, 0, 1, 1, 1, 1, 1}, {1, 1, 0, 1, 1, 1, 0, 1}, {1, 1, 0, 0,1, 1, 0, 1}, {1, 1, 1, 0, 1, 1, 0, 1}, {1, 1, 1, 0, 0, 1, 0, 1}, {1, 1, 1, 0, 0, 0, 0, 1}, {1, 1, 1, 0, 0, 0, 0, 0}, {1, 1, 1, 0,0, 0, 1, 0}, {1, 1, 1, 0, 0, 1, 1, 0}, {1, 1, 1, 0, 0, 1, 0, 0}, {1, 1, 1, 0, 1, 1, 0, 0}, {1, 1, 1, 0, 1, 0, 0, 0}, {1, 1, 1, 0,1, 0, 0, 1}, {1, 1, 1, 0, 1, 0, 1, 1}, {1, 1, 1, 0, 1, 0, 1, 0}, {1, 1, 1, 0, 1, 1, 1, 0}, {1, 1, 1, 0, 1, 1, 1, 1}, {1, 1, 1, 0,0, 1, 1, 1}, {1, 1, 1, 1, 0, 1, 1, 1}, {1, 1, 1, 1, 0, 1, 1, 0}, {1, 1, 1, 1, 0, 0, 1, 0}, {1, 1, 1, 1, 0, 0, 0, 0}, {1, 1, 1, 1,0, 0, 0, 1}, {1, 1, 1, 1, 1, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 0}, {1, 1, 1, 1,1, 0, 1, 0}, {1, 1, 1, 1, 1, 0, 0, 0}, {1, 0, 1, 1, 1, 0, 0, 0}, {1, 0, 1, 1, 1, 0, 0, 1}, {1, 0, 1, 1, 1, 0, 1, 1}, {1, 1, 1, 1,1, 0, 1, 1}, {1, 1, 1, 1, 0, 0, 1, 1}, {1, 1, 1, 0, 0, 0, 1, 1}, {1, 1, 0, 0, 0, 0, 1, 1}}}
```
---
`Tuples[{0,1},{l=Length@#}],{2}]`& generates the numbers 0...8 as binary lists.
The outer `Tuples...{2}` produces all ordered pairs of those binary numbers.
`Plus@@x` sums each of the pairs, generating triplets of 0, 1.
`Cases....Count[Plus@@x, 1]==1` returns all of the sums that contain a single 1. These arise when the two original binary numbers are connected by an edge.
`Rules` connects the vertices of the graph, each vertex being a binary number.
`Graph` creates a graph corresponding to said vertices and edges.
`FindPath` finds up to 2^n paths connecting vertex a to vertex b, the given numbers.
`Last` takes the longest of these paths.
---
For three dimensions, the graph can be represented in a plane as shown here:
[](https://i.stack.imgur.com/wEVza.png)
For the input, `{0,0,0}, {1,1,1}`, the following is output:
`{{{0, 0, 0}, {0, 0, 1}, {0, 1, 1}, {0, 1, 0}, {1, 1, 0}, {1, 0,
0}, {1, 0, 1}, {1, 1, 1}}}`
This path can be found in the above graph.
It can also be conceived as the following path in 3-space,
where each vertex corresponds to a point `{x,y,z}`. {0,0,0} represents the origin and {1,1,1} represents the "opposite" point in a unit cube.
So the solution path corresponds to a traversal of edges along the unit cube. In this case, the path is Hamiltonian: it visits each vertex one time (i.e. with no crossings and no vertices omitted).
[](https://i.stack.imgur.com/806HS.png)
[Answer]
# [Haskell](https://www.haskell.org/), ~~141~~ 123 bytes
```
c(a:b)=(1-a:b):map(a:)(c b)
c _=[]
q#z=[z]:[z:s|w<-c z,notElem w q,s<-(w:q)#w]
x!y=snd$maximum[(p*>x,p)|p<-[x]#x,last p==y]
```
Uses lists of integers.
[Try it online!](https://tio.run/##FcjRCsIgFIDh@z3Fie1CQ6Hdyk53PYVIOBs0UnO50Mne3RbfxQ//U8fXZG2thmgxUiQ9/1c4HY5BiYGRNgbuKFWztAVlUUIWEfc0cAOF@fd6s5ODBAuLAydJLLRNqsmnDaN/dE7n2X2dJOF8zSzQPQxcZtVmZnVcISBuqjo9e0AIn9mv0IHs2UHBCeSFHVT9AQ "Haskell – Try It Online")
## Explanation
The main function is `!`, and the auxiliary functions are `#` and `c`.
Given a list of bits, `c` gives all possible ways of flipping one of them, e.g. `[0,1,1] -> [[1,1,1],[0,0,1],[0,1,0]]`.
```
c(a:b)= -- c on nonempty list with head a and tail b is
(1-a:b): -- the list with negated a tacked to b, then
map(a:)(c b) -- c applied recursively to b, with a tacked to each of the results.
c _=[] -- c on empty list gives an empty list.
```
The function `#` takes a list of lists (the "memory") and a list (the "initial bitstring").
It constructs all hypercube paths that begin with the initial element, contain only distinct bitstrings, and do not step on the strings in the memory.
```
q#z= -- # on memory q and initial string z is
[z]: -- the singleton path [z], and
[z:s| -- z tacked to each path s, where
w<-c z, -- w is obtained by flipping a bit of z,
notElem w q, -- w is not in the memory, and
s<-(w:q)#w] -- s is a path starting from w that avoids w and all elements of q.
```
The main function `!` ties it all together.
A trick I use here is `p*>x` (`x` repeated `length p` times) instead of `length p`.
Since longer repetitions of `x` come later in the natural ordering of lists, `maximum` chooses the longest path in either case, since the first coordinates of pairs are compared before the second ones.
```
x!y= -- ! on inputs x and y is
snd$maximum -- the second element of the maximal pair in
[(p*>x,p)| -- the list of pairs (p*>x,p), where
p<-[x]#x, -- p is a path starting from x that avoids stepping on x, and
last p==y] -- p ends in y.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 27 [bytes](https://github.com/DennisMitchell/jelly)
+2 bytes to fix a bug with my golfing :( hopefully I'll find a shorter way though.
```
ṫi¥³ḣi
L2ṗŒ!瀵ạ2\S€ỊẠ×LµÞṪ
```
A full program taking the bit-strings using `1` and `2`\* as lists. The arguments are `from` and `to`. The program prints a list of lists of the same.
\* `0` and `1` may be used instead at the cost of a byte (add `’` between `L2ṗ` and `Œ!ç€...` to decrement).
**[Try it online!](https://tio.run/##y0rNyan8///hztWZh5Ye2vxwx@JMLh@jhzunH52keHj5o6Y1h7Y@3LXQKCYYyHy4u@vhrgWHp/sc2np43sOdq/7//x9tqAOEsSDaCEgDAA "Jelly – Try It Online")**
### How?
**updating...**
```
ṫi¥³ḣi - Link 1, getSlice: list of lists, bitstrings; list, toBitstring
³ - get 3rd command line argument (fromBitstring)
¥ - last two links as a dyad:
i - index (of fromBitstring in bitstrings)
ṫ - tail (bitstrings) from (that) index
i - index (of toBitstring in that result)
ḣ - head to (that) index
L2ṗŒ!瀵ạ2\S€ỊẠ×LµÞṪ - Main link: list, fromBitstring; list, toBitstring
L - length (of fromBitstring)
2 - literal two
ṗ - Cartesian power (of implicit range(2)=[1,2] with L(fromBitstring))
- ...i.e. all unique bitstrings of the required length (using [1,2])
Œ! - all permutations (of that list)
ç€ - call the last link (1) as a dyad (i.e. f(that, toBitstring))
µ µÞ - sort by the monadic function:
2\ - 2-wise reduce with:
ạ - absolute difference
S€ - sum €ach
Ị - insignificant (vectorises) (abs(z)<=1 - for our purposes it's really just used for z==1 since only positive integers are possible)
Ạ - all truthy? (1 if so 0 otherwise)
L - length
× - multiply
Ṫ - tail (the last one is one of the maximal results)
- implicit print
```
] |
[Question]
[
Write a piece of JavaScript code that calls `alert` with an array containing the first 50 Fibonacci numbers in order. You may only use the following characters: `+!()[]`.
As a reference, your code must be functionally equal to the following:
```
var fib = [], a = 1, b = 1;
for (var _ = 0; _ < 50; _++) {
fib.push(a);
var t = a; a = b; b = t + a;
}
alert(fib);
```
You may not assume any content on the webpage - your program will be run in the console on `about:blank`. Similarly, you may not 'cheat' and store any settings in cookies, settings or other data. Your solution must work on any fresh install of the latest Google Chrome **or** Firefox on any OS. When in doubt, try to remain as portable as possible.
---
Smallest source code in bytes wins.
[Answer]
# 7,576 chars
# Firefox / Safari 9 (WebKit Nightly)
The main byte-saver is `fill()`
```
alert(Array(48).fill().reduce(falsefalse=>falsefalse.unshift(falsefalse[1]+falsefalse[0]),falsefalse},[1,1]).reverse())
```
Most non-alphanumeric characters (especially `;` and `>`) are very expensive so I'm really trying to minimize their use.
Script
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+(+[![]]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[+(+!![]+[+!![]])]+(!![]+[])[+!![]]+(!![]+[])[+!![]]+(![]+[])[+!![]]+(+[![]]+[+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))])[+!![]+[+[]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[!![]+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+![]+![]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+([]+[])[(![]+[])[!![]+!![]+!![]]+([][[]]+[])[+[]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]]()[+!![]+[+[]]]+![]+![]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+([][[]]+[])[+[]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+!![]]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]])()((![]+[])[+!![]]+(+[![]]))[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[+[]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+![]+![]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]]]+(+!![])+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[]))+[])[!![]+!![]]+![]+![]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]]]+(+[])+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+[[]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]]([[]])+![]+![]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+[[]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]]([[]])+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]]]+(+!![])+[[]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]]([[]])+(+!![])+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]])()
```
# Chrome (11,605)
Original:
`;` is very expensive.
```
alert(Array(48).join(0).split(0).reduce(function(falsefalse){return falsefalse.unshift(falsefalse[1]+falsefalse[0]),falsefalse},[1,1]).reverse())
```
Script: [Pastebin](http://pastebin.com/8aFYr0Wp).
[Answer]
# 15,943 bytes
I just hardcoded the values and used the [JScrewit Compiler](http://jscrew.it/).
Original Code:
```
alert([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,2971215073,4807526976,7778742049,12586269025])
```
JSFuck Code:
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((+!![]+[!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]]+![]+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+![]+![]+(+!![])+![]+![]+(+!![])+(+!![])+![]+![]+(!![]+!![])+![]+![]+(+!![])+(!![]+!![])+![]+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+![]+(+!![])+(+!![])+![]+(+!![])+![]+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+(+!![])+![]+(!![]+!![])+![]+(!![]+!![])+![]+![]+(!![]+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+[])+![]+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+![]+![]+(+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+(+[])+![]+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(!![]+!![]+!![])+![]+(+!![])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+![]+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+[])+![]+(+!![])+![]+(+!![])+![]+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+[])+![]+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+!![])+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(!![]+!![])+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+![]+(+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+(+!![])+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+![]+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+!![])+![]+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+![]+(+!![])+(+[])+![]+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(!![]+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+![]+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(!![]+!![]+!![])+![]+(!![]+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+(!![]+!![])+![]+(+!![])+(+[])+![]+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+![]+(!![]+!![])+![]+(!![]+!![])+![]+![]+(+!![])+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+(+!![])+![]+(+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![])+![]+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+(+[])+![]+(+!![])+![]+(+!![])+(+!![])+![]+(+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+![]+(!![]+!![])+![]+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+(+[])+![]+(+!![])+(+[])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]))[(![]+[])[!![]+!![]+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))))[+!![]+[+[]]]+(![]+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[+[]]](![])[([]+(+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+(![]+[])[+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))))[+!![]+[+[]]]](([]+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]])()((![]+[])[+!![]]+(+[![]]))[+[]]+(![]+[])[+!![]]+(!![]+[])[+!![]]+(+[]+[][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+[]]][([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([][[]]+[])[!![]+!![]]](([][(![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]](![]+[])+[])[+!![]]+(+!![])+(!![]+!![]+!![])+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+(![]+[])[!![]+!![]]+(!![]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[+[]]+([![]][+!(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+!![]+[+[]]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+!![]+[+!![]]]+(![]+[])[+!![]]))[([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([![]]+[][[]])[+!![]+[+[]]]+([][[]]+[])[+!![]]]([]))()
```
Although hardcoding is longer than a golfed generator in normal js, numbers are (comparatively ;P) easily represented in JsFuck.
[Answer]
# ~~30287~~ ~~12419~~ 12288 Bytes
Original golf:
```
for(f=[1,1],t=1;t<49;)f.push(f[t-1]+f[t++]);alert(f)
```
Unshift and Reverse are cheaper than Push for a slight saving:
```
for(f=[1,1],t=48;t;t--)f.unshift(f[0]+f[1]);alert(f.reverse())
```
~~Doesn't fit! 30K character limit!
[Pastebin](http://pastebin.com/MKCDtnFL) here.~~
I tried jsfuck.com but that gave me 62399 bytes.
Following the suggestion of Stefnotch, changed compatibility to Chrome only and slashed the count dramatically.
JSFuck generated by [jscrew.it](http://jscrew.it/):
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(![]+[])[+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(+!![])+([][(![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]](![]+[])+[])[+!![]]+(+!![])+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+[!![]+!![]]]+([][(![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]](![]+[])+[])[+!![]]+(!![]+[])[+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](+[![]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]])[!![]+!![]+[+!![]]]+(!![]+[])[+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](+[![]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]])[!![]+!![]+[+!![]]]+(!![]+[])[+[]]+(+((+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+!![]))+[])[!![]+!![]]+(+((+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+!![]))+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(![]+[])[+[]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+([][[]]+[])[+[]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]])()((![]+[])[+!![]]+(+[![]]))[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(+[])+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+[!![]+!![]]]+(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[]))+[])[!![]+!![]]+(![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(+!![])+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+[!![]+!![]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](+[![]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]])[!![]+!![]+[+!![]]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(![]+[])[+[]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]])()
```
[Answer]
# ~~12,285~~ ~~12183~~ ~~12069~~ ~~11399~~ ~~11252~~ 11105 Bytes
Original code:
```
f=[1,1];for(i=0;i<48;)f.push(f[i++]+f[i]);alert(f)
```
After removing semicolon and replacing it with '\n': (Thanks [Dom Hasting](https://codegolf.stackexchange.com/users/9365/dom-hastings).)
```
f=[1,1]
for(i=0;i<48;)
f.push(f[i++]+f[i])
alert(f)
```
Using 'concat' instead of 'push' to save some bytes:
```
f=[1,1]
for(i=0;i<48;)
f=f.concat(f[i++]+f[i])
alert(f)
```
Updated code:
```
falsefalse =[1,1]
for(false0=0;false0<48;)falsefalse=falsefalse.concat(falsefalse[false0++]+ falsefalse[false0])
alert(falsefalse)
```
Removing empty space:
```
falsefalse=[1,1]
for(false0=0;false0<48;)falsefalse=falsefalse.concat(falsefalse[false0++]+ falsefalse[false0])
alert(falsefalse)
```
Removing empty space after '+':
```
falsefalse=[1,1]
for(false0=0;false0<48;)falsefalse=falsefalse.concat(falsefalse[false0++]+falsefalse[false0])
alert(falsefalse)
```
JSFuck Code:
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](![]+[![]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(+!![])+([][(![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]](![]+[])+[])[+!![]]+(+!![])+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+[!![]+!![]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()+[])[!![]+!![]+[!![]+!![]]]+(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+![]+(+[])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+(+[])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](+[![]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]])[!![]+!![]+[+!![]]]+![]+(+[])+([]+[])[(![]+[])[!![]+!![]+!![]]+([][[]]+[])[+[]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]]()[+[]]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](+[![]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]])[!![]+!![]+[+!![]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+![]+![]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+![]+![]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+![]+![]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+![]+(+[])+(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[]))+[])[!![]+!![]]+(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[]))+[])[!![]+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+[!![]+!![]]]+(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[]))+[])[!![]+!![]]+![]+![]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+![]+(+[])+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]+[!![]+!![]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()+[])[!![]+!![]+[!![]+!![]]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+![]+![]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]])()
```
[Answer]
# Firefox, 7446 bytes
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]]]+![]+![]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]]]+[+!![]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]](+!![]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[]))+[])[!![]+!![]]+![]+(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[]))+[])[!![]+!![]]+![]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[!![]+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]])+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](![]+[![]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+([][[]]+[])[+[]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(+[]+[![]])[!![]+!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[+[]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+![]+![]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]]]+(+!![])+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[]))+[])[!![]+!![]]+![]+![]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[!![]+!![]]]+(+[])+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+!![]+[+[]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]])+([(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]]((![]+[])[+!![]])+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+![]+![]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]))()
```
Source:
```
[].fill.constructor('[...[falsefalse=[1,1]].fill+false+false].reduce('+[].fill.constructor('falsefalse.unshift(falsefalse[1]+falsefalse[0])')+'),alert(falsefalse.reverse())')()
```
[Answer]
# 14,097 Bytes
First time doing one of these or coding in this language so I will come back and see if I can get it smaller
**Original code:**
```
for(i=1;i<51;i++){alert(Math.floor(((Math.pow(1.618033988749, i)/2.2360679775)+.5)))}
```
**JSFuck Code:**
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+([]+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]][([][[]]+[])[+!![]]+(![]+[])[+!![]]+([]+(+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+(!![]+[])[!![]+!![]+!![]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(![]+[])[+[]]+(!![]+[])[+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([]+(+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]])()(+[]+[+[]]+(+[![]])+![])[+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]])()(+[]+[+!![]]+(+[![]]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[+(+!![]+[+!![]])])[+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([![]]+[][[]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+(+!![]+[+[]]+(!![]+!![])+![]+(+!![])+(+!![])+(+!![])+![]+(+!![])+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(+[])+![]+(+!![])+(+[])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![])+(+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(+!![])+![]+(+!![])+(!![]+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+(+!![])+![]+(+!![])+(+!![])+(!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+(!![]+!![])+![]+(+!![])+(+[])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+(+!![])+![]+(+!![])+(+!![])+(+!![])+![]+(+!![])+(+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+[])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(+!![])+(+!![])+(!![]+!![])+![]+(+!![])+(+!![])+(+!![])+![]+(+!![])+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![])+(!![]+!![])+![]+(+!![])+(+[])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(+[])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![])+(+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![])+![]+(!![]+!![]+!![]+!![])+(+!![])+![]+(!![]+!![]+!![]+!![])+(+!![])+![]+(!![]+!![]+!![]+!![])+(+!![])+![]+(+!![])+(!![]+!![])+(!![]+!![]+!![]+!![]+!![]))[(![]+[])[!![]+!![]+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))))[+!![]+[+[]]]+(![]+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[+[]]](![])+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]])[!![]+!![]+[+[]]])())()
```
] |
[Question]
[
Write a program that takes in a string where every line consists of the character `0` indented by some number of spaces. The top line is not indented and every other line will be indented by at most one more space than the line just before it.
No lines will have trailing spaces but you may optionally assume there is a single trailing newline.
For example, the input might look something like this:
```
0
0
0
0
0
0
0
0
0
0
0
0
0
0
```
Your task is to number it like a [hierarchical outline](https://en.wikipedia.org/wiki/Outline_(list)#Alphanumeric_outline), using increasing positive integers as the line headers. This would be the output for the example:
```
1
1
1
2
2
2
1
2
3
1
3
1
1
2
```
Note how every hierarchical indentation level has its own set of increasing numbers, even if they only go up to one.
In the output, there should be no trailing spaces, but there may optionally be a single trailing newline.
Write a full program that takes the input string via stdin or command line, or write a function that takes the string in as an argument. Print the result or return it as a string.
**The shortest code in bytes wins.**
### Examples
If the empty string is input, the empty string should be output.
The next most trivial example is the input
```
0
```
which should become
```
1
```
Large example - Input:
```
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
```
Output:
```
1
1
1
2
1
3
1
2
1
2
1
1
2
3
4
2
3
1
2
3
2
1
1
2
1
2
3
4
5
6
7
8
9
10
11
1
1
1
12
1
3
4
5
1
1
1
1
1
1
2
2
2
2
2
2
1
2
1
2
6
7
```
[Answer]
# Python 2, 77
```
S={'0':0}
for w in input().split('\n'):S[w]+=1;S[' '+w]=0;print w[:-1]+`S[w]`
```
Like [Sp3000's answer](https://codegolf.stackexchange.com/a/53510/20260), but with a dictionary. The dict `S` stores the current number for each nesting level `'0', ' 0', ' 0'` and so on. For each line in the input, increment the corresponding nesting level, and reset the nesting level one higher to 0.
[Answer]
# Python 2, ~~86~~ ~~85~~ 81 bytes
```
S=[]
for r in input().split("\n"):S=([0]+S)[-len(r):];S[0]+=1;print r[:-1]+`S[0]`
```
*(-5 bytes thanks to @xnor)*
Takes input as a string via STDIN, e.g.
```
'0\n 0\n 0\n 0\n 0\n0\n 0\n 0\n 0\n 0\n0\n 0\n 0\n 0'
```
Alternatively, here's a function for 5 extra bytes:
```
def f(I,S=[]):
for r in I.split("\n"):S=([0]+S)[-len(r):];S[0]+=1;print r[:-1]+`S[0]`
```
[Answer]
# CJam, 25 bytes
```
LqN/{0+I,<))_IW@toNo+}fI;
```
Like my [Python answer](https://codegolf.stackexchange.com/a/53510/21487), this uses an array to store which number each indentation level is up to. One difference, however, is that this uses `t` (array set) to replace the 0 on each line with the number we want.
[Try it online](http://cjam.aditsu.net/#code=LqN%2F%7B0%2BI%2C%3C%29%29_IW%40toNo%2B%7DfI%3B&input=0%0A%200%0A%20%200%0A%200%0A%20%200%0A%200%0A%20%200%0A%20%200%0A%20%20%200%0A%20%20%200%0A%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%200%0A%20%20%200%0A%20%20%20%200%0A%20%20%20%200%0A%20%200%0A0%0A%200%0A%20%200%0A%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%20%200%0A%20%20%20%200%0A%20%20%20%20%200%0A%20%200%0A%20%20%200%0A0%0A0%0A0%0A%200%0A%20%200%0A%20%20%200%0A%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%20%20%200%0A%20%20%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%200%0A%20%20%200%0A%20%200%0A%200%0A%20%200%0A%20%200%0A%20%20%200%0A%20%20%200%0A0%0A0).
[Answer]
# JavaScript ES6, ~~83~~ 81 bytes
```
f=(z,a=[])=>z.replace(/ *0/g,e=>e.replace(0,a.fill(0,l=e.length)[--l]=a[l]+1||1))
```
This uses an array that holds the current number for each indentation level. Everything past that level is reset to 0 using `fill()`. EDIT: 2 bytes saved thanks to vihan1086's tip.
The Stack Snippet below can be used for testing because it is ungolfed slightly and uses better-supported ES5 syntax. The second function is a polyfill for `fill()` as there is not a short way to do it without ES6.
```
f=function(z){
a=[]
return z.replace(/ *0/g,function(e){
return e.replace(0,a.fill(0,l=e.length)[--l]=a[l]+1||1)
})
}
if(!Array.prototype.fill){
Array.prototype.fill = function(val, start){
var res = this;
for(var i = start; i<this.length; i++){
res[i] = val;
}
return res;
};
}
run=function(){document.getElementById('output').innerText=f(document.getElementById('input').value)};document.getElementById('run').onclick=run;run()
```
```
<textarea id="input" rows="15" cols="10">
0
0
0
0
0
0
0
0
0
0
0
0
0
0</textarea>
<pre id="output" style="display:inline-block; vertical-align:top; margin:0"></pre><br />
<button id="run">Run</button>
```
[Answer]
# Pyth, 18 bytes
```
V.z+PNhX0=Y>lN+0Y1
```
This is an exact translation of [@Sp3000](https://codegolf.stackexchange.com/a/53510/20080)'s answer. I tried many different approaches and variations, but I couldn't shorten it, so I am marking this CW.
[Demonstration.](https://pyth.herokuapp.com/?code=V.z%2BPNhX0%3DY%3ElN%2B0Y1&input=0%0A%200%0A%20%200%0A%200%0A%20%200%0A%200%0A%20%200%0A%20%200%0A%20%20%200%0A%20%20%200%0A%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%200%0A%20%20%200%0A%20%20%20%200%0A%20%20%20%200%0A%20%200%0A0%0A%200%0A%20%200%0A%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%200%0A%20%20%200%0A%20%20%20%200%0A%20%20%20%20%200%0A%20%200%0A%20%20%200%0A0%0A0%0A0%0A%200%0A%20%200%0A%20%20%200%0A%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%20%20%200%0A%20%20%20%20%20%200%0A%20%20%20%20%200%0A%20%20%20%200%0A%20%20%200%0A%20%200%0A%200%0A%20%200%0A%20%200%0A%20%20%200%0A%20%20%200%0A0%0A0&debug=0)
[Answer]
# Python - 191
```
def p(s,i,v,n=1):
while i<len(s)and s[i]and'0'not in s[i][:v]:
if s[i][v]=='0':s[i]=' '*v+str(n);n+=1;i+=1
else:i=p(s,i,v+1)
return(s,i)[v!=0]
z=lambda r:'\n'.join(p(r.split('\n'),0,0))
```
The function is `z`.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-rn`, ~~31~~ 27 bytes
```
{Wl#<alPU0l@>:-#aaR0++@l}Mg
```
Input from stdin. [Try it online!](https://tio.run/##K8gs@P@/OjxH2SYxJyDUIMfBzkpXOTExyEBb2yGn1jf9/38DLgUgUsCgwBiJgJL4KAzFEGOwG00MxrQZKgqBeNRhodHciMOnQPhftygPAA "Pip – Try It Online")
### Explanation
```
g is list of lines of stdin (-r flag); l is []
Note that l is a global variable
{ }Mg Map this function to each a in g:
Wl#<a While l is less in length than a:
lPU0 Push a 0 to (the front of) l
(This handles increasing the indent)
l@>: Slice and assign back to l...
-#a ... its last len(a) elements
(This handles decreasing the indent)
aR0 In a, replace 0 with
@l the first element of l
++ incremented in-place
The function returns the above expression
The resulting list from map is printed, newline-separated
(-n flag)
```
] |
[Question]
[
## Plot contrivance
You wake up to find that something has gone horribly wrong! Your time machine has malfunctioned and you are lost sometime between June 2022 and October 1991.
You check the computer that you keep on the desk to see what time it is, but alas the positron interference from your quantum undetangler has fried the system clock, the internet, and several other sensible ways to use a computer to check the time!
You wrack your brain, for some way to figure out the time. It's too dangerous to go outside... you haven't changed your decor in decades .. *Aha!* You've got it! You know for sure that over the last 31 years you've always kept a perfectly updated version of your favorite programming language on this very computer! You're still a bit loopy from the decompactification so you can't remember some things, but you do retain your perfect knowledge of the history of the Unicode standard.
## Task
Your task is to write a computer program which when run will output the approximate date or date range based on the implementation of Unicode available.
### Example
For example, since `ᚓ` (`Ogham Letter Eadhadh`) was added to Unicode in version 3.0 the following Haskell program determines if we are before the release of 3.0 in September 1999 or after.
```
import Data.Char
main =
putStrLn $
if
generalCategory 'ᚓ' == OtherLetter
then
"September 1999-present"
else
"October 1991-August 1999"
```
[Try it online!](https://tio.run/##NYsxCoNAFER7TzFIwMqApYVFMKVg4Qk2YaKSdV3@foucI11ul5NsZDHV8Jj3JhOetDbGefGrKK5GzbmdjGSLmR2aDPCbDiqdwwk7AfMjDTDSUYxtjXJc5YXi@3kXaBr0OlE6qlKSuqM7mnygVy43Cqq6rksvDHSap5s28O/1d10Pqyov27gFTUUe4w8 "Haskell – Try It Online")
## Rules
You may assume either
1. Your programming language has an *idealized* version of its Unicode handling library that has always implemented the current standard. (Even for dates before the invention of your language)
2. Your programming language has the *actual* up-to-date version of its Unicode library that would be available at the particular date, bugs, and all.
To keep things neat and tidy do not mix and match. If you exploit a bug you're on track two, if you use anachronistic language features you're on track one.
You should not use any language features other than the library to determine the date. For example, you can't just pull the language version string or check if a certain function exists. You must use calls to the Unicode handling library.
## Scoring
This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") so answers will be scored by their vote counts.
I encourage voters to consider the following criteria when judging programs:
1. Granularity. Vote-up programs that can distinguish the date to high levels of detail.
2. Conciseness. Not exactly code-golf, but I encourage you to vote up programs that determine the date in fewer checks.
3. Cleverness. No matter what I say people are going to vote up cleverer answers, but it's worth mentioning. I encourage you to vote up answers that use obscure Unicode trivia, exploit strange edge cases, etc.
[Answer]
# Java 4+, 20 date-ranges
```
/*
Language limitations: https://en.wikipedia.org/wiki/Java_(programming_language)#Versions
- String#replaceAll / java.util.regex.Pattern were added in Java 1.4 (February 6th, 2002)
- Alternatives Character.isDefined(int) / Character.getType(int) were added in Java 5 (September 30th, 2004)
Sources:
- Version changelogs with links: https://en.wikipedia.org/wiki/Unicode#Versions
- More accurate release dates: https://unicode.org/history/publicationdates.html
*/
class Main{
public static void main(String[]a){
String test = "A\u4E00\u1100\uBB5E\u20AC\u13A0\u10400\u1740\u10800\u1A00\u1B00\u102A0\u10B00\u1BC0\u11100\u20BA\u061C\u16AD0\u11700\u1E900\u11A00\u11800\u10FE0\u32FF\u10FB0\u1E290";
int length = test.replaceAll("\\p{Cn}","").length();
switch(length){
// 'A': Added as default
case 1: // no-op
System.out.print("v1.0.0:\tOctober 1991 (up to and including May 1992)");
break;
// '\u4E00': https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
case 2: // no-op
System.out.print("v1.0.1:\tJune 1992 (up to and including May 1993)");
break;
// '\u1100': https://en.wikipedia.org/wiki/Hangul#Unicode
case 3: // no-op
System.out.print("v1.1:\tJune 1993 (up to and including June 1995)");
break;
// '\uBB5E': https://unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/KSC/HANGUL.TXT
case 4: // no-op
System.out.print("v2.0:\tJuly 1996 (up to and including April 1998)");
break;
// '\u20AC': https://www.unicode.org/versions/Unicode2.1.0/ & https://www.unicode.org/Public/2.1-Update4/ReadMe-2.1.9.txt (search for "version 2.1.2")
case 5: // no-op
System.out.print("v2.1.2:\tMay 1998 (up to and including August 1999)");
break;
// '\u13A0': https://en.wikipedia.org/wiki/Cherokee_(Unicode_block)
case 6: // no-op
System.out.print("v3.0:\tSeptember 1999 (up to and including February 2001)");
break;
// '\u10400': https://en.wikipedia.org/wiki/Deseret_(Unicode_block)
case 8: // first case
//System.out.print("v3.1:\tMarch 2001 (up to and including February 2002)");
System.out.print("v3.1:\tMarch 2001 (February 6th, 2002 up to and including February 28th, 2002)");
break;
// '\u1740': https://en.wikipedia.org/wiki/Buhid_(Unicode_block)
case 9:
System.out.print("v3.2:\tMarch 2002 (up to and including March 2003)");
break;
// '\u10800': https://en.wikipedia.org/wiki/Cypriot_Syllabary_(Unicode_block)
case 11:
System.out.print("v4.0:\tApril 2003 (up to and including March 30th, 2005)");
break;
// '\u1A00': https://en.wikipedia.org/wiki/Buginese_(Unicode_block)
case 12:
System.out.print("v4.1:\tMarch 31st, 2005 (up to and including July 13th, 2006)");
break;
// '\u1B00': https://en.wikipedia.org/wiki/Balinese_(Unicode_block)
case 13:
System.out.print("v5.0:\tJuly 14th, 2006 (up to and including April 3rd, 2008)");
break;
// '\u102A0': https://en.wikipedia.org/wiki/Carian_(Unicode_block)
case 15:
System.out.print("v5.1:\tApril 4th, 2008 (up to and including September 30th, 2009)");
break;
// '\u10B00': https://en.wikipedia.org/wiki/Avestan_(Unicode_block)
case 17:
System.out.print("v5.2:\tOctober 1st, 2009 (up to and including October 10th, 2010)");
break;
// '\u1BC0': https://en.wikipedia.org/wiki/Batak_(Unicode_block)
case 18:
System.out.print("v6.0:\tOctober 11th, 2010 (up to and including January 30th, 2012)");
break;
// '\u11100': https://en.wikipedia.org/wiki/Chakma_(Unicode_block)
case 20:
System.out.print("v6.1:\tJanuary 31st, 2012 (up to and including September 25th, 2012)");
break;
// '\u20BA': https://en.wikipedia.org/wiki/Turkish_lira#Currency_sign
case 21:
System.out.print("v6.2:\tSeptember 26th, 2012 (up to and including September 29th, 2012)");
break;
// '\u061C': Diff https://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt and https://www.unicode.org/Public/6.3.0/ucd/UnicodeData.txt
case 22:
System.out.print("v6.3:\tSeptember 30th, 2012 (up to and including June 15th, 2014)");
// '\u16AD0': https://en.wikipedia.org/wiki/Bassa_Vah_(Unicode_block)
case 24:
System.out.print("v7.0:\tJune 16th, 2014 (up to and including June 16th, 2015)");
break;
// '\u11700': https://en.wikipedia.org/wiki/Ahom_(Unicode_block)
case 26:
System.out.print("v8.0:\tJune 17th, 2015 (up to and including June 20th, 2016)");
break;
// '\u1E900': https://en.wikipedia.org/wiki/Adlam_(Unicode_block)
case 28:
System.out.print("v9.0:\tJune 21st, 2016 (up to and including June 19th, 2017)");
break;
// '\u11A00': https://en.wikipedia.org/wiki/Zanabazar_Square_(Unicode_block)
case 30:
System.out.print("v10.0:\tJune 20th, 2017 (up to and including June 4th, 2018)");
break;
// '\u11800': https://en.wikipedia.org/wiki/Dogra_(Unicode_block)
case 32:
System.out.print("v11.0:\tJune 5th, 2018 (up to and including March 4th, 2019)");
break;
// '\u10FE0': https://en.wikipedia.org/wiki/Elymaic_(Unicode_block)
case 34:
System.out.print("v12.0:\tMarch 5th, 2019 (up to and including May 6th, 2019)");
break;
// '\u32FF': https://en.wikipedia.org/wiki/Reiwa#Technology
case 35:
System.out.print("v12.1:\tMay 7th, 2019 (up to and including March 9th, 2020)");
break;
// '\u10FB0': https://en.wikipedia.org/wiki/Chorasmian_(Unicode_block)
case 37:
System.out.print("v13,9:\tMarch 10th, 2020 (up to and including September 13th, 2021)");
break;
// '\u1E290': https://en.wikipedia.org/wiki/Toto_(Unicode_block)
case 39:
System.out.print("v14.0:\tSeptember 14th, 2021 (up to and including June 15th, 2022)");
break;
default:
System.err.printf("Unknown unicode version and date! (%d)%n", length);
break;
}
}
}
```
[(Don't) try it online.](https://tio.run/##jVh9b5s4GP8/n8KXalcytYCBvE77g6Tptm7dqiWdTnc9RS44gYZAzphmuWmfvWcbSMgtsalUIrD9@Pd73u0n9Iwun/zly4vxuvEJxYsMLTCIwlVIEQ2TOB2AgNJ1OjAMHOubcBmusR8iPSELg78ZN0zATFuTZEHQahXGi1lUSGmdfcMk5TIal2BCCRs7I3gdIQ@7UQQM8MSW6hkNI53gBf6u3yFKMYnBBhMMkO9jH4Qx4BsAqDtAu8aPJENkCzo0uACWaVotJtmN@CIG9hmnYBQggjz2QQ/TKzwPY@xrYUxbbLf90ALT6XaN84Ejm7WBNsFrilePmADbLDZzWo3GJMmIh9MB27bgBryA0cVRskjBJqQBU128VCrtPg69xMdVBd0mHIfnZQRRDAiOMEox8NlLRVqWrxOCgjClCdka6@wxCj1hLDFbD@gqarw2Gl6E0hTcojD@0QAgnwZSblYPPCehD1ZsSMsN89ffqMVngcJQgAmi4C1oug@ZMzbNhwxC/hwO2@OHzDLdEftiu/y76YjhriNeeuLFFc@heJpWPi1/G46ELCHMModMvNmBXFjHvRIjXTFt3M/3zAXBXKp5PWY/tnV9LV6GYqLVN5tvBHJmThDheMGM8Fbg1/fepjUfHtY/RvHP5kWz2dLzaVorX5gyw3mBln8s1ACAYYBz93wAXOEbKAU@nqMsosWwx80DB3xanFwm6@IzU@A2Za6jJxnV10yVVGs@Q93UzcED/eLRhPsU7Pch0LI1oAlAMXc8L8p8rvZbtOWjVqtZYON/jwSj5ZsKrNwm5yovG918nDFPm4fYn33wMY/QdZDOtML7Zo9R4i1bVT5WfT6Q8bnJYizgSsnYKjLcG5Rk3vOsEp0V2Kug7bqgq5Dt45DL4bYKMw@E8@OBeScizbh17@4@fH43Mb4MJ18@jadjY@xOpu7kg2t8nIyM9@7nd/ef9Okf0yoXpx4XS7jTTRYJBXeOc3HZ7IiP91RkeDxXyGw2G71K6LnIUmXasnTmAAb4/eSCQgNs3uX9miclx/iKkX@LL/nSvk6/U6ClGBEvAPOEgGaxA@DDVvPAJdt1NcJWMp0UPtc7oZJskbG8xib0lU7Jsps6wgJMkiXGspjq1CNgC5Pu6w7HeJzErgyyogSVNHh6VvK4wikrg1RGoydozEPC9Mc/7DY1jKNsoDAGtzCHqWZymPJqify1HwDyXXq7vkGlNVbNlEobZkHoy1TWH8j5WFU@J3NoMa7Oorz2qj12y/ZP6GyyjSL0yLQiIwChlIEjXDZPMxyhjMGujVJmVl7za@h@wXq7VBp40FKg3/uTDVOaoztVFnimtQsKHSWFYR0KKFJTsKUU2pUy4JTgZMXAJr6Y1FM7k1Un/SESolhKoK0gAHceVBI4kbqPdOTqHG7WMYTLDg5UQaOroGFVu7vCl06k7920ggY01e40quNOFC2lHHpSDp3DDhWW4E4EBIpFSi1tAdUptVaXxw5pyxWStqimgobo8kp4hS2gpXIqq12XCD@1KHlMM7IM02AWhQSdjTJCcOxtZ2m4iA@4QAUX66AlsDolRiWbfl02/PTF2FyF87mqnWNwWNuXeX7ZB14xlxO9HIehXGwfX3ygD0uhD/tAH3vnkzXzpWGdiioKl@RnzhqBlaZo9g0FUq90pMi7RaLmeEojOjLQ5SR1teQHZnWKC5KVFH5HCr9Xgd8tkUngW6Vh1JWSH/TV8P0IyfHLc1t/j98qM0JHegAs8HfV6q/TrfyJYtZr/YvIbPIPy0vSkm/L8xs0K1xKNXclXIqyCtUlH9bpH6/4LYIUvzyGIdzjLyOzJ2scS/w1iv31WI1/HG1XKPSkDOSxDPPDd46upNA/fQPSqUuAX2wp8X/F4QadTbEXxEmULLYHwNsq4LA4IXdVsDm3Iggss4bmh3VKe0JQulI0jLa804L2RX@n/LKDskxVPSxbd0t9XuYXiuryntBEykJ@9IPO/w/7TomvRiWzJEW9uKP8ZXdMSL77XGvex8s42cSgqNKgvHzhW/LLmt@A9spvvYqbF8V16vHNfjb4/8@Xl/8A)
**Explanation:**
Uses `\p{Cn}` regex-replacement to remove unassigned unicode characters from a string, before evaluating its length.
This uses rule option #2. Since [`String#replaceAll`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#replaceAll(java.lang.String,java.lang.String)) and [`java.util.regex.Pattern`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html) were added in Java 4, released on February 6th, 2002 (and alternatives [`Character#isDefined(int)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Character.html#isDefined(int)) and [`Character#getType(int)` with `Character.UNASSIGNED`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Character.html#getType(int)) since Java 5 of September 30th, 2004), it only works for beyond that date. I've added the previous Unicode versions and date-ranges to the code for completeness, but since Java 4 wasn't released yet at the time, they can be seen as no-ops.
This is just an initial version which looks at added characters in the Unicode versions, [mentioned on Wikipedia](https://en.wikipedia.org/wiki/Java_(programming_language)#Versions). I'll see if I can further define inner Unicode versions later on, since there are versions where the Unicode standard has been updated, but no characters were added/removed (e.g. added casing support for lower-/uppercase letters and things like that). But this already was quite time-consuming, so this will do for now.
[Answer]
# Erlang, 4 date ranges
```
#!/usr/bin/env escript
-module(norm).
main(_) ->
Versions = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
"v9.0:\tJune 21st, 2016 (up to and including May 6th, 2019)",
"v14.0:\tSeptember 14th, 2021 (up to and including June 15th, 2022)",
0,
"v13.0:\tMarch 10th, 2020 (up to and including September 13th, 2021)",
"v12.1:\tMay 7th, 2019 (up to and including March 9th, 2020)"},
Index =
%% Unicode 14.0.0
tryit(16#a7f2) +
%% Unicode 13.0.0
tryit(16#ab69) +
%% Unicode 12.1.0
tryit(16#32ff),
io:format("~s~n", [element(Index, Versions)]).
tryit(C) ->
NFKD = unicode:characters_to_nfkd_list([C]),
Hex = [io_lib:format("~.16B", [X]) || X <- NFKD],
io:format("~6.16B -> ~s~n", [C, lists:join(", ", Hex)]),
iolist_size(Hex).
```
**Explanation:**
This uses changes in normalization rules between Unicode versions. It gets the NFKD canonical form of three code points, adds the number of hex digits in the result, and uses that as an index into a tuple with date ranges shamelessly stolen from [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/248651).
As of Unicode 9.0, the three characters all decompose to themselves, giving a starting length of 12. The characters are:
* ㋿, 32FF, SQUARE ERA NAME REIWA, which decomposes into 令和 (4EE4 548C) as of Unicode 12.1. The length goes up by 4, to 16. (This character was introduced when [Naruhito](https://en.wikipedia.org/wiki/Naruhito) became emperor of Japan and adopted the era name Reiwa, succeeding his father Akihito and ending the Heisei era.)
* ꭩ, AB69, MODIFIER LETTER SMALL TURNED W, which becomes ʍ (28D) as of Unicode 13.0. The length goes down by 1, to 15.
* ꟲ, A7F2, MODIFIER LETTER CAPITAL C, which becomes C (43) as of Unicode 14.0. The length goes down by 2, to 13.
The `unicode` module was added to Erlang in release 20.0, supporting Unicode 9.0. It was upgraded to Unicode 10.0 in release 21.0, to 11.0 in release 22.0, to 12.1 in release 23.0, to 13.0 in release 24.0, and to 14.0 in release 25.0. I couldn't find any suitable characters to distinguish versions 9 to 11.
Using a bunch of Erlang installations I had lying around, the output is:
```
21.3.8.2:
A7F2 -> A7F2
AB69 -> AB69
32FF -> 32FF
v9.0: June 21st, 2016 (up to and including May 6th, 2019)
23.0.2:
A7F2 -> A7F2
AB69 -> AB69
32FF -> 4EE4, 548C
v12.1: May 7th, 2019 (up to and including March 9th, 2020)
24.3.4.1:
A7F2 -> A7F2
AB69 -> 28D
32FF -> 4EE4, 548C
v13.0: March 10th, 2020 (up to and including September 13th, 2021)
25.0.1:
A7F2 -> 43
AB69 -> 28D
32FF -> 4EE4, 548C
v14.0: September 14th, 2021 (up to and including June 15th, 2022)
```
[Answer]
# Python, 22 date ranges (21 Unicode versions)
```
codepoints_dates = {
b"\\u03F4": "2001 February 28", #3.1
b"\\u0220": "2002 March 22", #3.2
b"\\u0221": "2003 April 18", #4.0
b"\\u0240": "2005 March 30", #4.1
b"\\u0242": "2006 July 14", #5.0
b"\\u0370": "2008 April 4", #5.1
b"\\u0524": "2009 October 1", #5.2
b"\\u0526": "2010 October 11", #6.0
b"\\u058F": "2012 January 31", #6.1
b"\\u20BA": "2012 September 26", #6.2
b"\\u06A3": "2013 September 30", #6.3
b"\\u037F": "2014 June 16", #7.0
b"\\u08B3": "2015 June 17", #8.0
b"\\u1C80": "2016 June 21", #9.0
b"\\u0860": "2017 June 20", #10.0
b"\\u0560": "2018 June 5", #11.0
b"\\u0C77": "2019 March 5", #12.0
b"\\u32FF": "2019 May 7", #12.1
b"\\u08C0": "2020 March 10", #13.0
b"\\u061D": "2021 September 14", #14.0
b"\\u0CF3": "2022 September NN", #15.0
}
prev_date = ""
for code, date in codepoints_dates.items():
try:
code.decode("unicode_escape")
except:
break
prev_date = date
else:
date = ""
print(prev_date, "-", date)
```
Each codepoint has been introduced in the corresponding Unicode version. The information is taken from the *Delta Code Charts* ([here](https://www.unicode.org/charts/PDF/Unicode-14.0/) is the link to the Chart of version 14.0 as an example).
] |
[Question]
[
Let \$A\$ be a square matrix that is at least \$2 \times 2\$ where each element is an integer. \$A^2 = A \times A\$ will then have the same dimensions as \$A\$, and will have integer elements. For example, let
$$A = \left[ \begin{matrix}
-3 & 2 \\
0 & -1
\end{matrix} \right]$$
Therefore,
$$\begin{align}
A^2 & = \left[ \begin{matrix}
-3 & 2 \\
0 & -1
\end{matrix} \right]^2 \\
& = \left[ \begin{matrix}
-3 & 2 \\
0 & -1
\end{matrix} \right] \times \left[ \begin{matrix}
-3 & 2 \\
0 & -1
\end{matrix} \right] \\
& = \left[ \begin{matrix}
-3 \times -3 + 2 \times 0 & -3 \times 2 + 2 \times -1 \\
0 \times -3 + -1 \times 0 & 0 \times 2 + -1 \times -1 \\
\end{matrix} \right] \\
& = \left[ \begin{matrix}
9 & -8 \\
0 & 1
\end{matrix} \right]
\end{align}$$
---
Given an \$n \times n\$ matrix \$B\$ consisting only of integer elements, output any \$n \times n\$ integer matrix \$A\$ such that \$A^2 = B\$. You may optionally take \$n\$ as an input, and you may assume that you'll only have to handle matrices for which there exists such an \$A\$.
You may take input and output in any [convenient format and method](https://codegolf.meta.stackexchange.com/q/2447/66833). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
## Test cases
The outputs given below are not necessarily the only valid outputs
```
[[8, 96], [-84, -40]] -> [[-8, -8], [7, -4]]
[[18, 63], [14, 67]] -> [[0, 9], [2, 7]]
[[9, 0], [-10, 25]] -> [[3, 0], [5, -5]]
[[25, -58, 57], [0, 7, -4], [0, -24, 31]] -> [[5, -7, 5], [0, -1, -1], [0, -6, 5]]
[[12, -33, 42], [16, 19, 20], [-90, 18, 63]] -> [[6, -3, 3], [2, 5, 1], [-6, 0, 9]]
[[33, -80, 86], [72, 57, -13], [-88, 40, 44]] -> [[-8, 7, -3], [-1, 0, 8], [8, 8, -2]]
[[88, 8, -72, 65], [-12, 45, 17, 33], [-27, 21, 36, 31], [5, 40, -53, 119]] -> [[-5, -4, 3, -9], [-6, 0, 0, 7], [-5, 5, -4, 7], [-6, 3, 5, -3]]
[[45, 39, -25, -17, 61], [29, 69, -15, 2, 45], [42, 51, 7, -28, 67], [27, 65, -25, 7, 25], [-66, -61, 9, 63, 1]] -> [[9, 7, -3, -9, 3], [3, -3, 5, -8, -2], [5, 3, 5, -9, 2], [3, -2, 2, -8, -4], [-5, -4, 0, 7, 6]]
[[150, -73, -37, -40, -43, 119], [-62, 191, 95, -87, -10, -88], [-31, -32, -64, 137, 82, -54], [22, -81, 32, 24, 46, -149], [-5, -16, -6, 42, 63, -23], [106, -160, -115, 25, 20, -5]] -> [[8, -8, -3, 5, 6, 3], [-7, 6, 8, 5, 6, -4], [5, 1, -1, -7, 1, -9], [0, 9, 6, -8, -2, 9], [4, 3, 2, -1, -3, -2], [7, -7, 2, -5, -4, 1]]
[[146, -37, -60, -38, 30, -8], [71, -42, -33, -26, -15, -55], [-39, -74, 2, -46, -19, 31], [42, -136, -46, 19, -41, -3], [61, 23, 12, -8, 37, -59], [-73, -13, 88, 90, -71, -11]] -> [[4, 7, -2, -4, 4, -1], [8, -1, -3, -6, 2, 4], [-9, 5, -2, 6, 1, 3], [-7, 6, 1, -5, 4, 3], [5, -8, -8, 2, 3, -4], [-8, -8, -1, -4, -6, -2]]
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~98~~ 96 bytes
* -2 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler).
```
s a=[x|m<-[1..],x<-q(q[-m..m]a)a,a==[foldr1(z(+))$z(map.(*))r x|r<-x]]!!0
q=mapM.const
z=zipWith
```
[Try it online!](https://tio.run/##Tc69CsIwFAXgPU9xLQ6J@aERHITGJ9DJwSHc4WKVFpv@pBVL8d1ruzl@53DgFNS/HlU1zz2Q8@M3ZNpbY1CNme5453UwJiAJUuScfzZVHi2fuBRiO/FAreE7ISKM35jpEXGzSVnnlvxi7k3dD2xyU9neyqGYA5W1yxsGlOn4oPxcM2jfw3WI53rbF80HSMoE9AkSKVfz5ZJgsO5m761KUflUWUS2av@no4KlBK9tqmB/QPwB "Haskell – Try It Online")
The relevant function is `s`, which takes as input a matrix `a` as a list of lists of integers and returns a square root of `a` in the same form.
The matrix multiplication part is taken almost verbatim from [xnor's answer](https://codegolf.stackexchange.com/a/194216/82619) to [this challenge](https://codegolf.stackexchange.com/questions/100205/do-matrix-multiplication).
[Answer]
# [WolframLanguage (Mathematica)](https://www.wolfram.com/mathematica/), ~~54~~ ~~52~~ 45 bytes
```
Last@Solve[(q=s~Array~{#,#}).q==#2,Integers]&
```
–2 bytes from ovs.
–7 bytes due to reading the directions and realizing I can take *n* as an input.
[Try it online!](https://tio.run/##ZVLLSgNBELz7FQsBUZiRdM9jZw8BPQoeBI/BwyIhBoxisggS4q/Hqp4NGAPZMNPdVV1dPet@eF2s@2H10h@Ws8NDvx1unz7evhbzq8/Z9udus@m/f3YTN9lf33zOZhN19@/DYrnYbJ8vD4@b1ftwu5yr2@2Ka7q8d83Ol@gaH6f7/XNz8bdCUJIDSwQVuT0r6FwzNQaZukbTST4grwnECSypZRmKWnYaz17BGuQMJYpcCK6Jar2zawSdtLbqgByF/QcS4wvyxeZqlY0RklDHBCoiG@MJMtILpPDzhORUR8IxQr@AIVQCxVEF12y6EUqV0Sd0FulOeBN4SRA6jkonSJUNp4hlxgVxa8RopGCpJmkxx1lLVBo5WvOZYjJE@IxqUrH9SfNMHxOltTQlmO@8xlGpUSidJQXpi1nFmlIsHYRILiNjUUKOwluyBSqPhW7gwE1GCpJYqW1cU8g1VoVe61uaWmFmJ7H5@ZmL5yMYqam3@gBXgkm0BVNgPL4Wr3k01KdqkTnfRnPYV3ndcXMGE27SMkz4aAMzS1@VTtmQwFBBqqOZoYI/PprOLBYbxdQffgE)
[The request exceeded the 60 sec time limit, so it could only solve the first eight of the ten test cases.]
How it works:
```
q=s~Array~{#,#} //creates a dummy-indexed matrix with dimensions equal to *n* , calls it "q"
Solve[(q=s~Array~{#,#}).q==#2,Integers] //Solves q.q=#2 for q, where #2 is the input matrix, restricting the solutions to matrices with integer elements
Last@... //since there can be multiple solutions, this selects the last one (the first ones contain conditionals)
```
Here I leaned heavily on the OP's allowance that output could be in "any convenient format", since the above code specifies the solution matrix in terms of its indexed elements, i.e., s[*row*, *column*]. For example:
[](https://i.stack.imgur.com/0o1RT.png)
For 3 additional bytes (48 total), a nicer output can be obtained with a small modification of the code offered by att in the comments:
```
(q=s~Array~{#,#})/.Last@Solve[q.q==#2,Integers]&
```
[](https://i.stack.imgur.com/v7jqR.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
FAṀŒRṗLƲṁ€ðæ*2iị⁸
```
[Try it online!](https://tio.run/##ATwAw/9qZWxsef//RkHhuYDFklLhuZdMxrLhuYHigqzDsMOmKjJp4buL4oG4////W1s5LCAtOF0sIFswLCAxXV0 "Jelly – Try It Online")
It's been over a week, so I figured I'd reveal my brute-force Jelly approach. This makes the following assumption, which I haven't managed to prove, but can't find a counter example:
>
> Let \$B\$ be the input \$n \times n\$ matrix, and \$A\$ be an \$n \times n\$ matrix such that \$A^2 = B\$
>
>
> Let \$b = \max\{|B\_{ij}|, 1 \le i,j \le n\}\$ i.e. the largest absolute element of \$B\$. This answer assumes that, assuming \$A\$ exists, there is at least one matrix \$A\$ such that all its elements are in the inclusive range \$[-b, b]\$
>
>
> For example, for
> $$B = \left[ \begin{matrix} 9 & -8 \\ 0 & 1 \end{matrix} \right]$$,
> \$b = 9\$ and there exists at least one \$A\$ such that all elements are between \$-9\$ and \$9\$ (the example in the question, for example)
>
>
>
## How it works
```
FAṀŒRṗLƲṁ€ðæ*2iị⁸ - Main link. Takes B on the left
F - Flatten B
A - Absolute values of each.
Ʋ - Last 4 links as a monad f(abs(flat(B)):
Ṁ - Maximum
ŒR - Bounced range; [-max, +max]
L - Length i.e. number of elements of B
ṗ - Powerset
€ - Over each list:
ṁ - Mold it like B
Call this list of matrices M
ð - Begin a new dyadic chain with M on the left and B on the right
æ*2 - Matrix square of each matrix in M
i - Index of B in M
⁸ - Yield M
ị - Index back into M
```
One byte longer is a slightly more conventional way of extracting the root:
```
FAṀŒRṗLƲṁ€æ*2⁼ɗƇ⁸Ḣ
```
[Try it online!](https://tio.run/##AUAAv/9qZWxsef//RkHhuYDFklLhuZdMxrLhuYHigqzDpioy4oG8yZfGh@KBuOG4ov///1tbOSwgLThdLCBbMCwgMV1d "Jelly – Try It Online")
Here, the dyadic filter `æ*2⁼ɗƇ` means that it would save a byte over the dyadic chaining with the indexing. However, as we should only output one solution, and the `Ḣ` would chain to the filter without either `⁸` or `¹`, the indexing here actually saves a byte.
[Answer]
# [Julia 1.0](http://julialang.org/), ~~109~~ 100 bytes
```
I=Iterators
m%n=for i=I.countfrom(),j=I.product(fill(-i:i,n^2)...)
r=+m;r[:].=j;r^2==m&&return r end
```
[Try it online!](https://tio.run/##PY3BioMwFEX3@Yq3aUmYGIzjOLYh3fsNYkHaCBGTyPMJpT9vnSl0ec49cMd18r1@bFtjG3LYU8KFhUO0Q0LwtlG3tEYaMAUu5LjzjOm@3ogPfpp45s9exmshlFKCof0KBttzp@xo8FpYG45HdLRiBAQX7xu5hRbbslZDYSAH3UnWniCrP1DDqTK7KCEr8z@ha6i@DegSqt93ne@7zqH46VjHQj9zyi4z@khT5HRY/NNxkloI@f8mthc "Julia 1.0 – Try It Online")
9 bytes golfed by MarcMush.
Boring bruteforce solution. Takes input as matrix `m` and its size `n`. But here's also a bonus:
# [Julia 0.7](http://julialang.org/), ~~214~~ 194 bytes
```
~=round
m%n=.~filter(j->j≈.~j,1-2digits.(0:2^n-1,2,n).|>h->((t,z)=schur(m+0im);u=√t.*h;for i=n:-1:1,j=i+1:n a&k=a-u[i,k]*u[k,j];u[i,j]=reduce(&,t[i,j],i+1:j-1)/(u[i,i]+u[j,j])end;z)*u*z')[1]
```
[Try it online!](https://tio.run/##PVJLbqNAEN37FLVJBmyaofoHGOGLIEayYhKDbRJh2FgjrzNXmOPlIp5XHWkkEHRVvXofGJZzv88fj3s9vS/jYXV5Guv0/tqf526KBrUbvv58pvchYaUP/Vs/X9Mo2@pfo@JEJ2Oc/t4d1S6K5uQW19eX4zJFl03WX@Jqqb8@/87p@li9vk/U1@NW8ZaToe43vB1p/3yq92pp@uTUrpfmlAxtJaehrafusLx00XMyh3MigEFx/DOSgb7dLM2AetyNh@oWr5f17UfccPuYu@t8rZtVw6QryojbZNWUpIr/h4JKX6FgSdlMClyQNxWxJZ9/T2foc0batQmtGu1IuYJcLityoOSptCXDoc@alDFkwceeuCQt@BJ0sjiMoK2KjAoQ5xqbsN6IhoJsRtaGGRwKUmh7J/SarCPOycigzkkzGQ/KipyAlDPEXAYkBg0sik4APEZ0SR4VdiRrKmgjx6JdQxJ8YJ93AYHFQuc9bibAzHdK7MCRQ7YRx3i3gU9GNTxiFPgiDznBB@qGcSMKb4kBKvDqEJXGs4B2TUjMgoatbBGtwinSwKm0fIFM2h4LWZTjEp9BjQBFiTRNQSYLXzQHpf1OX2kf/CondiSO3MK8CoxlyE0mGRlKDSVlRXCFvEjDm8gkoXAiT5yzIXyTUnJgkdSu2tVl/xHNavcx9eN8HqOp25/TaH669rcOvz/HcZyEPzB@/AM "Julia 0.7 – Try It Online")
This is an attempt at an algebraic solution making use of Julia's rich linear algebra library. In fact, Julia's `sqrt` or `√` already works on matrices, but obviously only returns the principal root which may not be the one we need. Therefore, we resort to [Schur decomposition](https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_Schur_decomposition), and our task boils down to finding the square roots of the upper triangular matrix \$T\$ (notation is different from Wiki, but corresponds to Julia's):
\$M^\frac{1}{2}=ZT^\frac{1}{2}Z^{-1}\$
The square roots \$U\$ of matrix \$T\$ can be found by Björck-Hammarling method, which is what Julia itself uses in the implementation of `sqrt`:
\$U\_{ii}=T\_{ii}^\frac{1}{2}\$
\$U\_{ij}=\frac{T\_{ij} - \sum\_{k=i+1}^{j-1} U\_{ik}U\_{kj}}{U\_{ii}+U\_{jj}}, j>i\$
In order to find all solutions, we also need to apply all possible permutations of the signs of the roots in the first equation. The upper triangle can then be fixed according to the second equation.
All these computations introduce some roundoff errors, but when checking for integers, we can resolve this by using inexact comparison operator `≈`. ~~There is a problem with zero, for which it behaves the same as exact equality and comparisons fail.~~ *(It works just fine when applied to entire matrix that has both zeros and non-zeros).*
The results are composed of complex numbers with zero imaginary part, so in TIO footer, we extract the real part for nicer display. It would be -2 bytes if it's acceptable to output the values without cleaning the roundoff errors, and further -3, if we can actually output all found integer solutions instead of just one.
] |
[Question]
[
In the body of this challenge, \$\begin{pmatrix}n\\k\end{pmatrix}\$ is used to represent the [number of combinations](https://en.wikipedia.org/wiki/Combination) of \$k\$ elements of \$n\$, also written as \$\frac{n!}{k!(n-k)!}\$ or \$n\mathrm{C}r\$.
Any nonnegative integer \$m\$, for arbitrary natural (positive) \$r\$, can be written as [a unique series of \$r\$ combinations](https://en.wikipedia.org/wiki/Combinatorial_number_system) such that $$m=\sum\limits\_{i=1}^{r}\begin{pmatrix}C\_i\\i\end{pmatrix}$$ provided the sequence \$C\$ both strictly increases (i.e. \$C\_{\ell-1}\lneq C\_\ell\$) and consists solely of nonnegative integers. \$C\$ is not necessarily unique without these restrictions.
---
# Example
Consider \$m=19\$ and \$r=4\$. Values of \$C\_4\$, \$C\_3\$, \$C\_2\$ and \$C\_1\$ must be found for the equation $$19=\sum\limits\_{i=1}^4\begin{pmatrix}C\_i\\i\end{pmatrix}\\$$ which can be rewritten as $$\begin{pmatrix}C\_4\\4\end{pmatrix}+\begin{pmatrix}C\_3\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=19$$ Begin by finding the largest value of \$C\_4\$ which satisfies the inequality \$\begin{pmatrix}C\_4\\4\end{pmatrix}\leq 19\$. \$C\_4\$ is six: $$\begin{pmatrix}6\\4\end{pmatrix}+\begin{pmatrix}C\_3\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=19\\15+\begin{pmatrix}C\_3\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=19\\\begin{pmatrix}C\_3\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=4$$ The problem has been reduced to \$m=4\$ and \$r=3\$. The largest value of \$C\_3\$ which satisfies the inequalities \$\begin{pmatrix}C\_3\\3\end{pmatrix}\leq4\$ and \$C\_3\lneq C\_4\$ must be found. \$C\_3\$ is four: $$\begin{pmatrix}4\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=4\\4+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=4\\\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=0$$ Any combination of the form \$\begin{pmatrix}n\\k\end{pmatrix}\$ with \$n<k\$ is zero, and so \$C\_2=1\$ and \$C\_1=0\$: $$\begin{pmatrix}1\\2\end{pmatrix}+\begin{pmatrix}0\\1\end{pmatrix}=0\\0+0=0\\0=0\checkmark$$
Note that \$C\_2\$ cannot be zero because then \$C\$ would not strictly increase unless \$C\_1\$ were negative, which cannot be the case due to the condition that \$C\$ consists solely of nonnegative integers. The solution is summarized with the statement \$C=(0,1,4,6)\$ (here, 1-based indexing is used). The process followed here is guaranteed to produce the correct \$C\$.
---
# The Challenge
Given \$m\$ and \$r\$, find the elements of \$C\$.
# Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins.
* Assume only valid input will be given.
* Input and output may assume whatever form is most convenient. This can include outputting the elements of \$C\$ in any order, because \$C\$ strictly increases and so the actual order of the elements is trivially found by sorting them.
* Terms whose combinations evaluate to zero, e.g. \$C\_2\$ and \$C\_1\$ in the example, cannot be neglected in output.
* A program should theoretically work for arbitrarily large values of \$m\$ and \$r\$, but is still acceptable if it is limited by memory constraints.
# Test Cases
Here \$m\$ is the first number and \$r\$ is the second, and the output begins with \$C\_1\$.
```
In: 19 4
Out: 0 1 4 6
In: 0 4
Out: 0 1 2 3
In: 40000 6
Out: 6 8 9 11 12 20
In: 6 6
Out: 1 2 3 4 5 6
In: 6 5
Out: 0 1 2 3 6
In: 6 20
Out: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17 18 19 20 (note 14 is skipped)
In: 6 1
Out: 6
```
[Answer]
# JavaScript (ES6), ~~95 93 86~~ 82 bytes
Expects `(r)(m)`.
```
r=>F=(m,x=r)=>r?(g=k=>!k||g(--k)*(k-x)/~k)(r)>m?[...F(m-g(r--,--x)),x]:F(m,x+1):[]
```
[Try it online!](https://tio.run/##bc@7jsIwEIXhnqc4dDNLnHhCYi6SQ5eXQBSIS7RrQpBBKAXi1bNeoIGNGxf@9Ov4Z31dnzf@@3RRx2a76/a287YoLdVRaz3bwi@oss4WQ3e7VaSU4y9yquXk7pg8F/ViGcdxSbWqyCsVqfDGUbual3@JkfB8ueo2zfHcHHbxoaloT8iYAMiMGUkCDUEGM/hAhinT4TyRwRQziEBSpLrHhmC4HlaQYhyS@f9o/gb1i36yVPeyRxGT5xL9GiNjSA4xkAlkGj7VM0/ecqb7BQ "JavaScript (Node.js) – Try It Online")
## How?
### Helper function
The helper function \$g\$ is used to compute:
$$\binom{x}{r}=\frac{x(x-1)\dots(x-r+1)}{r!}=\prod\_{k=1}^{r}\frac{x-k+1}{k}$$
```
(g = k => // g is a recursive function taking k
!k // if k = 0, stop the recursion and return 1
|| // otherwise:
g(--k) // decrement k and do a recursive call with the updated value
* (k - x) // multiply the result by k - x
/ ~k // divide by -k - 1
// which is equivalent to g(k - 1) * (x - k + 1) / k
)(r) // initial call to g with k = r
```
### Main function
```
r => // r = requested number of combinations
F = (m, x = r) => // F is a recursive function taking the target number m
// and a counter x, initialized to r
r ? // if r is not equal to 0:
g(r) > m ? // if C(x, r) is greater than m:
[ ...F( // append the result of a recursive call to F:
m - g(r--, --x) // with m - C(x - 1, r) and r - 1
), // end of recursive call
x // append x (which was decremented above)
] //
: // else:
F(m, x + 1) // increment x until C(x, r) > m
: // else:
[] // stop the recursion
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞<æIù.ΔācOQ
```
Inputs in the order \$r,m\$.
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8m8PLPA/v1Ds35Uhjsn/g//8mXIaWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaNj/Rx3zbA4vizi8U@/clCONyf6Rgf9rdf5HRxta6pjE6ihEmxgAgY4ZiGkGo0whlJEBhDYEUYbmOsaxsQA).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,4,5,...]
< # Decrease it by 1 to include 0: [0,1,2,3,4,...]
æ # Get the powerset of this infinite list
Iù # Only leave sublists of a size equal to the first input `r`
.Δ # Find the first list which is truthy for:
ā # Push a list in the range [1,length] (without popping the list itself)
c # Get the binomial coefficient of the values at the same indices in the lists
O # Sum those
Q # And check if it's equal to the (implicit) second input `m`
# (after which the found list is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly)
I feel there may well be shorter, possibly by first creating an outer-product using the binomial function, \$m\$`cþ`\$r\$.
```
»Żœc⁸cJ$S⁼ɗƇ
```
A full-program accepting \$r\$ and \$m\$ which prints the result.
(Or a dyadic Link yielding a list containing the unique result.)
**[Try it online!](https://tio.run/##ASIA3f9qZWxsef//wrvFu8WTY@KBuGNKJFPigbzJl8aH////NP85 "Jelly – Try It Online")**
### How?
```
»Żœc⁸cJ$S⁼ɗƇ - Main Link: r, n
» - maximum (r,n)
Ż - zero range -> [0,1,2,...,max(r,n)]
⁸ - chain's left argument, r
œc - all (r-length) choices (of the zero range)
Ƈ - filter keep those for which:
ɗ - last three links as a dyad - f(selection, n)
$ - last two links as a monad - g(selection)
J - range of length -> [1,2,...,r]
c - binomial (vectorises) [s1C1, s2C2,...,srCr]
S - sum
⁼ - equals (n)?
- implicit print (a list containing a single element prints that element)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~125~~ ~~121~~ ~~114~~ ~~111~~ ~~108~~ 107 bytes
```
import math
c=math.comb
f=lambda n,r,k=0:n and(n<c(k+1,r)and f(n-c(k,r),r-1)+[k]or f(n,r,k+1))or[*range(r)]
```
[Try it online!](https://tio.run/##Xc1BDoIwEAXQPafosiPFtIpEjZyEsChFhJROm0k3nr6WhYk4m5/3k58J7zh7PF8DpbS44Ckyp@NcmHaLo/FuKKZ21W4YNUNBwrbyjkzjyPFhuC2VIMhiE8cqO0tQpaDsbO9pa7dNqQA8dQfS@Hpygj4FWjDyiaubqAGKL2uZTzQ/TfOny04nuWN@kz4 "Python 3.8 (pre-release) – Try It Online")
Explanation: Start from `k=0` and keep increasing `k` as long as `comb(k, r)` does not exceed `n`. Update `n` accordingly. Once the current value of `n` is 0, simply return the first `r` integers starting from 0.
[Answer]
# [R](https://www.r-project.org/), ~~98~~ 96 bytes
```
s=function(m,r,j=choose(1:(m+r),r))if(r)`if`(!m,1:r-1,c(s(m-max(j[j<=m]),r-1),max(which(j<=m))))
```
[Try it online!](https://tio.run/##bY7RSsNAFETf/YoRX@7iDeykybYp5ktErISEbGAb2K20fx@TRsFa53HmMDNxavpxTO17aqNvUz2luvs8Nic/HiVo1KFec@FewnM0Go3xnURz8N1BHoNyHzNqI0lCFj4uMrwOL3V4m8GMRhfn3Puml8U1s273hJUWBk@wIAq4h9u0sLPULYDDDhVIMEdu/3BuZYgcm7mmvCtyWv6sLMh9nNvf@bUC23XSfq9yA5agA7fgDqz@@8Hr1@kL "R – Try It Online")
Commented:
```
choose_series=
s=function(m,r, # recursive function s
j=choose((m+r):1,r)) # j = all relevant values of choose(c,r)
if(r) # if r==0 don't return anything else
`if`(!m, # if m==0 ...
1:r-1, # ...just return the remaining r-series minus 1
c( # otherswise return ...
s( # recursive call to self, with
m- # new m = current m minus ...
max(j[j<=m]) # ... highest value of j less than or equal to m
,r-1), # new r = r-1;
((m+r):1)[j<=m][1] # appended to the highest value of c for which...
) # ...j is less than or equal to m
)
```
(but, frustratingly, my approach here still comes-out longer than an **[84 byte](https://tio.run/##bY5LCoNAEET3OUVBNjOkhSk/oy7MVSKIEhdGmEnA2xs/EWJML3rR9bqq3Fjd@97XN1@7tvbF6Ivm9aiebf9QnTgZCqfbRjldtk2pVlYN4vS1k0p51QXbLeB0FRdQyzAvv/5fqPU@QzGXWOMMAyKGPe3V2EwjdgYsMuQgwRCh@eHsyhAhoskmORhZSbaUGTnKofnWFwuka6T5pDICE9CCKZiB@b8eXLqObw)** port of [Arnauld's approach](https://codegolf.stackexchange.com/questions/209885/combinatorial-decomposition/209893#209893)...)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 92 bytes
```
(S=Select)[Subsets[S[0~Range~Max[a=#,b=#2],#~(B=Binomial)~b<a+1&],{b}],Tr@B[#,Range@b]==a&]&
```
[Try it online!](https://tio.run/##XcuxCsIwFIXh3acQAqXFO7SlFgQvlO6CGLdwh5sSaqCp0EYQxLx6FAexnu078Dv2F@PY245jjzGVKM1gOp8pedOz8bOSKg8nHnsTDnxXjAI0ipJAhLTF1o5XZ3nIgt7zpkgIHvpJcJ6aVgn4ZI0mRE4oicfJjn7d9KrYQUWrL6v8Pah/nvpP24XKfMGCYnwB "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
NθF⮌ENE⊕ιλ«≔Π⊕ιηW¬›Π⊕ι×θη≦⊕ι≧⁻÷ΠιηθI⟦⊟ι
```
[Try it online!](https://tio.run/##dY8xC8JADIXn9lfcmEIFB3FxEgXpoBRxE4ezjTbQ3tW7tA7ibz9TFRHBjO@9vC8pKu0Kq@sQMtN2vOmaIzq4JLP4ZJ2CLfboPMJat/AdSFL1kgqHDRrGEki0OpFRtziae09nA7mzZVfwT06ClQCia0U1KthYhpVDzdL7d2FHDXq4DJsDQuBvxFcyVTTUfrwtnSuGNZnOpyozvKSeSvww6HlHqoZno9yRYVhoz7DPbSvmIRH9HsJkLBNPw6ivHw "Charcoal – Try It Online") Link is to verbose version of code. Outputs in descending order. Explanation:
```
Nθ
```
Input `m`.
```
F⮌ENE⊕ιλ«
```
Loop over the `n` ranges `[0..n-1]`, `[0..n-2]`, ... `[0, 1]`, `[0]`. These represent `Cᵢ` for `i` from `n` down to `1` but also the product calculates `Cᵢ!/(Cᵢ-i)!` for the binomial term.
```
≔Π⊕ιη
```
Take the product of the incremented range, which is just `i!`. This is used to complete the calculation of the binomial term.
```
W¬›Π⊕ι×θη≦⊕ι
```
Increment the range, effectively incrementing `Cᵢ`, until the next binomial term would exceed `m`. (I don't often get to increment a whole range in Charcoal!)
```
≧⁻÷Πιηθ
```
Subtract the current binomial term from `m`.
```
I⟦⊟ι
```
Output `Cᵢ` (which is always the last element in the range) on its own line.
] |
[Question]
[
**Introduction**
On 30 May 2020, NASA and SpaceX launched a crewed rocket to the international space station on the [SpaceX Demo 2](https://en.wikipedia.org/wiki/Crew_Dragon_Demo-2) mission. This is the first time humans have been launched into orbit from American soil since the retiring of the [Space Shuttle](https://en.wikipedia.org/wiki/Space_Shuttle) in 2011, and the first time ever that a private company has launched astronauts into orbit. The rocket bore the iconic [NASA worm logo](https://en.wikipedia.org/wiki/NASA_insignia), the first time this logo has been used since 1992. Let's celebrate NASA and SpaceX's achievement by drawing the worm logo.
I looked on the internet for a specification of this logo. The best I could find was on [Reddit](https://www.reddit.com/r/logodesign/comments/dme37b/nasa_logo_design_guidelines/). However there are a number of issues with this version. For example the thickness of vertical and curved lines is defined as 1 but for horizontal lines it is 0.95 and there is no specification of how to transition between the two thicknesses.
**Challenge**
Draw the simplified version of the NASA worm logo defined in the SVG below.
Some notes on the design:
* All parts of the worm are 100 units wide.
* All diagonal lines have a slope of 24/7. This takes advantage of the pythagorean triple `24^2 + 7^2 = 25^2` to ensure accurate and consistent positions of the thickness of the worm and the beginnings and endings of arcs while using only integer coordinates.
* As the vertical height of the arms of the A's are not multiples of 24, the `x` coordinates of the bottoms of the A are not integers, but they are integer multiples of `1/6`.
* The S is 500 units high, from `y=100` to `y=600`. The curved parts of the S have internal and external radii of 50 and 150.
* The internal and internal radii of the curved parts of the N and A's are 25 and 125. The `y` coordinates of the centres of these arcs are `y=215` and `y=485`. This means that the tops and bottoms of the arcs extend above and below the top and bottom of the S, specifically to `y=90` and `y=610`. This is similar to the official logo.
* The ends of the N terminate at `y=100 and y=600.` Similarly, the ends of the A's terminate at `y=600`.
* There is an overlap region between the first A and the S. The length of the upper and lower arms of the S is chosen to be 231.67 units so that this overlap region is triangular. The top of the lower arm of the S meets the A at `1043.33,600`
* In addition to the SVG script, A PNG image (not perfectly to scale) is given with annotations of the coordinates of all parts of the logo: all four coordinates of each straight section and the centre and radius of each curved section. Note that because of the way SVG defines arcs, the coordinates of the centres of the curved sections do not appear in the SVG script. Curved sections are shown in black and straight sections are shown in red, with the exception of the lower arm of the S, which is shown in blue to distinguish it from the part of the A which it overlaps.
**PNG**
[](https://i.stack.imgur.com/Q8A46.png)
**SVG**
```
<svg xmlns="http://www.w3.org/2000/svg" viewbox=0,0,2000,700>
<path fill="red" d="M110,600 L110,215 A125,125,0,0,1,355,180 L446,492 A25,25,0,0,0,495,485 L495,100 L595,100 L595,485 A125,125,0,0,1,350,520 L259,208 A25,25,0,0,0,210,215 L210,600"/>
<path fill="red" d="M587.5,600 L710,180 A125,125,0,0,1,950,180 L1072.5,600 L968.33,600 L854,208 A25,25,0,0,0,806,208 L691.67,600" />
<path fill="red" d="M1043.33,500 L1275,500 A50,50,0,0,0,1275,400 L1175,400 A150,150,0,0,1,1175,100 L1406.67,100 L1406.67,200 L1175,200 A50,50,0,0,0,1175,300 L1275,300 A150,150,0,0,1,1275,600 L1043.33,600"/>
<path fill="red" d="M1407.5,600 L1530,180 A125,125,0,0,1,1770,180 L1892.5,600 L1788.33,600 L1674,208 A25,25,0,0,0,1626,208 L1511.67,600" />
</svg>
```
**Rules**
The logo shall be in a single arbitrary colour on a distinctly coloured background.
The accuracy of the logo shall be within +/- 2 units of the specification given in this question.
It is not essential to use the coordinate system used in the specification given in this question. The logo may be rescaled, and different amounts of whitespace may be added above, below, left and right, so long as the logo can be visualized easily with free and easily available software. The logo may not be rotated.
The logo may be drawn filled, or as an outline. The first A and the S overlap slightly. If drawn as an outline, it is preferred that the lines at the overlap of these two letters are omitted, so that the A and S form a single continuous outline. It is however permitted to include the complete outline of the A and/or the complete outline of the S, with the shape specified in the PNG and SVG in the question. No other extraneous lines are permitted.
Any pre-existing graphics format is acceptable provided it can be viewed with free and easily available software. Any means of output accepted by standard rules on this site is acceptable, inlcuding viewing on the screen, output to a file, or (if applicable) as a returned value from a function call. Please Include instructions on how to view your output in your answer. Your program or function should take no input.
It is not acceptable to use a font with letters of the correct or similar shape to print "NASA", with or without modification. (In practice this is unlikely to be an issue, because although there are similar fonts, I think it's very unlikely that the letters match the proportions specified in this question.)
This is codegolf. Shortest code wins.
[Answer]
## SVG (HTML 5), 370 bytes
```
<svg viewbox=0,0,240,64 fill=none stroke=red stroke-width=12.5><path d=M82,62V11M180.4,62V11 transform=skewX(-17) /><path d=M90.8,62V11M189.2,62V11 transform=skewX(17) /><path stroke-width=12 d=M6,62V15.8A9,9,0,0,1,23.6,13.3L34.6,50.7A9,9,0,0,0,52.2,48.2V2M78,13.3a9,9,0,0,1,16.8,0M112,56H139.8a12,12,0,0,0,0,-24h-12A12,12,0,0,1,127.8,8H155.6M176.4,13.3a9,9,0,0,1,16.8,0
```
Based on my optimised answer, but drawing the logo as a stroked path rather than an outline, which takes a few more bytes to set up but requires fewer drawing operations. Edit: Original version was clipped incorrectly. Hopefully this one is nearer to the original.
[Answer]
# HTML / JS, 406 bytes
A RegPack'ed version of the reference SVG with slightly rounded values and uppercase keywords so that the full range `[Y-k]` is available for compression.
```
<script>for(_='5,k00jjLi9k1i5h9k485gi1f1f407,e15d7kc0,bbbab180`jA5b5aa1_,6^,208]jAdbdab1,1[A2k2kabZA12k12ka1,Y<SVG VIEWBOX=a2jb7j><PATH D=M110^f1b2dY35k180L446,492Z4gL4hhgY35b520L259]Z21b2dL210^jM587^i71`Y95`L1072^i968^i854]Z806]L692^jM1043,5f2c5_2c4f1c4[1cee2f1c2_1c3f2c3[275^f043^jM1407^id3`Y177`L1892^f788^f674]Z1626]Ld12^j>';G=/[Y-k]/.exec(_);)with(_.split(G))_=join(shift());document.write(_)</script>
```
[Answer]
# Wolfram Language (Mathematica), 342 bytes
```
a=#~Partition~2&;b=ToCharacterCode;c=Disk;d=Pi/2;e=ArcTan[24/7];Graphics[Thread/@{Cuboid@@@a[2a@b@"ê?êįĦHș?ʾʂ·ʾ{ʂį̍ó"],Parallelogram[a@b@"ĦfɃЌ؛ߤ",a@a@b@"ĒȭĒĨʍĒʍĒĨʍĒʍ"-149],c[f=6a@b@"NINĵN",150,{{d-e,2d},{-d-e,0},g={d-e,d+e},g}],c[h=6a@b@"êÖG",180,a@{-d,d,d,3d}],White,f~c~30,h~c~60}]&
```
Pure function. Takes no input and returns a `Graphics` object as output. In a Mathematica notebook, the output is automatically rendered to the screen. It can be seen in [this](https://www.wolframcloud.com/obj/2de411c7-78d4-4091-ab5e-ed65f77003c9) Wolfram Cloud notebook; a screenshot is shown below.

Some 1-pixel gaps may be visible, but those are just artifacts of the vector graphics. Also, several unprintable characters are used for compression, so here's a UTF-8 hexdump:
```
00000000: 613d 237e 5061 7274 6974 696f 6e7e 3226 a=#~Partition~2&
00000010: 3b62 3d54 6f43 6861 7261 6374 6572 436f ;b=ToCharacterCo
00000020: 6465 3b63 3d44 6973 6b3b 643d 5069 2f32 de;c=Disk;d=Pi/2
00000030: 3b65 3d41 7263 5461 6e5b 3234 2f37 5d3b ;e=ArcTan[24/7];
00000040: 4772 6170 6869 6373 5b54 6872 6561 642f Graphics[Thread/
00000050: 407b 4375 626f 6964 4040 4061 5b32 6140 @{Cuboid@@@a[2a@
00000060: 6240 2203 c3aa 3f03 c3aa c4af c4a6 48c8 b@"...?.......H.
00000070: 993f cabe 03ca 82c2 b7ca be7b ca82 c4af .?.........{....
00000080: cc8d c3b3 225d 2c50 6172 616c 6c65 6c6f ...."],Parallelo
00000090: 6772 616d 5b61 4062 4022 c4a6 66c9 8306 gram[a@b@"..f...
000000a0: d08c 06d8 9b06 dfa4 0622 2c61 4061 4062 .........",a@a@b
000000b0: 4022 c492 c295 1ec8 adc4 92c2 95c4 a8ca @"..............
000000c0: 8dc4 92c2 9502 ca8d c492 c295 c4a8 ca8d ................
000000d0: c492 c295 02ca 8d22 2d31 3439 5d2c 635b ......."-149],c[
000000e0: 663d 3661 4062 4022 1a4e 4918 c291 4ec4 f=6a@b@".NI...N.
000000f0: b54e 222c 3135 302c 7b7b 642d 652c 3264 .N",150,{{d-e,2d
00000100: 7d2c 7b2d 642d 652c 307d 2c67 3d7b 642d },{-d-e,0},g={d-
00000110: 652c 642b 657d 2c67 7d5d 2c63 5b68 3d36 e,d+e},g}],c[h=6
00000120: 6140 6240 22c3 aa1f c396 4722 2c31 3830 a@b@".....G",180
00000130: 2c61 407b 2d64 2c64 2c64 2c33 647d 5d2c ,a@{-d,d,d,3d}],
00000140: 5768 6974 652c 667e 637e 3330 2c68 7e63 White,f~c~30,h~c
00000150: 7e36 307d 5d26 ~60}]&
```
[Answer]
# [PostScript](https://en.wikipedia.org/wiki/PostScript), 325 bytes
Code (compressed version):
```
<</M{moveto}/L{lineto}>>begin 20 setlinewidth 0 50 translate 32 0 M 47 77 15 180 16.3 arcn 94 23 15 196.3 0 arc 109 100 L 126.4 -4.8 M 166 77 15 163.7 16.3 arcn 201.2 10 L 255 30 20 -90 90 arc 235 70 20 -90 90 arcn 281.4 90 L 290.6 -4.8 M 330 77 15 163.7 16.3 arcn 369.4 -4.8 L stroke 1 setgray 110 0 280 -9 rectfill showpage
```
Code (uncompressed version):
```
% define some short-named procedures for later use
<<
/M {moveto}
/L {lineto}
>> begin
% to get shorter code we use stroke (with a big linewidth) instead of fill
20 setlinewidth
0 50 translate % we need some empty space at the bottom
% draw N
32 0 M
47 77 15 180 16.3 arcn
94 23 15 196.3 0 arc
109 100 L
% draw A
126.4 -4.8 M % descender will be cut off later
166 77 15 163.7 16.3 arcn
201.2 10 L
% draw S
% no moveto here, so we get a connected line
255 30 20 -90 90 arc
235 70 20 -90 90 arcn
281.4 90 L
% draw A
290.6 -4.8 M % descender will be cut off later
330 77 15 163.7 16.3 arcn
369.4 -4.8 L % descender will be cut off later
stroke
1 setgray % white
110 0 280 -9 rectfill % overwrite the excess bottoms of A
showpage
```
Result:
[](https://i.stack.imgur.com/skdrg.png)
[Answer]
# PostScript, ~~259~~ 249 bytes
```
[/M{moveto}/L{lineto}/a{arcn}/m{77 15 163.7 16.3 a}/c{20 -90 90}>>begin
20 setlinewidth
32 0 M 47 77 15 180 16.3 a 94 23 15 196.3 0 arc 109 100 L
126.4 -4.8 M 166 m 201.2 10 L 255 30 c arc 235 70 c a 281.4 90 L
290.6 -4.8 M 330 m 369.4 -4.8 L
stroke
```
A shortened version of Thomas Fritsch's answer with more defs to save bytes, and flush with the bottom of the page so the final crop could be removed without changing the appearance.
(This should be a comment on Thomas's answer, but I can't comment yet).
[Answer]
## SVG (HTML5), ~~442~~ ~~440~~ 438 bytes
```
<svg viewbox=0,0,240,64><path fill=red d=M13.2,62V15.8A15,15,0,0,1,42.6,11.6L53.5,49a3,3,0,0,0,5.9,-.8V2h12V48.2A15,15,0,0,1,42,52.4L31.1,15a3,3,0,0,0,-5.9,.8V62m45.3,0L85.2,11.6a15,15,0,0,1,28.8,0L128.7,62H116.2L102.5,15a3,3,0,0,0,-5.8,0L83,62M125.2,50H153a6,6,0,0,0,0,-12H141A18,18,0,0,1,141,2H168.8V14H141a6,6,0,0,0,0,12h12A18,18,0,0,1,153,62H125.2m43.7,0L183.6,11.6a15,15,0,0,1,28.8,0L227.1,62H214.6L200.9,15a3,3,0,0,0,-5.8,0L181.4,62
```
Just an optimisation of the SVG given in the question. There's a better way of doing this!
] |
[Question]
[
Interleaved sequences represent an arbitrary merging of some number of sequences.
An interleaved sequence can be made by appending elements to a list one by one from some number of lists, choosing the next element from some list each time. Therefore, an interleaved sequence will contain exactly the same elements of all the lists combined, in an order consistent with all lists.
The only interleaving of 1 list is that same list.
# Challenge
Your challenge is to create a function/program that takes an arbitrary number of sequences and outputs all possible interleavings of those sequences.
# Examples
```
Input: [1, 2], [3, 4]
Output:
[1, 2, 3, 4]
[1, 3, 2, 4]
[1, 3, 4, 2]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 4, 1, 2]
Input: [1, 2, 3, 4, 5]
Output:
[1, 2, 3, 4, 5]
Input: []
Output:
[]
Input: <nothing>
Output:
[]
(also acceptable)
Input: <nothing>
Output: <nothing>
Input: [1, 2, 3], [4, 5]
Output:
[1, 2, 3, 4, 5]
[1, 2, 4, 3, 5]
[1, 2, 4, 5, 3]
[1, 4, 2, 3, 5]
[1, 4, 2, 5, 3]
[1, 4, 5, 2, 3]
[4, 1, 2, 3, 5]
[4, 1, 2, 5, 3]
[4, 1, 5, 2, 3]
[4, 5, 1, 2, 3]
Input: [1, 2], [3, 4], [5, 6]
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 5, 4, 6]
[1, 2, 3, 5, 6, 4]
[1, 2, 5, 3, 4, 6]
[1, 2, 5, 3, 6, 4]
[1, 2, 5, 6, 3, 4]
[1, 3, 2, 4, 5, 6]
[1, 3, 2, 5, 4, 6]
[1, 3, 2, 5, 6, 4]
[1, 3, 4, 2, 5, 6]
[1, 3, 4, 5, 2, 6]
[1, 3, 4, 5, 6, 2]
[1, 3, 5, 2, 4, 6]
[1, 3, 5, 2, 6, 4]
[1, 3, 5, 4, 2, 6]
[1, 3, 5, 4, 6, 2]
[1, 3, 5, 6, 2, 4]
[1, 3, 5, 6, 4, 2]
[1, 5, 2, 3, 4, 6]
[1, 5, 2, 3, 6, 4]
[1, 5, 2, 6, 3, 4]
[1, 5, 3, 2, 4, 6]
[1, 5, 3, 2, 6, 4]
[1, 5, 3, 4, 2, 6]
[1, 5, 3, 4, 6, 2]
[1, 5, 3, 6, 2, 4]
[1, 5, 3, 6, 4, 2]
[1, 5, 6, 2, 3, 4]
[1, 5, 6, 3, 2, 4]
[1, 5, 6, 3, 4, 2]
[3, 1, 2, 4, 5, 6]
[3, 1, 2, 5, 4, 6]
[3, 1, 2, 5, 6, 4]
[3, 1, 4, 2, 5, 6]
[3, 1, 4, 5, 2, 6]
[3, 1, 4, 5, 6, 2]
[3, 1, 5, 2, 4, 6]
[3, 1, 5, 2, 6, 4]
[3, 1, 5, 4, 2, 6]
[3, 1, 5, 4, 6, 2]
[3, 1, 5, 6, 2, 4]
[3, 1, 5, 6, 4, 2]
[3, 4, 1, 2, 5, 6]
[3, 4, 1, 5, 2, 6]
[3, 4, 1, 5, 6, 2]
[3, 4, 5, 1, 2, 6]
[3, 4, 5, 1, 6, 2]
[3, 4, 5, 6, 1, 2]
[3, 5, 1, 2, 4, 6]
[3, 5, 1, 2, 6, 4]
[3, 5, 1, 4, 2, 6]
[3, 5, 1, 4, 6, 2]
[3, 5, 1, 6, 2, 4]
[3, 5, 1, 6, 4, 2]
[3, 5, 4, 1, 2, 6]
[3, 5, 4, 1, 6, 2]
[3, 5, 4, 6, 1, 2]
[3, 5, 6, 1, 2, 4]
[3, 5, 6, 1, 4, 2]
[3, 5, 6, 4, 1, 2]
[5, 1, 2, 3, 4, 6]
[5, 1, 2, 3, 6, 4]
[5, 1, 2, 6, 3, 4]
[5, 1, 3, 2, 4, 6]
[5, 1, 3, 2, 6, 4]
[5, 1, 3, 4, 2, 6]
[5, 1, 3, 4, 6, 2]
[5, 1, 3, 6, 2, 4]
[5, 1, 3, 6, 4, 2]
[5, 1, 6, 2, 3, 4]
[5, 1, 6, 3, 2, 4]
[5, 1, 6, 3, 4, 2]
[5, 3, 1, 2, 4, 6]
[5, 3, 1, 2, 6, 4]
[5, 3, 1, 4, 2, 6]
[5, 3, 1, 4, 6, 2]
[5, 3, 1, 6, 2, 4]
[5, 3, 1, 6, 4, 2]
[5, 3, 4, 1, 2, 6]
[5, 3, 4, 1, 6, 2]
[5, 3, 4, 6, 1, 2]
[5, 3, 6, 1, 2, 4]
[5, 3, 6, 1, 4, 2]
[5, 3, 6, 4, 1, 2]
[5, 6, 1, 2, 3, 4]
[5, 6, 1, 3, 2, 4]
[5, 6, 1, 3, 4, 2]
[5, 6, 3, 1, 2, 4]
[5, 6, 3, 1, 4, 2]
[5, 6, 3, 4, 1, 2]
```
# Rules
* Standard loopholes forbidden (duh)
* Input may be taken in any reasonable format, e.g. a list of lists, vararg list of lists, parameter lists, etc... as long as it is unambiguous where lists begin and end.
* Output may be in any reasonable format, so long as it is clear where lists begin and end. Valid outputs include, but are not necessarily limited to:
+ stdout, with one list per line
+ A list of lists
+ An iterator over lists (can be implemented with a generator if your language has them)
* The order of the yielded interleavings does not matter, however, there should not be any repeated interleavings.
* To simplify repeat detection, you may assume that all elements across all input sequences are unique.
* If given no lists as input, both the empty list and no output are valid outputs.
* Types of the elements in the sequences is irrelevant. (e.g. they could all be one type or a mishmash of types, whichever is more convenient in your language)
* Your program/function must be guaranteed to terminate in a finite amount of time.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code for each language wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~103~~ ~~92~~ ~~79~~ 78 bytes
```
def f(A,c=[]):
if not[f([b[b==x:]for b in A],c+x[:1])for x in A if x]:print c
```
[Try it online!](https://tio.run/##PYs7DsMgEER7n2I7jLKNfymQKHyO1RaBZBUasCwKcnoCkZVqNG/mHZ/8TnGu9fkSkHFHb4m1GSAIxJRJRnLkrC2GJZ3gIETYGf2tkJlYd1Z@rAuFzXGGmMHX5tGEMyOph0LlFLMeOrzyau2CC6648R9Ak4AWhLXnhnBvW/0C "Python 2 – Try It Online")
Or:
# [Python 3](https://docs.python.org/3/), 73 bytes
```
def f(A,c=[]):[f([b[b==x:]for b in A],c+x[:1])for x in A if x]or print(c)
```
[Try it online!](https://tio.run/##PYsxDsMgEAT7vOI6QLnGwU6BROF3nK4wJKfQYMtyQV5PwLJSjXZ2d/senzXbWl9vAdEzRk9sHImmQMH74ljWHQKkDDNjvBdyA5vuyukgCRRucdtTPnQ0tV1pwAcjqUWhCorZ3Lq8eKU2QYsjTvwX0E5AFmHsnBCeras/ "Python 3 – Try It Online")
-1 by replacing `[x[0]]` with `x[:1]` as per [xnor](https://codegolf.stackexchange.com/users/20260/xnor)
-13 bytes by ~~shamelessly stealing~~ expanding upon `[b[b==x:]for b in A]` as suggested by [Neil's](https://codegolf.stackexchange.com/users/17602/neil) answer instead of longer `enumerate` approach.
Takes a list of lists `A` as input. If all elements of `A` are empty, then the list evaluated in the `if` will be empty, so we have reached the end of the recursion and can `print`. Otherwise, we have a list of one or more `None`'s; and we recurse.
[Answer]
# [Haskell](https://www.haskell.org/), ~~84~~ ~~77~~ 76 bytes
```
foldl((.(!)).(>>=))[[]]
a#b=(b:)<$>a
x@(a:c)!y@(b:d)=x!d#b++c!y#a
a!b=[a++b]
```
Thanks to @Lynn for 7 bytes and @user9549915 for a byte!
[Try it online!](https://tio.run/##Dcg9DsIgGADQvaeA0IEvYBN/h0ZIL@AJkJgPEG2klViH9vJilze8J06ve0olqmuJ7xQS5w2nAA3XWgEYY22FzCnuWjjXGqu549h6oEu3VgA108CcEJ4uDCukThkUwtkyYD8SRQbMlxvJn378kppEYsxW7qw0e3lYPcqTteXnY8LHVDY@5z8 "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
FŒ!fЀ⁼ṛɗÐf
```
[Try it online!](https://tio.run/##y0rNyan8/9/t6CTFtMMTHjWtedS45@HO2SenH56Q9v9wO1DAHYizHjXMObRNFwEObXvUMPf//2guhehoQx0Fo1gdhWhjHQWT2FgdmJCOAkhAR8EUIoaQgKsF0qY6CmYg@VgA "Jelly – Try It Online")
### How it works
```
FŒ!fЀ⁼ṛɗÐf Main link. Argument: A (array of arrays)
F Flatten A.
Œ! Take all permutations.
ɗÐf Filter by the chain to the left, keeping only permutations for which
it returns a truthy value.
fЀ Intersect the permutation with each array in A.
⁼ṛ Test if the result is equal to A.
```
[Answer]
# Ruby, 66 bytes
```
f=->a,*p{(a-=[[]])[0]?a.flat_map{|b|h,*t=b;f[a-[b]+[t],*p,h]}:[p]}
```
If there are no non-empty sequences, return an empty sequence. Otherwise, for each non-empty sequence, recurse with the first element removed then add it onto the beginning of each result. The implementation uses the assumption that elements are guaranteed to be globally unique, otherwise `a-[b]` could potentially remove more than 1 sequence from the recursive call. Although on reflection, maybe that'd actually be the right behavior to avoid duplicate output.
Example IO:
`f[[[1,2],[3,4]]]
=> [[1, 3, 2, 4], [1, 3, 4, 2], [1, 2, 3, 4], [3, 1, 4, 2], [3, 1, 2, 4], [3, 4, 1, 2]]`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~76~~ ~~75~~ 71 bytes
```
Cases[Permutations[Join@@#],x_/;And@@OrderedQ/@(x~Position~#&/@#&/@#)]&
(* or *)
Cases[Join/*Permutations@@#,x_/;And@@(x~Position~#&/@#&/*OrderedQ/@#)]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d85sTi1ODogtSi3tAQomp9XHO2Vn5nn4KAcq1MRr2/tmJfi4OBflJJalJoSqO@gUVEXkF@cCVJYp6ym7wDGmrFq/zWtA4oy80octNL0Haq5uKqrDXWManWqjXVMamt1IFwdIEfHFMIFkzAJqDqdalMds9paLi6u2v8A "Wolfram Language (Mathematica) – Try It Online")
Naive approach: find all permutations that are interleavings of the input.
### Explanation
```
Permutations[Join@@#]
```
Flatten `<input>` and find all of its permutations.
```
Cases[ ... ,x_/; ...]
```
Find all elements `x` such that...
```
(x~Position~#&/@#&/@#)
```
Replace all of the items in depth-2 of `<input>` with their respective position in `x`.
```
And@@OrderedQ/@ ...
```
Check whether all depth-1 lists are ordered (i.e. in increasing order).
### Actual implementation of interleaving, 117 bytes
```
Cases[{}~(f=ReplaceList[#2,{{a___,{b_,c___},d___}/;b>0:>#~Join~{b}~f~{a,{c},d},_:>#}]&)~#,{___},{Tr[1^(Join@@#)]+1}]&
```
[Try it online!](https://tio.run/##NYtPC4JAEEfv@zUWQmvAtD@HRBG6RYeIbmLLurkkpIXubZj96rZqXX7M471ppHlWjTS1koNOvOEo@6rPkaynk2v1eUlVneve5DwCRCmEACwFKHcQPMYN4jJdH1JuT@@6tViS1RYloHKeQDhDxcK3HHD6wVuXh3dvjLOM@8UqdHrw40tXtyZb6iBDxhBDiFy7gS0RzAgOYDfjtH/x6wB3sCdijNHwBQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~87~~ 84 bytes
```
f=lambda a:any(a)and[b[:1]+c for b in a if b for c in f([c[c==b:]for c in a])]or[[]]
```
[Try it online!](https://tio.run/##PYoxDoQgEEWv8kuJNLq7FiScZDLFgCGSrIMhNp4epbF6//284zq3onNryf9lD6tAnOg1iBFdKZCbeIxIpSIgKwQ5Pat77J4GihS9D47fT9hwqUTM7ahZzx7RZDGzBX0svp0/i4XZtBs "Python 2 – Try It Online") Port of my JavaScript answer. Edit: Saved 3 bytes thanks to @ChasBrown.
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
f l=max[[]][h:y|h:t<-l,y<-f$t:filter(/=h:t)l]
```
[Try it online!](https://tio.run/##Dci9CsMgEADgvU9xQ4YETkrTn0Hikxw3SNAovYgYhwT67DVZvuELdvs6kdY8iFntTsRMQR@/oOukBI9J@a5qH6W60t/N1YNwK8YD0QNHRnri6/KNH@bbamMCA7nEVKGDXlxaaoCCUIb2n73YZWtqzvkE "Haskell – Try It Online")
Adapted from [Chas Brown's Python answer](https://codegolf.stackexchange.com/a/162502/20260).
The `max[[]]` is a trick to give a base case of `[[]]` when the input only contains `[]` elements. In that case, the list used for empty, recursing is empty, and `max[[]][]` gives `[[]]`.
When recursing, rather than selectively dropping the first element of the chosen list `h:t`, we make a new list with `t` at the front and `h:t` filtered out.
[Answer]
## JavaScript (Firefox 30-57), 92 bytes
```
f=a=>a.some(b=>b+b)?[for(b of a)if(b+b)for(c of f(a.map(c=>c.slice(c==b))))[b[0],...c]]:[[]]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-Q`, 14 bytes
```
c á f@e_XfZ eZ
c // Flatten the input into a single array
á // and find all permutations.
f // Then filter the results for items
@e_ // where for each original input
XfZ eZ // the ordering of the items is unchanged.
```
Takes input as an array of arrays. `-Q` makes the output preserve the array notation.
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.5&code=YyDhIGZAZV9YZlogZVo=&input=W1sxLCAyXSwgWzMsIDRdXQotUQ==)
[Answer]
**Scala:** (not intended to be minimal, more a clear reference resource)
```
object Interleave {
private def interleavePair[A](x: Seq[A], y: Seq[A]): Seq[Seq[A]] =
(x, y) match {
case (a +: c, b +: d) =>
interleavePair(x, d).map(b +: _) ++ interleavePair(c, y).map(a +: _)
case _ => Seq(x ++ y)
}
def interleave[A](ssa: Seq[Seq[A]]): Seq[Seq[A]] =
ssa.foldLeft[Seq[Seq[A]]](Seq(Seq.empty)) {
case (sssat, sa) => sssat.flatMap(interleavePair(sa, _))
}
}
object Main extends App {
import Interleave._
println(interleave(Seq()))
println(interleave(Seq(Seq(1, 2), Seq(3, 4))))
}
```
[Try it online!](https://tio.run/##dVHLasMwELznK@YoYWHo4xRIIcdCA4UegwkbeU0d/FAtEWxKvt2V5KQ4phUI7bKzszNaq6micWyPJ9YOr43jrmI6M75XK8B05ZkcI@cC5W/tncpuv81Ev8YHf/lIYbiFcgqmJMPGkwCi9wiJmpz@9MSIR5NlCEKyhlY4hjeX2LwsBoXeXKY1GRExB4kkWWJ04I8YmjDzGYdA6gWJPnQOU@0S7N3bCpaspTsDf9rxoLRoq/yNC7eflTMRpvibcm3cIOXCq/WNTsFStBmztKjI7bzuhSFLyru4SfVirwvaUdmAe8dNbrE1ZlpTWZu2m28vPVy317iqmXFHgTLy/lMM90HhUar4ZU8KzzI0XMbxBw "Scala – Try It Online")
] |
[Question]
[
# Background
[Stack Cats](https://github.com/m-ender/stackcats) is a reversible esoteric language made by Martin Ender. Each command in Stack Cats is either the inverse of itself (represented as a symmetric character, such as `-_:T|`), or has its inverse command (represented as the mirror image, such as `()` `{}` `[]` `<>`). **Stack Cats has a strong syntactic requirement that the whole program should be the mirror image of itself.** Note that this means any valid Stack Cats program is a [natural mirror-image ambigram](https://en.wikipedia.org/wiki/Ambigram).
Here is the whole command set of Stack Cats:
* Self-symmetric: `!*+-:=ITX^_|`
* Symmetric pairs: `()` `{}` `[]` `<>` `\/`
Any other characters are invalid; any input having a character not in the character set above should output false.
The language has additional constraint that `()` and `{}` pairs must be always balanced, but for the sake of simplicity, you don't have to check for this condition.
The following are some examples of a **valid Stack Cats program** (again, note that you don't check for balanced parens):
```
{[+]==[+]}
[)>^<(]
({T)}|{(T})
<(*]{[:!-_:>}<[<)*(>]>{<:_-!:]}[*)>
```
These are not:
```
b<+>d
())(
({[<++<]})
```
# Challenge
Write a program or function that determines if the given string is a valid Stack Cats program. **Your code should also be a natural mirror-image ambigram**, which means:
* Your code should be a mirror image of itself.
+ Your code may have one or more newlines, as long as the whole code, displayed naturally, is a mirror image of itself.
+ You can omit or add trailing whitespaces on each line, since it doesn't change the display.
+ Tab characters are not allowed since they have some ambiguity on display.
**Note:** your code does **not** have to be a valid Stack Cats program; it may contain certain extra characters that are not allowed in Stack Cats. (See below for the complete list.)
For example, the following two programs are symmetric (and thus a **valid submission**), while the third is not:
```
({bTd})
[<q|p>]
```
```
({bTd})
IXI
```
```
({bTd})
IXI
```
* Regarding "mirror symmetry", only Stack Cats-style vertical symmetry is considered (e.g. `({IH})` is not a valid submission, even though it has horizontal mirror symmetry).
* Your code can only contain these sets of characters, plus newline:
+ Self-symmetric: space (`0x20`) + `!"'*+-.8:=AHIMOTUVWXY^_ovwx|`
+ Symmetric pairs: `()` `/\` `<>` `[]` `bd` `pq` `{}`
The character set is chosen to be strictly symmetric or self-symmetric when displayed as code on SE.
# Input and Output
The input range is any **one-line string of printable ASCII characters**.
You can choose to take input as a string, a list of chars, or a list of ASCII values.
You can choose to output either:
* Any of the truthy/falsy values as defined by the language of your choice
+ The actual result values may differ between inputs (e.g. output 1 for a truthy input and 2 for another truthy one).
+ Swapping truthy and falsy values is not allowed.
* Any two constant values for true/false respectively
+ In this case, the result values should exactly be one of the two constant values.
You should specify your input method and output values in your submission.
# Winning Condition
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest bytes in each language wins.
# Notes
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden as usual.
* Of course you can solve this in Stack Cats, but the catch is that you can't use a flag that allows you to reduce your code size by half. And it's a seriously hard language to pick up. :P
[Answer]
## JavaScript (ES6), ~~487~~ ~~467~~ ~~378~~ ~~298~~ ~~292~~ ~~280~~ ~~266~~ 264 bytes
*Saved 14 bytes thanks to @Bubbler*
```
I=>(V=v=>!I[v]||((T=o=>[[]][+!!A[o]]||[(I[v]!=A[o]||A)[o^o<88/8]]+T(++o))(8-8)==I.pop())*V(++v))(V|(A='(){}[]<>\\/ !*+-:=ITX^_|'))//\\(('|_^XTI=:-+*! \//<>[]{}()'=A)|V)((v++)V*(()qoq.I==(8-8)((o++)T+[[8\88>o^o](A||[o]A=![v]I)]||[[o]A!!+][[]]<=o=T))||[v]I!<=v=V)<=I
```
Defines an anonymous function that takes an array of chars and returns the desired output. Output is truthy/falsy; usually `1`/`0`, but the empty string gives `true`.
## How?
The most obvious trick is to use `//\\` as a center point to comment out the mirrored version of the code. After that, it becomes a game of figuring out the shortest way to solve the problem using only the charset given.
The first issue we run into is the lack of keywords and built-ins. We miraculously still have `.pop()`, but everything else will have to be done via the allowed operators (which includes `a[b]` and `f(c)`), with recursion to emulate loops.
The second issue is the lack of logical operators. Neither `&` and `?` are allowed, which means the *only* decision-making operator we can use is `||`. Therefore, we have to carefully structure our logic to account for this.
The first thing I did was to define a function `T` that mirrors an individual character. The basic idea is to loop through each character in a string of mirror-able chars, testing each for equality with the given char. If it is equal, we return its mirror—the char at `index^1` for `(){}[]<>\/`, or the char itself for the rest.
The first problem I ran into here was getting either the mirrored char or a falsy value on each iteration. The solution I eventually came up with was `(x!=A[o]||A)[o^o<88/8]`, where `x` is the input character, `A` is the mirroring alphabet, and `o` is the current index. If `x` is not the same as `A[o]`, this gives `true`, and the index expression evaluates to `undefined`; otherwise, the `||A` is activated, and we end up getting `A[o^(o<11)]`.
The second problem is how to terminate the recursion. I found that the best way to do this is to simply concatenate the results of every iteration, returning the empty string when the end of `A` is reached. This presents us with two further problems: converting the `undefined`s to empty strings, and returning the empty string `||` something. These can be solved with array abuse: `[a]+""` gives the string representation of `a`, or the empty string if `a` is undefined. As a bonus, `[]` is truthy but stringifies to the empty string, so we can conveniently use this as a "truthy empty string".
Now we can use the `T` function to mirror any single character. We do this recursively, comparing the mirror of `I[v++]` to `I.pop()` until the end of the array of chars is reached. We can't use `&&` or `&` to check if all of the comparisons are truthy, but so use `*` instead. Multiplying all of these results together gives `1` if every character is the mirror of the one opposite, or `0` if any comparison fails.
And that is basically how this answer works. I probably didn't explain it very clearly, so please ask any questions you may have and point out any mistakes I have made.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~76~~ 70 bytes
```
:Wx^^MH_=_"{([</!*+-:=ITX^_|":W-!*pq*!-W:"|_^XTI=:-+*!\>])}"_=_HM^^xW:
```
[Run and debug it](https://staxlang.xyz/#c=%3AWx%5E%5EMH_%3D_%22%7B%28%5B%3C%2F%21*%2B-%3A%3DITX%5E_%7C%22%3AW-%21*pq*%21-W%3A%22%7C_%5EXTI%3D%3A-%2B*%21%5C%3E%5D%29%7D%22_%3D_HM%5E%5ExW%3A&i=%7B%5B%2B%5D%3D%3D%5B%2B%5D%7D%0A%5B%29%3E%5E%3C%28%5D%0A%28%7BT%29%7D%7C%7B%28T%7D%29%0A%3C%28*%5D%7B%5B%3A%21-_%3A%3E%7D%3C%5B%3C%29*%28%3E%5D%3E%7B%3C%3A_-%21%3A%5D%7D%5B*%29%3E%0Ab%3C%2B%3Ed%0A%28%29%29%28%0A%28%7B%5B%3C%2B%2B%3C%5D%7D%29&a=1&m=2)
Stax is friend of Stack Cats and has internals to generate the later half of a Stack Cats program from the first half. If we don't care about the restriction on the source and don't need to check the charset, here is a 4-byte solution:
## 4 bytes
```
:R_=
```
[Run and debug it](https://staxlang.xyz/#c=%3AR_%3D&i=%7B%5B%2B%5D%3D%3D%5B%2B%5D%7D%0A%5B%29%3E%5E%3C%28%5D%0A%28%7BT%29%7D%7C%7B%28T%7D%29%0A%3C%28*%5D%7B%5B%3A%21-_%3A%3E%7D%3C%5B%3C%29*%28%3E%5D%3E%7B%3C%3A_-%21%3A%5D%7D%5B*%29%3E%0Ab%3C%2B%3Ed%0A%28%29%29%28%0A%28%7B%5B%3C%2B%2B%3C%5D%7D%29&a=1&m=2)
## Explanation
```
:Wx^^MH_=_"{([</!*+-:=ITX^_|":W-!*pq...
:W "Mirror" the string
Equivalent to appending the reverse of the string to itself
And map `{([</\>])}` to its mirror in the appended string
x^^ 2, but we can't just use `2` here ...
MH Partition the "mirror"ed string to two parts, take the later part.
_= The string is the same as the original one (*)
`:Wx^^MH_=` is just `:R_=`, but we can't use `R` here ...
_ Input string
"{([</!*+-:=ITX^_|":W- Remove valid characters from input
! The final string is empty (**)
* (*) and (**)
p Pop and print result
q Peek stack and print
Since the stack is now empty, this causes the program to terminate
... Not executed
```
] |
[Question]
[
A permutation of size **n** is a reordering of the first **n** positive integers. (meaning each integer appears once and exactly once). Permutations can be treated like functions that change the order of a list of items of size **n**. For example
```
(4 1 2 3) ["a", "b", "c", "d"] = ["d", "a", "b", "c"]
```
Thus permutations can be composed like functions.
```
(4 1 2 3)(2 1 3 4) = (4 2 1 3)
```
This brings about a lot of interesting properties. Today we are focusing on ***conjugacy***. Permutations **y** and **x** (both of size **n**) are conjugates iff there are permutations **g** and **g-1** (also of size **n**) such that
```
x = gyg-1
```
and **gg-1** is equal to the identity permutation (the first **n** numbers in proper order).
Your task is to take two permutations of the same size via standard input methods and decide whether they are conjugates. You should output one of two consistent values, one if they are conjugates and the other if they are not.
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.
There are lots of theorems about conjugate permutations that are at your disposal, so good luck and happy golfing.
You may take input as an ordered container of values (either 1-n or 0-n) representing the permutation like above, or as a function that takes a ordered container and performs the permutation. If you choose to take function you should take it as an argument rather than have it at a predefined name.
## Test Cases
```
(1) (1) -> True
(1 2) (2 1) -> False
(2 1) (2 1) -> True
(4 1 3 2) (4 2 1 3) -> True
(3 2 1 4) (4 3 2 1) -> False
(2 1 3 4 5 7 6) (1 3 2 5 4 6 7) -> True
```
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
f=lambda P,k:k<1or len({sum([x==eval('L['*k+'x'+']'*k)for x in L])for L in P})&f(P,k-1)
```
[Try it online!](https://tio.run/##TcyxDoIwFIXhvU/RybZyTSyIg7EDsDKwNx0w0kCAQhBNjfHZa@ui25f/ntz5ubaTiZ3TYqjHy7XGFfSn/synBQ@Noa/bfaTSCtE86oGSUpJtHxFLIqK8mPYzizuDS/V1GVy92UZT/2fHmcuE5BDDHg6QQKpQLmTiHUoKXKHid08hUciII5qXzqxYU5pBzsCw/1CE4D4 "Python 2 – Try It Online")
Takes input with `P` as a pair of both permutations and `k` their length. Outputs `1` for conjugates and `0` not.
This uses the result:
>
> Two permutations **x** and **y** are conjugate exactly if their **k**-th powers **xk** and **yk** have an equal number of fixed points for every **k** from **0** to **n**.
>
>
>
Two conjugate permutations satisfy this because their **k**-th powers are also conjugate, and conjugacy preserves the count of fixed points.
It's less obvious that any two non-conjugate permutations always differ. In particular, conjugacy is determined by the sorted list of cycle lengths, and these can be recovered from the counts of fixed points. One way to show this is with linear algebra, though it might be overkill.
Let **X** be the permutation matrix for **x**. Then, the number of fixed points of **xk** is **Tr(Xk)**. These traces are the [power sum symmetric polynomials](https://en.wikipedia.org/wiki/Power_sum_symmetric_polynomial) of the eigenvalues of **Xk** with multiplicity. These polynomials for **k** from **0** to **n** let us recover the corresponding [elementary symmetric polynomials](https://en.wikipedia.org/wiki/Elementary_symmetric_polynomial) of these eigenvalues, and therefore the characteristic polynomial and so the eigenvalues themselves.
Since these eigenvalues are roots of unity corresponding to the cycles of **x**, from these we can recover the cycle sizes and their multiplicities. So, our "signature" identifies the permutation up to conjugation.
[Answer]
# [J](http://www.jsoftware.com/), ~~25 bytes~~ ~~23 bytes~~ 16 bytes
*miles'* tacit solution :
```
-:&([:/:~#&>)&C.
```
OP's explicit solution :
```
c=:4 :'-://:~"1#&>C.&>x;y'
```
This checks whether permutations x and y have the same cycle type, using the built-in `C.` function to produce cycle representations.
```
4 1 3 2 c 4 2 1 3
1
3 2 1 4 c 4 3 2 1
0
2 1 3 4 5 7 6 c 1 3 2 5 4 6 7
1
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~20~~ ~~19~~ ~~17~~ 16 bytes
```
xY@!"&G@)@b)X=va
```
Input: two column vectors (using `;` as separator). Output: `1` if conjugate, `0` if not.
[Try it online!](https://tio.run/##y00syfn/vyLSQVFJzd1B0yFJM8K2LPH//2gTawVDawVjawWjWC4QxwjCjwUA) Or [verify all test cases](https://tio.run/##y00syfmf8L8i0kFRSdfQ3cDdQdMhSTPCtizxf6xLyP9ow1guCLZWMAJSRtYKhhiUCZCyVjCGqAByjCB8IMcYxjGByED5UK1gPlDU1FrB3FrBDGILRIkpWMIMKBELAA).
### Explanation
No theorems about permutations used (out of sheer ignorance); just brute force and these two facts:
* For two permutations **p** and **q**, the composition **pq** is equivalent to using **p** to index the elements of **q**.
* The condition **x** = **gyg**−1 is equivalent to **xg** = **gy**.
Commented code:
```
x % Implicitly input first permutation, x. Delete it. Gets copied into clipboard G
Y@ % Implicitly input second permutation, y. Push a matrix with all permutations
% of its elements, each permutation on a different row. So each matrix row is
% a permutation of [1 2 ...n], where n is the size of y
! % Transpose. Now each permutation is a column
" % For each column
&G % Push x, then y
@ % Push current column. This is a candidate g permutation
) % Reference indexing. This gives g composed with y
@ % Push current column again
b % Bubble up. Moves x to the top of the stack
) % Reference indexing. This gives x composed with g
X= % Are they equal as vectors? Gives true or false
v % Concatenate stack so far. The stack contains the latest true/false result
% and possibly the accumulated result from previous iterations
a % Any: gives true if any element is true. This is the "accumulating" function
% Implicit end. Implicit display
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes
```
Equal@@(PermutationCycles[#,Sort[0#]&]&/@#)&
```
[Try it online!](https://tio.run/##Pc09C8IwEIDhvb/iaCAonNSmH05KQNwLjiVDKC0W@oE1HaTkt8ezNi4h9z4J12vzqHtt2kq7Bs7gbs9Zd1LuinrqZ0MwDtd31dWvkuF9nEx5ZIorHkm2566Y2sEQQAiHC4QITcmUAg6RDGBZltgi0GExABpjBPENAuHfUrojJJvQJH7Be@JLuvkWvAv/nyhDOCHk607/MFslJ7HWug8 "Wolfram Language (Mathematica) – Try It Online")
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes
```
x_±y_:=Or@@(#[[x]]==y[[#]]&/@Permutations@x)
```
Using CP-1252 encoding, where `±` is one byte.
[Try it online!](https://tio.run/##PY1dCsIwDIDfd4pgYShEZN2PIEx6A/deyhgycA@dMCtsjB5qV9jFaqyrEPLzfQnRjXm0ujHdvXFurNdlqi/lbRBiz6QclSrLSUqmVHwSVTvot6HVZ/8S48FVQ9cbyRB2PhinAser72FdCCiIQQgRwTzPiUWgZDECGhME/gV082cZ9QjpZmjiPxB8Gki2@Q0Ez8M9qRzhjFD4n2Ex96YgY611Hw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
Œ!©Ụ€ịị"®⁸e
```
[Try it online!](https://tio.run/##y0rNyan8///oJMVDKx/uXvKoac3D3d1ApHRo3aPGHan/Dy830o/8/z/aMFYHhBWiDXWMgEwjHTAHTME4JjqGOsZgWRMdIxAbJGgMZpqABcFsqDYgx0THVMdcxwxkMFjKFChipmMeCwA "Jelly – Try It Online")
### How it works
```
Œ!©Ụ€ịị"®⁸e Main link. Left argument: x. Right argument: y
Œ!© Take all permutations g of x. Copy the result to the register.
Ụ€ Grade up each; sort the indices of each permutation g by their
corresponding values. For permutations of [1, ..., n], grading up
essentially computes the inverse, g⁻¹.
ị Let each g⁻¹ index into y, computing g⁻¹y.
ị"® Let the results index into the corresponding g, computing g⁻¹yg.
⁸e Test if x occurs in the result.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
¤¦ṠmöLU¡!
```
Returns `1` for conjugate and `0` for non-conjugate.
[Try it online!](https://tio.run/##yygtzv7//9CSQ8se7lyQe3ibT@ihhYr///@PNtIx1DHWMdEx1THXMYv9Hw3iGQF5JjpmOuaxAA "Husk – Try It Online")
## Explanation
The conjugacy class of a permutation **P** of **L =
[1,2,..,n]** is determined by the multiset containing the least period of each number in **L** under **P**.
When **P** is taken in list format, I can replace **L** with **P** and get the same multiset.
The program computes the corresponding multiset for each input and checks if one is a sub-multiset of the other.
Since they have the same number of elements, this is equivalent to being the same multiset.
```
¤¦ṠmöLU¡! Implicit inputs: two lists of integers.
¤ Apply one function to both and combine with another function.
ṠmöLU¡! First function. Argument: a list P.
Ṡm Map this function over P:
¡! iterate indexing into P,
U take longest prefix with unique elements,
öL take its length.
¦ Combining function: is the first list a subset of the other, counting multiplicities?
```
[Answer]
# Perl, ~~61~~ ~~58~~ 57 bytes
Includes `+2` for `ap`
Give 0-based permutations as 2 lines on STDIN
```
perl -ap '$_=[@1]~~[@1=map{-grep$_-$G[$i++%@G],@F=@G[@F]}@G=@F,0]'
3 0 2 1
3 1 0 2
^D
```
Algorithm is a minor variation on the one in [xnor's solution](https://codegolf.stackexchange.com/a/155906/51507)
This older version of the code hits a perl bug and dumps core for several inputs on my latest perl `5.26.1`, but it works on an older perl `5.16.3`.
```
@{$.}=map{-grep$_==$F[$i++%@F],@G=@F[@G]}@G=@F,0}{$_=@1~~@2
```
It's possibly yet another instance of my old perlgolf enemy, the fact that perl doesn't properly refcount its stack.
[Answer]
## JavaScript (ES6), ~~66~~ 64 bytes
```
(a,b,g=a=>b+a.map(h=(e,i)=>e-i&&1+h(a[e],i)).sort())=>g(a)==g(b)
```
If I've read the other answers correctly, the problem is equivalent to counting the periods of all the elements and checking that the two lists have the same number of each period. Edit: Saved 1 byte thanks to @Arnauld by calculating one less than the period. Saved another byte thanks to @Arnauld by abusing JavaScript's weird coercion rules to compare the arrays. Another byte could be saved by currying but I don't like curry unless it's chicken tikka masala.
] |
[Question]
[
# The beautiful pattern drawer
Good morning PPCG !
The other day, when I was trying to help someone on Stack Overflow, a part of his problem gave me an idea for this challenge.
First of all, check the following shape :
[](https://i.stack.imgur.com/dhlBh.png)
Where all black numbers are the index of the points in the shape and all dark-blue numbers are the index of the links between the points.
Now, given an hexadecimal number for 0x00000 to 0xFFFFF, you need to draw a shape in the console using only character space and "■" (using the character "o" is okay too).
Here are some examples where hexadecimal number is input and shape is output :
```
0xE0C25 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■
■ ■
■ ■
■ ■ ■ ■ ■ ■
■ ■
■ ■
■ ■
■ ■ ■ ■ ■
0xC1043 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■
■
■
■
■
■
■
■ ■ ■ ■ ■ ■ ■ ■ ■
0xE4F27 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
0xF1957 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
0xD0C67 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■
■ ■
■ ■
■ ■ ■ ■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
0x95E30 :
■ ■ ■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■
■ ■
■ ■
■ ■
0x95622 :
■ ■ ■ ■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■
■
■
■ ■ ■ ■ ■
0xC5463 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■
■ ■
■ ■
■ ■ ■ ■ ■
■ ■
■ ■
■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
0xE5975 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■
0xB5E75 :
■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■ ■ ■
0xF4C75 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■
■ ■ ■ ■ ■ ■
0xF5D75 :
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■
```
Here are some explanation about how it works :
```
0xFFFFF(16) = 1111 1111 1111 1111 1111(2)
```
You here have 20 bits, each bit says whether a link exists or not.
Index of the Most Significant Bit (MSB) is 0 (picture reference) or the Less Significant Bit (LSB) is 19 (picture reference again).
Here's how it works for the first shape given as example :
```
0xE0C25(16) = 1110 0000 1100 0010 0101(2)
```
Meaning you'll have the following existing links : 0,1,2,8,9,14,17,19.
If you highlight the lines on the reference picture with those numbers, it will give you this shape :
```
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■
■ ■
■ ■
■ ■ ■ ■ ■ ■
■ ■
■ ■
■ ■
■ ■ ■ ■ ■
```
Here is a simple and ungolfed Python implementation if you need more help :
```
patterns = [
0xE0C25, 0xC1043, 0xE4F27, 0xF1957,
0xD0C67, 0x95E30, 0x95622, 0xC5463,
0xE5975, 0xB5E75, 0xF4C75, 0xF5D75
]
def printIfTrue(condition, text = "■ "):
if condition:
print(text, end="")
else:
print(" "*len(text), end="")
def orOnList(cube, indexes):
return (sum([cube[i] for i in indexes]) > 0)
def printPattern(pattern):
cube = [True if n == "1" else False for n in str(bin(pattern))[2::]]
for y in range(9):
if y == 0: printIfTrue(orOnList(cube, [0, 2, 3]))
if y == 4: printIfTrue(orOnList(cube, [2, 4, 9, 11, 12]))
if y == 8: printIfTrue(orOnList(cube, [11, 13, 18]))
if y in [0, 4, 8]:
printIfTrue(cube[int((y / 4) + (y * 2))], "■ ■ ■ ")
if y == 0: printIfTrue(orOnList(cube, [0, 1, 4, 5, 6]))
if y == 4: printIfTrue(orOnList(cube, [3, 5, 7, 9, 10, 13, 14, 15]))
if y == 8: printIfTrue(orOnList(cube, [12, 14, 16, 18, 19]))
printIfTrue(cube[int((y / 4) + (y * 2)) + 1], "■ ■ ■ ")
elif y in [1, 5]:
for i in range(7):
if i in [2, 5]:
print(" ", end=" ")
printIfTrue(cube[y * 2 + (1 - (y % 5)) + i])
elif y in [2, 6]:
for i in range(5):
if i in [1, 2, 3, 4]:
print(" ", end=" ")
if i in [1, 3]:
if i == 1 and y == 2:
printIfTrue(orOnList(cube, [3, 4]))
elif i == 3 and y == 2:
printIfTrue(orOnList(cube, [6, 7]))
if i == 1 and y == 6:
printIfTrue(orOnList(cube, [12, 13]))
elif i == 3 and y == 6:
printIfTrue(orOnList(cube, [15, 16]))
else:
printIfTrue(cube[(y * 2 - (1 if y == 6 else 2)) + i + int(i / 4 * 2)])
elif y in [3, 7]:
for i in range(7):
if i in [2, 5]:
print(" ", end="")
ri, swap = (y * 2 - 2) + (1 - (y % 5)) + i, [[3, 6, 12, 15], [4, 7, 13, 16]]
if ri in swap[0]: ri = swap[1][swap[0].index(ri)]
elif ri in swap[1]: ri = swap[0][swap[1].index(ri)]
printIfTrue(cube[ri])
if y == 0: printIfTrue(orOnList(cube, [1, 7, 8]))
if y == 4: printIfTrue(orOnList(cube, [6, 8, 10, 16, 17]))
if y == 8: printIfTrue(orOnList(cube, [15, 17, 19]))
print()
for pattern in patterns:
printPattern(pattern)
```
Of course it's not perfect and it's pretty long for what it should do, and that's the exact reason why you're here !
Making this program ridiculously short :)
This is code-golf, so shortest answer wins !
[Answer]
## JavaScript (ES6), ~~202~~ ~~188~~ 187 bytes
```
let f =
n=>`0${x=',16,-54,21,-26,21,21,-26,21,166'}${x},16`.split`,`.map((d,i)=>(k-=d,n)>>i&1&&[..."ooooo"].map(c=>g[p-=(k&3||9)^8]=c,p=k>>2),g=[...(' '.repeat(9)+`
`).repeat(9)],k=356)&&g.join``
console.log(f(0xE0C25))
console.log(f(0xC1043))
console.log(f(0xE4F27))
console.log(f(0xF1957))
```
### How it works
```
n => // given 'n':
`0${x = ',16,-54,21,-26,21,21,-26,21,166'}${x},16` // build the list of delta values
.split`,`.map((d, i) => // split the list and iterate
(k -= d, n) >> i & 1 && // update 'k', test the i-th bit of 'n'
[..."ooooo"].map(c => // if the bit is set, iterate 5 times:
g[ //
p -= (k & 3 || 9) ^ 8 // compute the direction and update 'p'
] = c, // write a 'o' at this position
p = k >> 2 // initial value of 'p'
), //
g = [...(' '.repeat(9) + `\n`).repeat(9)], // initialization of the 'g' array
k = 356 // initial value of 'k'
) //
&& g.join`` // yield the final string
```
We work on a grid `g` of 9 rows of 10 characters. The grid is initially filled with spaces, with a LineFeed every 10th character.
Each segment is defined by a starting position and a direction.
Directions are encoded as follow:
```
ID | Dir.| Offset
---|-----|-------
0 | W | -1 Offset encoding formula:
1 | NE | -9 -((ID || 9) ^ 8)
2 | N | -10
3 | NW | -11
```
Each segment is encoded as an integer:
* the direction is stored in bits #0 and #1
* the starting position is stored in bits #2 to #8
For instance, segment #3 starts at position 55 and uses the 3rd direction. Therefore, it's encoded as `(55 << 2) | 3 == 223`.
Below is the resulting list of integers, from segment #19 to segment #0:
```
356,340,394,373,399,378,357,383,362,196,180,234,213,239,218,197,223,202,36,20
```
Once delta-encoded, starting at 356, it becomes:
```
0,16,-54,21,-26,21,21,-26,21,166,16,-54,21,-26,21,21,-26,21,166,16
```
Which is finally encoded as:
```
`0${x=',16,-54,21,-26,21,21,-26,21,166'}${x},16`
```
[Answer]
# Python 3, 289 bytes
```
def f(n):
for r in range(9):print(*(" o"[any(n&1<<ord(c)-97for c in"trq|t|t|t|tspon|s|s|s|sml|r|q||p|o|n||m|l|r||qp||o||nm||l|r|p||q|o|m||n|l|rpkih|k|k|k|qomkjgfe|j|j|j|nljdc|i|h||g|f|e||d|c|i||hg||f||ed||c|i|g||h|f|d||e|c|igb|b|b|b|hfdba|a|a|a|eca".split("|")[r*9+c])]for c in range(9)))
```
Nothing smart, just hardcoding.
[Answer]
# Ruby, 116 bytes
```
->n{s=[' '*17]*9*$/
20.times{|i|j=i%9
n>>19-i&1>0&&5.times{|k|s[i/9*72+(j>1?~-j/3*8+k*18:j*16)+k*(2--j%3*2)]=?O}}
s}
```
This relies on a couple of patterns I observed. Firstly, the pattern repeats every 9 lines. Secondly, if the start points of the horizontal lines are chosen appropriately, the x directions cycle continuously through right, left, straight.
**Ungolfed in test program**
```
f=->n{
s=[' '*17]*9*$/ #Setup a string of 9 newline separated lines of 17 spaces.
20.times{|i| #For each of the 20 bits..
j=i%9 #The pattern repeats every 9 bits.
n>>19-i&1>0&& #If the relevant bit is set,
5.times{|k| #draw each of the 5 points on the relevant line.
s[i/9*72+ #There are 9 lines starting on each row. Row y=0 starts at 0 in the string, row y=1 at 72, etc.
(j>1?~-j/3*8+k*18:j*16)+ #~-j=j-1. For j=2..8, the starting x coordinates are (0,0,1,1,1,2,2)*8. For j=0 and 1 starting x coordinates are 0 and 16.
k*(2--j%3*2) #From the starting points, draw the lines right,left,straight. Down movement if applicable is given by conditional k*18 above.
]=?O #Having described the correct index to modify, overwrite it with a O character.
}
}
s} #Return the string.
[0xE0C25, 0xC1043, 0xE4F27, 0xF1957,
0xD0C67, 0x95E30, 0x95622, 0xC5463,
0xE5975, 0xB5E75, 0xF4C75, 0xF5D75].map{|m|puts f[m],'---------'}
```
I believe there is a 112 byte solution using a 20-character string and some decoding to define the parameters of the 20 lines. I will try this later if I have time.
[Answer]
# PHP, ~~142~~ ~~150~~ 149 bytes
```
for($r="";$c=ord(",(NMKJIGFHDjigfecbd`"[$i]);)if(hexdec($argv[1])>>$i++&1)for($p=96^$c&~$k=3;$k++<8;$p+=7+($c&3?:-6))$r[$p]=o;echo chunk_split($r,9);
```
prints the shape as far as needed; i.e. if the lower part is empty, it will be cut.
Run with `php -nr '<code>' <input>`. Do not prefix input
**[Test it online](http://sandbox.onlinephpfunctions.com/code/c6c3f16b2d9c2705813df012c79a213f331fd6c9)**
Add 11 bytes for no cutting: Insert `,$r[80]=" "` after `$r=""`.
**encoding explained**
Every line can be described with a starting point and one of four directions.
Drawing on a 9x9 grid, the starting position ranges from `0,0` to `8,4`; or, combined, from `0` to `8*9+4=76`. Luckily, all starting points `[0,4,8,36,40,44,72,76]` are divisible by 4; so the direction code `[0..3]` can be squeezed into bits 0 and 1 -> no shifting needed at all.
For an easy calculation of the cursor movement, `0` is taken for east (only direction with no vertical movement) and `[1,2,3]` for south-west, south, south-east, where the offset is `9` (for vertical movement) plus `[-1,0,1]` -> `[8,9,10]` -> `delta=code?code+7:1`.
The direction for the first and last lines being east, that results in codes ranging from 0 to 76 `[0+0,4+0,0+2,0+3,4+1,4+2,4+3,8+1,8+2,...,44+1,44+2,72+0,76+0]`; and bitwise xor 96 on each value results in printable and unproblematic ascii codes `[96,100,98,99,101,102,103,105,106,68, 72,70,71,73,74,75,77,78,40,44]` -> ``dbcefgijDHFGIJKMN(,`. The code uses the LSB for bit 0, while line 0 corresponds to the MSB, so the string has to be reversed. Finito.
**breakdown**
```
for($r=""; // init result string, loop through line codes
$c=ord(",(NMKJIGFHDjigfecbd`"[$i]);)
if(hexdec($argv[1])>>$i++&1)// if bit $i is set, draw line 19-$i:
for($p=96^$c&~$k=3 // init $k to 3, init cursor to value&~3
;$k++<8; // loop 5 times
$p+=7+($c&3?:-6) // 2. map [0,1,2,3] to [1,8,9,10], move cursor
)
$r[$p]=o; // 1. plot
echo chunk_split($r,9); // insert a linebreak every 9 characters, print
```
**some golfing explained**
* Since `^96` has no effect on the lower two bits, it can be ignored when extracting the direction; so there is no need to store the value in a variable, which saves 5 bytes on the cursor init.
* Using `~3` instead of `124` saves one byte and allows the next golfing:
* Initializing the looping counter `$k=3` inside the `$p` assignment saves two bytes
and it doesn´t hurt the pre-condition (since the upper value still has one digit).
* Using a string for the result has the shortest initialization and plotting possible: When a character is set beyond the end of a string, PHP implicitly sets the missing characters to space. And `chunk_split` is the shortest way to insert the linebreaks.
I don´t even want to know how much more anything else would take.
* `7+($c&3?:-6)` is one byte shorter than `$c&3?$c%4+7:1`.
* Added `hexdec()` (8 bytes) to satisfy the input restriction.
[Answer]
## JavaScript, ~~184~~ ~~183~~ ~~178~~ ~~168~~ 167 bytes
```
f=
n=>[...`<>K[LM]NO\\^k{lm}no|~`].map((e,i)=>n>>i&1&&[0,2,4,6,8].map(i=>a[(e&102)*4+(e&17||15)*i]=`o`,e=~e.charCodeAt()),a=[...(` `.repeat(31)+`
`).repeat(9)])&&a.join``
```
```
<input oninput=o.textContent=f(+this.value)><pre id=o>
```
Was originally 206 bytes but @Arnauld's answer inspired me to investigate a one-dimensional array solution. Edit: Saved 1 byte thanks to @edc65. Saved ~~5~~ 15 bytes thanks to @Arnauld. Saved a further byte by tweaking the choice of characters.
[Answer]
## Batch, 491 bytes
```
@set n=%1
@for %%i in ("720896 524288 524288 524288 843776 262144 262144 262144 268288" "131072 65536 0 32768 16384 8192 0 4096 2048" "131072 0 98304 0 16384 0 12288 0 2048" "131072 32768 0 65536 16384 4096 0 8192 2048" "165248 1024 1024 1024 89312 512 512 512 10764" "256 128 0 64 32 16 0 8 4" "256 0 192 0 32 0 24 0 4" "256 64 0 128 32 8 0 16 4" "322 2 2 2 171 1 1 1 17")do @set s=&(for %%j in (%%~i)do @set/am=%1^&%%j&call:c)&call echo(%%s%%
:c
@if %m%==0 (set s=%s% )else set s=%s%o
```
Note: The last line ends with a space. Putting an `if` conditional with a variable inside a `for` loop is beyond batch so that needs its own subroutine. Since it does nothing visible I fall through into it to exit. The `~` unquotes the strings in the outer loop allowing the inner loop to loop over the numbers. The numbers are simply the bitmasks for all the places where `o`s should be drawn.
[Answer]
# C, 267 262 260 256 characters
Counting escapes as 1 character
```
void f(int i){char*k="\0\x1\x2\x3\x4\x4\x5\x6\x7\x8\0\x9\x12\x1b\x24\0\xa\x14\x1e\x28\x4\xc\x14\x1c\x2d\x4\xd\x16\x1f\x28\x4\xe\x18\x22\x2c\x8\x10\x18\x20\x28\x8\x11\x1a\x23\x2c\x24\x25\x26\x27\x28\x28\x29\x2a\x2b\x2c\x24\x2d\x36\x3f\x48\x24\x2e\x38\x42\x4c\x28\x30\x38\x40\x48\x28\x31\x3a\x43\x4c\x28\x31\x3a\x43\x4c\x28\x32\x3c\x46\x50\x2c\x35\x3e\x47\x50\x48\x49\x4a\x4b\x4c\x4c\x4d\x4e\x4f\x50";for(int n=0,s,l;n<81;!(++n%9)&&putchar(10))for(s=l=0;s<20;!(++l%5||++s^20)&&putchar(32))if(i<<s&1<<19&&k[l]==n&&putchar(111))break;}
```
k is a lookup referring to which boxes to put an 'o' in.
[Try it online!](https://tio.run/nexus/c-gcc#bZLhbpswFIX/5yncSkW4VIt9bUMQ8Kdp8hJlkwgBzQpzIqCVpbbPnl4DXT1pUpxwjj@fc4WzXhOuYkJIWJ@PDV2t1xGwe4X6RLTRo646PVSjPpsfhJP6d9VX9dj05IKrGerqMp0pQMXX17M@kjbUZiSavjn0/lTclqy0vLRQWlFaOX1UaePSJqXduM0U93GXHxCSzqhQIMUbNDbTgXpx8BeOk4PfHDN4@5dBmuMTYBTULtpytlhshpyFk3DMBzFTWGgBxwHMgmTGpoVDgeMOHoedAjmBnXKzeNgqXD@2yno@K9jisYVzHvYKzJPC4/7nudeEzxJ7FJu7Bc4nsEcms@cyJc4n3dnDfHZa7s04rnXcbdae@@kuTMEehocuM/mGZzdhFJm7lAbB5WV0VxRyRqlDh6IrWDbkwCaou1Pv71E0/ALmwQIo1XjFeT4EPM95GgSn5@5nURgvkHNKD31TnbKPqxvgT6VNSMnbCv9lbcjsjm1B0exLbjmT4lvu5B6Sb7nnqfLkE9vGnkzVTjBfxgBespKxn6zSxOt9VDtf7uX2H6mevmTfjC@9ISxbfVw/AQ)
[Answer]
# Befunge, 468 bytes
```
~:85+`!#v_86*-:9`7*-48*%\82**+
3%2:/2\<$v0%2:/2\*g02*!g03%2:/2\*!+4g07%2:/2\*g02*!-8g06%2:/2\*g02*!-4g0
g!*20g*^00>50g*\2/:2%00g8-!*40g*\2/:2%30g8-!*20g*\2/:2%60g66+-!*\2/:2%70
`\5:p00:<g^*!-8g00%2:\-10:\p07-g00:p06+g00:p05`3:p04`\5:p03:<0\p02`3:p01
#o 8`#@_^4>*50g*\2/2%00g!*40g*0\>:#<1#\+_$!1+4g,48*,\1+:8`!#^_55+,$\1+:
g03%2:/2<-^!g00%2:/2\*g01*!g03%2:/2\*g01*!g07%2:/2\*!-4g06%2:/2\*g01*!-4
70g4-!*\^>!*50g*\2/:2%00g4-!*40g*\2/:2%30g8-!*10g*\2/:2%60g8-!*10g*\2/:2%
```
[Try it online!](http://befunge.tryitonline.net/#code=fjo4NStgISN2Xzg2Ki06OWA3Ki00OColXDgyKiorCjMlMjovMlw8JHYwJTI6LzJcKmcwMiohZzAzJTI6LzJcKiErNGcwNyUyOi8yXCpnMDIqIS04ZzA2JTI6LzJcKmcwMiohLTRnMApnISoyMGcqXjAwPjUwZypcMi86MiUwMGc4LSEqNDBnKlwyLzoyJTMwZzgtISoyMGcqXDIvOjIlNjBnNjYrLSEqXDIvOjIlNzAKYFw1OnAwMDo8Z14qIS04ZzAwJTI6XC0xMDpccDA3LWcwMDpwMDYrZzAwOnAwNWAzOnAwNGBcNTpwMDM6PDBccDAyYDM6cDAxCiNvIDhgI0BfXjQ+KjUwZypcMi8yJTAwZyEqNDBnKjBcPjojPDEjXCtfJCExKzRnLDQ4KixcMSs6OGAhI15fNTUrLCRcMSs6CmcwMyUyOi8yPC1eIWcwMCUyOi8yXCpnMDEqIWcwMyUyOi8yXCpnMDEqIWcwNyUyOi8yXCohLTRnMDYlMjovMlwqZzAxKiEtNAo3MGc0LSEqXF4+ISo1MGcqXDIvOjIlMDBnNC0hKjQwZypcMi86MiUzMGc4LSEqMTBnKlwyLzoyJTYwZzgtISoxMGcqXDIvOjIl&input=RTBDMjU)
The first line reads a string from stdin, evaluating it as a hexadecimal number. The rest of the code is essentially just a double loop over the x/y coordinates of the grid, with a massive boolean calculation determining whether an `o` should be output for each location.
There's basically a separate condition for each of the 20 grid points, for example (the first four):
```
(y==0) * (x<5) * bit0
(y==0) * (x>3) * bit1
(x==0) * (y<5) * bit2
(x==y) * (y<5) * bit3
```
And then once we've calculated all 20 of them, we OR the lot together, and if that result is true, we output a `o`, otherwise we output a space.
Befunge doesn't have anything in the way of bit manipulation operations, so to extract the bits from the input, we're just repeatedly evalating `n%2` and then `n/=2` as we make our way through the 20 condition calculations.
] |
[Question]
[
# Task
Define a *mod-fold* as a function of the form **f(x) = x % a1 % a2 % … % ak**, where the **ai** are positive integers and **k ≥ 0**. (Here, **%** is the left-associative modulo operator.)
Given a list of **n** integers **y0, …, yn−1**, determine if there exists a mod-fold **f** so that each **yi = f(i)**.
You may choose and fix **any two outputs** *Y* and *N* for your function/program. If there exists such an **f**, you must always return/print exactly *Y*; if not, you must always return/print exactly *N*. (These could be `true`/`false`, or `1`/`0`, or `false`/`true`, etc.) Mention these in your answer.
The shortest submission in bytes wins.
# Example
Define **f(x) = x % 7 % 3**. Its values start:
```
| x | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ...
| f(x) | 0 | 1 | 2 | 0 | 1 | 2 | 0 | 0 | 1 | 2 | ...
```
Thus, given `0 1 2 0 1 2 0 0 1 2` as input to our solution, we would print *Y*, as this **f** generates that sequence. However, given `0 1 0 1 2` as input, we would print *N*, as no **f** generates that sequence.
# Test cases
The formulas given when the output is *Y* are just for reference; you must at no point print them.
```
0 1 2 3 4 5 Y (x)
1 N
0 0 0 Y (x%1)
0 1 2 0 1 2 0 0 1 2 Y (x%7%3)
0 0 1 N
0 1 2 3 4 5 6 0 0 1 2 Y (x%8%7)
0 1 2 0 1 2 0 1 2 3 N
0 2 1 0 2 1 0 2 1 N
0 1 0 0 0 1 0 0 0 0 1 Y (x%9%4%3%2)
```
[Answer]
# Pyth, 14 bytes
```
}Qm%M+RdUQy_Sl
```
Returns `True/False`. Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%7DQm%25M%2BRdUQy_Sl&input=%5B0%2C1%2C2%2C0%2C1%2C2%2C0%2C0%2C1%2C2%5D&test_suite_input=%5B0%2C1%2C2%2C3%2C4%2C5%5D%0A%5B1%5D%0A%5B0%2C0%2C0%5D%0A%5B0%2C1%2C2%2C0%2C1%2C2%2C0%2C0%2C1%2C2%5D%0A%5B0%2C0%2C1%5D%0A%5B0%2C1%2C2%2C3%2C4%2C5%2C6%2C0%2C0%2C1%2C2%5D%0A%5B0%2C1%2C2%2C0%2C1%2C2%2C0%2C1%2C2%2C3%5D%0A%5B0%2C2%2C1%2C0%2C2%2C1%2C0%2C2%2C1%5D%0A%5B0%2C1%2C0%2C0%2C0%2C1%2C0%2C0%2C0%2C0%2C1%5D&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=%7DQm%25M%2BRdUQy_Sl&input=%5B0%2C1%2C2%2C0%2C1%2C2%2C0%2C0%2C1%2C2%5D&test_suite=1&test_suite_input=%5B0%2C1%2C2%2C3%2C4%2C5%5D%0A%5B1%5D%0A%5B0%2C0%2C0%5D%0A%5B0%2C1%2C2%2C0%2C1%2C2%2C0%2C0%2C1%2C2%5D%0A%5B0%2C0%2C1%5D%0A%5B0%2C1%2C2%2C3%2C4%2C5%2C6%2C0%2C0%2C1%2C2%5D%0A%5B0%2C1%2C2%2C0%2C1%2C2%2C0%2C1%2C2%2C3%5D%0A%5B0%2C2%2C1%2C0%2C2%2C1%2C0%2C2%2C1%5D%0A%5B0%2C1%2C0%2C0%2C0%2C1%2C0%2C0%2C0%2C0%2C1%5D&debug=0)
### Explanation:
```
}Qm%M+RdUQy_SlQ implicit Q (=input) at the end
lQ length of input list
S create the list [1, 2, ..., len]
_ reverse => [len, ..., 2, 1]
y generate all subsets (these are all possible mod-folds)
m map each subset d to:
UQ take the range [0, 1, ..., len-1]
+Rd transform each number into a list by prepending it to d
e.g. if mod-fold = [7,3], than it creates:
[[0,7,3], [1,7,3], [2,7,3], [3,7,3], ...]
%M fold each list by the modulo operator
this gives all possible truthy sequences of length len
}Q so checking if Q appears in the list returns True or False
```
# Pyth, 11 bytes
```
q%M.e+k_tx0
```
Based on [@ferrsum's idea](https://codegolf.stackexchange.com/a/85580/29577). I actually thought about using the zero-indices for the subset generation, but didn't realize, that all zero-indices has to be the solution already.
[Answer]
# Python 3, ~~239~~ 218 bytes
```
from itertools import*
lambda z:z in[[eval(''.join([str(l)]+['%'+str(i[::-1][k])for k in range(len(i))]))for l in range(len(z))]for i in(i for j in(combinations(range(1,len(z)+1),i+1)for i in range(len(z)))for i in j)]
```
An anonymous function that takes input of a list `z` and returns `True` or `False` for `Y` and `N`.
This uses a method similar to @Jakube 's [answer](https://codegolf.stackexchange.com/a/85554/55526), and although it is essentially a brute force, runs very quickly.
```
from itertools import* Import everything from the Python module for
iterable generation
lambda z Anonymous function with input list z
combinations(range(1,len(z)+1),i+1) Yield all sorted i+1 length subsets of the range
[1,len(z)]...
...for i in range(len(z)) ...for all possible subset lengths
(i for j in(...)for i in j) Flatten, yielding an iterator containing all possible
mod-fold values as separate lists
...for i in... For all possible mod-fold values...
...for k in range(len(i)) ...for all mod-fold values indices k...
...for l in range(len(z)) ...for all function domain values in [0,len(z)-1]...
[str(l)]+['%'+str(i[::-1][k])...] ...create a list containing each character of the
expression representing the function defined by the
mod-fold values (reversed such that the divisors
decrease in magnitude) applied to the domain value...
eval(''.join(...)) ...concatenate to string and evaluate...
[...] ...and pack all the values for that particular
function as a list
[...] Pack all lists representing all functions into a list
...:z in... If z is in this list, it must be a valid mod-fold, so
return True. Else, return False
```
[Try it on Ideone](https://ideone.com/71cO7I)
[Answer]
# Python 2, 69 bytes
```
f=lambda a,i=0:i/len(a)or a[i]in[a[i-1]+1,i,0][i<=max(a)::2]*f(a,i+1)
```
Uses `True`/`False`.
The answer to what characterizes a mod-foldable series turns out to be less interesting than it seems at first. It is a series of the form 0, 1, ..., M - 1, 0, 1, ... x1, 0, 1, ..., x2, ... such that for all i, 0 <= xi < M. Such a sequence can be produced by the mod chain of all the (0-based) indices of the zeroes in the array, excluding the first.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~19~~ ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
LṗLUZ’1¦%/sLe@
```
Returns **1** for truthy, **0** for falsy. [Try it online!](http://jelly.tryitonline.net/#code=TOG5l0xVWuKAmTHCpiUvc0xlQA&input=&args=WzAsIDEsIDIsIDMsIDQsIDVd)
The algorithm is **O(nn)**, where **n** is the length of the list, making it too slow and memory-intensive for most of the test cases.
A modified version – which replaces the second `L` with a `5` – can be used to [verify all test cases](http://jelly.tryitonline.net/#code=TOG5lzVVWuKAmTHCpiUvc0xlQArDh-KCrEc&input=&args=WzAsMSwyLDMsNCw1XSwgWzFdLCBbMCwwLDBdLCBbMCwxLDIsMCwxLDIsMCwwLDEsMl0sIFswLDAsMV0sIFswLDEsMiwzLDQsNSw2LDAsMCwxLDJdLCBbMCwxLDIsMCwxLDIsMCwxLDIsM10sIFswLDIsMSwwLDIsMSwwLDIsMV0sIFswLDEsMCwwLDAsMSwwLDAsMCwwLDFd). Note that this modified version won't work for arbitrarily long lists.
### How it works
```
LṗLUZ’1¦%/sLe@ Main link. Argument: A (array of integers)
L L Yield the length l of A.
ṗ Take the l-th Cartesian power of [1, ..., l], i.e., construct
all arrays of length l that consist of elements of [1, ..., l].
U Upend/reverse each array. This way, the first l arrays start
with [1, ..., l], as do the next l arrays, etc.
Z Zip/transpose the array of arrays.
’1¦ Decrement the first array to map [1, ..., l] to [0, ..., l - 1].
%/ Reduce the array's columns by modulus/residue.
sL Split the result into chunks of length l.
e@ Verify if A belongs to the resulting array.
```
[Answer]
## JavaScript (ES6), ~~98~~ bytes
```
a=>a.every((n,i)=>n?n<(l+=p==i)&&n==p++:p=1,l=p=1)
```
Saved 48 bytes by switching to @Feersum's discovery. Any given value `n` in the array is either zero, in which case the next prediction `p` is 1, or it equals the next prediction, in which case `p` is incremented. We also measure the length `l` of the initial sequence by comparing `p` to `i`, as `n` must always be less than `l` at all times.
[Answer]
# Python 2, ~~103~~ 99 bytes
```
f=lambda l,r:r==x or l and f(l-1,[t%l for t in r])|f(l-1,r)
x=input();l=len(x);print+f(l,range(l))
```
Prints **1** for truthy and **0** for falsy. Test it on [Ideone](http://ideone.com/62bluK).
] |
[Question]
[
A pangram is a sentence or excerpt which contains all twenty-six letters of the alphabet, as is demonstrated in [this code golf challenge](https://codegolf.stackexchange.com/questions/66197/is-it-a-pangram). However, [a pangrammatic *window*](https://en.wikipedia.org/wiki/Pangrammatic_window) is a pangram in the form of some segment of text, which may end or begin halfway through a word, found somewhere within a larger work. These naturally occur everywhere, being proper subsets of true pangrams, so just verifying if something contains a pangrammatic window would be boring and also it was previously done.
So, we're interested in finding the smallest one there is in a given piece of text based on its letter length! In the shortest possible code in bytes, of course, to fit the theme.
## Rules and Guidelines
* Receive a string as the input and return the string of the smallest pangrammatic window in the input if there is one. If there is not, return either a Boolean False or an empty string.
* Whether a string is a pangrammatic window or not is case-insensitive and only depends on the 26 letters, not any punctuation or numbers or other odd symbols.
* Similarly, a pangrammatic window's **letter length** is the total number of how many appearances of *letters* occur in it alone, and not simply the number of every character. The returned value must be smallest based on this count. We're linguists, after all, not programmers.
* An output of a pangrammatic window must, however, must be an exact substring of the input, containing the same capitalization and punctuation, etc.
* If there are multiple shortest pangrammatic windows of the same letter length, return any one of them.
## Test Cases
```
'This isn't a pangram.'
==> False
'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
==> 'Quick-Brown-Fox (the one who jumped over some lazy ig'
'"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
==> 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ'
```
[Answer]
## Pyth, ~~20~~ ~~16~~ 14 bytes
```
hol@GNf!-GrT0.:
```
Explanation:
```
.: - substrings of input()
f!-GrT0 - filter to ones which contain the alphabet
ol@GN - sort by number of alphabetical chars
h - ^[0]
f!-GrT0 - filter(lambda T:V, substrings)
rT0 - T.lower()
-G - alphabet-^
! - not ^
o - sort(^, lambda N:V)
@GN - filter_presence(alphabet, N)
l - len(^)
```
[Try it here!](http://pyth.herokuapp.com/?code=hol%40GNf!-GrT0.%3A&test_suite=1&test_suite_input=%22This+isn%27t+a+pangram.%22%0A%22Everyone+knows+about+that+infamous+Quick-Brown-Fox+%28the+one+who+jumped+over+some+lazy+ignoramus+of+a+dog+so+many+years+ago%29.%22%0A%27%22The+five+boxing+wizards+jump+quickly.%22+stated+Johnny%2C+before+beginning+to+recite+the+alphabet+with+a+bunch+of+semicolons+in+the+middle.+%22ABCDEFGHI%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3BJKLMNOPQRSTUVWXYZ!%22+he+shouted+to+the+heavens.%27&debug=0)
When there isn't a correct solution, the program exits with an error with no output to stdout.
[Answer]
# Pyth - 22 bytes
\o/ FGITW!
```
h+ol@GrNZf}GS{rTZ.:z)k
```
[Test Suite](http://pyth.herokuapp.com/?code=h%2Bol%40GrNZf%7DGS%7BrTZ.%3Az%29k&test_suite=1&test_suite_input=This+isn%27t+a+pangram.%0AEveryone+knows+about+that+infamous+Quick-Brown-Fox+%28the+one+who+jumped+over+some+lazy+ignoramus+of+a+dog+so+many+years+ago%29.%0A%22The+five+boxing+wizards+jump+quickly.%22+stated+Johnny%2C+before+beginning+to+recite+the+alphabet+with+a+bunch+of+semicolons+in+the+middle.+%22ABCDEFGHI%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3BJKLMNOPQRSTUVWXYZ%21%22+he+shouted+to+the+heavens.&debug=0).
[Answer]
# Ruby, 100 bytes
Returns nil if no window is found.
```
->s{r=0..s.size
(r.map{|i|s[i,r.find{|j|(?a..?z).all?{|c|s[i,j]=~/#{c}/i}}||0]}-['']).min_by &:size}
```
[Answer]
# JavaScript (ES6), ~~139~~ ~~138~~ 136 bytes
```
s=>[r=l="",...s].map((_,b,a)=>a.map((c,i)=>i>b&&(t+=c,z=parseInt(c,36))>9&&(v++,n+=!m[z],m[z]=n<26||l&&v>l||(r=t,l=v)),t=m=[],v=n=0))&&r
```
*Saved 2 bytes thanks to @Neil!*
## Indented
```
var solution =
s=>
[r=l="",...s].map((_,b,a)=> // b = index of start of window to check
a.map((c,i)=>
i>b&&(
t+=c,
z=parseInt(c,36)
)>9&&(
v++,
n+=!m[z],
m[z]=
n<26||
v>l&&l||(
r=t,
l=v
)
),
t=m=[],
v=n=0
)
)
&&r
```
```
<textarea cols="70" rows="6" id="input">Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).</textarea><br /><button onclick="result.textContent=solution(input.value)">Go</button><pre id="result"></pre>
```
[Answer]
## PowerShell v2+, 218 bytes
```
param($a)$z=@{};(0..($b=$a.length-1)|%{($i=$_)..$b|%{-join$a[$i..$_]}})|%{$y=$_;$j=1;65..90|%{$j*=$y.ToUpper().IndexOf([char]$_)+1};if($j){$z[($y-replace'[^A-Za-z]').Length]=$y}}
($z.GetEnumerator()|sort Name)[0].Value
```
Yeah, so substring manipulation (there aren't any built-ins) isn't really PowerShell's strong suit...
We take input `param($a)` and set a new empty hashtable `$z`. This will be our storage of candidate pangrammatic substrings.
Using a slight modification of my code from [Exploded Substrings](https://codegolf.stackexchange.com/a/78712/42963), we construct *all* substrings of the input. Yep, even one-character punctuation-only substrings. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), not [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'"). ;-)
All of those substrings are encapsulated in parens and piped into another loop with `|%{...}`. We temporarily set `$y` to our current substring, set a helper counter `$j`, and start another loop `65..90|%{...}`, conveniently over the ASCII char codes for capital letters. Each inner loop, we take `$y`, make it all uppercase, and pull out the `.IndexOf` that particular char. Since this will return `-1` if not found, we `+1` the result before multiplying it into `$j`. This ensures that if any one character isn't found, `$j` will equal zero.
Which is exactly what the `if` is all about. If `$j` is non-zero, that means that every letter was found at least once in the substring `$y`, so we need to add that to our candidate pool. We do so by taking `$y` and `-replace`ing every non-letter with nothing, which gets us the letter-length of that substring. We use that as the index into hashtable `$z` and store `$y` at that index. This has the quirk of overwriting substrings of the same letter-length with the one that occurs "furthest" in the original string, but that's allowed by the rules, since we're only concerned about letter-length.
Finally, we need to sort through `$z` and pull out the smallest. We have to use the `.GetEnumerator` call in order to sort on the *objects inside* `$z`, then `sort` those on `Name` (i.e., the length index from above), selecting the `[0]`th one (i.e., the shortest), and outputting its `.Value` (i.e., the substring). If no such substring fits, this will toss an error (`Cannot index into a null array`) when it tries to index into `$z`, and output nothing, which is falsey in PowerShell. (the third test case below has an explicit cast as `[bool]` to show this)
### Test Cases
```
PS C:\Tools\Scripts> .\golfing\shortest-pangrammatic-window.ps1 '"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!"
PS C:\Tools\Scripts> .\golfing\shortest-pangrammatic-window.ps1 'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
Quick-Brown-Fox (the one who jumped over some lazy ig
PS C:\Tools\Scripts> [bool](.\golfing\shortest-pangrammatic-window.ps1 "This isn't a pangram.")
Cannot index into a null array.
At C:\Tools\Scripts\golfing\shortest-pangrammatic-window.ps1:2 char:1
+ ($z.GetEnumerator()|sort Name)[0].Value
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
False
```
[Answer]
# Haskell, 180 bytes
This was hard, but really fun without imports.
```
l=['a'..'z']
u=['A'..'Z']
f&[]=[];f&x=x:f&f x
g#h=(.g).h.g
f x|v<-[y|y<-(tail&)=<<(init&x),and$zipWith((`elem`y)#(||))l u]=last$[]:[z|z<-v,all((length.filter(`elem`l++u))#(<=)$z)v]
```
Much less golfed:
```
lowerCase = ['a'..'z']
upperCase = ['A'..'Z']
f & x = takeWhile (not . null) $ iterate f x
(#) = flip on
subStrings x = (tail &) =<< (init & x)
pangram p = and $ zipWith ((`elem` p) # (||)) lowerCase upperCase
leqLetters x y = (length . filter (`elem` lowerCase ++ upperCase)) # (<=)
fewestLetters xs = [ x | x <- xs, all (leqLetters x) xs]
safeHead [] = ""
safeHead xs = head xs
f x = safeHead . fewestLetters . filter pangram . subStrings
```
Surprise, surprise: it's really slow.
[Answer]
## Oracle SQL 11.2, 461 bytes
```
WITH s AS (SELECT SUBSTR(:1,LEVEL,1)c,LEVEL p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)),v(s,f,l)AS(SELECT c,p,p FROM s UNION ALL SELECT s||c,f,p FROM v,s WHERE p=l+1),c AS(SELECT CHR(96+LEVEL)c FROM DUAL CONNECT BY LEVEL<27),a AS(SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1) a FROM c)SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))FROM(SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c)))x FROM v,c GROUP BY s,f),a WHERE x=26;
```
Un-golfed
```
WITH s AS (SELECT SUBSTR(:1,LEVEL,1)c,LEVEL p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))
,v(s,f,l) AS
(
SELECT c,p,p FROM s
UNION ALL
SELECT s||c,f,p FROM v,s WHERE p=l+1
)
,c AS(SELECT CHR(96+LEVEL)c FROM DUAL CONNECT BY LEVEL<27)
,a AS(SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1) a FROM c)
SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))
FROM(SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c)))x FROM v,c GROUP BY s,f),a
WHERE x=26
```
The `s` view splits the input in characters and also returns the position of each character.
The recursive view `v` returns every substring of the input
s is the substring
f the position of the first character of the substring
l the position of the last character added to the current substring
The `c` view returns the alphabet, one letter at a time
The `a` view returns the alphabet concatenated as a single string
`SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c))`
Returns for each substring the number of distinct letters present in it
`INSTR` returns the pos of a letter in the substring, 0 if not present
`SIGN` returns 1 if pos > 0, 0 if pos = 0
`WHERE x=26`
Filters the substring containing the whole alphabet
`TRANSLATE(LOWER(s),' '||a,' ')`
Deletes every letter from the substring
`LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')`
Length in letters is the length of the substring minus the length of the subtring without letters
`SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))`
Keeps only the substring with the smaller letter count.
If there is more than one, the first one, sorted as strings ascending, is kept
[Answer]
# Python 3, ~~171, 167, 163, 157~~, 149 bytes.
Saved 4 bytes thanks to DSM.
Saved 8 bytes thanks to RootTwo.
```
lambda x,r=range:min([x[i:j]for i in r(len(x))for j in r(len(x))if{*map(chr,r(65,91))}<={*x[i:j].upper()}]or' ',key=lambda y:sum(map(str.isalpha,y)))
```
Having to sort based on the number of letters is killing me.
Test cases:
```
assert f("This isn't a pangram.") == ' '
assert f("Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).") == ' Quick-Brown-Fox (the one who jumped over some lazy ig', f("Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).")
assert f('"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.') == '. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ', f('"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.')
```
[Answer]
## PowerShell (v4), ~~198~~ 156 bytes
```
param($s)
-join(@(1..($y=$s.Length)|%{$w=$_
0..$y|%{(,@($s[$_..($_+$w)]))}}|?{($_-match'[a-z]'|sort -U).Count-eq26}|sort -Pr {($_-match'[a-z]').count})[0])
# Previous 198 byte golf
$a,$b,$c=@(1..($s="$args").Length|%{$w=$_
0..($s.Length-$w)|%{if((($t=$s[$_..($_+$w)]-match'[a-z]')|sort -u).Count-eq26){(,@($t.Length,$_,$w))}}}|sort -pr{$_[0]})[0]
(-join($s[$b..($b+$c)]),'')[!$a]
```
### Test Cases
```
PS C:\> .\PangramWindow.ps1 "This isn't a pangram."
PS C:\> .\PangramWindow.ps1 'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
Quick-Brown-Fox (the one who jumped over some lazy ig
PS C:\> .\PangramWindow.ps1 '"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!
```
---
### Ungolfed explanation of the original
It's a brute-force nested loop which makes sliding windows of all sizes:
```
.SubString(0, 1) -> slide window over the string
.SubString(0, 2) -> slide window over the string
..
.SubString(0, string.Length) -> slide window over the string
```
For each window, it filters for only letters (case insensitive regex matching by default), runs the remaining characters through a unique filter, checks if there are 26 unique characters as the pangram test.
All windows with pangrams are turned into triplets of *(number of letters including dupes, start index, window length including punctuation)*, which get sorted to find the shortest by overall character count, the first one is picked, and the output string built from that.
There's a lot of indexing outside the bounds of the string, which PowerShell usefully returns $null for, instead of throwing exceptions.
NB. the new 156 byte one is the same approach, but rewritten to use the pipeline a lot more.
```
$string = "$args"
# increasing window widths, outer loop
$allPangramWindows = foreach ($windowWidth in 1..$string.Length) {
# sliding windows over string, inner loop
0..($string.Length - $windowWidth) | ForEach {
# slice window out of string, returns a char array
$tmp = $string[$_..($_+$windowWidth)]
# filter the char array to drop not-letters
$tmp = $tmp -match '[a-z]'
# Drop duplicate letters
$tmpNoDupes = $tmp | sort -Unique
# If we're left with a 26 character array, this is a pangrammatic window. Output
# a PowerShell-style tuple of count of letters, start index, width.
if($tmpNoDupes.Count -eq 26){
(,@($tmp.Length,$_,$windowWidth))
}
}
}
# Force the result into an array (to handle no-results), sort it
# by the first element (num of letters in the window, total)
$allPangramWindows = @( $allPangramWindows | sort -Property {$_[0]} )
# take element 0, a window with the fewest letters
$windowCharCount, $windowStart, $WindowEnd = $allPangramWindows[0]
# uses the results to find the original string with punctuation and whitespace
if ($windowLen) {
$string[$windowStart..($windowStart + $windowLen)] -join ''
}
```
NB. not sure the ungolfed version works, because I didn't write that then golf it, it's just for exposition.
[Answer]
# [Julia](https://julialang.org), ~~111,110,108~~ 96 bytes
```
!S=minimum(['A':'Z'⊆(r=S[i:j])|>uppercase ? sum(isletter,r) : Inf,r]
for i=(k=keys(S)),j=k)[2]
```
## Attempt This Online!
* credits to @MarcMush: [96 bytes](https://ato.pxeger.com/run?1=nZC_TsMwEMbn5imuHhpbShmYUCWXPxJInSJUJqpKmMZJnNR25D-UQGcGXoGlSx-qG-JJcChQiZHpTnffd99P97at_FKwze49Y47RWYRuSmFBWBU7YNAwVRgmjxDQMSAUocsHblqtONRKryywe-0duJI5ECpnUnsL114s6uGF0Ss1vNKPgF3JobOsSg2Vlw3PQIczYLXksGRPLYhC6RATzDoPqZkuwhIkUy20nJmQU2jyDfGv8yiab73Lhye7u_6USqGE9BLP4vN4FN_GH68v2NDpTIyqOVmPfdNws2CWwynYIBN2yZ3jJjEERjBReWLmUa4NCIprWvPW4ikhSUVrMjv-yXnuBHiSpIR2n416aUqhP4l6Z8xabhzglFKEYDCA9KsjsF4DPhD9UuA0JZ1sob1yB5gwpfTvjJCIq2yPsNns6yc)
* my first attack: [108 bytes](https://ato.pxeger.com/run?1=nVJPb9MwFJe4NRe-wmuQ1lhqK7ET6uTCBh10wMKWMWBVD27ymrhLnoPttMvYmQNfgUsv-1Bw5JPgdNMkJg4IX2w9v9-f97O_Xy-qXIr1zwcPE2EFn3harHzfP8mkAWmoY0FAKSjVoui7OvAheC3f7972jZaoa0UI56RWBsRMVRZsJixImotCVQaOKhmf9_a0WlFvX11AYDOEBrLKFCyqosQElKMBowqEXFzWIFNSTtCB1dzpJyp1l1AIqqFGoZ1Oqlhjhw-dmf8SuJsA3KwIc7lEmKkLSSms5KXQidlA4XNDntd9H4wV1jEdqIyo7sIM50o7DKaSqIFZBRpjaREafZGXmZihdWw2czPMKoqzZhyDhYxVrsjlS5vWQiZJjn3wd_eevxjtv3w13vlzHbx-8_YwfHd0HJ28P_3w8dNZ2weHM5kL2zlywg1NhmKJZO5i-Wc2F8XUe1RqSTan4HR0HI3DQ3Zd2XnvyY-8HfFCkiyqIgg0jyZysJjudHY7g85Z59e3r1VZoo6FwUAzeAqxqsgG0uRoLequZnyoYQDbxIe-zzwXGUj-eBAQz5FSmwURY92FqxCbbE9vNb80bcG4GzLefEqvFYYc2mOv9UwYg9pCEHLuXm5rC8LNicHVFQR_MxWGrGm7Z8tVOb9fY8xDSm4srNc3-28)
##
It returns `""` for falsy cases; very ineffective (both for time and for memory); it does not optimize for window size/length - only the letter length is considered
[Answer]
## Haskell, 123 bytes
```
import Data.Lists
import Data.Char
h x=take 1$sortOn((1<$).filter isAlpha)[e|e<-powerslice x,['a'..'z']\\map toLower e==""]
```
Defines a function `h`, which returns the empty list if there's no pangrammatic window or a one element list with the minimum window. Usage example:
```
*Main> h "'The five boxing wizards jump quickly.' stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!' he shouted to the heavens."
[". 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ"]
```
How it works:
```
[e|e<-powerslice x ] -- for all continuous subsequences
-- e of the input
,['a'..'z']\\map toLower e=="" -- keep those where the list
-- difference with all letters is
-- empty, i.e. every letter appears
-- at least once
sortOn((1<$).filter isAlpha) -- sort all remaining lists on
-- their length after removing all
-- non-letters -> (1<$) see below
take 1 -- take the first, i.e. the minimum
calculating the length of a list: we're not interested in the length itself, but
in the relative order of the length. (1<$) replaces each element in a list with
the number 1, e.g. "abc" -> "111", "abcd" -> "1111", etc. Such '1'-strings have
the same order as the length of the original list. One byte saved!
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒʒlêAå}éΣág}н
```
[Try it online](https://tio.run/##VY5LUsJAFEW38szYygYcgfjDD4jgh1l38pJ@2nkP0h0Uq9gEO7AsB7gHRyknDih3FDrOvON7zr3ilCZsmu/1z9rWn536Y1Vvtu/1W776/WqaaGwQMlogaHkhzuGZXlWZOnisihnMK0qe7DKOwHnlMYW@GOblPmjMpAwM5sTcYl6gxIQ8gg9CZWdGafTB5g0o0BUnBiQDhwUlYoUdEP9VC0pTizFEne5h7@j45PTs4H/65xeXV4Ph9ehmPLm9u3@Y7kUQOGekah@F4VZjUC2QXbwD) or [verify all test cases](https://tio.run/##VZA7TsNAEIb7nGJwE5CIDwBFFB6BhEd4hGe3jifeJfZM8K4THJFL5AYIUcABEA0NFg0F4kZhHCq2nJ3/@34NWxUYnN@PvBYNM7cG4NXzatUv3lYrXidzi5mM5p@zr1lcvDSKp2nx/P1YPETTn/f53@bHa33e1caCsVR1oGCoKEpV4le2R5jmTAgD4rEFFXDmwGnlwFBfJZxZOM5Mb1DbSHlMtSbfwbLTCGVkrBlusmSIIbBgwHKCEKtJDiYiFryEuS@2kCP5hERRDjmqVDwRr/gVryukvhkhBHxnKIKxmag0tAsq3JbeOPc9sE45kbRZE@WrEGCfU8lgZIjKmGNIsWccQllNxUOtAnRCc1rsQUY9XRaxmJgex0xyB1qsJiYMY/TBa2xsbm03d3Zb6/9fe2//4LBzdHxy2j07v7i8ul7yQHJWy5mkkYhLjEY1QrL@Lw).
Or alternatively with just a sort-by without filter:
```
ŒéΣláDêAQig]н
```
[Try it online](https://tio.run/##VY5NUsJAEIWv0mZt5QKuEPwBQQXxB6pYzCSdTOukGzMTFI/hDSxXcgdXKbYWNwoTd7z1@773xClN2DTbz/rn79vWX7160xlTvtj9Nk00NQgZrRC0vBPn8EYfqkwdPFfFEl4rSl7sOo7AeeUxhYEY5vUxaMykDAzmxNxiXqDEhDyCD0Jll0Zp9MHmDSjQFScGJAOHBSVihR0Q/1cLSlOLMUSd027v7Pzisn9ymMHVcHR9czue3E3vHx6fZvOjCALnjFTtozDcagyqFbKL9w) or [verify all test cases](https://tio.run/##VZBLTgJBEIb3nKLsDZrIHEAXBEV8iyjiI3HRwxTTLTNVON0DDPEU3sC40gMYN24kbo03whpc2cvq@r/vT7HTocXFw1jt0yj3GwCqXlSrwfx9vaLauV/OZKQWX4/zl@/nZP7UnL82Oja@/flYqKD3t/v5Vl90jXVgHVU9aBhpijOdBpWdMWYFE8KQeOJAh5x78EZ7sDTQKecOOrntD2tbGU@o1uIprHqDUEYmhuEuT0cYAQsGHKcIiZ4VYGNiwUuYB2KLOJZPSDUVUKDOxBPzWlBRXSEN7Bgh5KmlGCZ2prPILalwX3qTIlDgvPYiOWBDVKxDiAPOJIOxJSpjniHDvvUIZTWdjIwO0QvNG7GHOfVNWcRhavucMMkdaLma2ihKMADV2Npu7rR29/Y3/7@Dw6Pjk/Zp5@y8e9G7vLq@WVEgOWfkTNJIxCXGoB4jueAX).
Both output an empty string as falsey. (Could have been 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) if we would be allowed to output `-1` as falsey with `ŒéΣág}.ΔlêAå`.)
**Explanation:**
```
Œ # Get all substrings of the (implicit) input-string
ʒ # Filter this list by:
l # Convert the current substring to lowercase
ê # Uniquify and sort all characters in the string
A # Push "abcdefghijklmnopqrstuvwxyz"
å # Check if the lowercase alphabet is in the uniquify-sorted substring
}é # After the filter: sort any remaining substrings from shortest to longest
Σ # Then sort it again by:
á # Leave just all the letters of the substring
g # Pop and push the length for the amount of letters
}н # After the sort-by: pop and leave just the first
# (or an empty string if the list is empty)
# (which is output implicitly as result)
```
```
Œ # Get all substrings of the (implicit) input-string
é # Sort them by length (shortest to longest)
Σ # Then sort it again by:
l # Convert the current substring to lowercase
á # Leave just all the letters of the substring
D # Duplicate it
ê # Uniquify and sort all characters in the letters in the string
AQi # Pop, and if it's equal to the lowercase alphabet:
g # Pop and push the length for the amount of letters
] # Close both the if-statement and sort-by
# (note, integers are always sorted before strings, even if there are
# digits in the input-string)
н # Pop and leave just the first result
# (or an empty string if the list is empty)
# (which is output implicitly as result)
```
] |
[Question]
[
The determinant of a 2 by 2 matrix
```
a b
c d
```
is given by `ad - bc`.
Given a matrix of digits with dimensions 2n by 2n, n ≥ 1, output the result obtained by recursively computing the determinant of each 2 by 2 sub-block until we reach a single number.
For example, given the input
```
3 1 4 1
5 9 2 6
5 3 5 8
9 7 9 3
```
After one step, we obtain:
```
(3*9 - 1*5) (4*6 - 1*2) = 22 22
(5*7 - 3*9) (5*3 - 8*9) 8 -57
```
And iterating once more, we get:
```
(22*-57 - 22*8) = -1430
```
Hence, the output should be `-1430`.
### Rules
* The elements of the matrix will always be single digit integers, i.e. 0 to 9.
* You may take input in any convenient list or string format, as long as no preprocessing of data is done. Since the matrix is always square, you may take input as a single 1D list instead of a 2D list if you wish.
* Input can be via function input, STDIN, command-line argument or closest alternative.
* Output should be a single integer to function output, STDOUT or closest alternative. You may not output the single integer in a list or matrix.
* You may use builtin determinant and matrix manipulation methods if your language happens to support them.
* Your algorithm must work in theory for any valid input.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
### Test cases
The following test cases are given as Python-style lists:
```
[[1,0],[0,1]] -> 1
[[1,9],[8,4]] -> -68
[[0,1,2,3],[4,5,6,7],[8,9,0,1],[2,3,4,5]] -> 40
[[3,1,4,1],[5,9,2,6],[5,3,5,8],[9,7,9,3]] -> -1430
[[9,0,0,9],[0,9,9,0],[9,0,9,0],[0,9,0,9]] -> 13122
[[1,0,0,0,0,0,0,0],[2,1,0,0,0,0,0,0],[3,2,1,0,0,0,0,0],[4,3,2,1,0,0,0,0],[5,4,3,2,1,0,0,0],[6,5,4,3,2,1,0,0],[7,6,5,4,3,2,1,0],[8,7,6,5,4,3,2,1]] -> 1
[[7,1,0,5,8,0,1,5],[9,9,6,6,1,2,4,8],[4,8,7,3,8,7,4,7],[4,6,1,9,7,0,1,7],[7,6,7,1,9,4,1,6],[8,0,0,8,5,5,9,9],[4,6,4,8,9,4,8,6],[9,0,8,7,6,2,1,5]] -> 2937504
[[1,2,3,4,5,6,7,8],[2,3,4,5,6,7,8,1],[3,4,5,6,7,8,1,2],[4,5,6,7,8,1,2,3],[5,6,7,8,1,2,3,4],[6,7,8,1,2,3,4,5],[7,8,1,2,3,4,5,6],[8,1,2,3,4,5,6,7]] -> -10549504
[[1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0],[0,1,1,1,1,0,0,1,0,1,1,1,1,1,1,0],[1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,0],[0,1,1,1,1,0,0,0,0,1,1,1,1,1,0,1],[1,0,1,0,1,1,1,0,0,1,1,1,1,0,1,0],[0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,0],[1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1],[1,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1],[1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1],[0,1,1,1,1,1,1,1,1,0,0,1,0,1,0,1],[1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,0,1,1,0,1,1,1,1,1,0,0,1,1,0],[1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,0,1,0,0,1,0,1,0,1,1,1,1,1,0,1],[1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1]] -> -8
```
*(Thanks to @MartinBüttner for help with this challenge)*
[Answer]
# J, ~~21~~ 25 bytes
```
0{0{(_2(_2-/ .*\|:)\])^:_
```
Usage:
```
]input=.(3,1,4,1),(5,9,2,6),(5,3,5,8),:(9,7,9,3)
3 1 4 1
5 9 2 6
5 3 5 8
9 7 9 3
(0{0{(_2(_2-/ .*\|:)\])^:_) input
_1430
```
At every step we cut up the matrix to 2-by-2's and compute each ones determinant resulting in the next step's input matrix. We repeat this process until the result doesn't change (the final element is the determinant itself). We convert the final result to a scalar with `0{0{`.
[Try it online here.](http://tryj.tk/)
[Answer]
# Mathematica, ~~52~~ 40 bytes
*Thanks to Martin Büttner for saving 12 bytes.*
```
Tr[#//.l:{_,__}:>BlockMap[Det,l,{2,2}]]&
```
---
**Explanation**
`BlockMap[f,expr,n]` split `expr` into sublists of size `n` and map `f` on every sublists. `BlockMap[Det,#,{2,2}]&` split the input array into 2\*2 blocks and calculate their determinants.
---
**Test case**
```
%[{{3,1,4,1},{5,9,2,6},{5,3,5,8},{9,7,9,3}}]
(* -1430 *)
```
[Answer]
# Jelly, ~~20~~ 17 bytes
```
s€2s2U×¥/€ḅ-µL¡SS
```
[Try it online!](http://jelly.tryitonline.net/#code=c-KCrDJzMlXDl8KlL-KCrOG4hS3CtUzCoVNT&input=&args=W1swLDEsMiwzXSxbNCw1LDYsN10sWzgsOSwwLDFdLFsyLDMsNCw1XV0) or [verify all test cases at once](http://jelly.tryitonline.net/#code=c-KCrDJzMlXDl8KlL-KCrOG4hS3CtUzCoVNTCltbMSwwXSxbMCwxXV0sW1sxLDldLFs4LDRdXSxbWzAsMSwyLDNdLFs0LDUsNiw3XSxbOCw5LDAsMV0sWzIsMyw0LDVdXSxbWzMsMSw0LDFdLFs1LDksMiw2XSxbNSwzLDUsOF0sWzksNyw5LDNdXSxbWzksMCwwLDldLFswLDksOSwwXSxbOSwwLDksMF0sWzAsOSwwLDldXSxbWzEsMCwwLDAsMCwwLDAsMF0sWzIsMSwwLDAsMCwwLDAsMF0sWzMsMiwxLDAsMCwwLDAsMF0sWzQsMywyLDEsMCwwLDAsMF0sWzUsNCwzLDIsMSwwLDAsMF0sWzYsNSw0LDMsMiwxLDAsMF0sWzcsNiw1LDQsMywyLDEsMF0sWzgsNyw2LDUsNCwzLDIsMV1dLFtbNywxLDAsNSw4LDAsMSw1XSxbOSw5LDYsNiwxLDIsNCw4XSxbNCw4LDcsMyw4LDcsNCw3XSxbNCw2LDEsOSw3LDAsMSw3XSxbNyw2LDcsMSw5LDQsMSw2XSxbOCwwLDAsOCw1LDUsOSw5XSxbNCw2LDQsOCw5LDQsOCw2XSxbOSwwLDgsNyw2LDIsMSw1XV0sW1sxLDIsMyw0LDUsNiw3LDhdLFsyLDMsNCw1LDYsNyw4LDFdLFszLDQsNSw2LDcsOCwxLDJdLFs0LDUsNiw3LDgsMSwyLDNdLFs1LDYsNyw4LDEsMiwzLDRdLFs2LDcsOCwxLDIsMyw0LDVdLFs3LDgsMSwyLDMsNCw1LDZdLFs4LDEsMiwzLDQsNSw2LDddXSxbWzEsMSwxLDAsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDBdLFswLDEsMSwxLDEsMCwwLDEsMCwxLDEsMSwxLDEsMSwwXSxbMSwxLDAsMSwxLDAsMSwxLDEsMSwxLDEsMSwxLDEsMF0sWzAsMSwxLDEsMSwwLDAsMCwwLDEsMSwxLDEsMSwwLDFdLFsxLDAsMSwwLDEsMSwxLDAsMCwxLDEsMSwxLDAsMSwwXSxbMCwwLDEsMSwxLDAsMSwxLDEsMSwxLDEsMSwwLDAsMF0sWzEsMSwxLDEsMSwwLDEsMCwxLDEsMSwxLDEsMSwxLDFdLFsxLDEsMCwxLDEsMSwxLDEsMSwxLDEsMSwwLDEsMCwxXSxbMSwxLDEsMSwxLDEsMSwxLDEsMSwwLDEsMSwxLDEsMV0sWzAsMSwxLDEsMSwxLDEsMSwxLDAsMCwxLDAsMSwwLDFdLFsxLDAsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxXSxbMSwxLDAsMSwxLDAsMSwxLDEsMSwxLDAsMCwxLDEsMF0sWzEsMSwxLDEsMSwxLDEsMSwwLDEsMSwxLDEsMSwxLDBdLFsxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxXSxbMSwwLDEsMCwwLDEsMCwxLDAsMSwxLDEsMSwxLDAsMV0sWzEsMSwxLDEsMSwxLDEsMSwxLDAsMCwxLDEsMSwwLDFdXcOH4oKs&input=).
### How it works
```
s€2s2U×¥/€ḅ-µL¡SS Main link. Input: M (matrix)
s€2 Split each row of M into pairs.
s2 Split the result into pairs of rows.
/€ Reduce each pair...
¥ by applying the following, dyadic chain:
U Reverse each pair of the left argument (1st row).
× Multiply element-wise with the right argument (2nd row).
ḅ- Convert each resulting pair from base -1 to integer.
This maps [a, b] -> b - a.
µ Turn the previous links into a monadic chain. Begin a new one.
L Yield the length of the input.
¡ Execute the previous chain L times.
log2(L) times would do, but who's counting?
SS Sum twice to turn the resulting 1x1 matrix into a scalar.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~93~~ 86 bytes
EDIT: Thanks to @Laikoni for shortening this a whole 7 bytes!
```
f[[a,b],[c,d]]=a*d-b*c
f m|let l=[take,drop]<*>[div(length m)2]=f[f.($b<$>m)<$>l|b<-l]
```
I didn't know you could put a let statement before the = and I've never gotten used to those monad operators. Thanks again @Laikoni
Old version:
```
f[[a,b],[c,d]]=a*d-b*c
f m=f[[f$a$map b m|a<-l]|b<-l]where h=length m`div`2;l=[take h,drop h]
```
[Try it online!](https://tio.run/##FY3LDoIwEEX3fsUsWJEhUXwS7Zc0kzClrSW0SLDRDf9ex83NyTmLG/g9uRhL8VozGkI9oCVSXNvG1MPOQ1KSfMVV4gUMpI0fTaTN/Pcb3OogqOjmZw6Qejt@@vYelc48SUC7vhYIVBKPs1rWcc5QgQet93jAFo/yd8IzXvAqdMMOxQtJQfFE5Qc "Haskell – Try It Online")
This is a function that recurs on itself in two different ways. First the pattern matching catches the the base case: a 2x2 matrix and it does the calculation. I use this to do the calculation in the recursive case by calling the function with a 2x2 matrix I generate that has the recursive solutions in it. That matrix is generated by iterating twice over an array of functions that each chop a list in half. I apply it to rows with a simple call and apply it to columns using `map`.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~30~~ 26 bytes
```
`tnX^teHHhZC2Ih2#Y)pwp-tnq
```
Input is a 2D array with rows separated by `;`, that is,
```
[3 1 4 1; 5 9 2 6; 5 3 5 8; 9 7 9 3]
```
[**Try it online!**](http://matl.tryitonline.net/#code=YHRuWF50ZUhIaFpDMkloMiNZKXB3cC10bnE&input=WzMgMSA0IDE7IDUgOSAyIDY7IDUgMyA1IDg7IDkgNyA5IDNd)
```
` % do...while loop
tnX^te % reshape into square matrix. Implicitly asks for input the first time
HHhZC % transform each 2x2 block into a column
2Ih2#Y) % push matrix with rows 2,3, and also matrix with remaining rows (1,4)
pwp- % multiplications and subtraction to compute the 2x2 determinants
tnq % condition of do...while loop: is number of elements greater than 1?
% implicitly end loop
% implicitly display
```
[Answer]
# Python, 166 bytes
```
def f(m):l=len(m)/2;g=lambda x,y:[(s[:l],s[l:])[x]for s in(m[:l],m[l:])[y]];return f(g(0,0))*f(g(1,1))-f(g(0,1))*f(g(1,0)) if l>1 else m[0][0]*m[1][1]-m[1][0]*m[0][1]
```
This passes all the test cases provided. m has to be a 2D array (like in the test cases), g selects the sub matrix.
[Answer]
# Pyth, 26
```
M-F*VG_HhhumgMCcR2dcG2llQQ
```
[Test Suite](http://pyth.herokuapp.com/?code=M-F%2AVG_HhhumgMCcR2dcG2llQQ&input=%5B%5B0%2C1%2C2%2C3%5D%2C%5B4%2C5%2C6%2C7%5D%2C%5B8%2C9%2C0%2C1%5D%2C%5B2%2C3%2C4%2C5%5D%5D&test_suite=1&test_suite_input=%5B%5B1%2C0%5D%2C%5B0%2C1%5D%5D%0A%5B%5B1%2C9%5D%2C%5B8%2C4%5D%5D%0A%5B%5B0%2C1%2C2%2C3%5D%2C%5B4%2C5%2C6%2C7%5D%2C%5B8%2C9%2C0%2C1%5D%2C%5B2%2C3%2C4%2C5%5D%5D%0A%5B%5B3%2C1%2C4%2C1%5D%2C%5B5%2C9%2C2%2C6%5D%2C%5B5%2C3%2C5%2C8%5D%2C%5B9%2C7%2C9%2C3%5D%5D%0A%5B%5B9%2C0%2C0%2C9%5D%2C%5B0%2C9%2C9%2C0%5D%2C%5B9%2C0%2C9%2C0%5D%2C%5B0%2C9%2C0%2C9%5D%5D%0A%5B%5B1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%5D%2C%5B2%2C1%2C0%2C0%2C0%2C0%2C0%2C0%5D%2C%5B3%2C2%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B4%2C3%2C2%2C1%2C0%2C0%2C0%2C0%5D%2C%5B5%2C4%2C3%2C2%2C1%2C0%2C0%2C0%5D%2C%5B6%2C5%2C4%2C3%2C2%2C1%2C0%2C0%5D%2C%5B7%2C6%2C5%2C4%2C3%2C2%2C1%2C0%5D%2C%5B8%2C7%2C6%2C5%2C4%2C3%2C2%2C1%5D%5D%0A%5B%5B7%2C1%2C0%2C5%2C8%2C0%2C1%2C5%5D%2C%5B9%2C9%2C6%2C6%2C1%2C2%2C4%2C8%5D%2C%5B4%2C8%2C7%2C3%2C8%2C7%2C4%2C7%5D%2C%5B4%2C6%2C1%2C9%2C7%2C0%2C1%2C7%5D%2C%5B7%2C6%2C7%2C1%2C9%2C4%2C1%2C6%5D%2C%5B8%2C0%2C0%2C8%2C5%2C5%2C9%2C9%5D%2C%5B4%2C6%2C4%2C8%2C9%2C4%2C8%2C6%5D%2C%5B9%2C0%2C8%2C7%2C6%2C2%2C1%2C5%5D%5D%0A%5B%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%5D%2C%5B2%2C3%2C4%2C5%2C6%2C7%2C8%2C1%5D%2C%5B3%2C4%2C5%2C6%2C7%2C8%2C1%2C2%5D%2C%5B4%2C5%2C6%2C7%2C8%2C1%2C2%2C3%5D%2C%5B5%2C6%2C7%2C8%2C1%2C2%2C3%2C4%5D%2C%5B6%2C7%2C8%2C1%2C2%2C3%2C4%2C5%5D%2C%5B7%2C8%2C1%2C2%2C3%2C4%2C5%2C6%5D%2C%5B8%2C1%2C2%2C3%2C4%2C5%2C6%2C7%5D%5D%0A%5B%5B1%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%5D%2C%5B0%2C1%2C1%2C1%2C1%2C0%2C0%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C0%5D%2C%5B1%2C1%2C0%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%5D%2C%5B0%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C0%2C1%5D%2C%5B1%2C0%2C1%2C0%2C1%2C1%2C1%2C0%2C0%2C1%2C1%2C1%2C1%2C0%2C1%2C0%5D%2C%5B0%2C0%2C1%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%5D%2C%5B1%2C1%2C1%2C1%2C1%2C0%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%5D%2C%5B1%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C1%2C0%2C1%5D%2C%5B1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C1%5D%2C%5B0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C1%2C0%2C1%2C0%2C1%5D%2C%5B1%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%5D%2C%5B1%2C1%2C0%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C1%2C1%2C0%5D%2C%5B1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C0%5D%2C%5B1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%5D%2C%5B1%2C0%2C1%2C0%2C0%2C1%2C0%2C1%2C0%2C1%2C1%2C1%2C1%2C1%2C0%2C1%5D%2C%5B1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C1%2C1%2C1%2C0%2C1%5D%5D&debug=0)
This has two parts: `M-F*VG_H` redefines the function `g` to calculate the determinant of a two by two matrix. This saves bytes even though we only use it once because it unpacks the two rows.
The other part is a large reduce statement that we call `log_2( len( input() ) )` times. Unfortunately, performing a step in the reduction on a 1 by 1 matrix causes the result to be wrapped in a list, so we don't get a fixed point. The reduce is mostly just splitting up the matrix to get 2 by 2 matrices and then applying `g`.
[Answer]
# [Perl 5](https://www.perl.org/), 120 + 1 (`-a`) = 121 bytes
```
while($#F){@r=();for$i(@o=0..($l=sqrt@F)/2-1){push@r,$F[$k=$i*$l*2+2*$_]*$F[$k+$l+1]-$F[$k+$l]*$F[$k+1]for@o}@F=@r}say@F
```
[Try it online!](https://tio.run/##TcxPC8IgGIDxr/JC70FdLrXWH0Lw5K1PECN2KCZJLl1EjH31LIJBt4ff4enO0Vc5P1vnzwRnlg4makL3lxDRERO0KEuCXqd77I2lC8UlHbpHak2coz3iVaNj6JkqFMNTzX5WoC9kzaeeVNbfqwmjsdrEMTUvY3MWIEHBElZQwRo2sIUd/Nk7dL0Lt5T5oSqFFJk3Hw "Perl 5 – Try It Online")
Takes the input as a list of space separated numbers.
[Answer]
## ES6, 91 bytes
```
(a,x=0,y=0,w=a.length)=>(w>>=1)?f(a,x,y,w)*f(a,x+w,y+w,w)-f(a,x,y+w,w)*f(a,x+w,y,w):a[x][y]
```
Straightforward recursive solution.
[Answer]
# [R](https://www.r-project.org/), 111 bytes
```
f=function(m)"if"((n=nrow(m))-2,f(matrix(c(f(m[x<-1:(n/2),x]),f(m[y<-x+n/2,x]),f(m[x,y]),f(m[y,y])),2)),det(m))
```
[Try it online!](https://tio.run/##jZBNboMwEIWvgrLxWB3aAambCo7QTdWdQyVCIUFKTAVOa05PbZoAMY5ULKT5ef7mjdtBNW@vuWprHSRhUJ1loepGQsdPYxF0Epbf@RG@8rYrQaX77rwDtt0KhqwAhn95ZjLOsOPmQ9k2P@mxlHt1AM0/Hp9x19vSOx@qdJpw4pu62gDI1OpNysMYK7iMLcCEwgyPXkA@xRx1xm1X9EmoH0xlKmjsry0bcYzN/1kqSxwqCKb9gAkRoT2EkfdQhmLu0aijlWIm0L8YdKMz8chYspcKmhiEfrcj8eJjccd1cuPUJcw@/N2ZQZ4@OYx777n2QStO5Ozi25nuOHWnkOtu9er@Xa6KjPGAD78 "R – Try It Online")
Takes input as an R matrix (which is converted by the function in the header).
[Answer]
# Groovy, ~~221~~ 189 bytes (At this point, could've used Java)
```
f={x->b=x.size();c=b/2-1;a=(0..c).collect{i->(0..c).collect{j->z=x.toList().subList(i*2,i*2+2).collect{it.toList().subList(j*2,j*2+2)};z[0][0]*z[1][1]-z[0][1]*z[1][0];}};a.size()==1?a:f(a)}
```
---
***Old crappy version, which might as well be Java (221 bytes):***
```
f={x->b=x.size();a=new int[b/2][b/2];for(i=0;i<b-1;i+=2){for(j=0;j<b-1;j+=2){z=x.toList().subList(i,i+2).collect{it.toList().subList(j,j+2)};a[(int)(i/2)][(int)(j/2)]=z[0][0]*z[1][1]-z[0][1]*z[1][0];}};a.size()==1?a:f(a)}
```
Ungolfed code:
```
f=
{x->
b=x.size();
int[][]a=new int[b/2][b/2];
for(i=0;i<b-1;i+=2) {
for(j=0;j<b-1;j+=2) {
z=x.toList().subList(i,i+2).collect{
it.toList().subList(j,j+2)
};
a[(int)(i/2)][(int)(j/2)]=z[0][0]*z[1][1]-z[0][1]*z[1][0];
}
}
a.size()==1
?
a:f(a)
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 25 bytes
```
ω(m(moF`-Fz*C2z*:1İ_)TmC2
```
[Try it online!](https://tio.run/##yygtzv7//3ynRq5Gbr5bgq5blZazUZWWleGRDfGaIbnORv///4@ONtYx1DHRMYzViTbVsdQx0jEDs4x1THUsgCxLHXOgqHFsLAA "Husk – Try It Online")
The testcases in this one are great.
] |
[Question]
[
Given an input of any valid [Glypho](http://esolangs.org/wiki/Glypho) program,
output its "human-readable" counterpart.
Glypho is an interesting esolang idea:
>
> The instruction reference is given here. For each instruction, the characters
> abcd represent the symbols composing each instruction. a refers to the first
> unique symbol, b refers to the second unique symbol, etc.
>
>
>
> ```
> aaaa ..... n NOP - no operation; do nothing
> aaab ..... i Input - push input onto top of stack
> aaba ..... > Rot - pops top stack element and pushes to bottom of stack
> aabb ..... \ Swap - swaps top two stack elements
> aabc ..... 1 Push - pushes a 1 onto the top of stack (creates new element)
> abaa ..... < RRot - pops bottom element and pushes to top of stack
> abab ..... d Dup - Duplicates top stack element
> abac ..... + Add - pops top two elements and pushes their sum
> abba ..... [ L-brace - skip to matching ] if top stack element is 0
> abbb ..... o Output - pops and outputs top stack element
> abbc ..... * Multiply - pops top two elements and pushes their product
> abca ..... e Execute - Pops four elements and interprets them as an instruction
> abcb ..... - Negate - pops value from stack, pushes -(value)
> abcc ..... ! Pop - pops and discards top stack element
> abcd ..... ] R-brace - skip back to matching [
>
> ```
>
> (credit: [Brian Thompson](http://esolangs.org/wiki/Brian_Thompson) aka
> Wildhalcyon)
>
>
>
So, for example, `PPCG` would represent the *Push* instruction—`PPCG` matches
the pattern `aabc`, where `a` represents `P`, `b` represents `C`, and `c`
represents `G`.
The input will be a single string consisting of only printable ASCII
characters. It will always have a length divisible by four (duh).
The output is each group of four characters in the input string replaced by
which instruction they designate. Use the single-letter instruction names (the
ones right after the five dots in the table quoted above).
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Test cases:
```
In Out
------------------------------------------------
Programming Puzzles & Code Golof ]!]!]]]+
nananananananana batman! dddd]]
;;;;;;;:;;:;;;:: ni>\
llamas sleep 1-*
8488133190003453 <[oe
<empty string> <empty string>
```
[Answer]
# Pyth, ~~37~~ ~~35~~ 34 bytes
The code contains unprintable characters, so here is the `xxd` hexdump:
```
0000000: 5663 7a34 7040 2e22 216f d78c 40bf d4f0 Vcz4p@."!o..@...
0000010: 38d6 7dfe 7312 3ff8 ea22 6958 4e7b 4e55 8.}.s.?.."iXN{NU
0000020: 5433 T3
```
Here's a printable version at 36 bytes:
```
Vcz4p@"ni >\\1 <d+[o*e-!]"iXN{NUT3
```
[Try it online.](https://pyth.herokuapp.com/?code=Vcz4p%40.%22!o%C3%97%C2%8C%40%C2%BF%C3%94%C3%B08%C3%96%7D%C3%BEs%12%3F%C3%B8%C3%AA%22iXN%7BNU4%203&input=Programming+Puzzles+%26+Code+Golof&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=Vcz4p%40.%22!o%C3%97%C2%8C%40%C2%BF%C3%94%C3%B08%C3%96%7D%C3%BEs%12%3F%C3%B8%C3%AA%22iXN%7BNU4%203&test_suite=1&test_suite_input=Programming+Puzzles+%26+Code+Golof%0Anananananananana+batman%21%0A%3B%3B%3B%3B%3B%3B%3B%3A%3B%3B%3A%3B%3B%3B%3A%3A%0Allamas+sleep%0A8488133190003453%0A%0A&debug=0)
### Explanation
```
Vcz4p@."…"iXN{NUT3 implicit: z = input
z input
c 4 split to 4-character blocks
V loop over that in N
X replace...
N in current part
{N unique chars in current part, in order
UT with numbers 0-9
i 3 interpret as base 3
@ take that item of
."…" string "ni >\\1 <d+[o*e-!]"
p and print without newline
```
[Answer]
## CJam, ~~42~~ ~~39~~ 35 bytes
*Saved 4 bytes borrowing user81655's idea of using base 3 instead of base 4.*
```
l4/{__&f#3b"ni >\1 <d+[o*e-!]"=}%
```
[Run all test cases.](http://cjam.aditsu.net/#code=qN%2F%7BS2*%2F0%3D%3AL%3B%0A%0AL4%2F%7B__%26f%233b%22ni%20%3E%5C1%20%20%20%3Cd%2B%5Bo*e-!%5D%22%3D%7D%25%0A%0A%5DoNo%7D%2F&input=aaaaaaabaabaaabbaabcabaaabababacabbaabbbabbcabcaabcbabccabcd%0AProgramming%20Puzzles%20%26%20Code%20Golof%20%20%5D!%5D%5D!%5D%5D%5D%2B%0Anananananananana%20batman!%20%20%20%20%20%20%20%20%20%20dddd%5D%5D%0A%3B%3B%3B%3B%3B%3B%3B%3A%3B%3B%3A%3B%3B%3B%3A%3A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ni%3E%5C%0Allamas%20sleep%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%201-*%0A8488133190003453%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3C%5Boe%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20)
There's gotta be a better way to compress the lookup table of commands...
[Answer]
# JavaScript (ES6), 97
For each block of 4 characters, I substitute each symbol with its position in the block, getting a base 4 number. For instance `'aabc' -> '0023'`. The possibile numbers are in the range 0..0123, that is 0..27 in decimal. I use the number as an index to find the right instruction character from a 28 chars string.
```
s=>s.replace(/.{4}/g,s=>'n..i....>.\\1....<d.+[o.*e-!]'[[...s].map(c=>n=n*4+s.indexOf(c),n=0),n])
```
**Test**
```
F=s=>s.replace(/.{4}/g,s=>'n..i....>.\\1....<d.+[o.*e-!]'[[...s].map(c=>n=n*4+s.indexOf(c),n=0),n])
function test() { O.textContent=F(I.value) }
test();
```
```
#I { width:90% }
```
```
<input id=I value="nananananananana batman!" oninput="test()">
<br><span id=O></span>
```
[Answer]
# MATLAB, 291 bytes
I hesitated for quite a long time if I should commit my answer. I was just playing around with MATLAB. I am aware that it's not really possible to generate dense code (a low number of instructions/bytes; about 3 times larget than your ~100 byte solutions) and that MATLAB might not be too suitable for code golf and I am new to code golf. But I simply wanted to try, and the code works (newline characters kept). Any hints welcome. :P
```
i=input('','s');
l=reshape(i,4,length(i)/4)';
m=']!- e';m(9)='*';m(12:22)='o[ + d <';m(33:34)='1\';m(39)='>';m(57)='i';m(64)='n';
s='';
for k = 1:size(l,1)
n=l(k,:);
c=combvec(n,n);
t=triu(reshape(c(1,:)==c(2,:),4,4),1);
t=sum(t([5,9:10,13:15]).*2.^[5:-1:0]);
s=[s,m(t+1)];
end
display(s)
```
[Answer]
# JavaScript (ES6), ~~115~~ 101 bytes
```
s=>s.replace(/..../g,g=>"ni >\\1 <d+[o*e-!]"[[...g].map(c=>r=r*3+(m[c]=m[c]||++i)-1,i=r=0,m={})|r])
```
*Saved 14 bytes thanks to [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)!*
## Explanation
Stores the list of instructions in a string with each character at it's base-3 index. For example, `+` corresponds to `abac` which can be represented in base-3 as `0102`, or `11` in decimal. The only instruction that cannot be represented in base-3 is `]`, but with the algorithm used to compute the base-3 number, it conveniently ends up needing to be at position 18 at the end of the string.
```
s=>
s.replace(/..../g,g=> // replace each four-character group with it's instruction
"ni >\\1 <d+[o*e-!]" // list of instructions at their base-3 index
[
[...g].map(c=> // for each character c
r=r*3+(m[c]=m[c] // shift r left and add the number associated with c to r
||++i)-1, // if nothing is associated, associate the next number to c
// save i + 1 to m[c] so that it is truthy for 0
i= // i = current number to assign to the next unique character
r=0, // r = 4-character group as a base-3 number
m={} // m = map of numbers assigned to each character
)
|r // return r
]
)
```
## Test
```
var solution = s=>s.replace(/..../g,g=>"ni >\\1 <d+[o*e-!]"[[...g].map(c=>r=r*3+(m[c]=m[c]||++i)-1,i=r=0,m={})|r])
```
```
<input type="text" id="input" value="Programming Puzzles & Code Golof" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# [Zsh](https://www.zsh.org/), 118 bytes
```
0="n i > \1${(l:11:)}<d + [o * e-!]"
for s (`tr \ £|fold -4`)(eval ';n+=$s[(i)$s['{2..4}]];printf $0[5#$n-30])
```
[Try it online!](https://tio.run/##HcQxDoIwAAXQ3VN8kUiRQEBxAXFxcGWHJpBQkKS0pkUHkNN4Ey9WjW94k74ZE2aWAHr8nVFG9kx4EkWJu5waeCgkdmD@mlqrVipokGpUKIHP@9VK3sCPK5ewZ83hpMLLbF2Q3v3tzPsgiBdK07vqxdjCDovjxhb@IaSuMbmSnaqHoRcd8sc0caaxxUU2DFfJZfsF "Zsh – Try It Online")
* `0="n i > \1${(l:11:)}<d + [o * e-!]"` - store this string in the variable `$0`. `${(l:11:)}` generates 11 spaces (literally, left-padding an empty string to a length of 11), and is 1 byte shorter than writing them literally.
* `tr \ £` - replace spaces (`\` ) with `£`s. This is because spaces in the input will be eaten when word splitting, messing up the 4 character grouping. Word splitting is useful though, because it allows us to loop over each line, which is how `fold` splits things. I used `£` because it's outside the printable ASCII range that we're required to accept and only 2 bytes in UTF-8 (I could probably technically save a byte if I used a different encoding, but that's not worth the effort). Unfortunately I can't use a control character because `zsh` doesn't like them.
* `fold -4` - group into 4 characters per line
* `for s (``)` - for each group, `$s`, of 4 characters:
+ `';n+=$s[(i)$s['{2..4}]]`: generate the string `;n+=$s[(i)$s[2]];n+=$s[(i)$s[3]];n+=$s[(i)$s[4]]`
+ `eval`uate that as `zsh` code:
- `$s[X]` - the `X`th character of `$s` (1-indexed)
- `$s[(i)]` - find the index of the first appearance of that character within `$s`
- `n+=` - append that to `$n` (which implicitly starts out empty)
- `eval` with brace expansion (like `{2..4}`) is a shorter way to do a simple loop than using `for`
- We only need to use `{2..4}` as the first index of the first character of the string will obviously always be `1`. This lets us save a byte when subtracting later (otherwise it would be -155 rather than -30)
- `5#$n` - interpret `n` as a base-5 integer (if zsh used 0-based indexing, this could be base 4, we wouldn't need to subtract anything, and the `$0` string could be shorter)
+ `-30` - the minimum base-5 value we can get from any combination of characters is `31`, and since `zsh` is 1-indexed, we subtract 30 to get an index into the string `$0`
+ `$0[]` - get that index into the string `$0` for the relevant character to print. The spaces in `$0` are padding to make the right characters appear in the right places since the possible base-5 values aren't contiguous.
+ `printf` - print that with no newline
- `()` - subshell; any changes to variables do not persist outside the brackets. This is used to reset `$n` to an empty string on each iteration.
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
'ni >\1 <d+[o*e-!]'{~_4(3#.~.i.])\]
```
[Try it online!](https://tio.run/##VcJNC4IwHIDx@z7FX4LsxYZjBqYWQVCXDt5TZOW0xV7C2cXAr76gTj2/5@Fcs8XgawG7ggBAVi8vZsFXXum/xyqa0QkescDlvCgdv91NgLN9k@KKwPkYgO1roYG4vDNtx5QSuoX8NQySW5jCwdQcTkaaBmn2D66sV0x7KP2VfE@TBEnJFLNgJedPFEdxTCglmzAMabSm6AM "J – Try It Online")
[Answer]
# Python 2, 158 bytes
Takes input like `"test"`. Output is a list of characters.
```
def b(s,i=0):
for c in s:i=i*4+s.index(c)
return"n..i....>.\\1....<d.+[o.*e-!]"[i]
print map(b,(lambda l,n:[l[i:i+n]for i in range(0,len(l),n)])(input(),4))
```
[**Try it Online!**](https://tio.run/##HY2xDoIwFAB3vuLJYFqoDRomIi4OruzAUGjBl5RXUiBRfh7Bmy654cbv/HZ02zZtOmjYJDBPeBbATuc8tIAEU4Y5Rmk8SSRtPqzl/@7NvHgKSUqUOw9ZVddD7lrGpZORuZzqsMQ6GD3SDIMaWSOYVUOjFVhBWWlLzDCm@jjhcfKKesMSYQ0xywXxmjOkcZkZFynn2xYW3vVeDQNSD8WyrtZMcIan0wZezrou/AE)
**Ungolfed:**
```
def chunks(l, n):
return (l[i:i+n] for i in range(0, len(l), n))
def convert(inst):
i = 0
for c in inst:
i = i*4 + inst.index(c)
return "n..i....>.\\1....<d.+[o.*e-!]"[i]
print map(convert, chunks(input(), 4))
```
] |
[Question]
[
### New Bonus! (See below)
The cartography team of U.S. Republican presidential hopeful Ben Carson is having some trouble with their maps (image via [Washington Post](https://www.washingtonpost.com/news/wonk/wp/2015/11/18/ben-carsons-campaign-made-a-u-s-map-and-put-a-bunch-of-states-in-the-wrong-place/)):
[](https://i.stack.imgur.com/Jkj3M.png)
The problem is they don't have the Right Tool For The Job™. They need the most compact and reliable program possible, so they never have to worry about making maps again. That's why they hired you. You need to take this map and output it again with the desired coloring:
[](https://upload.wikimedia.org/wikipedia/commons/1/1a/Blank_US_Map_%28states_only%29.svg)
>
> By Theshibboleth [GFDL (<http://www.gnu.org/copyleft/fdl.html>) or
> CC-BY-SA-3.0 (<http://creativecommons.org/licenses/by-sa/3.0/)]>, via
> Wikimedia Commons
>
>
>
If you don't know where all the states are (because you are not an American...or you are an American), here is a map with all the names (Washington D.C. is not required for this challenge):
[](https://i.stack.imgur.com/lb658.png)
>
> "Map of USA with state names 2". Licensed under CC BY-SA 3.0 via
> Wikimedia Commons -
> <https://commons.wikimedia.org/wiki/File:Map_of_USA_with_state_names_2.svg#/media/File:Map_of_USA_with_state_names_2.svg>
>
>
>
For example if the input is `Ohio, Indiana, Illinois;New York, New Jersey, Florida`, you output:
[](https://i.stack.imgur.com/8lPJr.png)
The blank map image is available in [SVG](https://upload.wikimedia.org/wikipedia/commons/1/1a/Blank_US_Map_%28states_only%29.svg) and [PNG](https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Blank_US_Map.svg/800px-Blank_US_Map.svg.png) formats. For your convenience, here is a list of [all 50 states in alphabetical order](http://liststates.com)
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'") challenge. Output must be as a SVG or image file. Simply displaying the output on the screen is not enough. Input must be taken from STDIN or by reading a text file. I am flexible with how you format the input, although it should contain the full names of each state, with red (Republican) states listed first and blue (Democratic) states second. Any two distinct shades of red and blue are acceptable for the coloring. Of course, you can have the blank map image in the same folder as your program with whatever file name you want.
## Accuracy Criteria
If your output is a raster file, it must be at least 800px by 495px, and the lines should not deviate from the result of scaling up the SVG to the same size by more than 1.5 pixels. If your output is a vector file, the lines should not deviate from the SVG by more than 1.5 pixels when both are scaled to 800px by 495px.
## Bonus!
Ben is trying to cut down dependence on foreign libraries, and is now offering a **-50%** bonus to anyone who uses only a raster graphics version of the map as input and creates their own algorithm for region detection. Ultimately, it is my judgment that determines whether your approach counts as "writing your own" algorithm.
Good Luck!
[Answer]
# Python 626
In the approach below, I added .rstate and .bstate based on .state in the CSS description. In my I renamed the provided .svg file to `v.svg`. It takes an input as described below and writes to a file `w.png`. To transfer from the full state name to the abbreviated version I look them up based on the first and last two letters of the states.
```
r='Ama,Aka,Ana,Aas,Cia,Cdo,Cut,Dre,Fda,Gia,Hii,Iho,Iis,Ina,Iwa,Kas,Kky,Lna,Mne,Mnd,Mts,Man,Mta,Mpi,Mri,Mna,Nka,Nda,Nre,Ney,Nco,Nrk,Nna,Nta,Oio,Oma,Oon,Pia,Rnd,Sna,Sta,Tee,Tas,Uah,Vnt,Via,Won,Wia,Win,Wng'.split(',')
y='lkzraotelaidlnasyaedainsotevhjmycdhkraicdnxttaaviy'
v=open('v.svg','r')
s=v.read()
v.close()
k=s.find('.state')
j=s.find('.',k+1)
t=input().split(';')
w=open('w.svg','w')
k+=1
c='#E0E0E0'
s=s[:j]+'.r'+s[k:j].replace(c,'red')+'.b'+s[k:j].replace(c,'blue')+s[j:]
c='rb'
for j in range(2):
for d in t[j].split(','):k=s.find('state '+d[0].lower()+y[r.index(d[0]+d[-2:])]);s=s[:k]+c[j]+s[k:]
w.write(s)
w.close()
```
Example input:
```
'California,Illinois,Iowa,Mississippi;New Mexico,Pennsylvania,South Dakota,Vermont'
```
Example output:
[](https://web.archive.org/web/20170919215822/https://imgh.us/w_2.svg)
Or inspired by the flag of France:
[](https://web.archive.org/web/20170919215822/https://imgh.us/w2.svg)
[Answer]
# Processing, 425 bytes (259 bytes + 1 +165 byte file)
Code:
```
size(959,593);String[]a=loadStrings("a"),b=loadStrings("b");PShape m=loadShape("M.svg");m.disableStyle();for(int i=0;i<51;i++){fill(255);int r=0;for(String j:a){if(j.isEmpty())r++;if(j.contains(b[i]))fill(r>0?#0000FF:#FF0000);}shape(m.getChild(i));}save("m");
```
Blank map should be named "**M.svg**" and stored in a folder called **/data** (all other files are in the same folder as the program.)
Input File ("**a**"):
```
Mississippi
California
Connecticut
Delaware
Florida
Wyoming
Hawaii
```
Key File ("**b**"): <http://pastebin.com/0pNufAH9>
Output ("**m.tif**"):
[](https://i.stack.imgur.com/LK0mr.png)
Ok, here is my try at my own challenge. Some notes:
* The output map looks different from the input map in the following ways
1. The input map had grey filling on a transparent background. The output has white filling on a gray background. I think this should be allowed, because white, gray, and transparency are all neutral.
2. The output map is missing the lines around Hawaii and Alaska that the input had. Once again, I think this is ok because the lines are not a significant part of the map.
* The program uses an external file to hold keys. According to this [meta post](http://meta.codegolf.stackexchange.com/a/4934/46313), I just need to add 1 byte for one additional file.
If anyone has any discrepancies with my self-adjudication of my code, feel free to leave a comment.
Also, if anyone is curious about trying this challenge in [Processing](http://www.processing.org), it supports both reading SVG files into `PShape`'s, as well as parsing SVG files as XML.
[Answer]
## PHP, 714 bytes
The output is the blank SVG file, which should be stored in a file named `a`, with additional CSS to colour the states, which should be stored in a file named `b` in the following format:
```
Ohio0Indiana0Illinois1New York0New Jersey0Florida
```
I've added some newlines for readability.
```
<?
$x=str_replace;echo$x('.b','#'.$x([0,1],[',#','{fill:red}#'],$x(split(0,'Alabama0Alaska0
Arizona0Arkansas0California0Colorado0Connecticut0Delaware0Florida0Georgia0Hawaii0Idaho0Illin
ois0Indiana0Iowa0Kansas0Kentucky0Louisiana0Maine0Maryland0Massachusetts0Michigan0Minnesota0M
ississippi0Missouri0Montana0Nebraska0Nevada0New Hampshire0New Jersey0New Mexico0New York0Nor
th Carolina0North Dakota0Ohio0Oklahoma0Oregon0Pennsylvania0Rhode Island0South Carolina0South
Dakota0Tennessee0Texas0Utah0Vermont0Virginia0Washington0West Virginia0Wisconsin0Wyoming'),s
tr_split(ALAKAZARCACOCTDEFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKORPARISCSDT
NTXUTVTVAWAWVWIWY,2),file(b)[0])).'{fill:blue}.b',implode('',file(a)));
```
Here is the ungolfed version:
```
<?php
$stateNames = 'Alabama0Alaska0Arizona0Arkansas0California0Colorado0Connecticut0Delaware0Florida0Georgia0Hawaii0Idaho0Illinois0Indiana0Iowa0Kansas0Kentucky0Louisiana0Maine0Maryland0Massachusetts0Michigan0Minnesota0Mississippi0Missouri0Montana0Nebraska0Nevada0New Hampshire0New Jersey0New Mexico0New York0North Carolina0North Dakota0Ohio0Oklahoma0Oregon0Pennsylvania0Rhode Island0South Carolina0South Dakota0Tennessee0Texas0Utah0Vermont0Virginia0Washington0West Virginia0Wisconsin0Wyoming';
$statesAbbreviations = 'ALAKAZARCACOCTDEFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY';
$blankSVG = implode('', file('a'));
$inputWithStateNames = file('b')[0];
$inputWithStateAbbreviations = str_replace(
explode('0', $stateNames),
str_split($statesAbbreviations, 2),
$inputWithStateNames
);
echo str_replace(
'.border',
'#'. str_replace(
[
'0',
'1'
],
[
',#',
'{fill:red}#'
],
$inputWithStateAbbreviations
) .'{fill:blue}.border',
$blankSVG
);
```
The principle is simple: in the blank SVG, each path has an ID corresponding to the abbreviation of the state that it represents (for instance, `<path d="…" id="HI" />` for Hawaii).
All we have to do is to add some CSS to colour this path in the appropriate shade. But there is already some CSS in the blank file (in particular the `<style type="text/css">…</style>` tag already exists), so it's really easy and short to do it. We can notice than the string `.b` is only found in the CSS for `.border`. Good news! We'll just replace `.b` with `OUR_WONDERFUL_CSS.b`.
Creating "our wonderful CSS" is not really more difficult:
1. Read the input from the file:
`Ohio0Indiana0Illinois1New York0New Jersey0Florida`.
2. Replace the names of the states with their abbreviations:
`OH0IN0IL1NY0NJ0FL`.
3. Replace the `0` characters with `,#`:
`OH,#IN,#IL1NY,#NJ,#FL`.
4. Replace the `1` character with `{fill:red}#`:
`OH,#IN,#IL{fill:red}#NY,#NJ,#FL`.
5. Add `#` at the beginning and `{fill:blue}` at the end:
`#OH,#IN,#IL{fill:red}#NY,#NJ,#FL{fill:blue}`.
[Answer]
# Mathematica 1025
Not elegant but it works.
I wasn't aware that SVG files had paths for each state, so I found the states using `MorphologicalComponents` and then associated each component with its respective state. States like Michigan (with upper and lower peninsulas) and Hawaii (multiple islands) have more than one component.
The code assumes that the map file is contained in the variable, *m*.
```
r=Thread[{"Washington","Montana","Maine","Minnesota","North Dakota","Oregon","Michigan","New Hampshire","Vermont","Wisconsin","New York","Idaho","South Dakota","Wyoming","Massachusetts","California","Connecticut","Nevada","Pennsylvania","Iowa","New Mexico","New Jersey","Ohio","Nebraska","Illinois","Indiana","Colorado","Delaware","Maryland","West Virginia","Virginia","Missouri","Washington, D.C.","Kansas","Kentucky","North Carolina","New Mexico","Tennessee","Arizona","Oklahoma","Arkansas","South Carolina","Georgia","Alabama","Mississippi","Texas","Louisiana","Alaska","Florida","Hawaii"}->{6,7,8,9,10,11,{13,23},14,16,18,{19,39},20,24,25,26,27,31,32,36,37,38,40,41,42,43,44,45,46,{47,55},49,50,51,52,53,56,57,58,59,60,61,62,65,66,67,69,{71,80,87},72,{73,75,82,93,101,104},74,{79,81,83,84,85,89,92}}];
v=Flatten;c=MorphologicalComponents@Binarize@m;
h@s_:=v[((Reverse/@Position[c,#])/.{x_,y_}:>{x,1241-y})&/@s,1]
k@{s_,c_}:=Thread[(h@s)->c]
f@{a_,b_}:=Export["f.jpg",(ReplacePixelValue[map,v[k[{v[#/.r],#2}]&@@@{{a,Red},{b,Blue}}]])]
```
Below is the image that will be exported by the following input:
```
f[{{"Ohio", "Indiana", "Illinois", "Alaska"}, {"New York", "Michigan","Oregon", "New Jersey", "Florida"}}]
```
[](https://i.stack.imgur.com/2VZZw.jpg)
] |
[Question]
[
Joe lives at the Bahamas. It is winter. His children are disappointed that there is no snow. Joe needs to make snow for his children. Fortunately, he has a 3-d printer. He plans to make snowflakes with it. Unfortunately he has no idea how a snowflake would look like. In fact, he has never seen a snowflake! Let us help him by creating a program that automatically generates a 2d-image of a snowflake for him.
# Input
The diameter of the image(in pixels), the percentage of the image that is actually a snowflake.
# Output
An image of a snowflake with the required diameter. It can be saved to a file or displayed to the user.
# Specifications
Create a wedge that has a 30 degree angle. Create a [Brownian Tree](http://en.wikipedia.org/wiki/Brownian_tree) with initial seed at the point of the wedge. Reflect the wedge around the center of the image 12 times to generate the rest of the image. The snowflake has the color White. The background has the color Black.
# Scoring
Due to the fact there are different ways to generate a Brownian Tree, the score is 10 \* number of upvotes - golf score.
Golf score is defined as the number of bytes in the program with the following bonuses:
-20% Can arbitrarily specify the symmetry of the snowflake.
-50% Can specify the shape of the snowflake. (By being able to specify the ratio of the lengths of the sides of the wedge.)
Highest score wins.
Here is a picture what the shape of the wedge would be with the ratio approximately 2:

Scoreboard:
Martin Buttner: 10 \* 14 - 409 = -269
Nimi: 10 \* 1 - 733 \* .5 = -356.5
Optimizer: 10 \* 5 - 648 = -598
The winner is Martin with score -269!
[Answer]
# Mathematica, 409 bytes
```
{n,p}=Input[];m=999;Clear@f;_~f~_=0;0~f~0=1;r=RandomInteger;For[i=0,i<m,++i,For[x=m;y=0,f[x+1,y]+f[x-1,y]+f[x,y+1]+f[x,y-1]<1,a=b=-m;While[x+a<0||y+b<0||(y+b)/(x+a)>Tan[Pi/6],a=-r@1;b=r@2-1];x+=a;y+=b];x~f~y=1];Graphics[{White,g=Point/@Join@@{c=Cases[Join@@Table[{i,j}-1,{i,m},{j,m}],{i_,j_}/;i~f~j>0],c.{{1,0},{0,-1}}},Array[Rotate[g,Pi#/3,{0,0}]&,6]},Background->Black,ImageSize->n*p,ImageMargins->n(1-p)/2]
```
Ungolfed:
```
{n,p}=Input[];
m = 999;
ClearAll@f;
_~f~_ = 0;
0~f~0 = 1;
r = RandomInteger;
For[i = 0, i < m, ++i,
For[x = m; y = 0,
f[x + 1, y] + f[x - 1, y] + f[x, y + 1] + f[x, y - 1] < 1,
a = b = -m;
While[x + a < 0 || y + b < 0 || (y + b)/(x + a) > Tan[Pi/6],
a = -r@1;
b = r@2 - 1
];
x += a;
y += b
];
x~f~y = 1
];
Graphics[
{White, g =
Point /@
Join @@ {c =
Cases[Join @@ Table[{i, j} - 1, {i, m}, {j, m}], {i_, j_} /;
i~f~j > 0], c.{{1, 0}, {0, -1}}},
Array[Rotate[g, Pi #/3, {0, 0}] &, 6]},
Background -> Black,
ImageSize -> n*p,
ImageMargins -> n (1 - p)/2
]
```
This expects input the form `{n,p}` where `n` is the image size in pixels, and `p` is the percentage of the image to be covered by the snowflake.
It takes something like half a minute to generate a snowflake with the given parameters. You can speed it up by changing the value of `m` from `999` to `99`, but then the result looks a bit sparse. Likewise, you can crank up the quality by using larger numbers, but then it'll take very long.
I'm forming the Brownian tree on an integer lattice, placing new particles at `{999, 0}`, and moving the randomly to the left and up or down (not to the right), until they hit the existing particles. I'm also constraining the motion to the wedge between 0 and 30 degrees. Finally, I reflect that wedge on the x-axis, and display it with its 5 rotations.
Here are some results (click for larger version):
[](https://i.stack.imgur.com/rgnzd.png)
[](https://i.stack.imgur.com/Ajqvj.png)
[](https://i.stack.imgur.com/f48ZU.png)
[](https://i.stack.imgur.com/BYTU5.png)
[](https://i.stack.imgur.com/9HmFx.png)
[](https://i.stack.imgur.com/ENqNr.png)
[](https://i.stack.imgur.com/wXjO3.png)
And here are two animations of the Brownian tree growing (10 particles per wedge per frame):

[Answer]
# JavaScript, ES6, ~~799 740 695 658~~ 648
*I am only counting the two canvas tags and the function `f` from the snippet below as part of the byte count.* Rest of the stuff is for live demo
To watch it in action, just run the snippet below in a latest Firefox giving the size and ratio via the input boxes
*Note that you will have to hide the result then show again before a consecutive snowflake*
```
f=(N,P)=>{E.width=E.height=D.width=D.height=N
E.style.background="#000"
C=D.getContext("2d"),F=E.getContext("2d")
C.strokeStyle='#fff'
M=Math,r=M.random,I=0,n=N/2
C.beginPath()
C.rect(n,n,2,2)
C.fill()
B=_=>{x=n*P/100,y=0,w=[]
do{w.push([x,y])
do{X=2*((r()*2)|0)
Y=2*(((r()*3)|0)-1)
}while(x-X<0||y-Y<0||(y-Y)/(x-X)>.577)
x-=X,y-=Y}while(!C.isPointInPath(n+x,n+y))
I++
w=w.slice(-4)
x=w[0]
C.moveTo(x[0]+n,x[1]+n)
w.map(x=>C.lineTo(n+x[0],n+x[1]))
C.stroke()
E.width=E.height=N
for(i=0;i<12;i++){F.translate(n,n)
i||F.rotate(M.PI/6)
i-6?F.rotate(M.PI/3):F.scale(1,-1)
F.translate(-n,-n)
F.drawImage(D,0,0)}
I<(n*n*P*.22/100)&&setTimeout(B,15)}
B()}
```
```
<input placeholder="Input N" id=X /><input placeholder="Input percentage" id=Y /><button onclick="f(~~X.value,~~Y.value)">Create snowflake</button><br>
<canvas id=E><canvas id=D>
```
Here are a few example renders with different size and percentages. The best one is called **SkullFlake** (first in the list). Click the images to see them in full resolution.
[](https://i.stack.imgur.com/QIaLb.jpg)
[](https://i.stack.imgur.com/V0rzT.jpg)
[](https://i.stack.imgur.com/Wcsxv.jpg)
[](https://i.stack.imgur.com/jB22M.jpg)
[](https://i.stack.imgur.com/Dmhdr.jpg)
[](https://i.stack.imgur.com/LY2yw.jpg)
A lot of help and input from Martin and githubphagocyte.
[Answer]
# Haskell, 781 733 Bytes
The program features the „specify the ratio of the lengths of the sides of the wedge“ option, so you have to call it with three command line arguments:
```
./sf 150 50 40
```
Argument #1 is the size of the image, #2 the % of pixels in the wedge and #3 the length (in %) of the shorter side of the wedge. The image is saved in a file called „o.png“.
150-50-40: 
My program produces snowflakes with cut-off spikes, because new pixels start on the middle axis of the wedge (green dot, see below) and tend to stay there, because they move equally random to the left, up or down. As pixels outside the wedge are discarded, straight lines appear on the boundary of the wedge (green arrow). I was too lazy to try out other paths for the pixels.
150-50-40: 
When the wedge is big enough (3rd argument 100) the spikes on the middle axis can grow and then there are 12 of them.
150-40-100: 
Few pixels make round shapes (left: 150-5-20; right 150-20-90).


The program:
```
import System.Environment;import System.Random;import Graphics.GD
d=round;e=fromIntegral;h=concatMap;q=0.2588
j a(x,y)=[(x,y),(d$c*e x-s*e y,d$s*e x+c*e y)] where c=cos$pi/a;s=sin$pi/a
go s f w p@(x,y)((m,n):o)|x<1=go s f w(s,0)o|abs(e$y+n)>q*e x=go s f w p o|elem(x-m,y+n)f&&(v*z-z)*(b-q*z)-(-v*q*z-q*z)*(a-z)<0=p:go s(p:f)w(s,0)o|1<2=go s f w(x-m,y+n)o where z=e s;a=e x;b=e y;v=e w/100
main = do
k<-getArgs;g<-getStdGen;let(s:p:w:_)=map read k
i<-newImage(2*s,2*s);let t=h(j 3)$h(\(x,y)->[(x,y),(d$0.866*e x+0.5*e y,d$0.5*e x-0.866*e y)])$take(s*d(q*e s)*p`div`100)$go s[(0,0)]w(s,0)$map(\r->((1+r)`mod`2,r))(randomRs(-1,1)g)
mapM(\(x,y)->setPixel(x+s,y+s)(rgb 255 255 255)i)((h(j(-3/2))t)++(h(j(3/2))t));savePngFile "o.png" i
```
[Answer]
# Processing 2 - 575 characters
Takes in a file f whose first line is the image size and the second is the flakes radius.
Every time a new point is placed it is rotated around the center 12 times. This creates a very similar effect as a rotated wedge, but not exactly the same.
```
int d,w,h,k,l,o,p,x,y;
String n[] = loadStrings("f.txt");
d=Integer.parseInt(n[0]);
h=Integer.parseInt(n[1]);
size(d,d);
w=d/2;
k=l=(int)random(d);
background(0);
loadPixels();
o=p=0;
pixels[w*w*2+w]=color(255);
while(true)
{
o=k+(int)random(-2,2);
p=l+(int)random(-2,2);
if(p*d+o>d*d-1 || p*d+o<0 || o<0 || o>d){
k=l=(int)random(d);
}
else
{
if(pixels[p*d+o]==color(255))
{
p=l-w;
o=k-w;
if(o*o+p*p>h*h){break;}
float s,c;
for(int j=0;j<12;j++)
{
s=sin(PI*j/6);
c=cos(PI*j/6);
x=(int)((o*c)-(p*s));
y=(int)(((p*c)+(o*s)));
pixels[(int)(d*y+x+w+(w*d))]=color(255);
}
k=l=(int)random(d);
}
else
{
k=o;
l=p;
}
}
}
updatePixels();
```


you can get processing [here](https://www.processing.org/download/)
] |
[Question]
[
I was playing with the Fibonacci sequence in binary like so (note that the binary representations are written here from smallest bit to largest bit):
```
1 1
1 1
01 2
11 3
101 5
0001 8
1011 13
10101 21
010001 34
111011 55
1001101 89
00001001 144
10010111 233
...
```
and I noticed that it took until the 11th Fibonacci number (1-indexed) to find a 2-by-2 square of the same bit:
```
1 00 1101
0 00 01001
```
I then wondered: in what row does the first *n*-by-*n* square filled with the same bit start?
## Task
Given an integer *n*, what is the index of the first Fibonacci number that contains part of an *n*-by-*n* square filled with the same bit?
## Rules
* You can have the Fibonacci sequence be either 0- or 1-indexed
* You do not have to worry about invalid input
* You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
* This is `code-golf`, so the shortest code in bytes per language wins
## Test cases:
```
Input (1-indexed) -> Output (0-indexed/1-indexed)
1 -> 0/1
2 -> 10/11
3 -> 22/23
6 -> 382/383
8 -> 4570/4571
```
## Format:
The answers can use one of the following input/output methods, and can be 0- or 1-indexed:
* Given some index *n* it can return the *n*-th entry of the list.
* Given some index *n* it can return all entries up to the *n*-th one in the sequence.
* Without taking any index, it can output *all* entries by e.g. ...
+ ...printing them one by one (potentially infinitely) or...
+ ...returning a list (lazy if the sequence is infinite) or...
+ ...returning a generator that represents the whole sequence.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 124 bytes
```
(n=k=#;While[!Or@@(!FreeQ[Split@Total@PadLeft@IntegerDigits[Fibonacci@t[n-1+b,{b,k}],2],#]&/@{0~(t=Table)~k,k~t~k}),n++];n)&
```
[Try it online!](https://tio.run/##BcHRCoIwFADQX0kEUbxhGkQgwn0IIQgyEnoQHzZbc2zOsPsm7tfXOROjUUyM1MC8rHxsK12F5WtURnTBfUGMg3oR4tE9v0YRtjMxgw1738SH8GpJSLFclFT062rFZ8uGQSF1dp@nHFYOeuuh6CHsowzXg4upahk3InEatCOntwRsmvalTSLfLMrSLkOZ4W7NoYAjnOC8@T8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 143 bytes
Expects a BigInt. The output is 0-indexed.
```
n=>eval("for(i=a=[],g=(p,q=a.reduce((q,v,i)=>i<n?p?q&v:q|v:q))=>q?(p?~q:q)&~-(1n<<n)&&g(p,q/2n):1n;g(a=[++i>2?a[0]+a[1]:1n,...a])&g(););i-[n]")
```
[Try it online!](https://tio.run/##ZcyxCoMwEMbxvY/hIHcY02qhFDXmQSRDsFFS5JJo61R8dZuOxeGG@/Hxf@pVL/1s/Ssn9zD7IHYSrVn1BMngZrBCi06xUYBnQWg@m8e7NwCBrcyiaG1D0suQrlX4xMNIQYKXW4hPuuVQUNMQpun4C5xLwqqgeoRYzTLbllJ3F5XprlDRGedcK4xbrLG2eUcqwb13tLjJ8MmNMMQe4umfyiNdj3Q70j3S/gU "JavaScript (Node.js) – Try It Online")
### Commented
This is a version without `eval()` for readability.
```
n => { // n = input
for( // main loop:
i = // i = iteration counter
a = [], // a[] = Fibonacci sequence in reverse order
g = ( // g is a helper function taking:
p, // p = flag (false: test 0s, true: test 1s)
q = a.reduce( // q = bitmask to be tested
(q, v, i) => // for each value v at index i in a[]:
i < n ? // if i is less than n:
p ? q & v // if p is set, update q to q AND v
: q | v // otherwise, update it to q OR v
: // else:
q // leave q unchanged
) // end of reduce()
) => //
q ? // if q is not 0:
(p ? ~q : q) // take either q or NOT(q) depending on p
& ~-(1n << n) // isolate the n least significant bits
&& // if the result is not 0 ...
g(p, q / 2n) // ... try again with q right-shifted by 1
: // else:
1n; // stop with a truthy value
g( // first call to g with a truthy flag:
a = [ // update a[]:
++i > 2 ? // increment i; if it's greater than 2:
a[0] + a[1] // append the sum of the first 2 terms
: // else:
1n, // append 1
...a // followed by the existing terms
] //
) & g(); // second call to g with a falsy flag
); // end of for
return i - [n] } // return the final position
```
[Answer]
# [Raku](https://raku.org/), ~~105~~ 101 bytes
```
->\n{(1,1,*+*...{@_.tail(n)».base(2).flip~~/^(\d*)((\d)$0**:{n-1})\d*[' '\d**{$0.chars}$1\d*]*$/})-n}
```
[Try it online!](https://tio.run/##DYhBDoIwEAC/siGNtCss1AMHE4j/ECVVaSTBSlovpCkf8@bHai8zmVlGOzfxtcJOQxvLrjeey0IWuEci8qeBPmqauRG/L92UG/lBkJ6nZduqK@8fKHiiYDXi0ZtSBpHeOYc8CT2r6f5U1gUmU1@QVUGUJkSnVsjYAG0HXgMbQgb6bUESNfEP "Perl 6 – Try It Online")
*Edit:* I had to use a workaround for an apparent Raku bug. Later I found that the [bug](https://github.com/rakudo/rakudo/issues/4309) has already been reported, and the bug report suggested a different workaround, four bytes shorter than mine.
This is an anonymous function that takes a single argument `n`. The body is just a lazy Fabonacci generator with a complicated ending condition between the braces:
```
(1, 1, * + * ... { ... }) - n
```
Subtracting `n` from the sequence coerces it to a number, its length; the difference is returned.
Anyway, as for the ending condition:
* `@_.tail(n)` looks at just the last `n` elements of the Fibonacci sequence.
* `».base(2)` converts each number to its binary representation.
* `.flip` coerces that sequence of strings to a single string, joining the individual elements with spaces, then reverses the entire string.
* `~~ / ... /` matches that space-delimited string of bit strings against the slash-delimited regex.
* `^` is the beginning of the string.
* `(\d*)` is zero or more digits. This is the part that comes before the square of identical bits. It's captured in group 0 so that we can check for prefixes of the same length on the following lines.
* `((\d) $0 **: {n-1})` is a sequence of `n` of the same digit, captured in group 1.
* `\d*` matches zero or more digits to the right of the square of bits.
* `[' ' \d ** {$0.chars} $1 \d* ]*` matches, zero or more times, a space, then a digit prefix consisting of the same number of characters as the prefix on the first row, then the row of identical digits in group 1, then zero or more other digits.
* `$` is the end of the string.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞<.ΔIÝ+Åf2вí2FøI"üÿ"δ.V}Aδ.ý˜ÅγIn@à
```
Given \$n\$, it'll output the 0-based value.
[Try it online](https://tio.run/##AT4Awf9vc2FiaWX//@KInjwuzpRJTCvDhWYy0LLDrTJGw7hJIsO8w78izrQuVn1BzrQuw73LnMOFzrNJbkDDoP//Ng) or [verify the first 5 test cases](https://tio.run/##AVAAr/9vc2FiaWX/NUVOwqk/IiDihpIgIj//4oiePC7OlMKuTCvDhWYy0LLDrTJGw7jCriLDvMO/Is60LlZ9Qc60LsO9y5zDhc6zwq5uQMOg/30s/w).
Pretty slow. Can barely output \$n=6\$ in about 55 seconds on TIO.
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,4,5,...]
< # Decrease it to a non-negative list: [0,1,2,3,4,...]
.Δ # Pop and find the first value that's truthy for:
IL # Push a list in the range [1,input]
+ # Add the current value to each in this list
Åf # For each of these values, get their 0-based Fibonacci number
2в # Convert each inner Fibonacci number to a binary-list
í # Reverse each inner list
2FøI"üÿ"δ.V} # Create overlapping input by input blocks:
2F } # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
I # Push the input-integer
"üÿ" # Push this string, replacing `ÿ` with the input
δ # Map over each inner row with this string as argument:
.V # Evaluate the string as 05AB1E code,
# where `ü#` creates overlapping items of size `#`
δ # Map over each row of input by input sized blocks:
A .ý # Intersperse it with the lowercase alphabet (or any rubbish value)
˜ # Then flatten it to a single list
Åγ # Run-length encode it; pushing the list of values and list of lengths
In # Push the squared input
@ # Check for each value whether it's >= this squared input
à # Get the flattened maximum to check if any is truthy
# (which means there was an input by input sized block consisting of
# the same bit)
# (after which the found index is output implicitly as result)
```
Minor note: `Aδ.ý˜ÅγIn@à` instead of just `εε˜Ë}}à` (nested map over the blocks `εε...}}`; flatten `˜`; check if all bits are the same (`Ë`); any `à`) is for the first few binary representations of Fibonacci numbers, which are smaller than an \$n\times n\$ block. The `2FøI"üÿ"δ.V}` will in those cases result in an empty (nested) list, which is unfortunately truthy for the `Ë` check.
[Answer]
# [Python](https://www.python.org), 182 bytes
```
def e(n,*l):
r=[*zip(*[bin(i)[:1:-1]for i in l[:n]])]
if len(r)>n>=1==min(len({*sum(r[i:i+n],())})for i in range(len(r)-n)):print((len(l)-n)*(n>1));n+=1
e(n,l[0]+l[1],*l)
e(1,1,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY87DsIwEET7nMLlrpNIuENGzkUsFyBsWMnZRCYpAHESmjRwBO7CbcgH0HRPM9Kb-7M9d8eGh-HRd6Fcv197H4QHLmREnYlkrLxQC9LuiIHQaqVL5UKTBAliEa1m59BlgoKIniFhxZVRxtRjfwJXeeprSJY05ewKQLzhf562fPCw7EpG1G0i7mAmcSISuFKIG86NymavaFcuj1a5yTDzoIoxuNh_T_zOfAA)
Prints the 0-based indices infinitely. (Contains a particularly horrible kludge to deal with `n=1`; let me know if you have a better solution.)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes
```
Nθ⊞υ¹W¬⊙01⊙υ⬤…⮌υθ№⌕A⮌⍘ξ²×κθν⊞υΣ✂υ±²Lυ¹I⁻Lυθ
```
[Try it online!](https://tio.run/##TU5BCsIwELz7iuBpAxVsPfZUC4KgRawfiHVpgmnSNkm1r49JoeDCwgwzOzsNZ2OjmfT@rHpnK9c9cYSB5pubMxxcQtKAP1xIJFBpC4WaYbtPtwmJKOiFlFDOjcSS6x7uOOFoEBxNyBC21E5ZOAn1ir5VPTKDtR2FauGbkIwG40N0aOAdrwJTdBmylqhdB7UUDUZSYcssQhZ8F1St5cu3lMbSIdNCyYyFq1DOwJ8hBNPc@4PfTfIH "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the desired number of bits.
```
⊞υ¹
```
Start with `F(1)=1`.
```
W¬⊙01⊙υ⬤…⮌υθ№⌕A⮌⍘ξ²×κθν
```
Check the last `n` Fibonacci numbers to see whether there is an index where they all share an overlapping match of a string of either all `n` `0`s or all `n` `1`s in their binary representations.
```
⊞υΣ✂υ±²Lυ¹
```
Calculate the next Fibonacci number. Unfortunately I have to start with just one Fibonacci number which makes the formula much longer than normal.
```
I⁻Lυθ
```
Calculate the 0-based index of the first of the last `n` Fibonacci numbers.
Bit twiddling is faster but longer at 65 bytes:
```
Nθ⊞υ¹≔⁰η≔⁰ζW¬∨№⍘η²×1θ№⍘ζ²×0θ«⊞υΣ✂υ±²≔↨υ⁰η≔ηζF…⮌υθ«≧&κη≧|κζ»»I⁻Lυθ
```
[Try it online!](https://tio.run/##dY9NbsIwEIXXySksVmPJlQKLbrKiWVWCgEgv4KZT2yJxgn9AUHH21E7IAlX1at7MN/Oea8lN3fFmGN51713p2080cKJ5uvdWgmdkGeq1tUpoyBiRT@oW1EWqBgmUnYOdgaLz2sEbt1g5o7QAyciKMvKhWrSwWC4YOdGg/3C3Jy6buPDIT5rMUSrfQtWoGqMoUXCHsIpQniaPUPFinGZ0yjr35RQ2@e4MgeJaN1jIrocDntHEDTr6RbNky/tp6aCEDBmVuyiLa/3FyPFx9B9mZ0ZkNLqn93Qffuag4NbBVmlvYYNaODm70XwYXoeXc/ML "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Calculates Fibonacci numbers, taking both the logical Or and logical And of the last `n` Fibonacci numbers, until either the logical Or contains `n` `0`s or the logical And contains `n` `1`s in their binary representation. Somewhat verbose because I can't take the logical Or or And of a list.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~262~~ ~~260~~ 205 bytes
Function `s` that accepts `n` as input (1-indexed) and returns the index 1-indexed. Quite slow, but in theory it works!
*Edit*:
* *-2 bytes thanks [@The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu)*
* *-54 bytes thanks [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
* *-1 byte: moved `i` as optional function argument*
```
f=lambda x:x>1and f(x-1)+f(x-2)or x
def s(n,i=0):
while 1:
i+=1;b=[bin(f(i+_))[::-1]for _ in range(n)]
for d in'01':
for p in range(i):
for k in b:
if k[p:p+n]!=d*n:break
else:return i
```
[Try it online!](https://tio.run/##TYtBDoIwEEX3nGJc2RFJrG5MTb0IIaRNW52AY1Mw4ukRMEZX8@b9/@Orv975cIxpHINuzc06A4MaztKwgyCGQmI@nz3eEwyZ8wE6wVvSO1QZPK/UepATAeVanqwuLbEIgvIasVSqkFWYhjUQQzJ88YKxmtqzdJNc7@R6Xi8i/lqEi110M2v7@YECNGVUMedqpd2GlU3eNEvm286r5PtHYqAxJuJedEIiZl/e//EBcXwD "Python 3.8 – Try It Online")
---
Commented code *(original version)*:
```
# lambda function that computes the Fibonacci numbers
f=lambda x: x>1 and f(x-1) + f(x-2) or x
# main function
def s(n):
# index of the i-th Fibonacci number that is evaluated
i = 0
while 1:
i + =1
# list of binary representations of n Fibonacci numbers
b = [bin(f(i+_-1))[2:][::-1] for _ in range(n)]
# check both digits
for d in '01':
# find digit at each position in binary repr
for p in range(len(b[0])):
# find if repeated digit is substring of binary repr
if b[0][p:].find(d*n) >= 0:
# search in following Fibonacci numbers
for k in b[1:]:
# if substring found at different position break loop
if k[p:].find(d*n) != 0: break
# for loop is terminated, found all substrings at same positions
else: return i
```
] |
[Question]
[
[Toki pona](https://en.wikipedia.org/wiki/Toki_Pona) is a minimalist constructed language, and thus it has minimalist phonotactics (rules describing what sounds make valid words).
Toki Pona has 8 consonant sounds `m`, `n`, `p`, `t`, `k`, `s`, `w`, `l` and `j` and 5 vowel sounds `a`, `e`, `i`, `o`, `u`. A single basic syllable in toki pona consists of any 1 consonant, any one vowel and optionally an `n`. So all of the following are valid:
```
pi
ko
wa
san
jen
```
There are four exceptions of sequences that are forbidden they are `ji, wu, wo, ti`.
With the basic syllables we can build words. A word is just a string of basic syllables with two special rules:
1. When we have an `n` followed by either `n` or `m` we drop the `n`. e.g. `jan` + `mo` is `jamo` not `janmo`
2. The initial syllable of a word can drop the initial consonant. e.g. `awen` and `pawen` are both legal and distinct words. This does allow for words consisting of just a vowel.
## Task
Your task is to take a non-empty string consisting of lowercase alphabetic characters (`a` through `z`) and determine if it makes a valid toki pona word.
When the input is a valid word you should output one value and when it is not you should output another distinct value.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with the goal being to minimize the size of the source.
## Test cases
Accept:
```
awen
jan
e
monsuta
kepekin
ike
sinpin
pakala
tamako
jamo
pankulato
pawen
an
nene
nenen
```
Reject:
```
bimi
ponas
plani
womo
won
tin
wu
miji
sunmo
anna
sam
kain
op
p
n
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~48~~ 47 bytes
```
A`ji|nm|nn|ti|wu|wo
^((^|[j-npstw])[aeiou]n?)+$
```
[Try it online!](https://tio.run/##FY4xCsMwEAT7e0cCNiFvCKnyCGPjDag4y9oTkYQa/V2Ru2EYlv25rES/T5@9v/dDG0MjW9ZWS6sm2zRtbTmejCnXdV7g1MrK1/y49Y7qKAcoToIxlQzxLjqvFPVOkjIOjPA4IRkB3kYebCj6ciJfdG18NahEI5LEE1SpNqpqlPFOapGgh0oqHBYkJCH8AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 1 obvious byte thanks to @ovs. Explanation:
```
A`ji|nm|nn|ti|wu|wo
```
Delete invalid inputs.
```
^((^|[j-npstw])[aeiou]n?)+$
```
Match valid inputs that weren't invalidated above.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~56~~ 51 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+1 to cater for strict IO (two distinct outputs rather than truthy vs falsey being allowed)
```
“jtklmnpsw”,ØẹŒpṖṖ¬3,8¦p”n;ƊṗⱮLẎF€⁾mnyw⁾nnƲÐḟḊ€;$e@
```
A (very inefficiant) monadic Link that yields `0` when the input string is not a Toki Pona word and `1` when it is.
(Don't) [Try it online!](https://tio.run/##y0rNyan8//9Rw5yskuyc3LyC4vJHDXN1Ds94uGvn0UkFD3dOA6JDa4x1LA4tKwDK5Fkf63q4c/qjjet8Hu7qc3vUtOZR477cvMpyIJWXd2zT4QkPd8x/uKMLKGGtkurw////rMQ8AA "Jelly – Try It Online") (it's so inefficient it'll only complete for words of length three or less!)
...but here is a [test-suite](https://tio.run/##JY6xasMwEIZfJuDFm5eAl0x9idLhChpkSSeBbEQ2t2OGEDq0HVoKHTKFQDPFGTrYxO8hvYiiU0Cn06/v139qmJTrGEP/1bRCKjTWhf67nD79Zbi@GT@8pzUeqnI57k0iWM8bP3yEv2PlL9uH8HoIL/8K1y41xPk07fz5x583CdSLOP6yVbLG@FiAY1iURQO0s1RKo@1aSCfBDBOc7rkgYjmaLA0IkORoQYHQ@bnSGdzTnrniJDWCpS4BSTudXU6Tp81RrqORvCFsO8wcECncgqJPQPI93QA "Jelly – Try It Online") that has all tests except the four syllable `pankulato` that (a) limits to three base-syllables, rather than that of the number of characters in the input string and (b) only calls the word-generating code once for all (hence the `e@` has been moved out to the footer).
### How?
We construct a list containing ALL valid Toki Pona words constructed from at most `length(input)` syllables and check if the input is in there.
Yep that's soooo nasty, but without easy regex access I imagine it's the golfiest way.
```
“jtklmnpsw”,ØẹŒpṖṖ¬3,8¦p”n;Ɗṗ - (partial) Link: integer (from below!)
“jtklmnpsw” - "jtklmnpsw"
Øẹ - "aeiou"
, - pair
Œp - Catesian product
ṖṖ - pop off "wu" and "wo"
3,8¦ - apply to indices 3 & 8 ("ji" & "ti"):
¬ - logical NOT (replace these with [0,0] (integers)
Ɗ - last three links as a monad:
”n - 'n'
p - Cartesian product (appends 'n' to each)
; - concatenate
ṗ - Catiasian power (the integer)
...ⱮLẎF€⁾mnyw⁾nnƲÐḟḊ€;$e@ - (continued) Link: string, S
... L - length of S
...Ɱ - map across [1..length(S)] with:
... - code above -> base-syllable combos of each length
Ẏ - tighten
F€ - flatten each
Ðḟ - filter discard those for which:
Ʋ - last four links as a monad:
⁾mn - "mn"
y - translate (convert ms to ns)
⁾nn - "nn"
w - index of first occurrence (or zero)
$ - last two links as a monad:
Ḋ€ - dequeue each
; - concatenate
@ - with swapped arguments:
e - S exists in there?
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 64 bytes
```
$_=!/[jt]i|wu|wo|nm|nn/&&/^([aeiou]n?)?([mnptkswlj][aeiou]n?)*$/
```
[Try it online!](https://tio.run/##RY5BagMxDEX3OkUahpAWppMusgptTtATDNOgghca218itvFmzl7X6aYb8XlfesjcPZyb3QV5P9x248duf2nD7f1pmte8yFbLVnVD3IDpcJi@jjM70bLg@nw9zhGWfaphXf7xyzC1xtWBVgY5iopUMpN35ryAxDtKAuvR2HNgyhzZa1@P2hF8CZwf6eHoCji4vwH6lihkCk5kgSFUtd9UBeWuq4WirEKpoFMGmBJH8tw7NTLCj1qW/k8bP8@vp7dTGy38Ag "Perl 5 – Try It Online")
[Answer]
# TypeScript type system, 313 bytes
```
type v="a"|"e"|"i"|"o"|"u";type i<T>=T extends""?1:T extends`${Exclude<`${"m"|"n"|"p"|"t"|"k"|"s"|"w"|"l"|"j"}${v}`,"ji"|"wu"|"wo"|"ti">}${infer r}`?i<r>extends 1?1:r extends`n${infer e}`?e extends`${"n"|"m"}${any}`?0:i<e>:0:0;type o<T>=T extends`${v}${infer p}`?i<p>extends 1?1:p extends`n${infer r}`?i<r>:0:i<T>
```
This is written entirely with TypeScript types - the `o` type outputs 1 if the input parameter is a valid word and 0 if it is not. There's probably some room for further golfing.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~59~~ ~~58~~ 55 bytes
```
∧θ¬⊙⪪”&↧q1o⁺VPα”²№θι≔aeiouηF⮌θ¿№ηι≔⁻”&↧ï⁸t∕p№t⟦”ηη¿⁻ιn⎚
```
[Try it online!](https://tio.run/##Lcw7DoMwDIDhvaewMjkSXboyIeZWVXuCiIZiCA7kAerp0/DwZFn/56ZTrrHKpPR0xAEr/uBcwMNu6w/fk6GAoicemQOtcbWigJssoLYx5zkluU15qbynL6NQmmzMUZdvrXWAL71o5zXOUgK1gIfsdgmnuhNHf9p@MCNPPqz7k/0RaOP1jo@QChAsMq@NVg5lmdKkeIhGBZuui/kD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
∧θ¬⊙⪪”&↧q1o⁺VPα”²№θι
```
Check that the word doesn't contain any of the illegal letter pairs contained in the compressed string.
```
≔aeiouη
```
Start by expecting the last character to be a vowel.
```
F⮌θ
```
Loop over the word in reverse.
```
¿№ηι
```
If we see an expected letter, ...
```
≔⁻”&↧ï⁸t∕p№t⟦”ηη
```
... then flip the set of expected letters by subtracting it from the string all the legal Toki Pona letters grouped into vowels and consonants.
```
¿⁻ιn
```
Otherwise, if the current letter is not an `n`, ...
```
⎚
```
... then erase any previous validity there might have been.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 49 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„nn„nm‚åà≠×ε.•2Ñ|qγù•žM⨨D27SèKD'n««N>ãJ}˜D€¦«Iå
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/241065/52210), but even slower.. :/
Outputs `1`/`0` for accept/reject respectively.
[Try it online.](https://tio.run/##AWAAn/9vc2FiaWX//@KAnm5u4oCebm3igJrDpcOg4omgw5fOtS7igKIyw5F8cc6zw7nigKLFvk3DosKowqhEMjdTw6hLRCduwqvCq04@w6NKfcucROKCrMKmwqtJw6X//25lbmU)
As is it's too slow for a test suite, but by adding `2äн` between the `×` and `ε` (map over halve the input-length instead), we can verify all but the longest few [truthy test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2ly/9HDfPy8kBE7qOGWYeXHl7wqHPB4elGh5dc2Htuq96jhkVGhyfWFJ7bfHgnkH10n@/hRYdWHFrhYmQefHiFt4t63qHVh1b72R1e7FV7eo7Lo6Y1h5YdWl15eOl/nf@pXIl5XFlAnJkNZJangji5@Vx5qXmpXAVgPoiZx1WcmVeQmQcUyk7MSeQqScxNzM7nys3PKy4tSeTKTi1IzQbL5mWX5iSW5AMA) and [falsey test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2ly/9HDfPy8kBE7qOGWYeXHl7wqHPB4elGh5dc2Htuq96jhkVGhyfWFJ7bfHgnkH10n@/hRYdWHFrhYmQefHiFt4t63qHVh1b72R1e7FV7eo7Lo6Y1h5YdWl15eOl/nf8FXHlc5aVc@QVc5fl5XCWZeVzFiblcSZm5mUCB3Hyu3MysTK7EvLxEruxEoGRBfl5iMVdBTmJeJldxaV5uPgA) respectively, in separated test suites.
**Explanation:**
```
„nn„nm‚ # Push pair ["nn","nm"]
åà≠ # Check that NEITHER is present in the (implicit) input
× # 'Multiply' it by the (implicit) input-string
# (the input if truthy; "" if falsey)
ε # Map over the characters:
.•2Ñ|qγù• # Push compressed string "jtklmnpsw"
žM # Push builtin vowels "aeiou"
â # Pop both, and create a list of all possible char-pairs
¨¨ # Remove the last two ("wu" and "wo")
D # Duplicate the list
27S # Push pair [2,7]
è # Index those into the copy: ["ji","ti"]
K # Remove those as well
D # Duplicate the list again
'n« '# Append an "n" to each string
« # Merge the two lists together
N # Push the 0-based map-index
> # Increase it by 1 to make it 1-based
ã # Cartesian product this index on the list of syllables
J # Join each inner list together to a string
}˜ # After the map: flatten the list of lists
D # Duplicate the list
€¦ # Remove the first consonant from each
« # Merge the two lists together
Iå # Check if the input-string is in this list
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•2Ñ|qγù•` is `"jtklmnpsw"`.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~56~~ ~~53~~ 47 bytes
*-3 bytes by porting [Neil's Retina answer](https://codegolf.stackexchange.com/a/241057/16766)*
```
X<>"jiwuwotinnnm"NIa&a~=+:`^|[j-nptsw]`+XV.`n?`
```
Returns 1 for a valid word, 0 for an invalid word. [Attempt This Online!](https://ato.pxeger.com/run?1=JU67agMxEOznM65IY-y0JuRRu3FpDMbmNqDAnk6jBUmoMfmNFGlsQiC_5L-JztfsDrM7j-8fU7tcfkv-WK5vj_vn127QWmrMSjJ02408yOfL4qk_nQ_DkpZTPfaL_W7V862fZVfM--_QWaR0x9uXVEcMQjiEyFSywDtzXgn1DklpDZp4GQVZgvjY3kNsFH0ZJU9o8mgWdHT3QbxrUEwZCTYKFTU2TY1Eq4taEHRQpMLGCilIEuCl3aLBwLnnPw)
[Verify all test cases](https://ato.pxeger.com/run?1=JU67SgQxFO3PVwwpbJZZWxFda4u1lIVlda4Q5U4mJ8EkpPDxGxY2gqjgH-3fmHWay7nnxXn_jBp_tqZ_nMzu93Zpun7VmeXTV8n3_cn-eHO2MqPWUkNWkt5cXcqRvJ4vToeb5-3YM-ZUd8Nic70ceDHMse-Xbt09YH4-9m9SLTEKYeEDU8kCZ6N1SqizSMrYYBQnkyCLFxea3YdG0ZVJ8gEdOloFLe3_Ie7UK2KgJMRJqKihZWog2lbUAq-jIhU2VkhBEg8nTQsREZz3_QE)
### Explanation
At its core, this solution works similarly to Neil's Retina answer:
* The input does not contain any of the illegal sequences `ji`, `wu`, `wo`, `ti`, `nn`, or `nm`; AND
* The input fully matches the regex `((^|[j-nptsw])[aeiou]n?)+`
First half:
```
X<>"jiwuwotinnnm"NIa
"jiwuwotinnnm" That string
<> Grouped into pairs of characters
X Converted to a regex that matches any of those pairs
NI Does not match in
a The command-line argument
```
Second half:
```
a~=+:`^|[j-nptsw]`+XV.`n?`
`^|[j-nptsw]` That regex
+ Wrapped in a non-capturing group and followed by
XV Built-in regex `[aeiou]`
. Followed by
`n?` That regex
+: Apply the + quantifier to the above wrapped in n.c. group
a~= Command-line argument fully matches that regex
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~97 88~~ 86 bytes
```
lambda x:re.sub("((?!ji|wu|wo|ti|.*n[nm])(^|[j-npstw])[aeiou]n?)*$","",x)>""
import re
```
[Try it online!](https://tio.run/##hU5Na8MwDL3nV2hmB7ukYWy3Qtsf0magMIcpjiUT2ziD/PfM3Q477iK9D/Gewlf6FH7bx/N9n9EPHwjrabFdzINWWl@fJtpK3opsibbuwDf2vdHv2206coip9OaGliT3fDWHZ9Uq1a7molRDPsiSYLH7KAusQAwKi2WYkMGCF445ITgbrKseOQuROFQY0OGMkNCjk3rupUrs8ozpgR4ZNYIt25/BqothpqTNqYGwECe9tqDOF9XCqFdjmuZXVUd1eH2p9O@hgTxBEMYIYUYmKFLbijCkapcMniaCmLmqyIwQ0YPD6kmAAHUV@a9@/wY "Python 3 – Try It Online")
return `False` for valid word, `True` for invalid
Thanks to @14m2 for -2 bytes
## How it works:
* at each syllable, we chek for `ji|wu|wo|ti` and prevent any capture if it is present. We also chek for the presence of either `nn` or `nm` further in the word.
* if it was absent, we capture the syllable (consonant + voyel (+ n))
* All the syllables captured are replaced by the empty string
* We then check if the result is greater than the empty string (falsey) or equal to the empty string (thruthy)
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), 195 bytes
Lexurgy is a tool made for conlangers for applying sound changes, so this is perfect for this challenge! ~~(and here I am bashing it into code golf)~~
Outputs the original word if it's valid Toki Pona, and an empty string otherwise.
Extremely slow version:
```
Class c {m,n,p,t,k,s,w,l,j}
Class v {a,e,i,o,u}
a:
{({j,t} i),(w {o,u}),({m,n} {m,n}),!@c&!@v}=>`
{(!n&@c @c),(@v @v)}=>` *
!@v&!n=>`/_ $
n=>`/$ _ $
c propagate:
[]=>`/{` _,_ `}
d:
`=>*
```
Much faster version, 199 bytes:
```
Class c {m,n,p,t,k,s,w,l,j}
Class v {a,e,i,o,u}
a:
{j,t} i=>`
w {o,u}=>`
{m,n} {m,n}=>`
!n&@c @c=>` *
@v @v=>` *
!@v&!n=>`/_ $
n=>`/$ _ $
!@c&!@v=>`
c propagate:
[]=>`/{` _,_ `}
d:
`=>*
```
Ungolfed:
```
Class cons {m,n,p,t,k,s,w,l,j}
Class vow {a,e,i,o,u}
remove-forbidden:
{j,t} i => ` # ji, ti
w {o,u} => ` # wo, wu
{m,n} {m,n} => ` # mn, mm, etc
!n&@cons @cons => ` * # no consecutive consonants
@vow @vow => ` * # no consecutive vowels
!@vow&!n => ` / _ $ # ending with a vowel or n
n => ` / $ _ $ # nothing of length 1
Then:
!@cons&!@vow => ` # convert any invalid character
Then propagate:
[] => ` / {` _, _ `} # spread the invalid
Then:
` => * # delete the invalid
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 438 bytes
```
#define R return
int c(l){char a[]={'n','m','p','t','k','s','w','l','j'};for(int i=0;i<9;i++)if(l==a[i])R 1;R 0;}
int v(l){R l==97||l==101||l==105||l==111||l==117?1:0;}
int f(char* s){int i,a,b;for(i=0;*s!=0;s++,i++){a =*s;b=*(s+1);if(!(c(a)||v(a))||((a=='j'||a=='t')&&b=='i'||a=='w'&&(b=='u'||b=='o')||a=='n'&&(b=='n'||b=='m'))||(c(a)&&c(b)&&a!='n')||(v(a)&&v(b))) R 0;}if(i==1&&c(*(s-1))) R 0;if(*s==0&&v(*(s-2))&&*(s-1)!='n') R 0;R 1;}
```
[Try it online!](https://tio.run/##pVLBjpswEL3nKxyqBTshUqi0Wu1S1H@IektyGByzdQCDMIQD8OtNZwxJ23MP4xnPm5n3PLLcfUp5v3@5qEwbxQ6sUW3XmJU2LZO8EIP8CQ2D4zkZAhOEQYlWo7VoOZpF69EKtGswxVnVcOrVyT7W395jvd0KnfEiSeCoz@LAovjA9vHkCG5EcGAIvr@NI7poHy3@dfbRco/evkcfj7aMk6gNs2JwVCGE6UyMpBu7xtNutyFRD8CSjY3TZMPtNhIxSllzyUGM4w1PdJxDkqD0cSTfBsL3Uwz0kugD3@eU6DBBvgrEjJgHYhakDNw8mu77kqd4wppgyt5c9oZZIZjbAErR@DIqRXG76AFgfmOTZE/VBHwV2DhXzNNcFS1yutPzS9CG3yp9Eathxdi8GpBS1e3xzBI2eNAr44XeFehUaGVlbNcCRrmqVa4pr3NCrDa1u9aQQ0EVLZSQV669rBxg8q6Ado7nyW6wUUYtznhT/JTSqKuSDympLjU1VgYs@QIM3fvKze4rGtQ6AX1HQvWVYNsZh4MxJMlCSdLB1VU1zSFiIkXWusGtZNz7oWy77IF9sFPjCdL07/@MXt0HxTyt7k/vi2WndsdeLtQXLsvU5zDjz1i4cdNfhKfGUc7v/U/KZWmO8hk/KKf7L5kV8Gnvu/43 "C (gcc) – Try It Online")
Explanations :
```
#define R return
// function to detect a consonant
int c(l){char a[]={'n','m','p','t','k','s','w','l','j'};for(int i=0;i<9;i++)if(l==a[i])R 1;R 0;}
// function to detect a vowel
int v(l){R l==97||l==101||l==105||l==111||l==117?1:0;}
int f(char* s){int i,a,b;for(i=0;*s!=0;s++,i++)
{
a =*s;b=*(s+1);
if(!(c(a)||v(a))|| // detect if characters are allowed
((a=='j'||a=='t')&&b=='i'||a=='w'&&(b=='u'||b=='o')||a=='n'&&(b=='n'||b=='m'))|| // detect if sequences ji, wu, wo & ti are not used
(c(a)&&c(b)&&a!='n')|| // detect if there are not 2 consecutives consonants
(v(a)&&v(b))) // detect if there are not 2 consecutives vowels
R 0;
if(i==1&&c(*(s-1))) R 0; // detect if it a single letter word & a vowel
if(*s==0&&v(*(s-2))&&*(s-1)!='n') R 0; // test if the last character is not a consonant except 'n'
R 1;
}
```
```
] |
[Question]
[
It's election time, and your job is to beat your competitor in a head-on rivalry! You are both trying to win over a city of 256 people in a 16x16 grid. Right now, the city hasn't been divided into voting regions yet, but that's where your gerrymandering skills come in! You can also campaign in arbitrary areas of the city to gain support.
## General
All bots (JS functions) will be run against all other bots once per game. In each game, the city will start out with all voters being neutral. The game will keep track of a number for each voter, determining who they support. From a particular bot's perspective, a positive number means that voter will vote for them, while a negative number is a vote for the opponent. Zero is neutral.
The city is divided into 16 blocks, which are all 4x4 squares. Voting regions are made up of one or more blocks. There are initially 16 of them, with each block having its own region.
Both bots start with $100, and can move once per turn. These moves are run effectively simultaneously, so there is no first turn advantage. Moves fall into four categories:
* **Campaigning:** This will cause every person in a specific area to increase their support for the candidate who is campaigning. The amount it changes depends on their neighbors.
* **Polling:** This will get each person's support for the candidate in a specific area.
* **Bribing:** This will cause a particular person to increase their support for the candidate.
* **Region Merging/Unmerging:** This will reshape voting regions.
At the end of each turn, after both candidates have moved, both will recieve $10.
## Details
The following moves are allowed. If an invalid move is given (insufficient money or invalid coordinates), the bot's turn will be skipped.
All coordinates should be within `0 <= n < 16`, and for the second pair in rectangular bounding areas `0 <= n <= 16` (as these are **exclusive**).
* **`campaign([x, y], [x, y])`:** Campaign within the boundary determined by the two coordinate pairs
+ Costs $1 per person affected
+ Each person within the area will change their support according to the following rules:
- For all neighbors orthogonally (including diagonals) adjacent, add 0.1 support for whichever candidate the majority support (weighted), or 0.2 if their total support is at least 2 for that candidate
- Add 0.25 for the candidate who is campaigning
* **`poll([x, y], [x, y])`:** Poll within the boundary determined by the two coordinate pairs
+ Costs $0.25 per person polled, rounded up
+ On the next turn, the following information is given about each person in the area (after the opponent's move):
- Their support for the polling candidate, where positive numbers indicate a vote for them, and negative numbers being a vote for the opponent
* **`bribe([x, y])`:** Bribe the person at the location determined by the coordinate pair
+ Costs at least $5
- For every time a person within the voting block (**not** the voting region) has been bribed, add $1
+ Add up to 3.5 support for the bribing candidate
- For every time a person within the voting block has been bribed, the support added is decreased by 0.15
- Eventually, this can cause bribing someone in a voting block to *reduce* their support for the candidate
* **`merge([x, y], [x, y])`:** Merge the voting regions determined by the two coordinate pairs
+ Costs $25 for every block in the newly formed region (one block is free)
+ Requires the regions which contain the two people specified to be touching
- Note that the coordinates correspond to people, not blocks. To reference a block, just multiply its coordinates by 4
* **`unmerge([x, y])`:** Unmerge the voting region determined by the coordinate pair
+ Costs $25 for every block in the region
+ Every block in the region becomes its own region
If both bots attempt a merge or unmerge on the same turn (even if they won't interfere), both turns will be skipped and neither will pay anything. Moves will be processed in the following order (the order of the rest don't matter):
1. Bribes
2. Support from neighbors in campaigning
3. Support from candidates in campigning
## Winning
At the end of each turn, after both candidates have moved, all regions will have their votes added. Each person will either vote for one candidate or be neutral, regardless of by how much (i.e., a score of +0.05 or +30 would be identical here). If the following conditons are met, an election will be held and the winner chosen:
* All regions are made up of less than half neutral voters
* The number of regions voting for each candidate are not tied
## I/O
All bots should be submitted in the form of Javascript functions. The following information will be provided as arguments to the function:
* An array of voting regions, represented as objects with the following properties:
+ `blocks`: An array of voting blocks, represented as the coordinates `[x, y]` of the top-left person (such as `[4, 0]` or `[12, 12]`)
+ `number_neutral`: The number of people in the region who are neutral
+ `number_you`: The number of people in the region voting for the bot
+ `number_opponent`: The number of people in the region voting for the bot's opponent
+ `absolute_average`: The average absolute value of people's support for a candidate
- Higher numbers indicate campaigning or bribing will typically be less effective
- Exactly 0 would mean every person in the region is neutral
* The amount of money the bot has
* An object containing the results of the last move (empty unless it was a poll)
+ An array `people` will contain objects representing each person polled:
- `position`: The person's coordinates, formatted as `[x, y]`
- `region`: The numbered ID of the region the person is in (the region's index in the first argument)
- `support`: A number indicating whether the person is neutral (0), voting for the bot (positive), or voting for the bot's opponent (negative)
+ An object `amounts` containing the following properties:
- `number_neutral`: The number of people in the region who are neutral
- `number_you`: The number of people in the region voting for the bot
- `number_opponent`: The number of people in the region voting for the bot's opponent
- `absolute_average`: The average absolute value of people's support for a candidate
* An object that can be used for storage between turns (but not between rounds/games)
To move, the result one of the functions above should be returned. For example:
```
{
"Example": (regions, money, result, storage) => {
storage.block = ((storage.block || 0) + 1) % 16;
return campaign(
[(storage.block / 4 | 0) * 4, (storage.block % 4) * 4],
[(storage.block / 4 | 0) * 4 + 4, (storage.block % 4) * 4 + 4]
);
}
}
```
## Rules
* Bots should take a reasonable amount of time to run
* Bots should play fairly, no manipulating the controller or other submissions in ways not allowed here
* Every bot will be run against every other bot once, with the winner being the bot which wins most often
+ In the event of a tie, the earlier bot wins
* Invalid return values or bots that error will assume no move for the turn
* Bots must be deterministic
Challenge idea and original sandbox proposal by HyperNeutrino.
**Controller:** <https://radvylf.github.io/political-simulator>
**Chatroom:** [Here](https://chat.stackexchange.com/rooms/115588/koth-political-simulator)
**Due Date:** Thursday, November 5th, 2020, UTC Noon (8:00 AM EST)
[Answer]
# Landgrab
Brief description of strategy:
1. On the first turn, do a large campaign in the center using up all the initial money.
2. Otherwise, if there is a region with more than 2 neutral voters, campaign in the region with the most neutral voters.
3. Otherwise, if there is a region in which me and my opponent have the same number of voters, campaign in that region.
4. Otherwise, campaign in the region with the most neutral voters.
This relies on the fact that it's much easier to claim neutral voters than voters who are already going to vote for your opponent. It doesn't know about gerrymandering, so might not do very well if someone messes with voting regions, but it's a start.
```
(regions, money, result, storage) => {
if(money == 100) { return campaign([2, 2], [12, 12]); }
var best = regions[0];
var tied;
for (var i = 0; i < regions.length; i++) {
if(regions[i].number_neutral > best.number_neutral) {
best = regions[i];
}
if(regions[i].number_neutral == 0 && regions[i].number_you == regions[i].number_opponent) {
tied = regions[i];
}
}
var b;
if (tied && best.number_neutral > 2) {
b = tied.blocks[money % tied.blocks.length];
} else {
b = best.blocks[money % best.blocks.length];
}
if (money >= 16) {
return campaign(b, [b[0] + 4, b[1] + 4])
} else if (money % 2 == 0) {
return campaign(b, [b[0] + 3, b[1] + 3])
} else {
return campaign([b[0] + 1, b[1] + 1], [b[0] + 4, b[1] + 4])
}
}
```
[Answer]
# Leftist Policy
### v1.1
Grabs the left side of the map, then gerrymanders the right side. Having accomplished that, it will slowly campaign the right side to avoid deadlock.
```
(regions, money, result, storage) => {
storage.phase = storage.phase || 0;
storage.merge = storage.merge || 0;
if (storage.phase == 0){
storage.phase+=2;
return campaign([1,2],[5,14]);
}
if (storage.phase <= 6) {
var result = campaign([storage.phase,1],[storage.phase+1,15]);
if(money >= 14) storage.phase++;
return result;
}
if(storage.phase == 7){
if(storage.merge < 4){
var result;
if(money >= 25){
result = merge([9,(storage.merge*4)+1],[15,(storage.merge)*4+1])
storage.merge++;
storage.phase = 1
}
return result;
}
else if(regions.filter(r => r.blocks[0][0] <= 5)
.filter(r => r.number_you > r.number_opponent + r.number_neutral).length >= regions.length / 2){
area = (storage.merge % 4)*4;
if(money >= 18){
storage.merge++;
storage.phase = 1;
return campaign([9,area],[15,area+3]);
}
}
else{
storage.phase = 1;
var result = campaign([storage.phase,1],[storage.phase+1,15]);
if(money >= 14) storage.phase++;
return result;
}
}
}
```
Currently only beats the example bot. The strategy is just too slow to win much.
[Answer]
# Randgrab
Started as an evolution of Landgrab to increase randomness, then slowly added more and more features until it currently beats all other contestants (Landgrab, Leftist Policy 1.1, and Greedy campaign 9).
Features include:
* Grabbing less land at the start to save money
* Grabbing adjacent areas at once if we have enough money
* De-priortize areas where we already have enough lead to win and the opponent hasn't campaigned yet
* Prioritize areas where the vote is closest (the "swing states," if you will)
* More randomness, including choosing at random any one of the four corners to claim when doing a 3x3
* A pretty chaotic (but still deterministic!) `r` variable which controls all randomness
Weaknesses include:
* Not prioritizing undecided states highly enough
* Not taking advantage of any non-campaign functions
* Can be thrown off by region changes, although this has been partially corrected for
* Can be thrown off by claims which don't align to borders well
```
(regions, money, result, storage) => {
if(money == 100) {return campaign([4, 4], [12, 12]);}
var r = money + money * regions.length;
regions.forEach(reg => r += reg.blocks[0][0] * reg.number_neutral + reg.blocks[0][1] * reg.number_you + money * reg.number_opponent + reg.blocks.length * reg.absolute_average);
r = Math.floor(r);
var tied = [];
var best = [regions[r % regions.length]];
var closest = [regions[(2*r) % regions.length]];
for (var i = 0; i < regions.length; i++) {
if(regions[i].number_neutral > best[0].number_neutral && !(regions[i].number_you > 8 && regions[i].number_opponent == 0)) {
best = [regions[i]];
} else if(regions[i].number_neutral == best[0].number_neutral && !(regions[i].number_you > 5 && regions[i].number_opponent == 0)) {
best.push(regions[i]);
}
if(regions[i].number_neutral == 0 && regions[i].number_you == regions[i].number_opponent) {
tied.push(regions[i]);
}
if(regions[i].number_opponent > regions[i].number_you && regions[i].absolute_average < closest[0].absolute_average) {
closest = [regions[i]];
} else if(regions[i].number_opponent > regions[i].number_you && regions[i].absolute_average == closest[0].absolute_average) {
closest.push(regions[i]);
}
}
var b;
var choice;
if (tied.length > 0 && best[0].number_neutral > 4) {
choice = tied;
} else {
choice = (best[0].number_neutral > 2 ? best : closest);
}
console.log(choice);
bt = choice[r % choice.length];
b = bt.blocks[r % bt.blocks.length];
var x = Math.floor(r/2) % 2;
var y = Math.floor(r/4) % 2;
if (money >= 18 && choice) {
for(var i = 0; i < choice.length; i++) {
for(var j = 0; j < choice[i].blocks.length; j++) {
var c = choice[i].blocks[j];
if(c[0] == b[0]-4 && c[1] == b[1]) {
return campaign([c[0]+1, c[1]], [b[0]+3, b[1]+3]);
} else if(c[0] == b[0]+4 && c[1] == b[1]) {
return campaign([b[0]+1, b[1]], [c[0]+3, c[1]+3]);
} else if(c[0] == b[0] && c[1] == b[1]-4) {
return campaign([c[0], c[1]+1], [b[0]+3, b[1]+3]);
} else if(c[0] == b[0] && c[1] == b[1]+4) {
return campaign([b[0], b[1]+1], [c[0]+3, c[1]+3]);
}
}
}
}
if (money >= 16) {
return campaign(b, [b[0] + 4, b[1] + 4]);
} else {
return campaign([b[0] + x, b[1] + y], [b[0] + 3 + x, b[1] + 3 + y]);
}
}
```
[Answer]
# Abotcus
Turns out you don't need so many fancy features to be just as good as or better than Randgrab! Abotcus grabs an area at the start, then afterwards applies a straightforward formula to weight each block and picks the block with the best weight. If it looks like there's some unnecessary stuff in there, it's because I expected to add a lot more fancy features... but I just didn't need to ¯\\_(ツ)\_/¯
```
(regions, money, result, storage) => {
if(money == 100) {return campaign([9,1],[15,15])}
var map = [[,,,],[,,,],[,,,],[,,,]];
var weights = [[,,,],[,,,],[,,,],[,,,]];
var blocks = [];
for(var r of regions) {
for(var b of r.blocks) {
map[b[1]/4][b[0]/4] = b;
weights[b[1]/4][b[0]/4] = weight(r.number_you, r.number_opponent, r.number_neutral, r.absolute_average)/r.blocks.length;
blocks.push([b, weights[b[1]/4][b[0]/4]]);
}
}
blocks.sort((a,b) => {
return b[1]-a[1];
});
var start_block = blocks[0][0];
console.log(blocks);
if(money >= 16) {
return campaign(start_block, [start_block[0]+4, start_block[1]+4]);
} else {
return campaign(start_block, [start_block[0]+3, start_block[1]+3]);
}
function weight(own, opp, neut, avg) {
var tot = own+opp+neut;
var cat = 0;
if(opp > tot/2) {
cat = 1;
} else if(own > tot/2) {
cat = 5;
}
return 1/(1+avg+cat);
}
}
```
```
[Answer]
# Greedy campaign 9 per each region
* Each turn, we have at least $10. This make it possible to campaign a 3x3 area.
* Since we only need 9 gird in each region. We just campaign top 3x3 but give up the ones on right or bottom.
* Every turn, we choice campaign position greedy: The more region support us in next turn, The better.
```
(regions, money, result, storage) => {
const turn = storage.turn = storage.turn + 1 || 1;
const gh = money < 21 ? 1 : 2;
const h = 4 * gh - 1;
const gw = 77 <= money ? 3 : 49 <= money ? 2 : 1;
const w = 4 * gw - 1;
const candidate = [];
for (let i = 0; i <= 4 - gw; i++) {
for (let j = 0; j <= 4 - gh; j++) {
let s = gw * gh;
for (let k = 0; k < gw; k++) {
for (let l = 0; l < gh; l++) {
let bx = i + k, by = j + l;
let region = regions.find(r => r.blocks.some(block => block == [bx * 4, by * 4] + ''));
let { number_neutral: n, number_opponent: o, number_you: y } = region;
if (y <= o) {
if (n + y > o) s += 1;
if (n + y == o) s += 0.5;
if (n + y < o) s += 0.5 ** (o - y - n / 2);
} else {
if (n + o > y) s += 0.5;
if (n + o < y) s += -(0.5 ** (y - o - n / 2));
if (n + o == y) s += 0.25;
}
}
}
candidate.push({ s, x: i, y: j });
}
}
const ts = Math.max(...candidate.map(c => c.s));
const best = candidate.filter(c => c.s === ts);
const { x: tx, y: ty } = best[turn % best.length];
return campaign([tx * 4, ty * 4], [tx * 4 + w, ty * 4 + h]);
}
```
[Answer]
# Liberal Agenda
The spiritual successor of Leftist Policy. Campaigns the whole left side turn one, then gerrymanders both of the top right blocks together, then goes back to protecting the left side. Once it's extremely confident it has the left covered, it moves on to the right.
```
(regions, money, result, storage) => {
storage.merge = (storage.merge||0)
if(money >= 100){
return campaign([1,1],[7,15])
}
else {
var map = [];
regions.forEach(reg => {
reg.blocks.forEach(b => {
map.push({
"pos": b,
"abs_avg":reg.absolute_average,
"num_you":reg.number_you / reg.blocks.length,
"num_opp":reg.number_opponent / reg.blocks.length,
"num_neu":reg.number_neutral / reg.blocks.length,
"won": (reg.number_neutral>=reg.number_you+reg.number_opponent) ? 0 : reg.number_you/ reg.blocks.length - reg.number_opponent / reg.blocks.length
});
});
});
map = map.sort((a,b)=>a.abs_avg-b.abs_avg).sort((a,b)=>a.won - b.won);
var leftmap = map.filter(b=>b.pos[0]<8)
if(money >= 25){
if(storage.merge == 0){
storage.merge++
return merge([8,0],[12,0])
}
return campaign([leftmap[0].pos[0],leftmap[0].pos[1]],[leftmap[0].pos[0]+4,leftmap[0].pos[1] + 4])
}
if(leftmap.every(b=> b.abs_avg > 3)) return campTarget3by3(map[0].pos).filter(b=>b.won<1)
return campTarget3by3(leftmap[0].pos)
}
function campTarget3by3(pos){
var a1,a2,b1,b2
if(pos[0]==0){
a1 = 1
b1 = 4
}
else {
a1 = pos[0]
b1 = pos[0] + 3
}
if(pos[1]==0){
a2 = 1
b2 = 4
}
else {
a2 = pos[1]
b2 = pos[1] + 3
}
return campaign([a1,a2],[b1,b2])
}
}
```
Ironically, it's the only thing Leftist Policy can beat!
] |
[Question]
[
[Pip](https://github.com/dloscutoff/pip) is an imperative golfing language with infix operators. It also borrows some features from functional and array programming.
What general tips do you have for golfing in Pip? I'm looking for approaches and tricks that are commonly useful for code golf and are specific to Pip (e.g. "remove comments" is not an answer).
Please post one tip per answer.
[Answer]
# Use preinitialized variables
Pip has many global variables that are pre-initialized so you can avoid manually writing a number/string/something else out yourself.
Here are some of them ([complete list](https://dloscutoff.github.io/pipdoc/vars)):
* `_` Identity function (== `{a}`)
* `h` 100
* `i` 0
* `k` `", "`
* `l` Empty list
* `m` 1000 (mnemonic: Roman numeral M)
* `n` Newline character
* `o` 1
* `s` Space character
* `t` 10
* `v` -1
* `w` Matches whitespace `\s+`
* `x` Empty string
* `z` Lowercase alphabet a to z
* `B` Block that returns its second argument (`{b}`)
* `G` Block that returns its argument list (`{g}`)
* `AZ` Uppercase alphabet A to Z
* `CZ` Lowercase consonants b to z
* `PA` All **P**rintable **A**SCII characters, 32 through 126
* `PI` \$\pi\$ (3.141592653589793)
* `VW` Lowercase vowels a to u
* `VY` Lowercase vowels a to y
* `XA` Matches one Latin letter `[A-Za-z]` (there are more `X*` commands)
[Link to documentation](https://dloscutoff.github.io/pipdoc/)
[Answer]
# Use the `Y` operator
From a quick survey, it looks like I use `Y` (or one of its variants, `YP` and `YO`) in one out of every three Pip answers--more so as the answers get more complex.
### Storing a value
`Y` stands for "yank," which will be familiar to Vim users as a command that copies the current line or selection into a buffer. The unary `Y` operator in Pip does something similar: it saves a copy of its operand in the `y` global variable and returns the operand unchanged. Essentially, `Y<expr>` is equivalent to `y:<expr>`, but shorter.
This alone makes `Y` (and the `y` variable) useful in many cases. Need to store something in a variable and don't care which one you use? `Y` saves a byte from the assignment. Need to use an expression twice? Yank it and use `y` twice instead. If the expression is longer than two bytes, you'll save.
But `Y` is also useful in another way:
### Manipulating operator precedence
Suppose we want to count the number of 0s in the input and then tack the count onto the end of that input. (For example, input of `1001101` should result in `1001101 3`.) Counting the 0s is `0Na`, and so we would like to do `a.s.0Na`. But that won't work because `N` is lower precedence than `.`, and the expression would parse as `((a.s).0)Na`. To enforce precedence, we can use parentheses: `a.s.(0Na)`. This always works, and sometimes it's the only option.
But often, we can use `Y` instead. The trick is that `Y` has very low [precedence](https://dloscutoff.github.io/pipdoc/precedence)--the lowest, in fact, together with `P` and `O`. So *any* expression to the right of `Y` will parse as `Y`'s operand, while the whole `Y` expression will in turn be the right operand of whatever comes to its left. And `Y` will pass its operand through unchanged (plus assign it to `y`, but we don't care about that as long as we're not using `y` for something else). If we write `a.s.Y0Na`, it parses as `(a.s).(Y(0Na))`, just as if we had parenthesized `0Na`. But it only costs one byte, while the parentheses cost two.
### Caveats
A `Y` expression can only be used on the right side of a binary operator, not the left, because `Y` will take *everything* to the right of it as its operand. For instance, if we wanted to prepend the count of 0s instead of appending it, we couldn't do `Y0Na.s.a`--that would parse as `Y(0N(a.s.a))`. Instead, we'd have to fall back on parentheses or another strategy.
There is only one `y` variable, so you can't yank two different values in the same program (unless you can structure your code so that you don't need both of them at the same time). You'll have to pick one to assign to a different variable. Try it both ways and see which one saves you more bytes.
Binary operators in Pip always evaluate their left-hand side first, which means that you generally can't use the new value of `y` in the same expression where you yanked it: If you want to calculate the square of `a+1`, you can't do `y*Ya+1` (`y` won't be `a+1` when it's evaluated, because `a+1` hasn't been yanked yet); and you can't do `Ya+1*a` (which would parse as `Y(a+(1*a))`). In situations like this, you'll probably want to yank the value first, in a separate expression: `Ya+1y*y`. If you absolutely need to do it in one expression, you can parenthesize the `Y` part: `(Ya+1)*y`. This works because the left-hand side of `*` is evaluated first, so `y` has the correct value when the right-hand side is evaluated.
[Answer]
# Replace simple functions with lambdas
Lambdas are a generally good way to save 2 bytes(at the very least), as compared to a regular function that requires braces.
Pip's lambdas, however, do not mimic the general attributes of a lambda in say, Python. You cannot shorten all standalone functions into lambdas.
They're an extension of the identity function `_`, where `_ = {a}`. This means that you can create a lambda out of a function *only* if you are writing a function with a single expression.
Lambdas in Pip have some interesting uses other than single expressions. For example, you can reference the main function's arguments without yanking/copying them.
From [Dlosc's tutorial on functions](https://github.com/dloscutoff/pip/wiki/2.-Functions):
>
> The function `_+a` adds its argument to the program's first command-line
> argument. `a` still has its top-level value because it's not inside
> curly braces.
>
>
>
The catch is that you cannot use commands(If, Else if, Loops) and everything must come down to one statement, as it is generally with applying operators on functions.
Due to those restrictions, Pip lambdas are generally better suited for small mapping or filtering functions. Happy golfing!
If you do find an interesting use case, do tell me.
[Answer]
# Manipulating operator precedence with `:`
The `:` meta-operator turns any regular operator into a compute-and-assign version that modifies its left-hand side (LHS) in place. For example, `x+:5` adds `5` to `x` and stores the result back into `x`. The expression evaluates to the result of the computation: if `x` was originally `2`, then `x+:5` would set `x` to `7` and also evaluate to `7`.
Besides adding the compute-and-assign semantics, the `:` meta-operator changes the operator's precedence and associativity to match the precedence and associativity of the assignment operator: very low precedence, right-associative. The main reason is so that the new compound operator behaves like an assignment operator. However, we can also take advantage of this behavior in many situations by treating `:` as a "lower the precedence" meta-operator.
### Example
Suppose we want to subtract 2 from each digit of a number. The straightforward way would be to split the argument into characters (digits) and subtract:
```
(^a)-2
```
Because `^` has lower precedence than `-`, we have to wrap it in parentheses, costing two extra bytes. Instead, we can use `:` to make the precedence of `-` lower, costing only one byte:
```
^a-:2
```
Now `-:` has lower precedence than `^`, and the expression parses as `(^a)-:(2)` without needing parentheses.
### Caveat
If the LHS of your higher-precedence operator is an [lvalue](https://en.wikipedia.org/wiki/Value_(computer_science)#Value_category) (an assignable value such as a variable or an item in a list), adding the `:` meta-operator will modify its value. Sometimes this is fine (e.g. if the expression is at the top level and you just want to output it and halt). Other times, you need the value to stay unmodified; in those cases, you'll probably need to go back to parentheses.
In the above example, the LHS of `-:` is the expression `^a`, which is not an lvalue. Therefore, nothing is modified (if you use the `-w` flag, you'll see a warning: `Attempting to assign to non-lvalue`). The expression still evaluates to the result of the computation, as desired.
[Answer]
# `M` can map a value instead of a function
Normally, you would use `M` like this:
```
UC_M"abc"
```
with the left-hand side being a function and the right-hand side being some iterable you want to map it to. If you need to swap the arguments, `"abc"MUC_` works too.
But in the case where you just want to replace every item in the iterable with a constant value, `M` can do that too--just give it a non-function as its left-hand side:
```
42M"abc"
```
This will return `[42;42;42]`: one `42` for every character in `"abc"`. If you don't mind that you're getting a list and not a string, this is one byte shorter than `42X#"abc"`, and it's two bytes shorter than the list equivalent `42RL#"abc"`.
The value can be literally anything\* that's not a function: Scalar, Pattern, List, Range, or even Nil.
This trick also works with some other map operators:
* `aMJb` joins the results into a string after mapping (may be particularly useful when `a` is not a Scalar to begin with)
* `aMMb` will give you a list of lists of `a`, the lengths of the sublists matching the lengths of the items in `b`
* `aMCb` will give you a `b`x`b` grid (nested list) of `a`
That last one is a useful alternative to `ZG` when you want a value other than 0 ([for example](https://codegolf.stackexchange.com/a/210551/16766)).
---
\* Technically, it'll behave differently if given a list that contains a function.
[Answer]
# Shortcuts for certain lists
Normally, if you need a list of constants, you just enclose the items in square brackets, with separators as necessary (`[4 8 15 16 23 42]`). But there are shorter ways to construct some commonly used lists:
* First, don't forget you can use preset variables if you haven't reassigned them. The empty list can be `l` instead of `[]`. Using `i` for `0` and `o` for `1` in a list can save a byte (or even two) if they are next to another number, since lowercase variables don't require a separator: `[0 5]` → `[i5]`. Using `v` for `-1`, `t` for `10`, `h` for `100`, or `m` for `1000` also saves bytes directly, since the variable names are shorter than the numbers they represent.
* Use a range if possible: `[0 1]` → `[io]` → `,2`. This still saves a byte if it's 1-based (`[o2]` → `\,2`) or starts at some other number (`[v0]` → `v,1`).
* For a list of digits, split a number: `[1]` → `^1`; `[3o4o5 9]` → `^314159`; `[oi]` → `^t`. This works for characters, too: `['#]` → `^'#`; `['h'i]` → `^"hi"`.
Note that the latter two methods involve operators with different precedences, which you'll need to take into account. If working around the precedence is too much trouble, you can always fall back on the standard list syntax.
[Answer]
# Use a list instead of concatenating
The default output format for Lists is to concatenate all of their items together. If you need to output more than three strings concatenated, you save bytes by throwing them all in a List instead of actually concatenating them:
```
m//60." hours, ".m%60." minutes"
[m//60" hours, "m%60" minutes"]
```
You may be able to save even more in specific cases by using one of the list-formatting flags:
```
[m//60"hours,"m%60"minutes"] ; (with -s flag to join on spaces)
```
This trick works even better if one of your items is actually a List, or involves an operator with lower precedence than concatenation:
```
"The arguments are ".(gJk).'!
["The arguments are "gJk'!]
```
If you're doing something with the result other than just outputting it, this approach may not work for you. One context where it *does* work, however, is with the `R`eplace operator: if the second argument is a Scalar or Pattern, a third argument that is a List will be converted to a string before being substituted.
[Answer]
# Use unary operators whenever possible
A lot of binary operators in Pip have unary versions. The concept should be familiar: many programming languages have binary `-` for subtraction and unary `-` for negation. Pip extends the idea to a lot of other operators:
* Binary `/` for division, unary `/` for reciprocal
* Binary `^` to split on a separator, unary `^` to split into a list of characters
* Binary `TB` to convert to a given base, unary `TB` to convert to binary
* Binary `||` to strip characters from a string, unary `||` to strip whitespace from a string
* Binary `Z` to zip two iterables together, unary `Z` to zip all the items of a list together
and many others.
The obvious benefit of unary operators is that they don't require two arguments. Instead of `1/x`, `/x` will do the trick for -1 byte. The less-obvious benefit comes when we start combining operators:
## Unary operators let you ignore precedence, sometimes
In an expression with two binary operators, the higher-precedence operator will be evaluated first: `vEa%2` is `(vEa)%2` because `E` has higher precedence than `%`. If we wanted `vE(a%2)` instead, we would need to use parentheses or some other trick to manipulate the precedence.
However, in an expression like `vE%a`, the only way to evaluate is `vE(%a)`: `E` is evaluated first, but its right argument can only be the subexpression `%a`; it can't "steal" an operand from the lower-precedence operator like it could from binary `%`.
In a sense, the precedence of a unary operator doesn't matter on its left, only on its right. An expression like `%vEa` is still going to parse as `%(vEa)` because `E` is higher precedence than unary `%`. But if you can set up your expression so that a unary operator is the right-hand side of a binary operator, you can drop the parentheses and save more bytes.
Here's a [real-life example](https://codegolf.stackexchange.com/a/226768/16766). We want to group (`<>`) the longer string before we weave (`WV`) it with the shorter string, but `WV` is higher precedence than `<>`.
```
"NESW"WV("NESESWNW"<>2) Original version, 23 bytes
"NESW"WV:"NESESWNW"<>2 Using a precedence trick, 22 bytes
"NESW"WV<>"NESESWNW" Using a unary operator, 20 bytes
```
[Answer]
# Output in pieces rather than concatenating
Say you have two expressions that you want to concatenate together and autoprint at the end of your program. The best-case scenario is that you simply use `.`:
```
a+b.'!
```
But sometimes the precedence doesn't cooperate:
```
(aJb).'!
```
You could lower the precedence of `.` [using the `:` meta-operator](https://codegolf.stackexchange.com/a/255093/16766), but that still costs an extra byte:
```
aJb.:'!
```
*If* this expression is the last expression in your program (i.e. you want it to be autoprinted and your program doesn't do anything else afterwards), and *if* you're concatenating Scalars (i.e. you're not depending on the vectorizing behavior of the `.` operator), then you can instead simply output the first expression using `O` and autoprint the second expression:
```
OaJb'!
```
This outputs the result of `aJb` without a trailing newline, then immediately outputs an exclamation point (with a trailing newline)--which produces the same output as concatenating them.
[Answer]
# How to crash the interpreter
Pip is designed to be pretty forgiving. Operations that cause errors in other languages, such as dividing by zero, usually just return nil (and print a warning message, but only if you enable warnings using the `-w` flag). But sometimes in golf, you *want* the program to crash. For example, it's the only way to break out of an infinite loop.
There are a couple of ways to get a fatal error, but the golfiest is to trigger a runtime parse error by evaluating a string as code. Evaluating any single character that's an operator will crash the interpreter, since the operator needs (at least one) operand. Shorter still, the variable `k` is preset to `", "`, which works just as well: `Vk`, 2 bytes.
] |
[Question]
[
Normal brackets (`()`,`[]`,`<>` and `{}`) are nice and unambiguous, however someone thought it would be a good idea to use non bracket characters as brackets. These characters, `|` and `"`, are ambiguous. For example does
```
""""
```
correspond to
```
(())
```
or
```
()()
```
It is impossible to tell.
Things start to get interesting when you mix types of ambiguous brackets, for example
```
"|""||""|"
```
Could be any of the following
```
([(([]))]),([()[]()]),([()][()])
```
## Task
Your task is to take a string made of ambiguous characters and output all the possible balanced strings the author could have intended.
More concretely you output all balanced strings that can be made replacing `|` with either `[` or `]` and `"` with either `(` or `)`. You should not output any balanced string twice.
## IO
As input you should take a string consisting of `|` and `"`. If you would like to select two distinct characters other than `|` and `"` to serve as replacements you may do so. You should output a container of balanced strings. You may choose to replace `[]` and `()` in the output with any other two bracket pairs (`()`,`[]`,`<>` or `{}`) you wish. Your output format should be consistent across runs.
## Scoring
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
```
"" -> ["()"]
"|"| -> []
||| -> []
"""" -> ["(())","()()"]
""|| -> ["()[]"]
"|"||"|" -> ["([([])])"]
"|""||""|" -> ["([(([]))])","([()[]()])","([()][()])"]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 135 bytes
```
s=input()
for k in range(2**len(s)):
try:c=''.join("[]() , ,"[int(c)|k>>i&1::4]for i,c in enumerate(s));eval(c);print c[::2]
except:0
```
[Try it online!](https://tio.run/##FcxBCoMwEIXhfU4xuGgSkWKHriJ6EXEhYdqm2jHEKBV699Qs3u5/nz/ia2FMaW0d@y0qLR5LgAkcQxj5SQrLciZWq9ZGQAyHsa2U1/fiWBX9oDRUUBW946is/k1d5y43Y@5DVlxls0O8fSiMkTLS0D7OZ9r4cH7A9sbgIIC@lnw0dUoSa8Q6DxGl@AM "Python 2 – Try It Online")
Expects input like `2002` instead of `"||"`, and wrapped in quotes.
Iterates over all 2N possible assignments of "open" and "close" to the string, creating strings `c` like:
```
"( [ ( ),],[ ( ),],),( ),"
```
If `eval`-ing this string throws an exception, it is unmatched. If not, we print `c[::2]`, giving:
```
([()][()])()
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~59~~ ~~56~~ 55 bytes
```
0`"
<$%">
}0`'
{$%"}
.+
$&_$&
+m`^_|(<>|{})(?=.*_)
A`_
```
[Try it online!](https://tio.run/##K0otycxLNPz/3yBBictGRVXJjqvWIEGdqxrIrOXS0@ZSUYtXUePSzk2Ii6/RsLGrqa7V1LC31dOK1@TickyI//9fSV1JSR2ElQA "Retina – Try It Online") Unfortunately testing for two sets of matched brackets exceeds the golfiness of a single .NET regex, so it saves 15 bytes to check manually. Edit: Saved ~~3~~ 4 bytes thanks to @H.PWiz. Explanation:
```
0`"
<$%">
```
Find a `"` and make two copies of the line, one with a `<` and one with a `>`. Do this one `"` at a time, so that each `"` doubles the number of lines.
```
}0`'
{$%"}
```
Similarly with `'`, `{` and `}`. Then, keep replacing until all `"`s and `'`s on all copies have been replaced.
```
.+
$&_$&
```
Make a duplicate of the brackets, separated by a `_`.
```
+m`^_|(<>|{})(?=.*_)
```
In the duplicate, repeatedly delete matched brackets, until none are left, in which case delete the `_` as well.
```
A`_
```
Delete all lines that still have a `_`.
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~74~~ ~~71~~ 70 bytes
```
0`"
<$%">
}0`'
{$%"}
Lm`^(.(?<=(?=\3)(<.*>|{.*}))(?<-3>)|(.))+(?(3)_)$
```
[Try it online!](https://tio.run/##K0otycxLNPz/3yBBictGRVXJjqvWIEGdqxrIrOXyyU2I09DTsLex1bC3jTHW1LDR07KrqdbTqtXUBIrqGttp1mjoaWpqa9hrGGvGa6r8/6@krqSkDsJKAA "Retina – Try It Online") Explanation: The first two stages are as above. The third stage directly prints the result of matching two sets of matched brackets. This uses .NET's balancing groups. At each stage in the match, the regex tries to match a character, then look back for a pair of matching brackets, then check that the top of the stack matches the open bracket. If it can do this, it means that the bracket balances, and the open bracket gets popped from the stack. Otherwise, the assumption is that we're at an open bracket that needs to be pushed to the stack. If these assumptions don't hold then the stack will not be empty at the end and the match will fail.
Alternative approach, also ~~74~~ 71 bytes:
```
Lm`^((?=(<.*>|{.*})(?<=(.))).|\3(?<-3>))+(?(3)_)$
```
Here, we look ahead for either `<`...`>` or `{`...`}`, then look behind to push the *closing* bracket on to the stack. Otherwise, we need to match and pop the closing bracket that we captured earlier. In this version the regex might not even make it to the end of the string, but some strings such as `<<<>` would slip through the net if we didn't check for an empty stack.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 19 bytes
```
fo¬ω`ḞoΣx½¨÷₂¨ΠmSe→
```
[Try it online!](https://tio.run/##yygtzv7/Py3/0JrznQkPd8zLP7e44tDeQysOb3/U1HRoxbkFucGpj9om/f/P9V8ppTglpRiEU5QA "Husk – Try It Online")
Uses the characters `ds` in the input, and the corresponding bracket pairs `de` and `st` in the output.
## Explanation
The idea is to generate all possible bracketings of the input and keep those that reduce to the empty string when we repeatedly remove adjacent brackets.
The `¨÷₂¨` is a compressed string that expands into `"dest"`, which was chosen because it has a short compressed form and consists of character pairs with adjacent codepoints.
Thus the program is equivalent to the following.
```
fo¬ω`ḞoΣx½"dest"ΠmSe→ Implicit input, say "ddssdd".
m Map over the string:
Se pair character with
→ its successor.
Result: ["de","de","st","st","de","de"]
Π Cartesian product: ["ddssdd","ddssde",..,"eettee"]
f Keep those strings that satisfy this:
Consider argument x = "ddsted".
ω Iterate on x until fixed:
½"dest" Split "dest" into two: ["de","st"]
`Ḟ Thread through this list (call the element y):
x Split x on occurrences of y,
oΣ then concatenate.
This is done for both "de" and "st" in order.
Result is "dd".
o¬ Is it empty? No, so "ddsted" is not kept.
Result is ["destde","ddstee"], print implicitly on separate lines.
```
[Answer]
# Perl, ~~56~~ ~~55~~ 53 bytes
Includes `+1` for `n`
uses `[` for `[]` and `{` for `{}`
```
perl -nE 's%.%"#1$&,+\\$&}"^Xm.v6%eg;eval&&y/+//d+say for< $_>' <<< "[{[[{{[[{["
```
Generates all 2^N possibilities, then uses perl `eval` to check if a string like '+[+{}]' is valid code and if so removes the `+` and prints the result
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~55~~ 53 bytes
```
{a/⍨~×≢¨'\(\)|\[]'⎕r''⍣≡a←⊃∘'()[]'¨¨(⊂'".'⍳⍵)+,⍳2⊣¨⍵}
```
[Try it online!](https://tio.run/##RY4xTsNAEEX7nCLaZmZFAoiSq9guVomMLCwZOW4QGwpAyDEY0aDQQgq2oEM0KZ2bzEXMnySAtNqZP//N33UX@Xh66fLibDzJ3WyWTXp5eskKuX8@7lPcV@5I2nC9WcrivQsUc2x9HCUEqiSSdiWLNwdOmlupX4ktvC50gaW5IXMI4kvab3swQnMizaoLkPO@rzSbN0tGbmnlsUZVUOoPFB0CSKVdn04pdVmOoDWMUh7uqDin@YCMoWqkr7AlKG88VdJ@Dsj7384YhYjZWhqC25FG/f0mfrvbxfnLizhKbLJPVWvr6VwNdYYqsMz/Iom24gc "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~203~~ ~~186~~ 179 bytes
```
?['(':l][')':t]= ?l t
?['[':l][']':t]= ?l t
?l[h:t]= ?[h:l]t
?[][]=True
?_ _=False
@['"']=[['('],[')']]
@['|']=[['['],[']']]
@[h:t]=[[p:s]\\[p]<- @[h],s<- @t]
$s=[k\\k<- @s| ?[]k]
```
[Try it online!](https://tio.run/##TY3BCsIwEETv@YpQhSjoDxRDPYggeNPbdpBQq5amqTTpQei3GxNz0MOyO293ZypdK@O7/jrqmneqMb4gsRC5BomlyB0kLzR3LFBKFP9U0yOp0DXiGQjyPIw1Ky78IvdK25ptSWQCkqIzVtEYiHBKkL4QCX79iJ65RVnSE5s1DxArGwcHNreS2rJso7RTCEYLf3JqcGzGrRsac@eSh8Apy6ZYITlsbqOpXNObsJsz@ZPpw7@rm1Z369eHo9@9jOqayn4A "Clean – Try It Online")
Uses only pattern-matching and comprehensions.
[Answer]
# Perl, 56 bytes
Includes `+` for `n`
Uses input `[` for output `[` or `]`
Uses input `{` for output `{` or `}`
```
perl -nE '/^((.)(?{$^R.$2})(?1)*\2(?{$^R.=$2^v6}))*$(?{say$^R})^/' <<< "[{[[{{[[{["
```
Uses a perl extended regex to match braces while keeping track of the choices made during backtracking. This can be much more efficient than generating all 2^N candidates since it already rejects many impossible assignments while partway through the input string
[Answer]
# [Kotlin](https://kotlinlang.org), ~~240~~ ~~236~~ 234 bytes
```
fold(listOf("")){r,c->r.flatMap{i->when(c){'"'->"()".map{i+it}
else->"[]".map{i+it}}}}.filter{val d=ArrayList<Char>()
it.all{fun f(c:Any)=d.size>1&&d.removeAt(0)==c
when(it){')'->f('(')
']'->f('[')
else->{d.add(0,it);1>0}}}&&d.size<1}
```
## Beautified
```
fold(listOf("")) {r,c ->
r.flatMap {i-> when(c) {
'"'-> "()".map {i+it}
else -> "[]".map {i+it}
}}
}.filter {
val d = ArrayList<Char>()
it.all {
fun f(c:Any)=d.size>1&&d.removeAt(0)==c
when(it) {
')' -> f('(')
']' -> f('[')
else -> {d.add(0,it);1>0}
}
} && d.size<1
}
```
## Test
```
private fun String.f(): List<String> =
fold(listOf("")){r,c->r.flatMap{i->when(c){'"'->"()".map{i+it}
else->"[]".map{i+it}}}}.filter{val d=ArrayList<Char>()
it.all{fun f(c:Any)=d.size>1&&d.removeAt(0)==c
when(it){')'->f('(')
']'->f('[')
else->{d.add(0,it);1>0}}}&&d.size<1}
data class Test(val input: String, val outputs: List<String>)
val tests = listOf(
Test("""""""", listOf("()")),
Test(""""|"|""", listOf()),
Test("""|||""", listOf()),
Test("""""""""", listOf("(())","()()")),
Test("""""||""", listOf("()[]")),
Test(""""|"||"|"""", listOf("([([])])")),
Test(""""|""||""|"""", listOf("([(([]))])","([()[]()])","([()][()])"))
)
fun main(args: Array<String>) {
for ((input, output) in tests) {
val actual = input.f().sorted()
val expected = output.sorted()
if (actual != expected) {
throw AssertionError("Wrong answer: $input -> $actual | $expected")
}
}
```
## Edits
* -4 [jrtapsell](https://codegolf.stackexchange.com/users/73772) - Reworked checking predicate
* -2 [jrtapsell](https://codegolf.stackexchange.com/users/73772) - `true` -> `1>0` and `== 0` -> `< 1`
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 315 bytes
* Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for 19 bytes.
```
j,b;B(char*S){char*s=calloc(strlen(S)+2,b=1)+1;for(j=0;S[j];b*=(S[j]<62||*--s==60)*(S[j++]-41||*--s==40))S[j]==60?*s++=60:0,S[j]<41?*s++=40:0;return*s>0&*--s<1&b;}f(S,n,k)char*S;{if(n<strlen(S))for(k=2;k--;)S[n]==46-k-k?S[n]=40+k*20,f(S,n+1),S[n]=41+k*21,f(S,-~n),S[n]=46-k-k:0;else B(S)&&puts(S);}F(int*S){f(S,0);}
```
[Try it online!](https://tio.run/##bZHNcoIwFIXX9SmYLJjckCg4jItGdPyrunZJWSijrUJjB3Ql9tVtbjC22s5kJrkHvnNOIBVvaXq57PhKDmn6vizYAk5mL6N0mef7lJaHIl8rugCvzVdRAF4gN/uC7iJfLuJdIlcsonjodtpVxYQoo6jjA0PN8xIRBlYNfQB8EZ/3Wel5en/2uWHDoFZCrchifTgWipU930WyG7gred7QBVc8g7qkPG03VHVv3QArZVFbZkJInaJ0StgRmcj6Zgh9L2NtnxsXLwBeqwGqgVHFl7Kq4XSPdV6unaF2d93P46HUB3l@oVt1wI@EjK@Fy8dyqyicGi3mEOKInhMTCiRxWKthKPKqBgQk9nYGcRIRzol8oQOQT4apSGWoO2JkiZEhmryJzAgkIlX1DzG2xBiJZtMA4xog5NaMAhCuCz5WnFh8UlesS04sf03UYJzcg1MLTmuwDp5eQX05vWx4TOMEkofkmTWY2avqZdJnNxN0@W2DPmjEcdCV6M@QxPRPxNxGzK8RmHENmeM//AY "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 334 bytes (old version)
```
j,b;B(char*S){char*s=calloc(strlen(S)+2,1)+1;for(b=1,j=0;S[j];j++){if(S[j]==60)*s++=60;if(S[j]<41)*s++=40;b*=!(S[j]>61&&*--s!=60)*!(S[j]==41&&*--s!=40);}return*s>0&*--s<1&b;}f(S,n,k)char*S;{if(n>=strlen(S))return B(S)&&puts(S);for(k=0;k<2;k++)S[n]==46-k-k&&(S[n]=40+k*20,f(S,n+1),S[n]=41+k*21,f(S,-~n),S[n]=46-k-k);}F(char*S){f(S,0);}
```
[Try it online!](https://tio.run/##dZA7b8IwFIVn8iuMh8h2nGAjN4tJJAoUmOkWZYCIPghNq4ROQP869SOmSKSSJfse@37nXBfha1FcLju6kY@oeFvXZIWPZm@SYr3ffxaoOdT7bYVWOBhSjgMuXz5rtEk43SVMrrJdLndBgI/vL0gXSRIzTJogULtstZHgVhJMbkjSN2Iac98nYdj0TUe/7RZXVTAsz/X28F1XpEmZUUfc38izotKKltjmldq6SpNrTmybwKM6@/7X96FRB5O6VInL0VCWKvAqq7RdHJZh6fvIlIIFJRkyagwCjqlVuVa5UcOfyqmmU0V8uv6bfqBDXwbEo6MUCAFiBuKhFwIAxIMXIQxEDAQDgntk4Hkf6/cK4aPXGxAAIQhTkEGEYQ7UZc8Eh8/b5gDGEEttAsZZnkBKoQRPaIylfaIuvZ5lnODJUO4IE0eYGEJEI8OY3DNOp38QU4eYakQUWcK0IwW8zoIwhlSN1DXUzPFmdqh2rFkXsM2kSFl@T5o70tyS2mjz7g9Sy8XLUJbjvCPbwhEX7rvUsvkWnVSNveVqsCZTXajQ6K/IM9TpuXSey9ZTmzrX5a3r@fIL "C (gcc) – Try It Online")
---
# Explanation (old version)
```
j,b;B(char*S){ // determine if string is balanced
char*s=calloc(strlen(S)+2,1)+1; // array to store matching brackets
for(b=1,j=0;S[j];j++){ // loop through string (character array)
if(S[j]==60)*s++=60; // 60 == '<', opening bracket
if(S[j]<41)*s++=40; // 40 == '(', opening bracket
b*=!(S[j]>61&&*--s!=60)* // 62 == '>', closing bracket
!(S[j]==41&&*--s!=40);} // 41 == ')', closing bracket
return*s>0&*--s<1&b;} // no unmatched brackets and no brackets left to match
f(S,n,k)char*S;{ // helper function, recursively guesses brackets
if(n>=strlen(S)) // string replaced by possible bracket layout
return B(S)&&puts(S); // print if balanced, return in all cases
for(k=0;k<2;k++) // 46 == '.', guess 40 == '(',
S[n]==46-k-k&&(S[n]=40+k*20, // guess 41 == '(', restore
f(S,n+1),S[n]=41+k*21, // 44 == ',', guess 60 == '<',
f(S,-~n),S[n]=46-k-k);} // guess 62 == '>', restore
F(char*S){f(S,0);} // main function, call helper function
```
[Try it online!](https://tio.run/##dZRNj6JAEIbPw6@o4eDQ0CgY1gtiMl87M2f3RjwgtoowjeFjEzPO/nW3urERV9aQaAfep96qejG2N3F8Ou3o0n8y4m1UmHPyBbef0QhWrGLFZ8IZJGsoqyLhG0hKWEZZxGO20kDKyyCOsiyPDXwiY9yYE2tMXWK5vmBERREdoMpRnxcMPqMq3grOsojilFWlBuu8MJaBS3eB48/D3cLfWVbXEUKyPN9DtS3yerNVRqT3KEaHTQ2iAdo0BCEIJg4xS8vCb/@6pYkDQQAP0wcK@Z7xjpOLfOq5jdq7Ugu518iNXvnSDO4lYDZxBwPTtst7aaRTfSzlM5THWV5ey@H@bN5r1Z5D/O9OdVfKSZ@8YFVdcLOcOVI7dQfLVnqW8xxqLhfAVu38IeIrcac9Z2xdiX3JBzWcCOU0JU1Q/K@@mGxZtsctrGseV0nOKXqJ66JMfrPsAJualSUrO/vGKfNZ0IaF9BDPKy7YPotiYfYA@7wsk2XGFAiy6JDXYm5N5/CErMFgX1cl/vCvcHukVSLDKrlUiRIOmF2II7TYJDHFFKbTsZ9iCHuceRO5giGuQHbWSQRamYdc7G9ip3Y6GBjy6DlWao4d2uiVym1zVDD5ZogAyGFbLqGN0BVCl3are1JG2@qXOCu9/YcrvbRxFSClusRQVf/Z/hUISCd2neqfEY7rsmXx1v@7@9PI1Oh0JoyitclYs1Hq/dCGBhGjw2F5rmaONE2wDPKl3Y1M0HWwZxDqBtEXgDfv5BL1X2gNHnXiC2fwGC4CnVLdh5/GI/GbR/CmdtcwjvpRUm4Iz4rwLAlDOpSM51vG8fgfxItCvAjEcNgQXnpc6G0vBiE6xZb6mnpVvNemqXNbr33AsyckhYtb0psivTWks7W3/gHhpeyFRrggix5v74r4rsaFV@PvvZcqsF2uAAsyFQc0bVwOi9Dorfmhan6ca4qiqupHt@r36S8 "C (gcc) – Try It Online")
] |
[Question]
[
In this challenge, **you are given a limited amount of information about a particular game of chess, and you need to predict who won the game**.
You are given two sets of data:
1. Piece counts (What pieces are still alive)
2. Board colors (The color of pieces on the board)
More importantly, **you *don't* know where the pieces are located**. You need to determine who you think will win.
Games are selected from all events listed on [PGNMentor](http://www.pgnmentor.com/files.html#events) from 2010 to now. I've selected 10% of all of the board positions from each game that ends in a win or a loss. Board positions will always be at least 30 moves into the game. The test cases can be found [here](https://gist.githubusercontent.com/nathanmerrill/57243dfcd87bbd1b0acf9bbb3e242990/raw/961790f3b40fe3152d199fa4862dd83577c7a72e/test_cases.txt). (White wins are listed first, followed by black wins)
## Input
The piece count will be a string consisting of a character for each piece: `k`ing, `q`ueen, `r`ook, k`n`ight, `b`ishop, or `p`awn. Lowercase means black, uppercase is white. The board will be a string of 64 characters (8 rows by 8 columns). `B` represents a black piece, `W` represents a white piece, and `.` represents an empty spot. Sample:
```
W..WB......W.BB....W..B..W.WWBBB..W...B....W..BBWWW...BB.W....B.,BBKPPPPPPPQRRbbkpppppppqrr
```
would represent the following board
```
...B.BB.
.BBBBBBB
.B.B....
B..W....
WWWW.W..
....W.W.
...W..WW
W.....W.
```
and where both colors have 2 Bishops, 1 King, 7 Pawns, 1 Queen, 2 Rooks
## Output
You need to return a floating-point number between 0 and 1 (inclusive) to determine how likely it is that white wins. Sample:
```
0.3 (30% chance that white wins)
```
More details:
* Each test case is worth 1 point. Your score will be `1 - (1-Output)^2` if white wins, or `1 - (Output)^2` if black wins.
* Your final score will be the sum across all test cases.
* If I feel that submissions are hardcoding the input, I reserve the right to change the test cases. (If I do change them, they will have the SHA-256 hash `893be4425529f40bb9a0a7632f7a268a087ea00b0eb68293d6c599c6c671cdee`)
* Your program must run test cases independently. No saving information from one test case to the next.
* **If you are using machine learning, I highly recommend training on the first 80% of the data, and testing using the remaining 20%**. (Or whatever percentages you use). I use the games multiple times in the data, but I put the same games together sequentially.
* **UPDATE:** I've added over a [million test cases](https://github.com/nathanmerrill/chess_parser) for testing and learning purposes. They are split into black and white parts because of github repo size limits.
Good luck and have fun!
[Answer]
# Java 8 + Weka, 6413 points, 94.5%
This answer uses a machine learning approach. You need to retrieve the [Weka](http://www.cs.waikato.ac.nz/ml/weka/) library, notably `weka.jar` and `PackageManager.jar`.
Here, I use a multilayer perceptron as classifier; you can replace `mlp` with any `Classifier` class of Weka to compare results.
I have not tinkered much with the parameters of the MLP, and simply eyeballed them (one hidden layer of 50 neurons, 100 epochs, 0.2 learning rate, 0.1 momentum).
I threshold the output value of the MLP, so the output really is either 1 or 0 as defined in the challenge. That way the number of correctly classified instances as printed by Weka is directly our score.
### Feature vector construction
I turn each instance from a string to a vector of 76 elements, where:
* The first 64 elements represent the cells of the board, in the same order as in the string, where `1` is a white piece, `-1` is a black piece and `0` is an empty cell.
* The last 12 elements represent each type of piece (6 per player); the value of those elements is the number of pieces of that type on the board (`0` being "no piece of that type"). One could apply normalization to refit those values between -1 and 1 but this is probably not very helpful here.
### Number of training instances
If I use all test cases given to train my classifier, I have managed to get **6694 (i.e. 98.6588%) correctly classified instances**. This is obviously not surprising because testing a model on the same data you used to train it is way too easy (because in that case it is actually good that the model overfits).
Using a random subset of 80% of the instances as training data, we obtain the **6413 (i.e. 94.5173%) correctly classified instances** figure reported in the header (of course since the subset is random you might get slightly different results). I am confident that the model would work decently well on new data, because testing on the remaining 20% of the instances (that weren't used for training) gives **77.0818%** correct classification, which shows that the models generalizes decently well (assuming the instances we are given here are representative of the new test cases we would be given).
Using half the instances for training, and the other half for testing, we get **86.7502%** on both training and testing data, and **74.4988%** on only the test data.
### Implementation
As I've said, this code requires `weka.jar` and `PackageManager.jar` from Weka.
One can control the percentage of data used in the training set with `TRAIN_PERCENTAGE`.
The parameters of the MLP can be changed just below `TRAIN_PERCENTAGE`. One can try other classifiers of Weka (e.g. `SMO` for SVMs) by simply replacing `mlp` with another classifier.
This program prints to sets of results, the first one being on the entire set (including the data used for training) which is the score as defined in this challenge, and the second one being on only the data that was not used for training.
One inputs the data by passing the path of the file containing it as an argument to the program.
```
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.functions.MultilayerPerceptron;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Test {
public static void main(String[] arg) {
final double TRAIN_PERCENTAGE = 0.5;
final String HIDDEN_LAYERS = "50";
final int NB_EPOCHS = 100;
final double LEARNING_RATE = 0.2;
final double MOMENTUM = 0.1;
Instances instances = parseInstances(arg[0]);
instances.randomize(new java.util.Random(0));
Instances trainingSet = new Instances(instances, 0, (int) Math.floor(instances.size() * TRAIN_PERCENTAGE));
Instances testingSet = new Instances(instances, (int) Math.ceil(instances.size() * TRAIN_PERCENTAGE), (instances.size() - (int) Math.ceil(instances.size() * TRAIN_PERCENTAGE)));
Classifier mlp = new MultilayerPerceptron();
((MultilayerPerceptron) mlp).setHiddenLayers(HIDDEN_LAYERS);
((MultilayerPerceptron) mlp).setTrainingTime(NB_EPOCHS);
((MultilayerPerceptron) mlp).setLearningRate(LEARNING_RATE);
((MultilayerPerceptron) mlp).setMomentum(MOMENTUM);
try {
// Training phase
mlp.buildClassifier(trainingSet);
// Test phase
System.out.println("### CHALLENGE SCORE ###");
Evaluation test = new Evaluation(trainingSet);
test.evaluateModel(mlp, instances);
System.out.println(test.toSummaryString());
System.out.println();
System.out.println("### TEST SET SCORE ###");
Evaluation test2 = new Evaluation(trainingSet);
test2.evaluateModel(mlp, testingSet);
System.out.println(test2.toSummaryString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static Instances parseInstances(String filePath) {
ArrayList<Attribute> attrs = new ArrayList<>(); // Instances constructor only accepts ArrayList
for(int i = 0 ; i < 76 ; i++) {
attrs.add(new Attribute("a" + String.valueOf(i)));
}
attrs.add(new Attribute("winner", new ArrayList<String>(){{this.add("white");this.add("black");}}));
Instances instances = new Instances("Rel", attrs, 10);
instances.setClassIndex(76);
try {
BufferedReader r = new BufferedReader(new FileReader(filePath));
String line;
String winner = "white";
while((line = r.readLine()) != null) {
if(line.equals("White:")) {
winner = "white";
} else if(line.equals("Black:")) {
winner = "black";
} else {
Instance instance = new DenseInstance(77);
instance.setValue(attrs.get(76), winner);
String[] values = line.split(",");
for(int i = 0 ; i < values[0].length() ; i++) {
if(values[0].charAt(i) == 'B') {
instance.setValue(attrs.get(i), -1);
} else if(values[0].charAt(i) == 'W') {
instance.setValue(attrs.get(i), 1);
} else {
instance.setValue(attrs.get(i), 0);
}
}
// Ugly as hell
instance.setValue(attrs.get(64), values[1].length() - values[1].replace("k", "").length());
instance.setValue(attrs.get(65), values[1].length() - values[1].replace("q", "").length());
instance.setValue(attrs.get(66), values[1].length() - values[1].replace("r", "").length());
instance.setValue(attrs.get(67), values[1].length() - values[1].replace("n", "").length());
instance.setValue(attrs.get(68), values[1].length() - values[1].replace("b", "").length());
instance.setValue(attrs.get(69), values[1].length() - values[1].replace("p", "").length());
instance.setValue(attrs.get(70), values[1].length() - values[1].replace("K", "").length());
instance.setValue(attrs.get(71), values[1].length() - values[1].replace("Q", "").length());
instance.setValue(attrs.get(72), values[1].length() - values[1].replace("R", "").length());
instance.setValue(attrs.get(73), values[1].length() - values[1].replace("N", "").length());
instance.setValue(attrs.get(74), values[1].length() - values[1].replace("B", "").length());
instance.setValue(attrs.get(75), values[1].length() - values[1].replace("P", "").length());
instances.add(instance);
}
}
} catch (Exception e) { // who cares
e.printStackTrace();
}
return instances;
}
}
```
[Answer]
## [GNU sed](https://www.gnu.org/software/sed/) + bc, ~~4336~~ 5074.5 points, ~~64~~ 75 %
**Update:** the OP gave a new way to calculate the score of the prediction for an individual test case. Using [Wolfram Alpha](https://www.wolframalpha.com/input/?i=plot+x,+1-x,+1-((1-x)%5E2),+1-(x%5E2),+with+0%3C%3Dx%3C%3D1), I plotted both sets of formulas to see the differences.
The current way brings a strong incentive to output actual probabilities, and not just the extremes, 0 and 1, for which the new formulas give the same maximum score as before. This is why the unchanged algorithm below, has now a better prediction rate, in fact a great rate given its simplicity.
However, there's also a drawback associated with the new formulas, as explained in 'Edit 1'.
---
This is a simple estimation based only on the material advantage / disadvantage, ignoring the actual placement of the pieces. I was curious how this will perform. The reason I use sed, and not some language that can do this in one line, is because it is my favorite esoteric language.
```
/:/d # delete the two headers
s:.*,:: # delete board positions
s:$:;Q9,R5,B3,N3,P1,K0,q-9,r-5,b-3,n-3,p-1,k-0: # add relative piece value table
:r # begin replacement loop
s:([a-Z])((.*)\1([^,]+)):\4+\2: # table lookup: letter-value repl.
tr # repeat till last piece
s:;.*:: # delete value table
s:.*:echo '&0'|bc:e # get material difference: bc call
/^0$/c0.5 # print potential draw score
/-/c0 # print potential black win score
c1 # print potential white win score
```
Standard piece values used:
* 9 - Queen
* 5 - Rook
* 3 - Knight
* 3 - Bishop
* 1 - Pawn
* 0 - King
I calculate the material for both sides and subtract black's material from that of white. The output for each test case is based on that difference as follows:
* if difference > 0, then output = 1 (potential white win)
* if difference = 0, then output = 0.5 (potential draw).
This is my only fractional output, hence the reason of the improvement as explained above.
* if difference < 0, then output = 0 (potential black win)
The prediction rate for this method was 64 %. Now it is 75 % with the new formulas.
>
> I initially expected it to be higher, say 70 %, but as a chess player myself I can understand the result, since I've lost so many games when I was +1 / +2, and won that many when I was down in material. It's all about the actual position. (Well, now I got my wish!)
>
>
>
**Edit 1:** the drawback
The trivial solution is to output 0.5 for each test case, because this way you scored half a point regardless who won. For our test cases, this meant a total score of 3392.5 points (50 %).
But with the new formulas, 0.5 (which is an output you'd give if you're undecided who wins) is converted to 0.75 points. Remember that the maximum score you can receive for a test case is 1, for 100% confidence in the winner. As such, the new total score for a constant 0.5 output is 5088.75 points, or 75 %! In my opinion, the incentive is too strong for this case.
That score is better, though marginally, than my material advantage based algorithm. The reason for that is because the algorithm gives a probability of 1 or 0 (no incentive), assumed wins or losses, more times (3831) than it gives 0.5 (incentive), assumed draws (2954). The method is simple in the end, and as such it doesn't have a high percentage of correct answers. The boost from the new formula to constant 0.5, manages to reach that percentage, artificially.
**Edit 2:**
It is a known fact, mentioned in chess books, that it is usually better to have a bishop pair than a knight pair. This is especially true in the middle to end stage of the game, where the test cases are, since it's more likely to have an open position where a bishop's range is increased.
Therefore I did a second test, but this time I replaced the bishops's value from 3 to 3.5. The knight's value remained 3. This is a personal preference, so I didn't make it my default submission. The total score in this case was 4411 points (65 %). Only 1 percentage point increase was observed.
With the new formulas, the total score is 4835 points (71 %). Now the weighted bishop underperforms. But, the effect is explained because the weighted method now gives even more times assumed wins or losses (5089), than assumed draws (1696).
[Answer]
**Python 3 - 84.6%, 5275 points on a validation set**
If we cheat and use all the data, we can achieve **an accuracy of 99.3%, and a score of 6408**
Just a simple large MLP with dropout using Keras
```
import collections
import numpy as np
import random
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers.noise import GaussianDropout
from keras.optimizers import Adam
np.random.seed(0)
random.seed(0)
def load_data():
with open('test_cases.txt', 'r') as f:
for line in f:
yield line.split(',')
def parse_data(rows):
black_pieces = "kpbkrq"
white_pieces = black_pieces.upper()
for i, row in enumerate(rows):
if len(row) >= 2:
board = row[0]
board = np.array([1 if c == 'W' else -1 if c == 'B' else 0 for c in board], dtype=np.float32)
pieces = row[1]
counts = collections.Counter(pieces)
white_counts = np.array([counts[c] for c in white_pieces], dtype=np.float32)
black_counts = np.array([counts[c] for c in black_pieces], dtype=np.float32)
yield (outcome, white_counts, black_counts, board)
else:
if 'White' in row[0]:
outcome = 1
else:
outcome = 0
data = list(parse_data(load_data()))
random.shuffle(data)
data = list(zip(*data))
y = np.array(data[0])
x = list(zip(*data[1:]))
x = np.array([np.concatenate(xi) for xi in x])
i = len(y) // 10
x_test, x_train = x[:i], x[i:]
y_test, y_train = y[:i], y[i:]
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(76,)))
model.add(GaussianDropout(0.5))
model.add(Dense(512, activation='relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(512, activation='relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='mean_squared_error', optimizer=Adam())
use_all_data = False
x_valid, y_valid = x_test, y_test
if use_all_data:
x_train, y_train = x_test, y_test = x, y
validation_data=None
else:
validation_data=(x_test, y_test)
batch_size = 128
history = model.fit(x_train, y_train, batch_size=batch_size, epochs=50, verbose=1, validation_data=validation_data)
y_pred = model.predict_on_batch(x_test).flatten()
y_class = np.round(y_pred)
print("accuracy: ", np.sum(y_class == y_test) / len(y_test))
score = np.sum((y_pred - (1 - y_test)) ** 2) * (len(y) / len(y_test))
print("score: ", score)
```
[Answer]
**Python 3 - 94.3% accuracy, 6447 points on a validation set of 20% of the data**
Uses 3 neural networks, a nearest neighbours regressor, a random forest, and gradient boosting. These predictions are combined with a random forest which also has access to the data.
```
import collections
import numpy as np
import numpy.ma as ma
import random
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, BatchNormalization, Activation, Conv2D, Flatten
from keras.layers.noise import GaussianDropout
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
import tensorflow
tensorflow.set_random_seed(1)
np.random.seed(1)
random.seed(1)
def load_data():
with open('test_cases.txt', 'r') as f:
for line in f:
yield line.split(',')
def parse_data(rows):
black_pieces = "kqrnbp"
white_pieces = black_pieces.upper()
for i, row in enumerate(rows):
if len(row) >= 2:
board = row[0]
board = np.array([1 if c == 'W' else -1 if c == 'B' else 0 for c in board], dtype=np.float32)
pieces = row[1]
counts = collections.Counter(pieces)
white_counts = np.array([counts[c] for c in white_pieces], dtype=np.float32)
black_counts = np.array([counts[c] for c in black_pieces], dtype=np.float32)
yield (outcome, white_counts, black_counts, board)
else:
if 'White' in row[0]:
outcome = 1
else:
outcome = 0
data = list(parse_data(load_data()))
random.shuffle(data)
data = list(zip(*data))
y = np.array(data[0])
x = list(zip(*data[1:]))
conv_x = []
for white_counts, black_counts, board in x:
board = board.reshape((1, 8, 8))
white_board = board > 0
black_board = board < 0
counts = [white_counts, black_counts]
for i, c in enumerate(counts):
n = c.shape[0]
counts[i] = np.tile(c, 64).reshape(n, 8, 8)
features = np.concatenate([white_board, black_board] + counts, axis=0)
conv_x.append(features)
conv_x = np.array(conv_x)
x = np.array([np.concatenate(xi) for xi in x])
s = x.std(axis=0)
u = x.mean(axis=0)
nz = s != 0
x = x[:,nz]
u = u[nz]
s = s[nz]
x = (x - u) / s
i = 2 * len(y) // 10
x_test, x_train = x[:i], x[i:]
conv_x_test, conv_x_train = conv_x[:i], conv_x[i:]
y_test, y_train = y[:i], y[i:]
model = Sequential()
def conv(n, w=3, shape=None):
if shape is None:
model.add(Conv2D(n, w, padding="same"))
else:
model.add(Conv2D(n, w, padding="same", input_shape=shape))
model.add(BatchNormalization())
model.add(Activation('relu'))
conv(128, shape=conv_x[0].shape)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(2, w=1)
model.add(Flatten())
model.add(GaussianDropout(0.5))
model.add(Dense(256))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1))
model.add(BatchNormalization())
model.add(Activation('sigmoid'))
model.compile(loss='mse', optimizer=Adam())
model5 = model
model = Sequential()
model.add(Dense(50, input_shape=(x.shape[1],)))
model.add(Activation('sigmoid'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='mse', optimizer=Adam())
model0 = model
model = Sequential()
model.add(Dense(1024, input_shape=(x.shape[1],)))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1024))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1024))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='mse', optimizer=Adam())
model4 = model
use_all_data = False
x_valid, y_valid = x_test, y_test
if use_all_data:
x_train, y_train = x_test, y_test = x, y
validation_data=None
else:
validation_data=(x_test, y_test)
def subsample(x, y, p=0.9, keep_rest=False):
m = np.random.binomial(1, p, size=len(y)).astype(np.bool)
r = (x[m,:], y[m])
if not keep_rest:
return r
m = ~m
return r + (x[m,:], y[m])
epochs=100
x0, y0, x_valid, y_valid = subsample(conv_x_train, y_train, keep_rest=True)
model5.fit(x0, y0, epochs=epochs, verbose=1, validation_data=(x_valid, y_valid), callbacks=[EarlyStopping(patience=1)])
x0, y0, x_valid, y_valid = subsample(x_train, y_train, keep_rest=True)
model0.fit(x0, y0, epochs=epochs, verbose=1, validation_data=(x_valid, y_valid), callbacks=[EarlyStopping(patience=1)])
x0, y0, x_valid, y_valid = subsample(x_train, y_train, keep_rest=True)
model4.fit(x0, y0, epochs=epochs, verbose=1, validation_data=(x_valid, y_valid), callbacks=[EarlyStopping(patience=1)])
model1 = RandomForestRegressor(n_estimators=400, n_jobs=-1, verbose=1)
model1.fit(*subsample(x_train, y_train))
model2 = GradientBoostingRegressor(learning_rate=0.2, n_estimators=5000, verbose=1)
model2.fit(*subsample(x_train, y_train))
model3 = KNeighborsRegressor(n_neighbors=2, weights='distance', p=1)
model3.fit(*subsample(x_train, y_train))
models = (model0, model1, model2, model3, model4, model5)
model_names = [
"shallow neural net",
"random forest",
"gradient boosting",
"k-nearest neighbors",
"deep neural net",
"conv-net",
"ensemble"
]
def combine(predictions):
clip = lambda x: np.clip(x, 0, 1)
return clip(np.array([y.flatten() for y in predictions]).T)
def augment(x, conv_x):
p = combine([m.predict(x) for m in models[:-1]] + [models[-1].predict(conv_x)])
return np.concatenate((x, p), axis=1)
model = RandomForestRegressor(n_estimators=200, n_jobs=-1, verbose=1)
model.fit(augment(x_train, conv_x_train), y_train)
def accuracy(prediction):
class_prediction = np.where(prediction > 0.5, 1, 0)
return np.sum(class_prediction == y_test) / len(y_test)
predictions = [m.predict(x_test).flatten() for m in models[:-1]] + [models[-1].predict(conv_x_test).flatten()]+ [model.predict(augment(x_test, conv_x_test))]
for s, p in zip(model_names, predictions):
print(s + " accuracy: ", accuracy(p))
def evaluate(prediction):
return np.sum(1 - (prediction - y_test) ** 2) * (len(y) / len(y_test))
for s, p in zip(model_names, predictions):
print(s + " score: ", evaluate(p))
```
[Answer]
# Python 3 - 4353.25/6785 points - 64%
So I worked on this mostly yesterday. My first post golfing, and I've only been using python a week or so now, so forgive me if not everything is optimized.
```
def GetWhiteWinPercent(a):
finalWhiteWinPercent=0
i=a.index(',')
#position
board=a[:i]
blackBoardScore=0
whiteBoardScore=0
for r in range(i):
if board[r] == 'B': blackBoardScore += abs(7 - (r % 8))
if board[r] == 'W': whiteBoardScore += r % 8
if whiteBoardScore > blackBoardScore: finalWhiteWinPercent += .5
elif whiteBoardScore < blackBoardScore: finalWhiteWinPercent += .0
else: finalWhiteWinPercent+=.25
#pieces
pieces=a[i:]
s = {'q':-9,'r':-5,'n':-3,'b':-3,'p':-1,'Q':9,'R':5,'N':3,'B':3,'P':1}
pieceScore = sum([s.get(z) for z in pieces if s.get(z) != None])
if pieceScore < 0: finalWhiteWinPercent += 0
elif pieceScore > 0: finalWhiteWinPercent += .5
else: finalWhiteWinPercent += .25
return finalWhiteWinPercent
```
I ended up along the same path as seshoumara's answer to begin with. But the large number of test cases that had even counts of pieces left me dissatisfied.
So I googled traits that dictate who is winning in chess (I don't play the game myself) and noticed board position, specifically center control, is big. That's where this bit comes in.
```
for r in range(i):
if board[r] == 'B': blackBoardScore += abs(7 - (r % 8))
if board[r] == 'W': whiteBoardScore += r % 8
if whiteBoardScore > blackBoardScore: finalWhiteWinPercent += .5
elif whiteBoardScore < blackBoardScore: finalWhiteWinPercent += .0
else: finalWhiteWinPercent+=.25
```
Both of those halves combined are used to find the score (0.0, 0.25, 0.50, 0.75, 1.0)
Very interesting that this board position extra doesn't seem to increase the chance at all of guessing the winner.
If you drop the test cases into some files, here's the testing.
```
whiteWins=0
blackWins=0
totalWins=0
for line in open('testcases2.txt','r'):
totalWins += 1
blackWins += 1 - GetWhiteWinPercent(line)
for line in open('testcases.txt','r'):
totalWins += 1
whiteWins += GetWhiteWinPercent(line)
print(str(whiteWins+blackWins) +'/'+str(totalWins))
```
I know this isn't a golf challenge, but any tips or advice in that regard is appreciated!
] |
[Question]
[
I came up with this challenge independently, but it turns out to be the inverse to [this challenge by Doorknob](https://codegolf.stackexchange.com/q/21927/8478). As I really like his spec, I decided to steal large parts of it instead of cooking up my own explanations.
## The Challenge
Given the abbreviation of one of the 32 points on the compass, print the corresponding degrees. Feel free to skip ahead to the table below if you're not interested in an explanation of the 32 points.
Here is the full compass:

By Denelson83 (Own work) [[GFDL](http://www.gnu.org/copyleft/fdl.html) or [CC-BY-SA-3.0](http://creativecommons.org/licenses/by-sa/3.0/)], via [Wikimedia Commons](http://commons.wikimedia.org/wiki/File:Compass_Card.png)
Each direction is 11.25 (360 / 32) degrees farther than the previous. For example, N (north) is 0 degrees, NbE (north by east) is 11.25 degrees, NNE (north-northeast) is 22.5 degrees, etc.
In detail, the names are assigned as follows:
* 0 degrees is N, 90 degrees is E, 180 degrees is S, and 270 degrees is W. These are called cardinal directions.
* The halfway points between the cardinal directions are simply the cardinal directions they're between concatenated. N or S always go first, and W or E always are second. These are called ordinal directions. The ordinal and cardinal directions together form the principal winds.
* The halfway points between the principal winds are the directions they're between concatenated. Cardinal directions go first, ordinal second. These are called half winds.
* The halfway points between principal and half winds are the adjacent principal wind "by" the closest cardinal direction away from the principal wind. This is denoted with a `b`. These are called quarter winds.
This results in the following chart:
```
# Degrees Abbrv. Name
1 0 N North
2 11.25 NbE North by east
3 22.5 NNE North-northeast
4 33.75 NEbN Northeast by north
5 45 NE Northeast
6 56.25 NEbE Northeast by east
7 67.5 ENE East-northeast
8 78.75 EbN East by north
9 90 E East
10 101.25 EbS East by south
11 112.5 ESE East-southeast
12 123.75 SEbE Southeast by east
13 135 SE Southeast
14 146.25 SEbS Southeast by south
15 157.5 SSE South-southeast
16 168.75 SbE South by east
17 180 S South
18 191.25 SbW South by west
19 202.5 SSW South-southwest
20 213.75 SWbS Southwest by south
21 225 SW Southwest
22 236.25 SWbW Southwest by west
23 247.5 WSW West-southwest
24 258.75 WbS West by south
25 270 W West
26 281.25 WbN West by north
27 292.5 WNW West-northwest
28 303.75 NWbW Northwest by west
29 315 NW Northwest
30 326.25 NWbN Northwest by north
31 337.5 NNW North-northwest
32 348.75 NbW North by west
```
[Here is a more detailed chart and possibly better explanation of the points of the compass.](http://en.wikipedia.org/wiki/Points_of_the_compass)
Your task is to take as input one of the 32 abbreviations from the third column and output the corresponding degrees in the second column.
You may assume that input will always be exactly one of those 32 strings (and you may optionally but consistently expect a single trailing newline). Output should also be given exactly as listed above, although trailing zeroes are allowed. You may optionally output a single trailing newline.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
This is code golf, so the shortest answer (in bytes) wins.
[Answer]
# Ruby, ~~118~~ 106
Thanks to Martin Büttner for 12 bytes saved.
This is currently the same length regardless of whether it's a function or a program.
lambda function
```
->s{n=4
d=0,0
s.chars{|e|c="SWNE".index e
c ?d[c%2]+=c/2*2*n-n :n=1}
(Complex(*d).arg*5.1).round%32*11.25}
```
program
```
n=4
d=0,0
gets.chars{|e|c="SWNE".index e
c ?d[c%2]+=c/2*2*n-n :n=1}
p (Complex(*d).arg*5.1).round%32*11.25
```
This is a cartesian walk through the points. The characters `NSEW` add or subtract 4 from the x and y coordinates stored in `d[]`. After a `b` (or any symbol other than `NSEW`) is encountered, this is reduced to 1.
The x and y data is then treated as a complex number to extract the angular argument. This is multiplied by 16/PI=`5.1` . Although there are some geometrical errors in the approach, rounding this angle is sufficient to give the correct number `-15..+16`. Modulo is used to correct this to `0..31` (in Ruby `%` always returns positive.) Finally the result is multiplied by 11.25.
[Answer]
# Javascript (ES6), 153 bytes
Just wanted to get the ball rolling with a simple one.
```
x=>'N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE SEbE SE SEbS SSE SbE S SbW SSW SWbS SW SWbW WSW WbS W WbN WNW NWbW NW NWbN NNW NbW'.split` `.indexOf(x)*45/4
```
Not particularly innovative, but it works, and perhaps there's some tips that could be derived from it. Don't worry, I'll think of another (hopefully better) technique.
[Answer]
# Pyth, 47 bytes
```
c*45x"NuMD¢¼Ew
XSj.{§/gWbZ¹°"C%CzC\½4
```
Hexdump, due to unprintable characters:
```
0000000: 632a 3435 7822 4e86 754d 0344 a2bc 4504 c*45x"N.uM.D..E.
0000010: 770a 9518 1c58 536a 2e7b a77f 2f67 5762 w....XSj.{../gWb
0000020: 5ab9 15b0 8798 2243 2543 7a43 5cbd 34 Z....."C%CzC\.4
```
[Test harness](https://pyth.herokuapp.com/?code=c*45x%22N%C2%86uM%03D%C2%A2%C2%BCE%04w%0A%C2%95%18%1CXSj.%7B%C2%A7%7F%2FgWbZ%C2%B9%15%C2%B0%C2%87%C2%98%22C%25CzC%5C%C2%BD4&input=SW&test_suite=1&test_suite_input=N%0ANbE%0ANNE%0ANEbN%0ANE%0ANEbE%0AENE%0AEbN%0AE%0AEbS%0AESE%0ASEbE%0ASE%0ASEbS%0ASSE%0ASbE%0AS%0ASbW%0ASSW%0ASWbS%0ASW%0ASWbW%0AWSW%0AWbS%0AW%0AWbN%0AWNW%0ANWbW%0ANW%0ANWbN%0ANNW%0ANbW&debug=0)
Due to a bug in the official command line compiler, this code only works via the online compiler, linked above, or the `-c` flag of the offline compiler. (The bug was fixed after the question was asked.)
This solution is very similar to @Dennis's CJam answer, using the process of hashing the input, looking up the result in a 32 byte lookup string, and then multiplying by 11.25.
The hash function I use is converting the input to a string as if it was a base 256 integer with `C`, taking the result modulo `C` of `½`, which is 189, but saves a byte due to superior parsing, and converting that back to a string with `C` again.
Multiplying by 11.25 is accomplished by multiplying by 45, then dividing by 4, which saves a byte.
[Answer]
# CJam, 49 bytes
```
0000000: 72 34 62 32 35 33 25 63 22 4e bf 6f f1 80 e8 dc 38 r4b253%c"N.o....8
0000011: 45 3d f0 2e 94 3c d3 12 53 24 e5 5f a6 63 28 60 57 E=...<..S$._.c(`W
0000022: 5b 14 20 92 17 81 d1 22 23 31 31 2e 32 35 2a [. ...."#11.25*
```
The above is a hexdump, which can be reversed with `xxd -r -c 17 -g 1`.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r4b253%25c%22N%C2%BFo%C3%B1%C2%80%C3%A8%C3%9C8E%3D%C3%B0.%C2%94%3C%C3%93%12S%24%C3%A5_%C2%A6c(%60W%5B%14%20%C2%92%17%C2%81%C3%91%22%2311.25*&input=NW).
### How it works
```
r e# Read a token from STDIN.
4b e# Convert the string (array of code points) from base 4 to integer.
253% e# Take the result modulo 253.
c e# Cast to character.
"…" e# Push a 32 byte lookup table.
# e# Find the index of the character.
11.25* e# Multiply the index by 11.25.
```
[Answer]
## Java, 653 (characters)
I know Java can't win but I like to make the effort anyway.
```
class C{float c=1/8f;int n=0;float a;public C(String s){if(s.contains("W"))n=4;switch(s.length()){case 1:p(d(s));case 2:p(e(s));case 3:if(s.contains("b"))f(s,1);g(s);}f(s,2);}int v(char x){switch(x){case 'N':return n;case 'E':return 1;case 'S':return 2;}return 3;}int d(String s){return v(s.charAt(0));}float e(String s){return (v(s.charAt(0))+v(s.charAt(1)))/2f;}void f(String s,int i){if(i<2)a=v(s.charAt(0));else a=e(s.substring(0,i));if(v(s.charAt(1+i))<a)c=-c;p(a+c);}void g(String s){p((d(s.substring(0,1))+e(s.substring(1)))/2f);}void p(float x){System.out.printf("%.2f",x*90);System.exit(0);}public static void main(String[]r){C c=new C(r[0]);}}
```
It takes input from the commandline and outputs to the console.
Ungolfed version:
```
class Compass
{
float c = 1/8f;
int n = 0;
float a;
public Compass( String s )
{
if( s.contains( "W" ) )
{
n = 4;
}
switch( s.length() )
{
case 1:
print( parse1( s ) );
case 2:
print( parse2( s ) );
case 3:
if( s.contains( "b" ) )
{
parse3b4( s , 1 );
}
parse3( s );
}
parse3b4( s , 2 );
}
int getValue( char x )
{
switch( x )
{
case 'N':
return n;
case 'E':
return 1;
case 'S':
return 2;
}
return 3;
}
int parse1( String s )
{
return getValue( s.charAt( 0 ) );
}
float parse2( String s )
{
return ( getValue( s.charAt( 0 ) ) + getValue( s.charAt( 1 ) ) ) / 2f;
}
void parse3b4( String s , int i )
{
if( i < 2 ) a = getValue( s.charAt( 0 ) );
else a = parse2( s.substring( 0 , i ) );
if( getValue( s.charAt( 1 + i ) ) < a )
{
c = -c;
}
print( a + c );
}
void parse3( String s )
{
print( ( parse1( s.substring( 0 , 1 ) ) + parse2( s.substring( 1 ) ) ) / 2f );
}
void print( float x )
{
System.out.printf( "%.2f" , x * 90 );
System.exit( 0 );
}
public static void main( String[] args )
{
Compass compass = new Compass( args[ 0 ] );
}
}
```
It works by assigning 0-3 to N-W (or 4 for N if W is involved).
It recognizes 4 different situations:
* parse1 is for single letter points, it just returns the value.
* parse2 is for double letter points, it averages the values of the 2 points.
* parse3 is for triple letter points, it takes the average of the average of the double and the single points.
* parse3b4 is for all the ones with a 'b' in them, it calculates the value of the point before the 'b' and adds or subtracts 1/8 based on the 'direction' of the point after the 'b'.
In print() the value is multiplied by 90 to get the actual angle.
[Answer]
# Python 3, 149 bytes
I tried a recursive algorithmic approach. The quarter winds were harder to handle than I thought at first, so this solution grew relatively long.
```
def f(s):
if'W'in s:s=s.replace(*'Nn')
a=(len(s)-2)/8;return'b'in s and(1-a)*f(s[:-2])+a*f(s[-1])or a>=0and(f(s[0])+f(s[1:]))/2or'NESWn'.find(s)*90
```
Ungolfed:
```
def f(s):
if 'W'in s:
s = s.replace('N','n')
a=(len(s)-2)/8
if 'b' in s:
a = 1/8 if len(s)==3 else 1/4
return (1-a)*f(s[:-2])+a*f(s[-1])
else:
if len(s)==1:
return 'NESWn'.find(s)*90
else:
return (f(s[0])+f(s[1:]))/2
```
[Answer]
# Haskell, 206 bytes
```
c l=11.25*(fromIntegral$b$l)
b l|(p y l)<0=a l+16|0<1=mod(a l)32
a l=round$(16/pi*)$atan$d$l
d l=p x l/p y l
p z[]=0.0
p z('b':[r])=z r/4
p z(a:r)=z a+p z r
x 'E'=4
x 'W'=(-4)
x c=0
y 'N'=4
y 'S'=(-4)
y c=0
```
Convenient test:
```
*Main> map c ["N","NbE","NNE","NEbN","NE","NEbE","ENE","EbN","E","EbS","ESE","SEbE","SE","SEbS","SSE","SbE","S","SbW","SSW","SWbS","SW","SWbW","WSW","WbS","W","WbN","WNW","NWbW","NW","NWbN","NNW","NbW"]
[0.0,11.25,22.5,33.75,45.0,56.25,67.5,78.75,90.0,101.25,112.5,123.75,135.0,146.25,157.5,168.75,180.0,191.25,202.5,213.75,225.0,236.25,247.5,258.75,270.0,281.25,292.5,303.75,315.0,326.25,337.5,348.75]
```
[Answer]
### PowerShell - 350
[](https://i.stack.imgur.com/vqEZN.png)
```
Add-Type -AssemblyName *sys*forms*
$f=new-object windows.forms.form
$c=new-object windows.forms.combobox
$c.DataSource=(-split"N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE SEbE SE SEbS SSE SbE S SbW SSW SWbS SW SWbW WSW WbS W WbN WNW NWbW NW NWbN NNW NbW")
$c.Parent=$f
$c.Add_SelectedValueChanged({$f.text=$c.SelectedIndex*11.25})
$f.ShowDialog()
```
[Answer]
# Julia, 151 147 142 bytes
```
t=strchr
p=s->if ""==s 0;else i=t(s,'b')
(32/2^i)^sign(i)*p(i>0?s[1:i-1]:s[2:])+im^t("ESWN",s[i+1])end
f=s->90int(16mod(angle(p(s)),2pi)/pi)/8
```
A bit ungolfed:
```
# return approx. direction in term of complex number of absolute value 1,
# whose argument is the direction:
# N -> 0, E -> 0+1j, S -> -1, W -> 0-1j
function p(s)
if ""==s 0;
else
i=strchr(s,'b');
if i!=0
# if 'b' is 2nd in the word, following direction weight is 1/8,
# if 'b' is 3rd in the word, following direction weight is 1/4.
weight=2^(5-i)
# the first term to count avg is all before 'b'
first_term=s[1:i-1]
else
# weights are equal for the counted and the new (eg. 'NNW <= avg(N, NW)')
weight=1
# the first term to count avg is all after the first character
first_term=s[2:]
end
# the return value - average of two vectors
# s[i+1] evaluates to FIRST character if 'b' didn't occur
# or to the LAST CHARACTER (after 'b') if it did.
e^(im*angle(weight*p(first_term)+im^t("ESWN",s[i+1])));
end
end
# ... And the proper function for returning angle
# there are errors (sic!) in the counted direction, but dividing by 11.25,
# rounding and remultiplying by 11.25 filters them out
f=s->int32(mod(angle(p(s)),2pi)/pi*16)*11.25
```
In the ungolfed code, I count the average of two vectors as [](https://i.stack.imgur.com/ecXju.gif) in order to have the vector still normalized. However, the errors due to elongation of the first vector are not yet accumulating with so little additions in our recursion, so while golfing the normalization step was removed and the computation goes[](https://i.stack.imgur.com/kI69a.gif) simply. Errors less than 1/64 of full circle are filtered out by rounding.
] |
[Question]
[
Inspired by [Fibonacci domino tiling](https://codegolf.stackexchange.com/questions/37886/fibonacci-domino-tiling), this problem is about generating ASCII art representing another famous combinatorial sequence.
A *n-step mountain diagram* is a drawing of a mountain range, using exactly *n* '/' and *n* '\' characters, such that characters sketch a continuous curve which never dips below its initial "altitude". For example,
```
/\/\
/\/ \
```
and
```
/\
/\/ \/\
```
are both 4-step mountain diagrams, but
```
/\ /\/\
\/
```
is not.
**Input**
The program should accept an integer *n* from stdin or as the parameter to a function.
**Output**
Print all *n*-step mountain diagrams to stdout. The diagrams can be in any order, but should be separated by some sort of whitespace. You can decide if different diagrams will be output horizontally, vertically, etc.
As in the domino tiling problem, you can use whatever whitespace you want. This includes extra newlines before or after the printed output.
**Example**
Some sample valid outputs for *n*=3:
Valid output A:
```
/\
/\ /\ / \ /\/\
/\/\/\ / \/\ /\/ \ / \ / \
```
Valid output B:
```
/\
/\/ \
/\/\
/ \
/\/\/\
/\
/ \
/ \
/\
/ \/\
```
Valid output C:
```
/\
/ \ /\
/ \ /\/ \
/\/\
/\ / \
/ \/\ /\/\/\
```
This is code golf; shortest program (in bytes) wins.
[Answer]
# Python 2: 151 chars
```
N=2*input()
for i in range(2**N):
L=[];c=1;exec"b=i%2;c+=2*b-1;L+=[[' ']*N];L[-1][b-c]='\/'[b];i=i/2*(c>0);"*N
for x in(c==1)*zip(*L):print"".join(x)
#Output for n=3:
/\
/ \
/ \
/\/\
/ \
/\
/\/ \
/\
/ \/\
/\/\/\
```
Wow, this is a mess.
The first idea is to use the numbers `0 to 2**N-1` to encode all sequences of `N` up-moves and down-moves in their bits. We read off these bits one by one by repeated `%2` and `/2`, iterated in an `exec` loop.
We store the running mountain range sideways in a transposed list of strings `L`. Each time, we generate a new a row of spaces are replace one space in the new row with `/` or `\` depending on whether an up-move or down-move happened.
The index of that space is `c` spaces from the end, where `c` is the running height. Doing it from the front would make the mountains upside down. We further shift it by `b` to align upward and downward moves , getting `[b-c]`. Starting `c` at 1 rather than 0 fixes an off-by-one error.
To eliminate cases where `c` dips below the start value `1`, when this happens, we set `i` to `0`, which causes all further moves to be downward, making `c` become more negative. Then, when we check whether `c` ended at `1`, we also check whether `c` ever fell below it. We only `print` the mountain range if `c` is `1`.
To print, we do `zip(*L)` to transpose the range from vertical to horizontal, and print each joined string. A lot of trouble in this answer came from Python treats strings as immutable, so we worked with them as lists of characters and only joined them into strings for printing.
Thanks to @flornquake for help and improvements.
[Answer]
## APL (88)
```
{{⍉↑'\/'[1+⍵=1]/⍨¨¯1+2×K=⊂⌽⍳⌈/K←(⍵≠1)++\⍵}¨Z/⍨{(0=+/⍵)∧∧/0≤+\⍵}¨Z←↓⍉¯1+2×(N/2)⊤⍳2*N←2×⍵}
```
Output for `n=3`:
```
{{⍉↑'\/'[1+⍵=1]/⍨¨¯1+2×K=⊂⌽⍳⌈/K←(⍵≠1)++\⍵}¨Z/⍨{(0=+/⍵)∧∧/0≤+\⍵}¨Z←↓⍉¯1+2×(N/2)⊤⍳2*N←2×⍵}3
/\/\/\ /\ /\ /\/\ /\
/\/ \ / \/\ / \ / \
/ \
```
Explanation:
* `(N/2)⊤⍳2*N←2×⍵`: get a bitfield for each number from `0` to `2^⍵`.
* `Z←↓⍉¯1+2×`: multiply by 2 and subtract 1, giving `1` for up and `-1` for down. Store a vector of vectors, each vector containing the representation for one number, in `Z`.
* `{`...`}¨Z`: for each element of `Z`:
+ `∧/0≤+\⍵`: check that the running sum never falls below `0` (doesn't go below ground level),
+ `(0=+/⍵)`: and that the total sum is `0` (ends up back at ground level).
* `{`...`}¨Z/⍨`: select those elements from `Z` for which that is true. For each of them:
+ `K←(⍵≠1)++\⍵`: find the height for each character, and store in `K`. Raise each `\` up one, so that they line up with the `/`s properly. This makes the ground height `1`.
+ `¯1+2×K=⊂⌽⍳⌈/K`: for each column, make a list `[1..max(K)]`, and mark the position of the character in that column with `1` and the rest as `-1`. (Replicating by -1 fills that position with a space.)
+ `'\/'[1+⍵=1]/⍨¨`: find the correct character for each column, and replicate it by the list for that column.
+ `⍉↑`: turn the result into a matrix and put it right-side-up
[Answer]
# Python, ~~261~~ ~~241~~ 236 characters
```
import itertools as I
n=input()
S={}
for q in I.permutations((-1,1)*n):
s=0;B=[[' ']*n*2 for _ in range(n+2)];o=0
for i in q:
B[n-s+(i==-1)][o]=' /\\'[i];s+=i;o+=1
if s<0:break
else:
for l in (B,[])[q in S]:print''.join(l)
S[q]=1
```
It starts taking a while for `n=5` and up...
```
$ echo 1 | py mountrange.py
/\
Laxori@Laxori-PC /cygdrive/c/Programmin
$ echo 2 | py mountrange.py
/\/\
/\
/ \
Laxori@Laxori-PC /cygdrive/c/Programmin
$ echo 3 | py mountrange.py
/\/\/\
/\
/\/ \
/\
/ \/\
/\/\
/ \
/\
/ \
/ \
Laxori@Laxori-PC /cygdrive/c/Programmin
$ echo 4 | py mountrange.py
/\/\/\/\
/\
/\/\/ \
/\
/\/ \/\
/\/\
/\/ \
/\
/ \
/\/ \
/\
/ \/\/\
/\ /\
/ \/ \
/\/\
/ \/\
/\/\/\
/ \
/\
/\/ \
/ \
/\
/ \
/ \/\
/\
/ \/\
/ \
/\/\
/ \
/ \
/\
/ \
/ \
/ \
```
[Answer]
# JavaScript (ES6) 159 ~~163~~
Just like my answer for Fibonacci Domino Tiling, I examine all the sequences of n+n bits, with 1 marking a '/' and 0 marking a '\' (just for output, '2' is later added to mark a newline). While building tha ascii pattern I check the balance - same numbers of 0 and 1, and never going below the starting base line - and output what obey the rules.
Output done with 'alert', that is standard for JS codegolf but quite annoying, and maybe against the rules. Using console.log the character count goes to 165.
```
F=n=>{
for(i=0;++i<1<<n+n;l||alert((o+'').replace(/,\d?/g,r=>'\\/\n '[r[1]||3])))
for(p=l=o=[],j=i;l+1&&p++-n-n;j/=2)
b=j&1,
l-=1-b-b,
(o[k=b+n-l]=o[k]||[2])[p]=b;
}
```
**Less golfed**
```
F=n=>{
m = n+n
outer:
for (i=1; i < 1<<m; i+=2)
{
o=[]
l=0;
p=1;
for (j = 1; j <1<<m; j+=j,p++)
{
if (i&j)
{
q=o[n-l]||[]
q[p]=1;
o[n-l]=q
++l;
}
else
{
--l;
if (l<0) continue outer;
q=o[n-l]||[]
q[p]=0;
o[n-l]=q
}
}
if (l==0) console.log(o.join('\n').replace(/,\d?/g,r=>'\\/'[r[1]]||' '));
}
}
```
**Test** in FireFox/FireBug console.
```
F(4)
```
*Output*
```
/\
/ \
/ \
/ \
/\/\
/ \
/ \
/\
/\/ \
/ \
/\
/ \
/\/ \
/\
/ \/\
/ \
/\/\/\
/ \
/\/\
/\/ \
/\ /\
/ \/ \
/\
/\/\/ \
/\
/ \
/ \/\
/\/\
/ \/\
/\
/\/ \/\
/\
/ \/\/\
/\/\/\/\
```
[Answer]
# CJam, 84 bytes
```
q~:Q{Q[XW]*mr1\{\_@+}%_{*}*{(\{_Q\-)S*@2$m0<" /""\\"?+QS*+Q)<\}%);z{N\++}*o}{;}?1}g
```
Note that this program prints the mountains in an infinite loop so the online interpreter will not help you; invoke at the command line using
```
java -jar cjam-0.6.2.jar mountain.cjam <<< 5
```
or to try online use
```
q~:Q{Q[XW]*mr1\{\_@+}%_{*}*{(\{_Q\-)S*@2$m0<" /""\\"?+QS*+Q)<\}%);z{N\++}*o}{;}?}fZ
```
and just hit the run button a bunch of times in succession and imagine the output is concatenated.
The basic idea is that we know a mountain range of size Q has Q of each upward and downward transitions.
```
Q[XW]*mr #shuffled list of Q 1s and -1s
1 {\_@+}% #height map after each transition
_{*}* #if it passes through 0 it's invalid
```
Then if it's valid we print it, if not we pop it from the stack so it doesn't overflow.
The print routing basically builds each column as Q - height spaces, then the symbol, then enough more spaces to hit Q+1 total characters, and then we transpose and print the lines with newlines between them.
```
z{N\++}*o #transpose, insert newlines, print
```
[Answer]
# C,179
excluding unnecessary whitespace.
A similar strategy to edc65. I run through all the `n*2`-bit binary values, considering `/`=1 and `\`=0.
I format a single string containing `n` linebreaks every `n*3` characters. As written the string contains 1000 characters, so there is usually a lot of whitespace printed after the mountain. (This can be fixed by adding `s[n*n*3]=0` before the `puts`.) Anyway, this enables me to output the whole mountain with a single `puts` after checking that it complies with the rules.
I will try converting it to a function and reducing to a single `for` loop later.
```
i,n,x,y,q,r;
main(){
scanf("%d",&n);
for(i=1<<n*2;i--;){ //run though all n*2-digit binary numbers
char s[]={[0 ...999]=32}; //fill an array with spaces. This syntax is allowed by GCC
y=n; //start y one square below the grid (note: r is initialised to 0 by default.)
for(x=n*2;x--;) //for each digit of i
q=i>>x&1,
y+=q+r-1, //move up if the current and last digit are 0, down if they are 1, and stay on the same line if they are different.
y<n?s[y*n*3]=10,s[y*n*3+x+1]=92-45*q:(x=0), //if y is within the grid, put a newline (ASCII 10)at the beginning of the row and write \ or / (ASCII 92 or 47) to the correct square. Otherwise abort the x loop.
r=q; //store the current bit of i to r as it will be needed on the next iteration
n-1-y||puts(s); //if y is on the bottom row of the grid, output the mountain
}
}
```
**Output** (note the massive amount of whitespace to the right)
```
$ ./a
4
/\
/ \/\/\
/\
/\/ \/\
/\/\
/ \/\
/\
/ \
/ \/\
/\
/\/\/ \
/\ /\
/ \/ \
/\/\
/\/ \
/\/\/\
/ \
/\
/ \/\
/ \
/\
/ \
/\/ \
/\
/\/ \
/ \
/\/\
/ \
/ \
/\
/ \
/ \
/ \
```
[Answer]
# Haskell, 140 bytes
After several attempts failed to be very golfable, I ended up with this Haskell implementation. I'm happy just to be within a factor of 2 of the APL solution!
**Golfed solution:**
```
e=' ':e
m=[[]]:[[('/':e):map(' ':)x++('\\':e):y|k<-[0..n],x<-m!!(n-k),y<-m!!k]|n<-[0..]]
f n=putStr$unlines[map(!!(n-k))a|a<-m!!n,k<-[1..n]]
```
**Ungolfed and commented:**
The program builds the set of *n*-step mountain diagrams recursively. Each diagram is represented by a list of infinitely-long strings, representing the mountain drawn sideways followed by spaces extending to infinity. This ensures that all diagrams have the same height, which makes the recursion easier. The mountain printer accepts a parameter which clips the height to a finite value.
```
import Data.List (transpose)
-- Elementary picture slices, extending to infinity.
empty = ' ' : empty
up = '/' : empty
down = '\\': empty
-- A function which draws a mountain picture to stdout, clipping
-- its height to n.
printMtn n = putStr . unlines . reverse . take n . transpose
{-- Combine mountain pictures x and y by
x
x # y == / \y
--}
x # y = up : raised x ++ down : y
where raised = map (' ':)
-- Given two sets X,Y of mountain pictures, compute the set X <> Y of all
-- combined pictures x#y for x in X, y in Y.
xs <> ys = [ x # y | x <- xs, y <- ys ]
-- Compute the (++,<>)-convolution of a list with itself, e.g.:
-- autoConvolve [x0,x1,x2] == (x2 <> x0) ++ (x1 <> x1) ++ (x0 <> x2)
autoConvolve xs = concat $ zipWith (<>) (reverse xs) xs
{--
mtns is a list whose nth entry is the list of all n-step mountain diagrams.
It is defined recursively by:
-- The only 0-step mountain diagram is empty.
-- Each (n+1)-step diagram can be uniquely drawn as x#y for
some k-step diagram x and (n-k)-step diagram y.
--}
mtns = [[]] : [autoConvolve (prefix n) | n <- [1..]]
where prefix n = take n mtns
-- The driver function: apply the height n mountain printer to each
-- n-step mountain diagram. Whitespace is guaranteed by the order
-- in which the diagrams appear.
test n = mapM_ (printMtn n) $ mtns!!n
```
**Sample usage:**
```
$ ghci mtn3.hs
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main ( mtn3.hs, interpreted )
Ok, modules loaded: Main.
λ> f 3
/\
/ \
/ \
/\/\
/ \
/\
/ \/\
/\
/\/ \
/\/\/\
λ>
```
[Answer]
# GolfScript 103 ([demo](http://golfscript.apphb.com/?c=OzMKCjIqOsKnMlw%2FLHsyYmFzZS4swqdcLVswXSpcKzphIDFcey4yKkAoLkArQEArfSU6bCQpXDspLC0xJXthLCx7Lmw9MiQ9XGE9MSQrKicgXFwvJz0gfSVcO24rfSVcMT0qbCQoXDswPip9Lw%3D%3D&run=true))
```
2*:§2\?,{2base.,§\-[0]*\+:a 1\{.2*@(.@+@@+}%:l$)\;),-1%{a,,{.l=2$=\a=1$+*' \\/'= }%\;n+}%\1=*l$(\;0>*}/
```
The program takes an integer parameter tries to render as mountains all binary representations of the numbers from 0 to 2^(n-1). It does not render invalid combinations (ex: the ones that go below level 0).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 54 bytes
```
mȯ¶↔T' §zoFz:,mömR' ∫Ẋo±+:_1†o!"/¦">0uf(Λ≥0∫)†?I←IPṘḋ2
```
[Try it online!](https://tio.run/##AVsApP9odXNr//9tyK/CtuKGlFQnIMKnem9GejosbcO2bVInIOKIq@G6im/CsSs6XzHigKBvISIvwqYiPjB1ZijOm@KJpTDiiKsp4oCgP0nihpBJUOG5mOG4izL///80 "Husk – Try It Online")
Does surprisingly well in this challenge.
## Explanation
`ḋ2` array [0,1]
`Ṙ` repeat each \$n\$ times : `3 → [1,1,1,0,0,0]`
`†?I←I` decrement the zeroes
`f(Λ≥0∫)` filter out the non-ranges using cumulative sum
`u` uniquify
`§zoFz:,` apply the following two functions a & b to the above result and zip them together
`mömR' ∫Ẋo±+:_1` Function a: convert unequal pairs to 0's and create the required amount of spaces
`†o!"/¦">0` Function b: convert 1 to / and -1 to \
These are now joined to create the mountains.
`↔T'` Transpose each mountain, filling with spaces then reverse
`mȯ¶` join with newlines
Each mountain is then auto-displayed with newlines.
] |
[Question]
[
# The Challenge
Create an **terminating** expression in [SKI Combinator Calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) in less than 200 combinators (S, K, I) that reduces to the expression with the most combinators.
There will be no limit on how many parenthesis/applications can be used.
# SKI
SKI expressions are created using S, K, I and parenthesis. They are reduced like so:
```
(((Sx)y)z) => ((xz)(yz))
((Kx)y) => x
(Ix) => x
```
When parenthesis with more than two expressions are in an expression, they are assumed to be nested to the left.
```
(xyz) = ((xy)z)
```
# Scoring
The score will be the number of combinators in the output, the goal is for this to be as large as possible.
# Examples
Here is an example of a reduction in SKI using the rules stated above.
```
(((SI)I)(((SI)I)S))
((I(((SI)I)S))(I(((SI)I)S)))
((((SI)I)S)(I(((SI)I)S)))
(((IS)(IS))(I(((SI)I)S)))
((S(IS))(I(((SI)I)S)))
((SS)(I(((SI)I)S)))
((SS)(((SI)I)S))
((SS)((IS)(IS)))
((SS)(S(IS)))
((SS)(SS))
```
So the expression `(((SI)I)(((SI)I)S))` scores 4.
[Answer]
# 44 combinators, score: \$\approx f\_{\omega+1}(3\uparrow\uparrow\uparrow\uparrow3)\$
```
(S (S (K S) (S S K)) (K I)) arrow_diag (S (S (K S) K) (S (S (K S) K) I)) S K
where arrow_diag = S (S (S I (K (S (S (K S) (S (K (S I)) K)) (K I)))) (S (K (S I)) K)) I
```
This reduces to an expression of `S (S (S (...(S K)...)))` which contains `n` copies of `S`, where `n` is the value obtained by repeatedly applying `arrow_diag` function (a 1-input function that diagonalizes over the Knuth's up arrow notation, explained below) `arrow_diag 3` times to the number 3.
**Edit:** Fixed the `arrow_diag` function, and changed 2 to 3 because I found `arrow_diag 2` was just 4. Though I guess `arrow_diag (arrow_diag (arrow_diag (arrow_diag 2)))` would still be insanely large.
The first idea is that we will construct a Church numeral for a very large natural number `n`, which is `\f. \x. f (f (f ... f x))` (`f` applied `n` times to `x`), and then force it by applying `S` and `K` to it. Then the normal form would be `S (S (... S K))` which has exactly `n+1` combinators.
Now, let's find a way to build large numbers. A good start point is the deceptively short power function
```
-- x^y
exp x y = y x
exp = \x. \y. y x
```
Then we can repeat the partially applied `exp` to build tetration and beyond (corresponding to \$x\uparrow\uparrow y\$, \$x\uparrow\uparrow\uparrow y\$ and so on):
```
-- x^^y = x^(x^...(x^x))
tet x y = y (x^) 1
tet = \x. \y. y (\y. y x) 1
-- x^^^y = x^^(x^^...)
quad x y = y (x^^) 1
quad = \x. \y. y (\y. y (\y. y x) 1) 1
-- in general:
arrow<N> = \x. \y. y (arrow<N-1> x) 1
```
Then we can try converting these into SKI. Since the next arrow notation involves a partially applied previous one, just partially converting gives helpful insights.
```
exp = \x. \y. y x
= \x. S I (K x)
tet = \x. \y. y (\y. y x) 1
= \x. \y. y (S I (K x)) I
= \x. S (\y. y (S I (K x))) (K I)
= \x. S (S I (K (S I (K x)))) (K I)
quad = \x. \y. y (\y. y (\y. y x) 1) 1
= \x. \y. y (S (S I (K (S I (K x)))) (K I)) I
= ...
```
Here we can spot a pattern. Here comes the beauty of pure lambda calculus: we can extract arbitrary subexpression into a lambda. Meanwhile, we can change 1 to `y` to get a higher number and save 1 combinator.
```
\x. \y. y (someexpr) 1
= \x. S (S I (K someexpr)) (K I)
= \x. (\e. S (S I (K e)) (K I)) someexpr
\x. \y. y (someexpr) y
= \x. S (S I (K someexpr)) I
= \x. (\e. S (S I (K e)) I) someexpr
tet' = \x. 1 (\e. S (S I (K e)) I) (S I (K x))
arrow<n> = \x. n (\e. S (S I (K e)) I) (S I (K x))
```
Here `arrow<n> x y` (roughly) calculates \$x \uparrow^{n+1} y\$.
Now we diagonalize over the arrow notation, by using `x`, the input value, instead of `n`.
```
arrow_diag2 = \x. x (\e. S (S I (K e)) I) (S I (K x))
= S (S I (K (S (S (K S) (S (K (S I)) K)) (K I)))) (S (K (S I)) K)
```
But it is still a binary function that calculates (roughly) \$x \uparrow^{x+1} y\$, so let's make it unary:
```
arrow_diag = \x. arrow_diag2 x x
= S arrow_diag2 I
= S (S (S I (K (S (S (K S) (S (K (S I)) K)) (K I)))) (S (K (S I)) K)) I
```
This has just **22** combinators. To get a non-trivial number (don't forget, we're also adding `S K` at the end to get a deterministic combinator count), we evaluate
```
arrow_diag 3 arrow_diag 3 S K
= (\x y. x y x y) arrow_diag 3 S K
= (S (S (K S) (S S K)) (K I)) arrow_diag (S (S (K S) K) (S (S (K S) K) I)) S K
```
which has just **44** combinators but evaluates to an... extremely large number that I don't know how to express correctly.
] |
[Question]
[
Write a program or function that estimates the Shannon entropy of a given string.
If a string has *n* characters, *d* **distinct** characters, *xi* is the *i* th distinct character, and *P(xi)* is the probability of that character occuring in the string, then our Shannon entropy estimate for that string is given by:
[](https://i.stack.imgur.com/nLEj2.png)
For the estimation in this challenge we assume that the probability of a character occurring in a string is simply the number of times it occurs divided by the total number of characters.
Your answer must be accurate to at least 3 digits after the period.
---
Test cases:
```
"This is a test.", 45.094
"00001111", 8.000
"cwmfjordbankglyphsvextquiz", 122.211
" ", 0.0
```
[Answer]
## Python 3.3+, 64 bytes
```
import math
lambda s:sum(math.log2(len(s)/s.count(c))for c in s)
```
Got `math.log2` from [mbomb007's solution](https://codegolf.stackexchange.com/a/78544/20260).
[Answer]
# Jelly, ~~11~~ 8 bytes
```
ċЀ÷Ll.S
```
[Try it online!](http://jelly.tryitonline.net/#code=xIvDkOKCrMO3TGwuUw&input=&args=IlRoaXMgaXMgYSB0ZXN0LiI)
[Answer]
# APL, ~~18~~ 14 bytes
```
+/2⍟≢÷(+/∘.=⍨)
```
This is an unnamed, monadic function train that accepts a string on the right and returns a real.
Like all good things in life, this uses [xnor's formula](https://codegolf.stackexchange.com/a/78552/20469). We get a matrix of booleans corresponding to the occurrences of each character in the string using `∘.=⍨`, sum this along the first axis (`+/`) to get the number of occurrences of each character, divide the length of the string by each, then take log base 2 (`2⍟`) and sum.
[Try it here](http://tryapl.org/?a=f%u2190+/2%u235F%u2262%F7%28+/%u2218.%3D%u2368%29%20%u22C4%20f%20%27This%20is%20a%20test.%27%20%u22C4%20f%20%2700001111%27%20%u22C4%20f%20%27cwmfjordbankglyphsvextquiz%27%20%u22C4%20f%20%27%20%20%20%20%20%20%20%20%20%20%20%20%20%27&run)
Saved 4 bytes thanks to Dennis!
[Answer]
# MATL, 17 bytes
```
S4#Y'ts/tZl*sGn_*
```
[Try it online!](http://matl.tryitonline.net/#code=UzQjWSd0cy90Wmwqc0duXyo&input=J1RoaXMgaXMgYSB0ZXN0Lic)
[Answer]
## JavaScript (ES6), 67 bytes
```
s=>[...s].map(c=>t+=Math.log2(s.length/~-s.split(c).length),t=0)&&t
```
I need to use `~-s.split` because that accepts strings rather than regexps. As usual, `map` beats `reduce` by a byte.
```
s=>[...s].reduce((t,c)=>t+Math.log2(s.length/~-s.split(c).length),0)
```
[Answer]
# Perl 5, 58 bytes
A subroutine:
```
{for$a(@a=split'',pop){$t+=(log@a/grep/\Q$a/,@a)/log 2}$t}
```
A tip of my hat to [xnor](/a/78552) for the formula.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
!Gu=stGn/Zl*s|
```
[**Try it online!**](http://matl.tryitonline.net/#code=IUd1PXN0R24vWmwqc3w&input=J2N3bWZqb3JkYmFua2dseXBoc3ZleHRxdWl6Jw)
```
! % transpose implicit input into column vector
Gu % row vector with unique elements of input
= % test for equality, element-wise with broadcast
s % sum of each column
tGn/ % duplicate. Divide by number of input characters
Zl % binary logarithm
* % element-wise multiplication
s % sum of array
| % absolute value. Display implicitly
```
[Answer]
# Julia, 37 bytes
```
x->sum(log2(endof(x)./sum(x.==x',1)))
```
Takes a character array as input. [Try it online!](http://julia.tryitonline.net/#code=ZiA9IHgtPnN1bShsb2cyKGVuZG9mKHgpLi9zdW0oeC49PXgnLDEpKSkKCmZvciB4IGluICgiVGhpcyBpcyBhIHRlc3QuIiwgIjAwMDAxMTExIiwgImN3bWZqb3JkYmFua2dseXBoc3ZleHRxdWl6IiwgIiAgICAgICAgICAgICAiKQogICAgcHJpbnRsbihmKFt4Li4uXSkpCmVuZA&input=)
[Answer]
# J - ~~18~~ ~~16~~ 14 bytes
```
1#.2^.#%1#.=/~
```
Shortened using the idea in Dennis' method.
## Usage
```
f =: 1#.2^.#%1#.=/~
f 'This is a test.'
45.0936
f '00001111'
8
f 'cwmfjordbankglyphsvextquiz'
122.211
f ' '
0
```
## Explanation
```
1#.2^.#%1#.=/~ Input: string S
=/~ Create a table testing for equality
1#. Convert each row from a list of base 1 digits to decimal
This is equivalent to taking the sum and forms a list of tallies
# Get the length of S
% Divide the length by each tally
2^. Log base 2 of each
1#. "Sum" those values and return
```
[Answer]
# Pyth - 17 bytes
```
*_lQsm*FlBc/QdlQ{
```
[Try it online here](http://pyth.herokuapp.com/?code=%2a_lQsm%2aFlBc%2FQdlQ%7B&test_suite=1&test_suite_input=%22This+is+a+test.%22%0A%2200001111%22%0A%22cwmfjordbankglyphsvextquiz%22%0A%22+++++++++++++%22&debug=0).
[Answer]
# Jolf, 26 bytes
```
_*liuΜGμiEd*γ/l miLeHlimzγ
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=XypsaXXOnEfOvGlFZCrOsy9sIG1pTGVIbGltes6z&input=VGhpcyBpcyBhIHRlc3QuCgowMDAwMTExMQoKY3dtZmpvcmRiYW5rZ2x5cGhzdmV4dHF1aXoKCiAgICAgICAgICAgICA) (Note that the test suite function is borked.)
## Explanation
```
_*liuΜGμiEd*γ/l miLeHlimzγ
μi unique members of i
G E split on ""
Μ d map over function
_miLeH match i with regex escaped member
/l li divide length of (^) by length of i
γ γ = (^)
* mzγ (^) * log_2(γ)
*li (^) * length of i
_ negate
```
[Answer]
# Python 3.3+, ~~95~~ ~~91~~ ~~89~~ 85 bytes
Simple solution. Version 3.3 is required to use `math.log2`.
```
import math
def f(s):C=s.count;return-sum(C(x)*math.log2(C(x)/len(s))for x in set(s))
```
[**Try it online**](http://ideone.com/E4NnyF)
[Answer]
# Java 7, 207 bytes
```
double C(String x,Map<Character,Integer>f){double H=0,g;for(char c:x.toCharArray())f.put(c,f.containsKey(c)?f.get(c)+1:1);for(char c:f.keySet()){g=f.get(c);H+=g*Math.log(g/x.length())/Math.log(2);}return-H;}
```
**Detailed** [try online](http://ideone.com/QyQzLK)
```
double log2(double d) { return Math.log(d) / Math.log(2); }
double C(String x, Map<Character,Integer>f)
{
double H=0,g;
// frequency
for(char c : x.toCharArray())
{
f.put(c, f.containsKey(c) ? f.get(c)+1 : 1);
}
// calculate entropy
for(char c : f.keySet())
{
g = f.get(c);
H += g * log2(g / x.length());
}
return -H;
}
```
[Answer]
# Factor, 98 bytes
```
[ [ length ] [ dup [ [ = ] curry dupd count ] { } map-as nip ] bi [ / log 2 log / ] with map sum ]
```
This is a direct translation of [this Python answer](https://codegolf.stackexchange.com/a/78552/46231). I'll add an explanation over dinner.
[Answer]
# Racket, 130 bytes
:c
```
#lang racket
(require math)(λ(S)(let([s(string->list S)])(sum(map(λ(c)(/(log(/(length s)(count(λ(x)(char=? c x))s)))(log 2)))s))))
```
Translation of my Factor answer, so it's an indirect translation of Kenny Lau's Python answer.
[Answer]
# k (32 bytes)
```
{-+/c*(log c%n:+/c:#:'=x)%log 2}
```
Or in `q`, the translation is not all that short but clearer:
```
{neg sum c*2 xlog c%n:sum c:count each group x}
```
[Answer]
# Mathematica, 45 bytes
```
Tr[Log[2,Tr@#/#]#]&@Values@CharacterCounts@#&
```
## Usage
This returns exact results so we approximate them with `N`.
```
f = Tr[Log[2,Tr@#/#]#]&@Values@CharacterCounts@#&
f["This is a test."]//N
45.0936
f["00001111"]//N
8.
f["cwmfjordbankglyphsvextquiz"]//N
122.211
f[" "]//N
0.
```
[Answer]
# R, 67 bytes
```
l=length(i<-strsplit(readline(),"")[[1]]);-sum(log2(l/table(i)[i]))
```
### Explanation
Take input from stdin and split it into a list of characters. (This clunky syntax is why string golf challenges are so tough in R...)
```
i<-strsplit(readline(),"")[[1]])
```
This assignment is hidden inside of a `length` command, so we get two assignments for the price of one. We have `i`, the list of characters, and `l`, its length.
```
l=length(i<-strsplit(readline(),"")[[1]]);
```
Now we calculate the entropy. R has a nice function `table` which returns the counts of all unique values. For input `This is a test`, `table(i)` returns
```
> table(i)
i
. a e h i s t T
3 1 1 1 1 2 3 2 1
```
This is indexed by characters, which is nice, as we can then use `i` as an index to get the count of each character, like so:
```
> table(i)[i]
i
T h i s i s a t e s t .
1 1 2 3 3 2 3 3 1 3 2 1 3 2 1
```
The rest of the code is then a simple implementation of the entropy formula, flipped around a little.
```
-sum(log2(l/table(i)[i]))
```
[Answer]
# C#, 159 bytes
Golfed:
```
string f(string s){var l=s.Length;double sum=0;foreach(var item in s.GroupBy(o=>o)){double p=(double)item.Count()/l;sum+=p*Math.Log(p,2);}return(sum*=-l)+"";}}
```
Ungolfed:
```
string f(string s)
{
var l = s.Length;
double sum = 0;
foreach (var item in s.GroupBy(o => o))
{
double p = (double)item.Count() / l;
sum += p * Math.Log(p, 2);
}
return (sum *= -l) + "";
}
```
Test:
```
var codeGolf = new StringHistogramEntropyEstimation();
Console.WriteLine(codeGolf.f("This is a test.")); //45.0935839298008
Console.WriteLine(codeGolf.f("00001111")); //8
Console.WriteLine(codeGolf.f("cwmfjordbankglyphsvextquiz")); //122.211432671668
Console.WriteLine(codeGolf.f(" ")); //0
```
[Answer]
# Groovy, 100 Bytes
```
{a->n=a.size();a.toList().unique().collect{p=a.count(it)/n;p*(Math.log(p)/Math.log(2.0f))}.sum()*-n}
```
## Tests:
```
This is a test. = 45.09358393449714
00001111 = 8.0
cwmfjordbankglyphsvextquiz = 122.21143275636976
aaaaaaaa = -0.0
```
] |
[Question]
[
Take a look at the sevens multiplication table from 7×0 to 7×9:
```
0, 7, 14, 21, 28, 35, 42, 49, 56, 63
```
If we just look at the digits in the one's place we get a permutation of the digits 0 through 9:
```
0, 7, 4, 1, 8, 5, 2, 9, 6, 3
```
Consider taking some positive decimal integer N and replacing each digit D in N with the the digit in the one's place of 7×D.
For example, `15209` becomes `75403` because `1` maps to `7`, `5` maps to `5`, `2` maps to `4`, `0` maps to `0`, and `9` maps to `3`.
Now lets repeat this process with this new decimal integer until we see a cycle, i.e. until an integer we've already seen comes up.
For example, with `15209` we get the cycle
```
15209 -> 75403 -> 95801 -> 35607 -> 15209 -> repeats...
^
|
cycle restarts here
```
As another example, `505` has the short cycle
```
505 -> 505 -> repeats...
^
|
cycle restarts here
```
It turns out that for any N these cycles will always contain exactly 1 or 4 distinct integers. (I'll leave it to you to figure out why that is.) What's interesting is that if you sum all the distinct integer in a cycle, you almost always get a decimal integer that only consists of `2`'s and `0`'s.
For example, 15209 + 75403 + 95801 + 35607 = 222020.
N = 505 is one of the exceptions. The only integer in the cycle is 505 so the total sum is 505 itself.
Here are the sums of the cycles for N = 1 to 60:
```
N sum
1 20
2 20
3 20
4 20
5 5
6 20
7 20
8 20
9 20
10 200
11 220
12 220
13 220
14 220
15 220
16 220
17 220
18 220
19 220
20 200
21 220
22 220
23 220
24 220
25 220
26 220
27 220
28 220
29 220
30 200
31 220
32 220
33 220
34 220
35 220
36 220
37 220
38 220
39 220
40 200
41 220
42 220
43 220
44 220
45 220
46 220
47 220
48 220
49 220
50 50
51 220
52 220
53 220
54 220
55 55
56 220
57 220
58 220
59 220
60 200
```
We'll call this the Seven's Cycle Sum Sequence.
# Challenge
Write a program or function that takes in a positive decimal integer N and prints or returns, in decimal, the corresponding term of the Seven's Cycle Sum Sequence.
For example, if the input is `95801`, the output should be `222020`. If the input is `505`, the output should be `505`. If the input is `54`, the output should be `220`.
The shortest code in bytes wins.
[Answer]
## Python 2, 69 bytes
```
lambda n:[''.join('02'[x>'0']for x in`n`)+'0',n][set(`n`)<=set('05')]
```
The function is simple to describe:
* If n consists of only 0's and 5's, output it unchanged.
* Otherwise, replace each digit of n with 2, except 0 stays 0, and tack on a 0 to the end.
The golfing can be improved, I'm mostly posting to share the method. A language with native regex should allow a short solution.
An alternative statement of the function is
* In n, replace each digit with a 5, except 0 stays as 0
* If this changed n (it had a digit other than 0 or 5), multiply the result by 4
[Answer]
# Python 2, 63 bytes
```
lambda s:s.strip('05')and''.join(`(c>'0')*2`for c in s)+'0'or s
```
Input argument is expected to be a string.
[Answer]
## CJam, 16 bytes
Using the same algorithm as everyone else:
```
r_50s-{:~2fe&0}&
```
[Test suite.](http://cjam.aditsu.net/#code=q~%7B)s%3AQ%3B%0A%0AQ_50s-%7B%3A~2fe%260%7D%26%0A%0A%5DoNo%7D%2F&input=500) (Generates all results from 1 to the input.)
### Explanation
```
r_ e# Read input and duplicate
50s e# Push the string "50".
- e# Remove all '5' and '0' characters from the input.
{ e# If any characters remained in the input...
:~ e# Evaluate each digit character to turn it into an integer.
2fe& e# Map (&& 2) over the list. Due to short-circuiting, zeros remain zeros and
e# everything else becomes 2.
0 e# Push a trailing zero.
}&
```
[Answer]
# JavaScript (ES6), ~~54~~ 51 bytes
Using [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s method:
```
n=>/[^05]/.test(n)?`${n}0`.replace(/./g,d=>+d&&2):n
```
*Saved 3 bytes thanks to [@charlie](https://codegolf.stackexchange.com/users/47940/charlie)!*
## Explanation
```
n=>
(s=n+"").match`[^05]` // if there are any digits which aren't 5 or 0
?s.replace(/\d/g,d=>+d&&2)+0 // replace every digit except 0 with 2 then add a 0
:s // else return the input unchanged
```
## Test
```
<input type="number" id="input" value="0" oninput='result.textContent=(
n=>(s=n+"").match`[^05]`?s.replace(/\d/g,d=>+d&&2)+0:s
)(+input.value)' />
<pre id="result"></pre>
```
## Naive method, 102 bytes
```
n=>(c=x=>~r.indexOf(x+=m="")?eval(r.join`+`):[...r[++i]=x].map(d=>m+="0741852963"[d])&&c(m))(n,i=r=[])
```
```
n=>
(c=x=> // c = recursive function
~r.indexOf( // if we have calculated this number before
x+=m="")? // cast x to a string, m = calculated result
eval(r.join`+`): // return the sum of all the calculated numbers
[...r[++i]=x].map(d=> // else add x to the list of calculated numbers
m+="0741852963"[d] // map each digit of x to the "seven" digits
)&&c(m) // calculate the value of the result
)(n,i=r=[]) // r = array of previously calculated values
```
```
<input type="number" id="input" value="0" oninput='result.textContent=(
n=>(c=x=>~r.indexOf(x+=m="")?eval(r.join`+`):[...r[++i]=x].map(d=>m+="0741852963"[d])&&c(m))(n,i=r=[])
)(+input.value)' />
<pre id="result"></pre>
```
[Answer]
## Mathematica, ~~83~~ ~~77~~ 60 characters
```
Tr@Union@NestList[FromDigits@Mod[7IntegerDigits@#,10]&,#,4]&
```
**Ungolfed**
```
Tr@
Union@
NestList[
FromDigits@Mod[7 IntegerDigits@#, 10] &,
#,
4
] &
```
[Answer]
# JavaScript (ES5), 40 bytes
```
n=>(s=`${n}`.replace(/[^0]/g,5))^n?s*4:n
```
It's an evolution of the [user81655](https://codegolf.stackexchange.com/a/65901/47940)'s solution, using the alternative approach described by [xnor](https://codegolf.stackexchange.com/a/65898/47940).
### Explanation
Sum of a non-zero digit in the 4-cycle is always 20, since the digit cycles either through 1→7→9→3, or 2→4→8→6, or 5→5→5→5. So replacing every such a digit with 5 doesn't change the sum.
That replacement action is reused to distinguish the 4-cycle from 1-cycle — if the replacement result is different from the input, then it's a 4-cycle, otherwise it's a 1-cycle.
*N.B.: The template string ``${n}`` is just for readability, `(n+'')` has the same length.*
[Answer]
# Pyth, 14 bytes
```
s.uieM*R7jNTTQ
```
Not sure, why everybody determines the result by looking at patterns in the numbers. Simply doing the process, calculating all numbers of the circle and summing them up is shorter. At least in Pyth ;-)
Try it online: [Demonstration](http://pyth.herokuapp.com/?input=15209&code=s.uieM%2AR7jNTTQ&test_suite_input=1%0A2%0A3%0A4%0A5%0A10%0A11%0A12%0A505%0A506&test_suite=0) or [Test Suite](http://pyth.herokuapp.com/?input=15209&code=s.uieM%2AR7jNTTQ&test_suite_input=1%0A2%0A3%0A4%0A5%0A10%0A11%0A12%0A505%0A506&test_suite=1)
Btw, this is my 200th code-golf answer. So this post earns me the Gold code-golf badge.
### Explanation:
```
s.uieM*R7jNTTQ implicit: Q = input number
.u Q apply the following expression to N=Q until it reaches a circle
jNT convert N to base 10
*R7 multiply each digit with 7
eM and perform modulo 10 for each number
i T convert digits from base 10 to a number
update N
.u returns the list of all intermediate results of N,
so we have now all numbers of the circle
s sum them up
```
[Answer]
# sed, 26 bytes
`/[^05]/{s/[^0]/2/g;s/$/0/}`
*(Another take on the "replace by 2's" approach.)*
### Examples
`echo '500' | sed '/[^05]/{s/[^0]/2/g;s/$/0/}'` → `500`
`echo '501' | sed '/[^05]/{s/[^0]/2/g;s/$/0/}'` → `2020`
[Answer]
# [Perl 6](http://perl6.org), ~~68 55 53 36~~ 33 bytes
```
{[+] $^a,{[~] $^b.comb.map: {'0741852963'.comb[$_]}}...^{$++*?/$a/}} # 68
```
```
{$_=@=$_.comb;[~] (@$_,(|.map(2*?+*),0))[$_⊈qw<0 5>]} # 55
```
```
{[~] ($_=@=$_.comb)⊆qw<0 5>??@$_!!(|.map(2*?+*),0)} # 53
```
```
{/^<[05]>+$/??$_!!S:g/./{2*?+$/}/~0} # 36
```
```
{m/^<[05]>+$/||S:g/./{2*?+$/}/~0} # 33
```
This is definitely the wrong way to do this, if the number is consists only of `5`s and `0`s it will return a Match object, otherwise it replaces everything but `0` with a `2`, and append a `0` to the end.
( The Match object will behave like a number if you use it as one )
Though since it is doing it wrong, it makes it easy to point out the rare numbers by calling the `gist` method.
usage:
```
# give it a name
my &code = {...}
.say for (0..60,505,15209).flat.map({ code($_).gist.fmt: '%4s' }).rotor(1,10 xx 6,:partial)
( 「0」)
( 20 20 20 20 「5」 20 20 20 20 200)
( 220 220 220 220 220 220 220 220 220 200)
( 220 220 220 220 220 220 220 220 220 200)
( 220 220 220 220 220 220 220 220 220 200)
( 220 220 220 220 220 220 220 220 220 「50」)
( 220 220 220 220 「55」 220 220 220 220 200)
(「505」)
(222020)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
D×7%⁵ƊƬḌS
```
[Try it online!](https://tio.run/##ATAAz/9qZWxsef//RMOXNyXigbXGisas4biMU/8xNTIwOSw1MDU7NjBSwqQ7w4ck4oKsR/8 "Jelly – Try It Online")
## How it works
```
D×7%⁵ƊƬḌS - Main link. Takes an integer n on the left
D - Convert to digits
ƊƬ - Repeat the following until a value is repeated and collect all intermediate values:
×7 - Multiply each digit by 7
%⁵ - Take the ones digit
Ḍ - Convert each list of digits back to a number
S - Take the sum
```
] |
[Question]
[
Consider this nested array
`[[1,2,4],[1,2,3],[2,3]]`
In each subarray in which 1 appears, a 2 appears. You might say that 1's presence is dependent on 2's presence.
The converse is not true, as 2 appears in a subarray without 1.
Additionally, 3 is dependent on 2, and 4 is dependent on 1 and 2.
## Task
Given a list of lists of positive integers (in whatever I/O form is most convenient for you) remove only the integers which are dependent on integers larger than themselves. In other words, for every integer A that is dependent on an integer B, and B>A, remove A.
## You may assume:
Positive integers only
Input will not be nested further than one level, as in the example above
No integer will appear more than once in a given subarray
Subarrays will be sorted (increasing or decreasing, whichever is more convenient as long as you state in your answer)
No empty arrays anywhere in input
## Examples:
```
in: [[1,2,4],[1,2,3],[2,3]]
out: [[2,4],[2,3],[2,3]]
in: [[3,4],[5,6]]
out: [[4],[6]]
in: [[1,2,3],[1,2,3,4],[2,3,4]]
out: [[3],[3,4],[3,4]]
in: [[1]]
out: [[1]]
in: [[2,12],[2,13],[2,14]]
out: [[2,12],[2,13],[2,14]]
```
Shortest code wins :)
[Answer]
# [Python](https://www.python.org), ~~104~~ 93 bytes
```
lambda i:[[x for x in a if~-any(x<c>0<all(c in d for d in i if x in d)for c in a)]for a in i]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY5NCsIwEEb3nmKWCaRgWhWR6kViFrEhGKhpKRHajRdxUxDFK3kb81eUrubNfG-Yub_awZ4bMz7U_vi8WpVtP7wWl5MUoHeM9aCaDnrQBtxA3TJhBtSX1WFZirpGlQ9kcKRH7ZxoS-yHIReYexZB4OnIu-20sUghxiiBnMCKE0hYeAyVY7z4iUWy1gQ2s-hvMWFyJ5zps95ZNE86nc7TsBX_HcdYvw)
Stupid naïve iterative solution which I'm really not happy with. A recursive solution will be shorter.
-11 bytes thanks to a hint from xnor.
```
for a in z for b in a for c in b for d in c for e in d for f in e for g in f for h in g for i in h for j in i for k in j for l in j for m in l for n in m for o in n for p in o for q in p for r in q for s in r for t in s for u in t for v in u for w in v for x in w for y in x for z in y please kill me why is python's syntax so whitespace and keyword heavy
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
IEθΦι⬤ι∨¬›νλ⊙θ‹№πν№πλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQR8EtM6cktUgjU0fBMScHRPkXafjll2i4F6UmgiTydBRyNDWBsnmVIOU@qcXFGs75pUBTCnQU8oAScA5QGRRY//8fHR1tqGOkYxyrA6F1TIAsCB0b@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over subarrays
ι Current subarray
Φ Filtered where
ι Current subarray
⬤ All elements satisfy
ν Innermost element
¬› Not greater than
λ Inner element
∨ Logical Or
θ Input array
⊙ Any subarray satisfies
№ Count of
ν Innermost element
π In innermost subarray
‹ Is less than
№ Count of
λ Inner element
π In innermost subarray
I Cast to string
Implicitly print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ċƇf/>Ƈ⁹ȧ
çⱮFḟ@Ɱ
```
A monadic Link accepting a list of lists of strictly positive integers that yields a list of lists of strictly positive integers.
**[Try it online!](https://tio.run/##y0rNyan8//9I97H2NH27Y@2PGneeWM51ePmjjevcHu6Y7wCk/x9uf9S05uikhztnAOnI//@jo6MNdYx0TGJ1wLQxkAaRsVw60dHGYGFTHTMIFyYPpsFSEBoiCaGMdAyNwBKGEJMMQdKxAA "Jelly – Try It Online")** (The footer calls the Link for each and formats the output)
### How?
```
ċƇf/>Ƈ⁹ȧ - Helper Link: list of lists, A; integer, I
Ƈ - filter keep those lists in A for which:
ċ - count occurrences of I - truthy if the list contains I
/ - reduce this list of lists that contain I by:
f - filter keep
- gets us a list of those values appearing in all of them
⁹ - use I as the right argument of:
Ƈ - filter keep those for which:
> - greater than I?
ȧ - logical AND I (non-vectorising)
- i.e. I if it is a consistently dependent smaller integer, else 0
çⱮFḟ@Ɱ - Link: list of lists, A
F - flatten A
Ɱ - map across each integer I in that with:
ç - call the Helper Link as a dyad - f(A, I)
Ɱ - map across each list in A with:
@ - with swapped arguments:
ḟ - filter discard
```
[Answer]
# [R](https://www.r-project.org/), ~~167~~ ~~163~~ ~~159~~ ~~157~~ 147 bytes
Or **[R](https://www.r-project.org/)>= 4.1, 126 bytes** by replacing three `function` occurrences with `\`s.
*Edit: -2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) and -10 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(x,b=combn(c(0,sort(unique(unlist(x)))),2))lapply(x,setdiff,b[1,apply(b,2,function(y,`+`=function(k)sapply(x,match,x=y[k],0))all(!+1|+2))])
```
[Try it online!](https://tio.run/##bU9BboMwELz3FTSnXbGHrElySMRLCFLAjRUUx6TBSCD179TGqS@uD7Nja2fG81pUuajRSNv1BiZqS9k/WgMStjT0Lwuj6b7Hqxu6GyxM6A4JRN08n3p2guFqvzqlqK2YwltLgqLjTJf8UsbrHYc/4aOx8kZTOVf3mraIjdbwmfNP7txrXBSsgRLY2e2QAik88QMxO2WysbDpR3vMqsot1eSweGN9NmezwY/oUwSXPR1SsZceUklMXEnQB5I4@Nhi/YLH1ClVcLoliEXI4HdR3v3XlMVakkNXjnnLLw "R – Try It Online")
That turned out long...
Straightforward approach:
1. Create all pairs of values from input list (leading zeros to fix issues with 1-length inputs). `unique` and `sort` take care of the "first element is smaller" requirement.
2. Define a helper function `+` to look for a value in nested list.
3. Which pairs are dependent? (Uses \$\lnot p \lor q\$ for implication.) Extract first elements from them.
4. `setdiff` those from all sublists.
[Answer]
# Haskell, ~~80~~ 70 bytes
```
f l=filter(\n->all(\m->m<=n||any((&&).elem n<*>all(/=m))l)$l>>=id)<$>l
```
[Try it Online!](https://tio.run/##NYxBDsIgEEWvMgvSgKEaWnUFXISyIJFG4kCa2o1J745IcfNfZt7Pf7r3yyPmPAOqOeDmVzqlXjtEOsVeR6nSvrv0obTr2Nmjj5DkqfqLiowhI6i1Cg8micYcXUigYFlD2oBAdAvMYIwRfOBXyyvHwl9a4EWN9X/j93b/G5XVHWy2ceBiqEoca6IUbP4C)
-10 bytes thanks to Wheat Wizard
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εʒδåÏ.«Ãy›O_
```
[Try it online](https://tio.run/##yy9OTMpM/f//3NZTk85tObz0cL/eodWHmysfNezyj///PzraUMdIxyRWB0wbA2kQGQsA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f9zW09NOrfl8NLD/XqHVh9urnzUsMs//n9trQ4XSB1XeUZmTqpCUWpiikJmHldKPpeCgn5@QYk@xDgohWaDjYIKWG1e6v/oaEMdIx2TWB0wbQykQWQsV3S0MVjUVMcMzIPJgmmwDIQGy4FJIx1DI7CwIcQUQ5AkAA).
**Explanation:**
```
ε # Map over each inner list of the (implicit) input list of lists:
ʒ # Filter this inner list by:
δ # Map over each list of the (implicit) input list of lists:
å # Check if it contains the current integer
Ï # Only keep those lists from the (implicit) input list of lists
.« # Reduce the remaining list of lists by:
à # Keep the values which are present in both lists
y› # Then check which remaining values are larger than the current integer
O # Sum to get the amount of values for which this is truthy
_ # Check if this sum is 0
# (after which the modified list of lists is output implicitly as result)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes
```
#/.Table[#⋂##&@@#~Select~MemberQ@ii||i->Set@$,{i,Max@#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfLyQxKSc1WvlRd5OyspqDg3JdcGpOanJJnW9qblJqUaBD5vsJ2zNrajJ17YJTSxxUdKozdXwTKxyUa2PV/geWZgLFAooy80qilXXt0hyUY9XqgpMT8@qquaqrDXWMdExqdcC0MZAGkbU6QAljsLCpjhmEC5MH02ApCA2RhFBGOoZGYAlDiEmGYGmwPBYLoIIwIa7a/wA "Wolfram Language (Mathematica) – Try It Online")
The private-use character is [`\[VectorLessEqual]`](https://reference.wolfram.com/language/ref/VectorLessEqual.html).
```
Table[ ,{i,Max@#}] for positive i up to the max
#/. i->Set@$ remove i if
#⋂##&@@ intersection of
#~Select~MemberQ@i lists containing i
i|| not all <=i
```
[Answer]
# JavaScript (ES6), 79 bytes
Expects an array of sets.
```
a=>a.map(([...b])=>b.filter(p=>!b.some(q=>q>p&a.every(b=>b.has(q)|!b.has(p)))))
```
[Try it online!](https://tio.run/##bZA9bsMwDIV3n0JZChpQGchpsxTS1hNkNDxQrtwkcCz5BwkK9O6uRSVtA4SDKPB970ngkc401sMhTM@d/3Bzo2fShvBEAaBERFvl2lhsDu3kBgjarCyO/uSg16Y34YnQnd3wBTZSexqhz79X6RbyWPNbmQlRlkoW8qWS3DdLj2clBdd6vQBJ/ieybcPTV7n9hf@KbVHeXuFbNvdb3NKjleEoJoHHyfQg@e4FdQULqQqOVOmLakm4Ax8BWZVh44d3qvdAQhtR@270rcPWf0IDadM2Cp27iJ2bwKa1/QA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 85 bytes
```
->l{l.map{|a|a-l.flatten.select{|x|l.select{|c|c&[x]!=[]}.reduce(&:&).any?{|y|y>x}}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkcvN7GguiaxJlE3Ry8tJ7GkJDVPrzg1JzW5pLqmoiYHzk6uSVaLrohVtI2OrdUrSk0pTU7VULNS09RLzKu0r66prKm0q6gFgv8FCmnR0dGGOkY6JrE6YNoYSIPI2FguiKQxWMpUxwwo9B8A "Ruby – Try It Online")
] |
[Question]
[
Jimmy has had a busy last week with all [these](https://codegolf.stackexchange.com/questions/187586/will-jimmy-fall-off-his-platform) [platforms](https://codegolf.stackexchange.com/questions/187682/how-many-jimmys-can-fit) [and](https://codegolf.stackexchange.com/questions/187731/jimmy-needs-your-help) [ropes](https://codegolf.stackexchange.com/questions/187759/can-jimmy-hang-on-his-rope), and poor Jimmy doesn't even have legs or feet to stand on!
---
Your job is to take a string containing multiple Jimmys and give them legs and shoes!
Get input in the form of a Jimmy String
Jimmy String => `/o\ /o\ /o\`
containing only `/o\` and
give each Jimmy in the input a pair of feet that look like this:
```
/o\
_/ \_
```
Turn the inputed floating head Jimmy string into Jimmy with feet string, like so:
```
// Input
/o\ /o\ /o\
// Output
/o\ /o\ /o\
_/ \_ _/ \_ _/ \_
```
If 2 Jimmys are close together they must move over to make room,
Jimmys will always move towards the right to make room for other Jimmys.
```
// Input
/o\/o\
// Output
/o\ /o\
_/ \__/ \_
```
Other Jimmys that are further away must not be moved unless necessary
```
// Input
/o\/o\ /o\
// Output
/o\ /o\ /o\
_/ \__/ \_ _/ \_
// Input
/o\/o\ /o\
// Output
/o\ /o\ /o\
_/ \__/ \__/ \_
```
Standard rules and loopholes apply,
This is code-golf, so may the shortest answer win.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~131~~ ~~120~~ ~~115~~ ~~114~~ ~~121~~ 118 bytes
```
o=1;W=[]
for g in map(len,input().split('/o\\')):W+=[' '*(g-o)];o=max(o-g,0)+2
for q in' /o\ ','_/ \_':print q.join(W)
```
[Try it online!](https://tio.run/##hU@xTsMwEJ3rrziJ4WyaptAxVcaysiBlaKoqhCNxm/pcxxHt1wcnRQRY8PD8dO/uvTt79TWbVV/yG6UOEXtOH9dZut2Jd3ZQgTZwKqxsyETa2M5LFbe20V7ikvMclUqyebpFwHtZLVjt1pyeiovkRRU9qPlqdDkHF4TQDxjhfgn5HhPrtPFwjg@sjcxUH6LFR60bghfXUSJm3l0DzuhCJQzbiUBLsh42z08b59gN6quj4ijEHRy61oPnsOuRoO0cga8JmiJU2RDoNng4R6WP41iM2TcEhNsbrpm@H0Xsx0tHKr7pJAv8Gprwb99v6d/ATw "Python 2 – Try It Online")
4 bytes thx to [movatica](https://codegolf.stackexchange.com/users/86751/movatica); 10 bytes lost for bug fix.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
F⌕Aθ/«J∧ι⊖ι¹WKK→P_/ \_M↗/o\
```
[Try it online!](https://tio.run/##PY5BC8IwDIXP268IPaUwGV71NBAPwmCI3gpjbNGVdW0t3TyIv712Uww5vJd8j6TtG9eaRoVQOak9MmB8n96MAzxK3RVK4SMDljPO4ZUmp2m0F4OF7lBmcKDW0UjaU7ScZ7CN2eTZS0WAFdGAMVWamXB3lvfeL9tyUl7a7606ByFqto5X6mr/3O@d3AixAO8QoowNa0WRhs2sPg "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
```
Print a space to defeat Charcoal's automatic left margin.
```
F⌕Aθ/«
```
Loop over all of the left arms.
```
J∧ι⊖ι¹
```
Jump to the desired left foot location. Note that Charcoal has no problem drawing at `(-1, 1)`, but the question does not allow that, so we have to take care to avoid drawing at negative positions.
```
WKK→
```
Move past any existing output.
```
P_/ \_M↗/o\
```
Output the feet and then move to output the Jimmy.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, ~~77~~ 75 bytes
The "don't move Jimmy if not needed" rule was quite an ordeal to work around but I think it worked out quite well. Shorter than Python by quite a bit (at time of writing), at least.
-2 bytes from recursive.
```
r=/(\\ ?|^)(\S+) ?/
gsub(r){"#$1 #$2"}while~r
puts$_
gsub(/ .o. ?/,'_/ \_')
```
[Try it online!](https://tio.run/##KypNqvz/v8hWXyMmRsG@Jk5TIyZYW1PBXp8rvbg0SaNIs1pJWcVQQVnFSKm2PCMzJ7WuiKugtKRYJR6iQF9BL18PqFxHPV5fISZeXfP/f/38GAhSgAIg819@QUlmfl7xf90CAA "Ruby – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 96 bytes
```
($o=$args-split'/o.'|%{' '*($w=($l+=$_.Length-1)*($l-gt0));$l-=$w+1})-join' /o\ '
$o-join'_/ \_'
```
[Try it online!](https://tio.run/##jZFBasMwEEX3c4pBTCqpseJmHQQ5QI8QMKVVHQdhubaCC47P7qpWGrsQl2oxSH/@fyOYyrWmbo7G2oHeUWM3CHKaXuq8UU1lC89Tt@GXVceRPwpqtSC71pRtnk2Z@6PayqBalfsnKXfhoqldb3upTq4oOabugBzIxWeW4iHjQw@wFwCJAAyHYTzf1p86SSyBf7gw2Gaucc614kxiIKexIfaLPzLnrDGylLvzwRtgCYN/wRZQ90kTSOIFV9iNBirK6uwTJPNZmVdv3sI6KYut2jRn64PwELYcjRF67TBlPtgtyOYh6Icv "PowerShell – Try It Online")
Unrolled:
```
$o=$args-split'/o.'|%{
$len += $_.Length-1
$width = $len*($len-gt0) # len or 0, if len < 0
' '*$width
$len -= $width+1
}
# $o is array of space strings now
$o-join' /o\ '
$o-join'_/ \_'
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~152~~ ~~148~~ 140 bytes
```
o=[-4]
for i,c in enumerate(input()):o+=[max(i,o[-1]+5)]*('/'==c)
for s in' /o\ ','_/ \_':print''.join('%*s'%(b-a,s)for a,b in zip(o,o[1:]))
```
[Try it online!](https://tio.run/##bY7dCoMwDIXv@xRFkLRaJw53I/RJVES7jnVgI/6A28t31rGNwXKRhBO@kzPc5yvao1N41jIIAoeyTPKaXHCkRihqLNV26fXYzpoZOywz47zAWJZ9uzIjsEyyOj7xOmKQgpSK7@i0gUBTrCgIaFJaNVAMo7EzwOGGxjIIowlC1iWtmLgnWtH5Zw8zMNxcs6Lm3O0I2WIRoletqE8Z5Q7oq7z/u3@lCghs42f7c/wITw "Python 2 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~40~~ 37 bytes
```
\+`(^|\S.)(/\S*) ?
$1 $2
/o. ?
_/ \_
```
[Try it online!](https://tio.run/##K0otycxLNPz/P0Y7QSOuJiZYT1NDPyZYS1PBnkvFUEHFiEtBP18PyInXV4iJ//9fPz8GiBTAAMgAAA "Retina – Try It Online")
Thanks to Value Ink for golfing off 3 bytes.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~29~~ ~~28~~ ~~24~~ 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¢▄▌ß╙EVäN»0►,δñï◙,Θ╙BÅhΓ?
```
[Run and debug it](https://staxlang.xyz/#p=9bdcdde1d34556844eaf30102ceba48b0a2ce9d3428f68e23f&i=%2Fo%5C%2Fo%5C%0A%2Fo%5C%2Fo%5C++++++%2Fo%5C%0A%2Fo%5C%2Fo%5C++++%2Fo%5C&a=1&m=2)
There was a bug in the 24 byte solution that caused some off-by-1 errors in some cases.
[Answer]
# JavaScript (ES6), 107 bytes
```
s=>` /o\\
_/ \\_`.replace(/.*/g,j=>s.split(/.o./).map(s=>s.slice(n,l=s.length,n=n>l?n-l+2:2),n=1).join(j))
```
[Try it online!](https://tio.run/##fY@xbsMwDER3fwU3ibUttUGnAHLnTvkBAYngKq4NhhJCJb/v2knRdCjKhbh3B@I4hWuQ/jzm0nL6iPPRzeK6A9jkPVR7C97vD@YcM4U@amue7NBMrhMjmcaygGQsmlPIWm6UxiXGDTkxFHkonw077uiNW6o32w0u8gXNlEbWE@JcohRwIOA66BNLomgoDVq9c76UrWcF9eLWoDx73l3Kgx614N1YlWrV2jKGol@fEatqvawV3Of2zc/6BRV@B1fxJ/gn@zDmLw "JavaScript (Node.js) – Try It Online")
[Answer]
# MATLAB, 111 bytes
[Try it online](https://tio.run/##lU/baoQwEH33K@Yx6eri5KKrIV9StrDY2AbcWKztQ3/eziTPCy1yJnPmXMB12m/f4TjmrzTtcU2Q/CTuskp@28JMm1v8Z/wJItUo3bxuED2OSxU8nu3pbJ9Eg/IljmpcXBKhHqUvz2kLH/fbLpKIxOolpLf9XQTJNSG9ZhyTeFZgoIOLgxYUwThAWiyYq6xIZqIdeSxYR8YHAkcbLMpfGvnAdX1BsWQUkwba6QBIBTSpTRnQCL3i2bWAA@fhwiIMNC30jqnJR0UODbr7T12bw9jRn5ACjRoeFiKZ@WsUx7DA5RMTdZXHLw)
```
function J(s)
s=[' ' s];s=replace(s,{'\/','\ /'},'\ /');for k=find(s=='o')
o(k-2:k+2)='_/ \_';end
char(s,o)
```
] |
[Question]
[
Write a program or function that takes in a nonempty list of integers in any reasonable convenient format such as `4, 0, -1, -6, 2` or `[4 0 -1 -6 2]`.
Print or return a string that depicts the list as an ASCII art forest where each number becomes a tree of proportional height. Each tree takes up four columns of text in the output as follows:
* A positive integer N becomes a tree whose base is `__|_` and top is `^` , with N layers of `/ \` in between.
For example, when N = 1 the tree is
```
^
/ \
__|_
```
when N = 2 the tree is
```
^
/ \
/ \
__|_
```
when N = 3 the tree is
```
^
/ \
/ \
/ \
__|_
```
and so on.
* A negative integer N becomes just like the corresponding positive tree except a vertical bar is between the branch slashes instead of a space.
For example, when N = -1 the tree is
```
^
/|\
__|_
```
when N = -2 the tree is
```
^
/|\
/|\
__|_
```
when N = -3 the tree is
```
^
/|\
/|\
/|\
__|_
```
and so on.
* When the integer is 0 there is technically no tree, just an empty space of four underscores:
```
____
```
The underscores at the base of each tree must line up in the output, i.e. all the trees must have their bases at the same level. Also, a single underscore is added to the end of the line of underscores after the last tree. This makes it so every tree has an empty column of "air" on either side of it.
As an example, the output for `4 0 -1 -6 2` would be
```
^
/|\
^ /|\
/ \ /|\
/ \ /|\ ^
/ \ ^ /|\ / \
/ \ /|\ /|\ / \
__|_______|___|___|__
```
Note how the tree patterns always have a leading column of empty space but an underscore had to be added to pad the right side of the last tree.
Also:
* Trailing spaces on any lines are fine, but there should be no unnecessary leading spaces.
* Leading newlines are not allowed (the tallest tree should touch the top of the output text grid) and only up to one trailing newline is allowed.
* The list may contain any integers from -250 to 250 inclusive. Handling taller trees is not required.
**The shortest code in bytes wins.**
# More Examples
`3`:
```
^
/ \
/ \
/ \
__|__
```
`-2`:
```
^
/|\
/|\
__|__
```
`0`:
```
_____
```
`0, 0`:
```
_________
```
`0, 1, 0`:
```
^
/ \
______|______
```
`0, -1, 2, -3, 4`:
```
^
^ / \
^ /|\ / \
^ / \ /|\ / \
/|\ / \ /|\ / \
______|___|___|___|__
```
[Answer]
# Python 2, 165 bytes
```
a=input()
l=max(map(abs,a))
while l+2:s=' _'[l<0];print(s+s.join((([' ^ ','//| \\\\'[x>0::2],' '][cmp(abs(x),l)],'_|_')[l<0],s*3)[x==0]for x in a)+s).rstrip();l-=1
```
This is a full program that accepts a list as input. I'm still golfing this horrid mess.
[Answer]
# Pyth, 48 bytes
```
j_.t+sm.i,J\_?d++\|sm?>d0\ \|d\^Jms+Jmkd"/\\"QJd
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=j_.t%2Bsm.i%2CJ%5C_%3Fd%2B%2B%5C%7Csm%3F%3Ed0%5C%20%5C%7Cd%5C%5EJms%2BJmkd%22/%5C%5C%22QJd&test_suite=0&input=4%2C%200%2C%20-1%2C%20-6%2C%202&test_suite_input=3%2C%0A-2%2C%20%0A0%2C%20%0A0%2C%200%0A0%2C%201%2C%200%0A0%2C%20-1%2C%202%2C%20-3%2C%204) or [Test Suite](http://pyth.herokuapp.com/?code=j_.t%2Bsm.i%2CJ%5C_%3Fd%2B%2B%5C%7Csm%3F%3Ed0%5C%20%5C%7Cd%5C%5EJms%2BJmkd%22/%5C%5C%22QJd&test_suite=1&input=4%2C%200%2C%20-1%2C%20-6%2C%202&test_suite_input=3%2C%0A-2%2C%20%0A0%2C%20%0A0%2C%200%0A0%2C%201%2C%200%0A0%2C%20-1%2C%202%2C%20-3%2C%204)
Too lazy for a full explanation. Here just short overview:
I generate the columns first. So the image:
```
^
^ /|\
/ \ /|\
__|___|__
```
gets generated as:
```
["_", "_/", "| ^", "_\", "_", "_//", "|||^", "_\\", "_"]
```
Notice, that I'm generating only the lower part (everything without the spaces). And I'm also generating them from bottom to top. This is done pretty straightforward.
Then I can use the `.t` method to append spaces to the strings, so that each string has an equal length. And afterwards I reverse the order and print.
[Answer]
# PHP, 231 ~~277~~ bytes
This challenge has a beautiful output.
```
$x=fgetcsv(STDIN);for(;$i<2+max(array_map(abs,$x));$i++)for($j=0;$j<count($x);){$_=$x[$j++];$o[$i].=!$i?$_?'__|_':____:(abs($_)>=$i?0>$_?' /|\\':' / \\':($i-1&&abs($_)==$i-1?' ^ ':' '));}echo implode("
",array_reverse($o))."_";
```
Reads a comma separated list (whitespaces are optional) from `STDIN`:
```
$ php trees.php
> 1, 2, 0, -4, 6
```
**Ungolfed**
```
$x=fgetcsv(STDIN);
for(;$i<2+max(array_map(abs,$x));$i++)
for($j=0;$j<count($x);){
$_=$x[$j++];
$o[$i] .= !$i ? $_?'__|_':____
: (abs($_)>=$i ? 0>$_?' /|\\':' / \\'
: ($i-1&&abs($_)==$i-1 ? ' ^ ' : ' '));
}
echo implode("\n",array_reverse($o))."_";
```
**Edits**
* *Saved* **46 bytes**. Discarded array initialization, replaced `if/else` with ternary operators and moved some of the variables around to save a few bytes.
[Answer]
# Ruby, ~~157~~ ~~156~~ 153 characters
```
->h{r=[]
h.map{|i|j=i.abs
r+=[s=?_,?/*j+s,i==0?s:?^+(i>0?' ':?|)*j+?|,?\\*j+s].map{|l|l.rjust(h.map(&:abs).max+2).chars}}
r.transpose.map{|l|l*''}*$/+?_}
```
Written just because initially `Array.transpose` looked like a good idea. Not anymore.
Sample run:
```
2.1.5 :001 > puts ->h{r=[];h.map{|i|j=i.abs;r+=[s=?_,?/*j+s,i==0?s:?^+(i>0?' ':?|)*j+?|,?\\*j+s].map{|l|l.rjust(h.map(&:abs).max+2).chars}};r.transpose.map{|l|l*''}*$/+?_}[[4, 0, -1, -6, 2]]
^
/|\
^ /|\
/ \ /|\
/ \ /|\ ^
/ \ ^ /|\ / \
/ \ /|\ /|\ / \
__|_______|___|___|__
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 167 bytes
```
$h=(($r=($args|%{$a,$x=$_,-$_-ge0
'_';'_'+'/'*$a;'|_'[!$_]+(' ','|')[$_-lt0]*$a+'^'*!!$_
'_'+'\'*$a})+'_')|% Le*|sort)[-1]
$z=$r|% *ht $h;--$h..0|%{-join($z|% Ch* $_)}
```
[Try it online!](https://tio.run/##jZNRb9owEMff/Smu1NRxsEug1V5QJKS97hsAsaLWI5nShCWu1hbz2dnFIZAEJs2SFft@9z/77uJd8UeXVaKz7Eh/Qgj7I01Cz6Nl6NG43FZ2vKexoB8hVUJSJbc6IEyxBc4JmzKfxgtmFVvdUbWZeAyYYJbxFXpmJtggnrCI@XeIiZOsa8mBT3DD7Rh@aN9WRWn4Ss42hH6FtESrnxigyUJKmjw@BngF@atIc49@Ifue@EAVPxwPhCw9Iryl9ywgECBnOL8JmHMBCBj0RtR8mBiAqV13QPQPMIX1f4JoCKIG1PsecMYOUMqqZtjLZJwTl@LTOanuAbcXfaWcX0vtur/oK4KTwF3mYsUid8EQzi78dsXbxJsD20QHUeomzvHzJOD5Zh9Pka/66OrcVqJn7Ba/63kFWkO/K4OOnCvFwcIY9qRW4ksp408BVH/s9IvRr/iQ8Id3qNTVe2bQ8IDva@kc4R6qXRYbk@Zb5zQ6eY2k/j06Bxk5dt9GqNfwnr8Ub286N2CStIIszTWYAl7TOuAnNK4VORz/Ag "PowerShell – Try It Online")
Explanation:
1. Draw a rotated forest line by line
[](https://i.stack.imgur.com/QT1Lx.png)
2. Pad right and
3. Rotate -90.
Unrolled:
```
# a rotated forest with underscore after the last tree
$rotatedForest=$args|%{
$abs,$x=$_,-$_-ge0
'_'
'_'+'/'*$abs
'|_'[!$_]+(' ','|')[$_-lt0]*$abs+'^'*!!$_
'_'+'\'*$abs
}
$rotatedForest += '_'
# calc height
$height = ($rotatedForest|% Length|sort)[-1]
# PadRight all trees
$z = $rotatedForest|% PadRight $height
# Rotate -90
--$height..0|%{
-join($z|% Chars $_)
}
```
[Answer]
# C#, 318 bytes
I tried transposing the array. I'm not sure if that was the best solution.
```
string F(int[]a){int i=a.Length,j,w=i*4+1,h=0;string f="",o=f;for(;i-->0;){j=a[i];f+=","+" _,".PadLeft(j=j>0?j+3:-j+3,'\\')+(j>3?"^"+"|_,".PadLeft(j,a[i]<0?'|':' '):"_,")+" _,_".PadLeft(j+1,'/');h=h<j?j:h;}f="_".PadLeft(h=h>3?h:2,'\n')+f;for(i+=h<3?1:0;++i<h;)for(j=w;j-->0;)o+=f.Split(',')[j].PadLeft(h)[i];return o;}
```
Indentation and newlines for clarity:
```
string F(int[]a)
{
int i=a.Length,
j,
w=i*4+1,
h=0;
string f="",o=f;
for(;i-->0;){
j=a[i];
f+=","+" _,".PadLeft(j=j>0?j+3:-j+3,'\\')+(j>3?"^"+"|_,".PadLeft(j,a[i]<0?'|':' '):"_,")+" _,_".PadLeft(j+1,'/');
h=h<j?j:h;
}
f="_".PadLeft(h=h>3?h:2,'\n')+f;
for(i+=h<3?1:0;++i<h;)
for(j=w;j-->0;)
o+=f.Split(',')[j].PadLeft(h)[i];
return o;
}
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 41 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
H?¹⤢\ /*¹0<? /∙|/╋} v∔↕_|__¶∔↕]_4×}+}_;+↕
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXVGRjFGJUI5JXUyOTIyJTVDJTIwLyV1RkYwQSVCOSV1RkYxMCV1RkYxQyV1RkYxRiUyMC8ldTIyMTklN0MvJXUyNTRCJXVGRjVEJTIwdiV1MjIxNCV1MjE5NV8lN0NfXyVCNiV1MjIxNCV1MjE5NSV1RkYzRF8ldUZGMTQlRDcldUZGNUQldUZGMEIldUZGNURfJXVGRjFCJXVGRjBCJXUyMTk1,i=JTVCMCUyQyUyMC0xJTJDJTIwMiUyQyUyMC0zJTJDJTIwNCU1RA__,v=8)
] |
[Question]
[
# Recursive Binary Description
Recently, I made my very first contribution to OEIS by extending and adding a b-file to sequence [A049064](https://oeis.org/A049064). The sequence starts with `0`, and then the next values are derived from giving a "binary description" of the last item.
For example, the second term would be `10`, because there was one `0` in the first element. The third term would be `1110`, because there was one `1` and one `0`. The fourth would be `11110`. because there are three **(`11` in binary!)** `1`s and one `0`. Below is a breakdown of the fifth term to make this process clear:
```
> 11110
> 1111 0 (split into groups of each number)
> 4*1 1*0 (get count of each number in each group)
> 100*1 1*0 (convert counts to binary)
> 100110 (join each group back together)
```
And here's an example for going from the 6th to the 7th term:
```
> 1110010110
> 111 00 1 0 11 0
> 3*1 2*0 1*1 1*0 2*1 1*0
> 11*1 10*0 1*1 1*0 10*1 1*0
> 111100111010110
```
You can check out a reference programφ I made to calculate the terms.
# Your Job
You need to create a *program or function* which takes in a number `n` via *standard input or function arguments*, and prints out the sequence from the `1st` term to the `(n+1)th` term, separated by a newline. If you would like a look at the lower numbers, you may refer to the b-file from the OEIS page. However, your program/function should support `0 <= n <= 30`, i.e. up to the 31st term. This is no small feat, as `A049064(30)` is over 140,000 digits longδ. If you would like to see what the 31st term should be, I've put it on [Pastebin](http://pastebin.com/ZpqSVJvQ).
# Example I/O
```
func(10)
0
10
1110
11110
100110
1110010110
111100111010110
100110011110111010110
1110010110010011011110111010110
1111001110101100111001011010011011110111010110
1001100111101110101100111100111010110111001011010011011110111010110
func(0)
0
func(3)
0
10
1110
11110
```
There is only one rule: **No standard loopholes!**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte count wins.
---
φ - Gist can be found [here](https://gist.github.com/kade-robertson/d7e2c14975ef45063455), and an ideone demo is [here](http://ideone.com/zLFrFG).
δ - Just in case you were wondering, my estimates at the length of the 100th term put it at approximately 3.28x10250 characters long, which would be quite a lot for anyone to calculate.
[Answer]
# CJam, ~~18~~ 17 bytes
```
0{sN1$e`2af.b}ri*
```
*Thanks to @MartinBüttner for golfing off one byte!*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=0%7BsN1%24e%602af.b%7Dri*&input=10).
### How it works
```
0 e# Push 0.
{ }ri* e# Repeat int(input)) times:
s e# Stringify the element on top of the stack.
EXAMPLE: [[[1 1] '1] [[1] '0]] -> "11110"
N e# Push a linefeed.
1$ e# Copy the last stack.
e` e# Perform run-length encoding.
e# EXAMPLE: "100110" -> [[1 '1] [2 '0] [2 '1] [1 '0]]
2a e# Push [2].
f.b e# For each pair [x 'y], execute: [x 'y][2].b
e# This pushes [x2b 'y], where b is base conversion.
```
[Answer]
# Pyth, ~~18~~ 17 bytes
```
J]0VQjk~JsjR2srJ8
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=J]0VQjk~JsjR2srJ8&input=10&debug=0)
Thanks to @isaacg for saving one byte.
### Explanation:
```
implicit: Q = input number
]0 create an initial list [0]
J and store in J
VQ for loop, repeat Q times:
rJ8 run-length-encoding of J
s sum, unfolds lists
jR2 convert each value to base 2
s sum, unfolds lists
~J store the result in J
but return the old list,
jk join it and print it
```
This uses the fact, that 0 and 1 in binary are also 0 and 1.
[Answer]
# Python 2, ~~125~~ ~~116~~ 110 bytes
```
from itertools import*
v='0'
exec"print v;v=''.join(bin(len(list(g)))[2:]+k for k,g in groupby(v));"*-~input()
```
Saved 1 byte thanks to @Sp3000 and 5 bytes by removing a redundant `int` call.
Older version:
```
import itertools as t
v='0'
exec"print v;v=''.join(bin(int(len(list(g))))[2:]+k for k,g in t.groupby(v));"*-~input()
```
Saved many, many bytes thanks to @Vioz-!
Original version:
```
import itertools as t
v='0'
for n in range(input()+1):print v;v=''.join(bin(int(len(list(g))))[2:]+k for k,g in t.groupby(v))
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 37 bytes
```
{,/{(,/$2\#x),*x}'(&~~':x)_x}\[;,"0"]
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpHv1pDR1/FKEa5QlNHq6JWXUOtrk7dqkIzvqI2JtpaR8lAKfZ/mrqhgYKBgvF/AA "K (ngn/k) – Try It Online")
* `{...}\[;,"0"]` set up a scan, seeded with `,"0"` and run for a number of times equal to the (implicit) input
* `(&~~':x)_x` split into groups of the same characters
* `{...}'` for each group...
+ `(,/$2\#x)` get the binary representation of the count of each group
+ `(...),*x` append the first character of each group (i.e. whether it is a group of `0`s or of `1`s)
* `,/` flatten the results and feed to the next iteration of the scan
[Answer]
# Ruby, ~~80~~ ~~72~~ 69 bytes
As a function:
```
f=->m{l=?0;0.upto(m){puts l;l.gsub!(/1+|0+/){$&.size.to_s(2)+$&[0]}}}
```
Call it for example with: `f[6]`
[Answer]
# Python 2, 102 bytes
```
import re
o='0'
exec"print o;o=''.join(bin(len(x))[2:]+x[0]for x in re.findall('0+|1+',o));"*-~input()
```
Somehow the combination of `itertools` being longer than `re` and `groupby` returning `grouper` objects means that using regex is a bit shorter...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ŒrUBFƲСY
```
[Try it online!](https://tio.run/##y0rNyan8///opKJQJ7djmw5POLQw8v9/QwMA "Jelly – Try It Online")
Takes input from STDIN.
## Explanation
```
ŒrUBFƲСY Main niladic link
Implicitly start with 0
С Repeat [number from STDIN] times and collect all values
Ʋ (
Œr Run-length encode -> [[digit, repetitions], ...]
U Reverse each sublist -> [[repetitions, digit], ...]
B Convert all numbers to binary
F Flatten
Ʋ )
Y Join by newlines
The numbers are automatically concatenated
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes
```
µṄŒrUFV€BFṾ€ø¡
```
[Try it online!](https://tio.run/##y0rNyan8///Q1oc7W45OKgp1C3vUtMbJ7eHOfUD68I5DC///NwUA "Jelly – Try It Online")
~~I still feel like there's some better way to do the string printing.~~
-2 bytes from xigoi.
[Answer]
# Cobra - 128
```
do(i)=if(i-=1,(r=RegularExpressions).Regex.replace(f(i),'1+|0+',do(m=r.Match())=Convert.toString('[m]'.length,2)+'[m]'[:1]),'0')
```
[Answer]
# Haskell, ~~136~~ 130 Bytes
```
import Text.Printf
import Data.List
f n=putStr.unlines.take(n+1).iterate(concatMap(\n->(printf"%b"$length n)++[head n]).group)$"0"
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
î╩∩▬╒«ç╚¢↓}~
```
[Run and debug it](https://staxlang.xyz/#p=8ccaef16d5ae87c89b197d7e&i=10%0A0%0A3&m=2)
] |
[Question]
[
When working on [Non-Palindromic Polyglot Boggle](https://codegolf.stackexchange.com/q/51124/8478), I found it quite tedious to pack the codes as efficiently as possible onto the Boggle board, even with only two strings. But we're programmers, right? We know how to automate things.
Given a list of strings, you're to generate a Boggle board on which each of those strings can be found (independently of the others). The challenge is to make the Boggle board as small as possible. As this is (hopefully) a rather difficult task, this is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"): there is no requirement for optimality - the challenge is to do it as well as you can.
## Rules
* The Boggle board will be rectangular and contain only upper case letters. Therefore, the input strings will also contain only upper case letters.
* The usual Boggle rules apply: a string is part of the board if, starting anywhere, you can find the string by repeatedly moving to adjacent characters (horizontally, vertically, or diagonally). To form a single string, you cannot use any cell of the board more than once. However, characters *may* be reused between different strings.
* You've got 30 minutes to process the test data, and your code must not use more than 4 GB of memory. I will give a little bit of leeway on the memory limit, but if your program consistently uses more than 4 GB or spikes significantly above it, I will (temporarily) disqualify it.
* I will test all submissions on my own machine, which is running Windows 8. I do have a Ubuntu VM, but if I have to test on that you won't be able to make as much use of the 30 minutes as otherwise. Please include a link to a free interpreter/compiler for your chosen language, as well as instructions on how to compile/run your code.
* Your score will be the size of the Boggle board for the test data below (not counting the newlines). In the case of a tie (e.g. because multiple people managed to produce an optimal solution), the winner will be the submission that produces this optimal solution faster.
* You must not optimise your code specifically towards the test data. If I suspect anyone of doing so, I reserve the right to generate new test data.
## Example
Given the strings
```
FOO
BAR
BOOM
```
Once could trivially put them in a 4x3 Boggle board:
```
FOOX
BARX
BOOM
```
By making use of the fact that strings don't have to be straight, we can compress it to 5x2:
```
BORFO
OMABO
```
But we can make it even smaller by reusing characters between different strings, and fit the strings in 4x2:
```
FOOM
BARX
```
Now the `B` is used for both `BOOM` and `BAR`, and the `OO` is used for both `BOOM` and `FOO`.
## Test Data
Your submission will be tested on the following 50 strings. For testing purposes you can simply use smaller subsets of this data which should then run more quickly. I believe that the absolute lower bound for this test data is a board with 120 characters, although this is not necessarily achievable.
```
T
WP
GVI
CIHM
EGWIV
QUTYFZ
LWJVPNG
XJMJQWSW
JLPNHFDUW
SWMHBBZWUG
XVDBMDQWDEV
TIUGAVZVUECC
IWDICFWBPSPQR
MMNWFBGMEXMSPY
YIHYXGJXKOUOIZA
BZSANEJNJWWNUJLJ
XTRMGOVPHVZYLLKKG
FLXFVVHNTWLMRRQYFQ
VZKJRAFQIYSBSXORTSH
FNQDIGCPALCHVLHDNZAV
GEAZYFSBSWCETXFKMSWLG
KWIZCEHVBDHEBGDGCJHOID
SKMQPHJAPDQKKHGTIPJCLMH
ZSFQDNYHALSUVWESQVVEUIQC
HXHBESUFCCECHNSTQGDUZPQRB
DSLXVHMOMLUXVHCNOJCBBRPVYB
DVTXKAOYYYRBVAVPSUAOYHIPPWN
PJAIYAWHMTNHTQDZDERPZYQEMLBZ
SYNSHJNOIWESMKWTBIANYUAUNRZOS
WADGUKIHUUFVRVUIBFUXQIOLAWIXAU
LGLXUFIXBEPSOFCKIAHXSHVKZPCXVPI
LIUYFHITTUYKDVQOZPNGZLWOZSRJTCTZ
IZDFTFFPNEBIYGVNTZHINICBXBXLBNBAL
BSKQNTPVUAVBXZGHVZCOUCRGCYISGFGYAS
DPGYYCIKDGCETXQOZGEQQLFQWACMVDTRYAT
RQDNIPGUHRYDRVHIPJLOWKBXMIBFAWCJGFMC
PFKOAGEQLXCMISSVEARWAPVYMRDCLSLPJOMQQ
EQPCNHQPTWABPFBVBXHQTFYELPNMNCWVKDDKGR
RAHTJMGIQJOJVWJBIHVRLJYVCSQJCKMEZRGRJMU
SZBJBPQYVYKDHAJHZMHBEWQEAQQKIEYCFACNLJBC
ANVDUCVXBPIZVRAXEBFEJOHSYKEKBIJELPIWEYXKH
DJUNPRLTISBFMGBEQNXSNUSOGDJNKESVKGAAMTIVXK
TZPUHDSHZFEURBNZTFBKXCDPYRELIAFMUWDIQTYWXGU
FJIKJROQSFSZUCGOOFJIEHBZREEUUSZWOLYFPCYHUSMR
TPMHJEAWVAJOCSDOPMQMHKRESBQSTRBXESYGCDVKLFOVS
ABJCCDJYMYDCYPZSGPGIAIKZQBYTZFDWYUZQBOESDSDGOY
IIHKTVPJNJDBCBOHCIYOPBKOVVKGNAKBDKEEKYIPRPHZOMF
IABGEPCSPNSMLVJBSGLRYNFSSYIALHWWAINTAVZAGJRVMDPW
GFMFVEFYJQJASVRIBLULUEHPMZPEXJMHIEMGJRMBLQLBDGTWT
YPWHLCVHQAVKVGHMLSOMPRERNHVYBECGCUUWTXNQBBTCMVTOVA
```
## Verifier
You can use the following Stack Snippet to verify whether a Boggle board contains all strings in a given list. I ported the Boggle search code from [edc65's answer over here](https://codegolf.stackexchange.com/a/31752/8478). Let me know if anything seems buggy.
```
function verify() {
var strings = document.getElementById("strings").value;
var board = document.getElementById("board").value;
strings = strings.match(/[A-Z]+/g) || [];
board = board.split('\n');
var valid = true;
var len = board[0].length;
var result = 'Valid';
for (var i = 0; i < board.length; ++i)
{
if (board[i].length != len)
{
valid = false;
result = 'Invalid: Board not rectangular.';
}
if (/[^A-Z]/.test(board[i]))
{
valid = false;
result = 'Invalid: Board contains invalid character on line '+i+'.';
}
if (!valid) break;
}
if (valid)
for (i = 0; i < strings.length; ++i) {
if (!findInBoard(board, strings[i]))
{
valid = false;
result = 'Invalid: String "'+strings[i]+'"not found in board.';
break;
}
}
document.getElementById("output").innerHTML = result;
}
function findInBoard(b, w) {
var l = b[0].length;
var r = 0;
var Q = function(p, n) {
return (r |= !w[n]) ||
(
b[p] = 0,
[1,l,l+1,l+2,-1,-l,-l-1,-l-2].map( function(q) { return b[q+=p]==w[n] && Q(q,n+1) }),
b[p] = w[n-1]
);
}
b = (b+'').split('');
b.map(function(e, p) { return e==w[0] && Q(p,1) });
return r;
}
```
```
Strings that should be part of the Boggle board:
<br>
<textarea id="strings" cols="60" rows="10"></textarea>
<br>
Boggle board:
<br>
<textarea id="board" cols="60" rows="10"></textarea>
<br>
<input type="button" value="Verify" onclick="verify()" />
<br>
<br>
<div id="output"></div>
```
[Answer]
# C++11, score = 992 ~~1024~~
The algorithm is really stupid, but so far no one else made a serious one either, so I'll post it. It more or less randomly sticks words on a square board, and then starts over if it doesn't manage to make them fit. It kind of tries to maximize overlap with the existing words, but in a really inefficient way.
Edit: Improved score by adding 1 to a side length and trying a rectangle after failing 50 times. Also sorted input strings by size instead of randomizing the order.
```
#include <iostream>
#include <cstring>
#include <string>
#include <random>
#include <algorithm>
using namespace std;
struct grid {
char *g;
int h,w;
grid(int h, int w):h(h),w(w) {
g = new char[h*w];
memset(g,0,h*w*sizeof(*g));
}
grid(const grid &o) {
h=o.h, w=o.w;
g = new char[h*w];
memcpy(g,o.g,h*w*sizeof(*g));
}
grid(grid &&o) {
h=o.h, w=o.w;
g = o.g;
o.g = 0;
}
grid& operator=(const grid &o) {
h=o.h, w=o.w;
memcpy(g,o.g,h*w*sizeof(*g));
return*this;
}
grid& operator=(grid &&o) {
h=o.h, w=o.w;
g = o.g;
o.g = 0;
return*this;
}
char& operator()(int i, int j) {
return g[i*w+j];
}
~grid() { delete []g; }
};
typedef struct { int n, i, j; grid g; } ng;
const int qmax = 140;
const bool sizesort = true;
const int maxtries = 50;
inline int sq(int x){return x*x;}
bool operator<(const ng &a, const ng& b) {return a.n < b.n;}
void search(vector<string>& s) {
int tl = 0;
for(auto&x: s) tl += x.size();
int l = 0;
while(l*l < tl) l++;
vector<string*> v;
for(size_t i = 0; i < s.size(); i++) v.push_back(&s[i]);
struct{bool operator()(string*a,string*b){return a->size()>b->size();}} scmp;
if(sizesort) sort(v.begin(), v.end(), scmp);
mt19937 rng;
for(;;l--) {
int tries = 0;
int side2 = l;
retry:
tries++;
if(!sizesort) shuffle(v.begin(), v.end(), rng);
if(tries == maxtries) cout<<"rectangle",side2++;
grid g(l,side2);
for(string* x: v) {
string& z = *x;
vector<ng> p;
for(int i = 0; i < g.h; i++)
for(int j = 0; j < g.w; j++) {
if(g(i,j) && g(i,j) != z[0]) continue;
p.push_back({!g(i,j), i,j, g});
p.back().g(i,j) = z[0]|32;
}
for(size_t zi = 1; zi < z.size(); zi++) {
vector<ng> p2;
for(ng &gg: p) {
for(int i = max(gg.i-1,0); i <= min(gg.i+1,g.h-1); i++)
for(int j = max(gg.j-1,0); j <= min(gg.j+1,g.w-1); j++) {
if(!gg.g(i,j) || gg.g(i,j) == z[zi]) {
p2.push_back({gg.n+!g(i,j),i,j,gg.g});
p2.back().g(i,j) = z[zi]|32;
}
}
}
shuffle(p2.begin(), p2.end(), rng);
sort(p2.begin(), p2.end());
if(p2.size() > qmax) p2.erase(p2.begin() + qmax, p2.end());
p = move(p2);
}
if(p.empty()) goto retry;
g = p[0].g;
for(int i = 0; i < g.h; i++)
for(int j = 0; j < g.w; j++)
g(i,j) &= ~32;
}
cout<<g.w*g.h;
for(int i = 0; i < g.h; i++) {
cout<<'\n';
for(int j = 0; j < g.w; j++)
cout<<(g(i,j)?g(i,j):'X');
}
cout<<endl;
}
}
int main()
{
vector<string> v = {"T","WP","GVI","CIHM","EGWIV","QUTYFZ","LWJVPNG","XJMJQWSW","JLPNHFDUW","SWMHBBZWUG","XVDBMDQWDEV","TIUGAVZVUECC","IWDICFWBPSPQR","MMNWFBGMEXMSPY","YIHYXGJXKOUOIZA","BZSANEJNJWWNUJLJ","XTRMGOVPHVZYLLKKG","FLXFVVHNTWLMRRQYFQ","VZKJRAFQIYSBSXORTSH","FNQDIGCPALCHVLHDNZAV","GEAZYFSBSWCETXFKMSWLG","KWIZCEHVBDHEBGDGCJHOID","SKMQPHJAPDQKKHGTIPJCLMH","ZSFQDNYHALSUVWESQVVEUIQC","HXHBESUFCCECHNSTQGDUZPQRB","DSLXVHMOMLUXVHCNOJCBBRPVYB","DVTXKAOYYYRBVAVPSUAOYHIPPWN","PJAIYAWHMTNHTQDZDERPZYQEMLBZ","SYNSHJNOIWESMKWTBIANYUAUNRZOS","WADGUKIHUUFVRVUIBFUXQIOLAWIXAU","LGLXUFIXBEPSOFCKIAHXSHVKZPCXVPI","LIUYFHITTUYKDVQOZPNGZLWOZSRJTCTZ","IZDFTFFPNEBIYGVNTZHINICBXBXLBNBAL","BSKQNTPVUAVBXZGHVZCOUCRGCYISGFGYAS","DPGYYCIKDGCETXQOZGEQQLFQWACMVDTRYAT","RQDNIPGUHRYDRVHIPJLOWKBXMIBFAWCJGFMC","PFKOAGEQLXCMISSVEARWAPVYMRDCLSLPJOMQQ","EQPCNHQPTWABPFBVBXHQTFYELPNMNCWVKDDKGR","RAHTJMGIQJOJVWJBIHVRLJYVCSQJCKMEZRGRJMU","SZBJBPQYVYKDHAJHZMHBEWQEAQQKIEYCFACNLJBC","ANVDUCVXBPIZVRAXEBFEJOHSYKEKBIJELPIWEYXKH","DJUNPRLTISBFMGBEQNXSNUSOGDJNKESVKGAAMTIVXK","TZPUHDSHZFEURBNZTFBKXCDPYRELIAFMUWDIQTYWXGU","FJIKJROQSFSZUCGOOFJIEHBZREEUUSZWOLYFPCYHUSMR","TPMHJEAWVAJOCSDOPMQMHKRESBQSTRBXESYGCDVKLFOVS","ABJCCDJYMYDCYPZSGPGIAIKZQBYTZFDWYUZQBOESDSDGOY","IIHKTVPJNJDBCBOHCIYOPBKOVVKGNAKBDKEEKYIPRPHZOMF","IABGEPCSPNSMLVJBSGLRYNFSSYIALHWWAINTAVZAGJRVMDPW","GFMFVEFYJQJASVRIBLULUEHPMZPEXJMHIEMGJRMBLQLBDGTWT","YPWHLCVHQAVKVGHMLSOMPRERNHVYBECGCUUWTXNQBBTCMVTOVA"};
search(v);
return 0;
}
```
The board:
```
TGBHXEXMPYTECWBSFYOXKXKXFSQJXKXX
UZBWMLJKSXXPIXSVYYXATVDLVOCVCXMT
WWPSJGBUFWPOUHPAKRZMXIPCHHXJYEAX
SQPBNXFQNMLAYSQVBGAESYGWQJOVXJZY
RJXWJJDWMNSGFUQXSEAWXBMIJAYWLRTR
XMXFEIWIHTIHIGMOJTKVARJNPSVFJVDG
XJHNCGCCQXTYLSJHVNOJXHTSCKERBHMR
XVCLACEDGTCCDGLPMCJXXMQMQPVGIAJC
DLZSFPURZYUGRKENTWSDPVLSHBFFHBMA
HNBUQYZPDOKNMYDDVBBOGJBQGKSMLUWQ
XXZRSEBQNCQDPVFNKSSQNCDLXERPMSLF
XKVAIHMHTGZVUXPTQUSXXGEBRXEZHOUQ
XRJUXYNLQFJLHAVQPNNXTCXYMRJPKEQH
FAPIHATDBSWXWGBHCQHPBWUVNMJGKGVP
XQVVWMLJRZZOVRZXESFQTAUFHIMLLYZV
XIWXUSOQTXTLSEABVBIPXGXSYEAEMGOX
WEYQCBIUXCNSJKGRFZXTBXXSMFLIRYPQ
XGSBIPFLPAMIBEEMVEJLXDWDUBHTYXDX
XQSUXIZQGFOCPLKSUOAREVYQDWDVXCTA
XXVEBKXLEKCIOFYYHCBJPCTKIAWKIMZE
ORVEUGVIXYEWFPCCDJCNUDANHIBODFCI
XTOFPUSHKQXAZYDYIYOBJZVZBFMXLGOU
SZNSCXHLWQQSGCTQMBPDGAXXTRACJJXO
HRUAUKIAXEUOPGUIKWRJMNKKDGUWPBGK
ZVEYNGDNBUEOJIAZQORVGBDSEEOYIYXX
VMHCCAIBHRHFAESSBXVJKQOSKYFZHVPB
ALEVJPTWLMZJHXXFJYXIZUEFLIGUSRRB
GZCBDHPKMXXBXDSBTZJDUYVXNQPPHDYC
UIPJQKEQSBNICKYPNEFHWVHFDFRUZOJX
KWTGKXGBEOIJHNVQFBTLNTNMYXLTXNMX
DIOHJCXDGWHZTSGYIFJPMRRQOMXVHCFX
```
[Answer]
# Python 3, score = 1225
In this solution we use only 1 row. Starting from the empty string in every step we add the word which guarantees the largest possible overlap. (The words are checked in all 4 possible orientations.)
This gives a score of 1225 which is 50 lower than the score of 1275 for concatenating all the words together with no overlapping.
The result:
```
CBJLNCAFCYEIKQQAEQWEBHMZHJAHDKYVYQPBJBZSFQDNYHALSUVWESQVVEUIQCMFGJCWAFBIMXBKWOLJPIHVRDYRHUGPINDQRQPSPBWFCIDWIPVXCPZKVHSXHAIKCFOSPEBXIFUXLGLWSMKFXTECWSBSFYZAEGWIVGNPVJWLIUYFHITTUYKDVQOZPNGZLWOZSRJTCTZPUHDSHZFEURBNZTFBKXCDPYRELIAFMUWDIQTYWXGUWZBBHMWSKMQPHJAPDQKKHGTIPJCLMHICCEUVZVAGUITAYRTDVMCAWQFLQQEGZOQXTECGDKICYYGPDIOHJCGDGBEHDBVHECZIWKXVITMAAGKVSEKNJDGOSUNSXNQEBGMFBSITLRPNUJDSLXVHMOMLUXVHCNOJCBBRPVYBZSANEJNJWWNUJLJLPNHFDUWPDMVRJGAZVATNIAWWHLAIYSSFNYRLGSBJVLMSNPSCPEGBAIZDFTFFPNEBIYGVNTZHINICBXBXLBNBALQUTYFZBLMEQYZPREDZDQTHNTMHWAYIAJPFKOAGEQLXCMISSVEARWAPVYMRDCLSLPJOMQQFYQRRMLWTNHVVFXLFNQDIGCPALCHVLHDNZAVOTVMCTBBQNXTWUUCGCEBYVHNRERPMOSLMHGVKVAQHVCLHWPYPSMXEMGBFWNMMXJMJQWSWADGUKIHUUFVRVUIBFUXQIOLAWIXAUMJRGRZEMKCJQSCVYJLRVHIBJWVJOJQIGMJTHARGKDDKVWCNMNPLEYFTQHXBVBFPBAWTPQHNCPQEXVDBMDQWDEVZKJRAFQIYSBSXORTSHXHBESUFCCECHNSTQGDUZPQRBSKQNTPVUAVBXZGHVZCOUCRGCYISGFGYASYNSHJNOIWESMKWTBIANYUAUNRZOSVOFLKVDCGYSEXBRTSQBSERKHMQMPODSCOJAVWAEJHMPTWTGDBLQLBMRJGMEIHMJXEPZMPHEULULBIRVSAJQJYFEVFMFGKKLLYZVHPVOGMRTXYIHYXGJXKOUOIZANVDUCVXBPIZVRAXEBFEJOHSYKEKBIJELPIWEYXKHDVTXKAOYYYRBVAVPSUAOYHIPPWNFJIKJROQSFSZUCGOOFJIEHBZREEUUSZWOLYFPCYHUSMRABJCCDJYMYDCYPZSGPGIAIKZQBYTZFDWYUZQBOESDSDGOYIIHKTVPJNJDBCBOHCIYOPBKOVVKGNAKBDKEEKYIPRPHZOMF
```
The code:
```
import sys
def com_len(a,b):
for i in range(min(len(a),len(b)),-1,-1):
if (a[-i:] if i else '')==b[:i]:
return i
def try_s(a,b,sn,mv):
v=com_len(a,b)
if v>mv:
return a+b[v:],v
return sn,mv
ws=[w.rstrip() for w in sys.stdin.readlines()]
s=''
while ws:
mv=-1
sn=None
mi=None
for i in range(len(ws)):
mvo=mv
for a in [s,s[::-1]]:
for b in [ws[i],ws[i][::-1]]:
sn,mv=try_s(a,b,sn,mv)
if mvo<mv:
mi=i
s=sn
del ws[mi]
print(s)
```
[Answer]
# C, score 1154
```
AVOTVMCTBBQNXTWUUCGCEBYVHNRERPMOSLMHGVKVAQHVCLHWPYGOSUNSXNQEBGMFBSITLRPNUJDXJMHIEMGJRMBLQLBDGTWTWVJOJQIGMJTHARYPDCXKBFTZNBRUEFZHSDHUPZTCUZSFSQORJKIJFYNDQFSZOWLZGNPZOQVDKYUTTIHFYUILHWWAINTAVZAGJRVMDPWPQRBEAWVAJOCSDOPMQMHKRESBQSTRBXESYGCDVKLFOVSOYNUAUYNAIBTWKMSEWIONJHSNYSKYVYQPBJBZSOHCIYOPBKOVVKGNAKBDKEEKYIPRPHZOMFGJCWAFBIMXBKWOLJPIHVRDYRHUGPINDQRQPSPBWFCIDWIVPAWRAEVSSIMCXLQEGAOKFPFFTFDZIWLMRRQYFQSXORTSHLUXVHCNOJCBBRPVYBMKSNTPVUAVBXZGHVZCOUCRGCYISGFGYASOZGEQQLFQWACMVDTRYATIAJPVUECCYFSBSWCETXFKMSWLGFUUHIKUGDAWIYXCPZKVHSXHAIKCFOSPEBXIFUXLGLJNHFDUWSWQJMJXWSMXEMGBFWNMMGOVPHVZY
NDUCVXBPIZVRAEBFEJOHSYKEKBIJLPIWEYXKKXITMAGKSEKNJDFMFVEFYJQJASVRILULUEHMZPEUMRGRZKCJQSCVYJRVHIBJUGXWYTDWUFAILERMSUHYCPYLOWZSUERBEIJFOOGQIEVVQEWVUSLAHZTCTJRIABGEPCSNSMLJBSGLRYNFSSYAXHBESUFCCECHNSTQGUZTMHJABJCCDYMYDCYZSGPGIAIKZBYZFDWYUZQBOESDSDGZRCBJLNCAFCYEIQQAQEBHMZJAHDIIHKTVJNDCBNWPPHAUSPVABRYYYOAKXTVDWQDMBDVXCRGKDDKVWCNNPLEYFTQHXBBFPBAWTPQHCPEQMOJLSLCDRMYLABNBLXBXBCNIHZTNVYIBENLXVVHNTVZKJAFISBDLVHMOMCJPITGHKKQDPAJHPQBSQKWIZCEHDHEBDGCJHIDDPYYCKDCETXQZBLMYZPREDZDQTHNMHWYUGVZIWGAZUAXIWALOIQUBIUVRVAZIOUOXJXYHPVAZNDHLCLAPCGDQNBZANJNJWWNUJLPGPVJWLGUZBBHMYPHICQUTYZXTRVIXGKKLL
```
Use two lines so newly added words can reuse the letters from the top line.
```
char l[2][2000];
char s[2][2000];
char w[100][200];
int d[200];
void pri() {
puts(l[0]);
puts(l[1]);
}
void sav() { memcpy(s,l,sizeof(l)); }
void res() { memcpy(l,s,sizeof(l)); }
int fit(char *t, int l0, int l1) {
if (!*t) return 0;
if (l[0][l0] == *t && (l0 <= l1 || l[1][l1])) return 1+fit(t+1,l0+1,l1+(l1<l0));
if (l[1][l1] == *t && (l1 <= l0 || l[0][l0])) return 1+fit(t+1,l0+(l0<l1),l1+1);
if (!l[0][l0]) {
strcpy(l[0]+l0,t);
return 0;
}
if (!l[0][l1]) {
strcpy(l[0]+l1,t);
return 0;
}
if (!l[1][l1]) {
l[1][l1] = *t;
return fit(t+1,l0+(l0<l1),l1+1);
}
return 1000;
}
int main(){
int j,i,n,best,besti,bestk,c,tot = 0;
for (i = 0; scanf("%s ",w[i])>0; i+=2) {
int j = strlen(w[i]);
for (c = 0; c < j; c++) w[i+1][c] = w[i][j-c-1];
}
n = i;
pri();
for (j = 0; j < n/2; j++) {
int k = -1;
best = -1;
for (k = 0; k <= strlen(l[1]); k++) {
for (i = 0; i<n; i++) if (!d[i/2]) {
sav();
c = fit(w[i],k,k);
if (c < 1000 && c >= best) best = c, besti = i, bestk = k;
res();
}
}
fit(w[besti],bestk,bestk);
d[besti/2] = 1; tot += best;
}
pri();
printf("%d - %d\n",tot, strlen(l[0])+strlen(l[1]));
return 0;
}
```
[Answer]
# CJam, ~~1122~~ 1089 letters
```
qN%{,}$__W%Wf%+:A;s[,mQ)__2#_S*:B;+2/:P;:DX1$W*W]:M;1:L;{BQCelt:B;}:T;
{A,,{B:G;P:H;D:I;L:J;A=:Z{:C;PL+D-:QB=C=
{T}{QD+:QB=C={T}{BPCelt:B;PD+:PL+B=' ={MD#)M=:D;ML#)M=:L;}&}?}?}/BS-,Z,-G:B;H:P;I:D;J:L;}$
0=:KA={:C;PL+D-:QB=C={T}{QD+:QB=C=
{T}{BPCelt:B;PD+:PL+B=' ={MD#)M=:D;ML#)M=:L;}&}?}?}/Beu:B;AKWtK~WtW-:A}g
{PL+B=' -PD-L+B=' -e&}{BP'Zt:B;PD+:P;}w
BM0=/Sf-Oa-N*
```
The program constructs the rectangle from its center, spiraling outwards. This is a rather simple approach so far. There's still room for improvement.
The code is a big mess right now. I'll clean it up when I'm satisfied with my score.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%25%7B%2C%7D%24__W%25Wf%25%2B%3AA%3Bs%5B%2CmQ)__2%23_S*%3AB%3B%2B2%2F%3AP%3B%3ADX1%24W*W%5D%3AM%3B1%3AL%3B%7BBQCelt%3AB%3B%7D%3AT%3B%0A%7BA%2C%2C%7BB%3AG%3BP%3AH%3BD%3AI%3BL%3AJ%3BA%3D%3AZ%7B%3AC%3BPL%2BD-%3AQB%3DC%3D%0A%7BT%7D%7BQD%2B%3AQB%3DC%3D%7BT%7D%7BBPCelt%3AB%3BPD%2B%3APL%2BB%3D'%20%3D%7BMD%23)M%3D%3AD%3BML%23)M%3D%3AL%3B%7D%26%7D%3F%7D%3F%7D%2FBS-%2CZ%2C-G%3AB%3BH%3AP%3BI%3AD%3BJ%3AL%3B%7D%24%0A0%3D%3AKA%3D%7B%3AC%3BPL%2BD-%3AQB%3DC%3D%7BT%7D%7BQD%2B%3AQB%3DC%3D%0A%7BT%7D%7BBPCelt%3AB%3BPD%2B%3APL%2BB%3D'%20%3D%7BMD%23)M%3D%3AD%3BML%23)M%3D%3AL%3B%7D%26%7D%3F%7D%3F%7D%2FBeu%3AB%3BAKWtK~WtW-%3AA%7Dg%0A%7BPL%2BB%3D'%20-PD-L%2BB%3D'%20-e%26%7D%7BBP'Zt%3AB%3BPD%2B%3AP%3B%7Dw%0ABM0%3D%2FSf-Oa-N*&input=T%0AWP%0AGVI%0ACIHM%0AEGWIV%0AQUTYFZ%0ALWJVPNG%0AXJMJQWSW%0AJLPNHFDUW%0ASWMHBBZWUG%0AXVDBMDQWDEV%0ATIUGAVZVUECC%0AIWDICFWBPSPQR%0AMMNWFBGMEXMSPY%0AYIHYXGJXKOUOIZA%0ABZSANEJNJWWNUJLJ%0AXTRMGOVPHVZYLLKKG%0AFLXFVVHNTWLMRRQYFQ%0AVZKJRAFQIYSBSXORTSH%0AFNQDIGCPALCHVLHDNZAV%0AGEAZYFSBSWCETXFKMSWLG%0AKWIZCEHVBDHEBGDGCJHOID%0ASKMQPHJAPDQKKHGTIPJCLMH%0AZSFQDNYHALSUVWESQVVEUIQC%0AHXHBESUFCCECHNSTQGDUZPQRB%0ADSLXVHMOMLUXVHCNOJCBBRPVYB%0ADVTXKAOYYYRBVAVPSUAOYHIPPWN%0APJAIYAWHMTNHTQDZDERPZYQEMLBZ%0ASYNSHJNOIWESMKWTBIANYUAUNRZOS%0AWADGUKIHUUFVRVUIBFUXQIOLAWIXAU%0ALGLXUFIXBEPSOFCKIAHXSHVKZPCXVPI%0ALIUYFHITTUYKDVQOZPNGZLWOZSRJTCTZ%0AIZDFTFFPNEBIYGVNTZHINICBXBXLBNBAL%0ABSKQNTPVUAVBXZGHVZCOUCRGCYISGFGYAS%0ADPGYYCIKDGCETXQOZGEQQLFQWACMVDTRYAT%0ARQDNIPGUHRYDRVHIPJLOWKBXMIBFAWCJGFMC%0APFKOAGEQLXCMISSVEARWAPVYMRDCLSLPJOMQQ%0AEQPCNHQPTWABPFBVBXHQTFYELPNMNCWVKDDKGR%0ARAHTJMGIQJOJVWJBIHVRLJYVCSQJCKMEZRGRJMU%0ASZBJBPQYVYKDHAJHZMHBEWQEAQQKIEYCFACNLJBC%0AANVDUCVXBPIZVRAXEBFEJOHSYKEKBIJELPIWEYXKH%0ADJUNPRLTISBFMGBEQNXSNUSOGDJNKESVKGAAMTIVXK%0ATZPUHDSHZFEURBNZTFBKXCDPYRELIAFMUWDIQTYWXGU%0AFJIKJROQSFSZUCGOOFJIEHBZREEUUSZWOLYFPCYHUSMR%0ATPMHJEAWVAJOCSDOPMQMHKRESBQSTRBXESYGCDVKLFOVS%0AABJCCDJYMYDCYPZSGPGIAIKZQBYTZFDWYUZQBOESDSDGOY%0AIIHKTVPJNJDBCBOHCIYOPBKOVVKGNAKBDKEEKYIPRPHZOMF%0AIABGEPCSPNSMLVJBSGLRYNFSSYIALHWWAINTAVZAGJRVMDPW%0AGFMFVEFYJQJASVRIBLULUEHPMZPEXJMHIEMGJRMBLQLBDGTWT%0AYPWHLCVHQAVKVGHMLSOMPRERNHVYBECGCUUWTXNQBBTCMVTOVA).
### Board
```
GXVDBDQDEVGPVJWLWSWQJMJMHCFNQDIGC
UIWESMKWBIANYUANRZOLGLXUFIXBEPSOP
WOPZUDGQTSHCCCUSEBHSKMQHJADKKHGFA
ZNQDKVWCMNPLEYFTQHXBVBPBATPQHNTCL
BJRDOWLZNPZQVDKYUTTIHFYILWADGCIKH
BHBKZXZGHZCOUCGCIGFGYSUGXYQIUPJAV
MSNGSBSMLVJSGLRYNSSIALHWWNTDKQCHL
WYWPRVNDSEBQZUYWFZTYBQZIAIAWIELXD
GSPAJAPSDIOHJDGHDBECZIWKSGVUHQMSN
VTHITUCGAWUUCGEBYVHNERPMZPZMUQHVZ
EIOYCVPONTFOOCUZSSQORJKOBGAFUMDKA
WGUAZTEYVXJYGDVKLFOSFMISJSJIVOPZV
IASWRNGTDNISBCBDJJPVTOJLBZRLRJGCS
IVPHDQBWUQHEOGOSUNNQKZFMPYVEVPYXF
WZVMNKATCBBXHDTROXSEHHTHQCMRULYVQ
DUATISIGVTZBCJSVZFBGIPMGYDPYISCPD
IEVNPBSDXCERINHKTYSMIRHVYMWDBLIYN
FCBHGRXLBMETYKDJQUIFKPJKDJGCFCKHA
WCRTUAVQPVUSOEURAFQBXIEVHDFXUDGYL
BQYQHTHLITUQPSNPLTISVYAQACMKQRCXS
PFYDRJMBZOZSBVKGAAMTIKWHJCFBIMEGU
SQYZYGOMRVWEKOVNKBDKEEVCHJVFOYTJV
PROEDILJXAORHMQMPOSCOJALZBETLVXKW
QRAPRQUGECLYFPCYHUMRYPWHMAFZAPQOE
WMKZVJXMFBJNCAFEIKQQAEQEBHYNWROUS
ULXYHOVIEJOHSYKKBJELPIWYXKJBIAZIQ
DWTQIJCHMXEPZMPHEULUBRVSAJQRXEGAV
FNVEPVNOJCBBRPVYBTZPHDSHZFEUAVQGV
PHDMJWJBIHVRLJYCSQJCKMEZRGRJMSQKE
LVMBLOKXMBFAWCGFMCPFOAGQLXCMISLKU
JVNZGEAZYFSBSETXKSWLGTYRTDVAWQFLI
WFWFBMXMSPYZANJNJWNUJLJXMGOPHVZYQ
PXLLANBLXBXBCIIHZTVGYIBENPFFTFDIC
```
[Answer]
# Python 3, score = 1014
Starting from a null sized area we add words letter by letter to the area in a way that the area will always be a rectangular spiral:
```
.
32.
41.
567
```
We keep 10 boards candidates throughout the computation. At every step to every candidate we try to add every word that board has left in every possible legal way keeping the spiral layout. We score each of the resulting new boards based on the `total used word length / total area used` fraction. We keep the best 10 boards and repeat the step until there are no words left.
To minimize unused space at the end of the spiral we try taking some steps ahead before spiraling to create non-square spirals. E.g.:
```
98765
.1234
..
```
The word list is given in stdin. The (quite ugly) code takes about 30 minutes on my slow laptop. (If you want to wait less, you can choose `nonspiral_length=13` rather than looping through the possible values.)
The resulting board:
```
JFOOGCUZSFSQORKIJFYGDSDSEOQZUYWDFZTYBQZ
ISDHUZTIIHKTJNJDBCBOHIYOPBKVVGNAKBDKEEK
EHOJPSLCDRMYVPAWESSIMCLQEGAOKFPJLCAFCKI
BZMFYLPNMNKDKGRAVMCTBBXTWUUCGCBYHNREYPA
RFQTXESYGCDVKLFOVSSFQNYHALSVWESQVEQRIRI
EELQBZNGZLWOZSRJTCTZWDGUIHUUFVRVUICPKPG
UUAHROPSCPGBAVXCPZVHXAIKCOSPBXIFUBTMQHG
SRBXTQNSXYEIPLJIBKKYSHOJEFBEXRIPXFAOQZS
WZNBSVMAHKWZCEHVDHEGDGHIDTIGAVZBLQYSAOZ
OTLVQDLYXMTIVXKBYVRBCJONHVXULMVXGIRLEMP
LFXFBKVGHAFBGEXMSPSPBWFCIDWIMOUCLOTMQFY
YKBPSYJFBAWNTMRRQYNQDIGPALCHXLEDTADHWTC
FDXBEUBGEGMHJWLSMKFXTECBSFYVDSCVXWVGEWD
HPCARTLSSKMVVGUWZBBHMWSGEAZLBJCNKIMKBTY
UYIWKTRIUVZFPNQTYFXJJQWIVNDHMLPAOXCVHGM
SRNTHINYFSKXLFYIHXGKOUOZAEWQDJNIYAWAMDY
MEIPMHFGCEJRASBSXORTSHBSJNJWNUHTYUQHZBJ
XLZHQYSRCKNDGOUNNQEBGMFITLRPUDFGYXFVJLD
XITNMNSUECHSTQGDUZPSKQPHJAPDQKKHRTLCAQC
XAVCPHYOCZVGZXBVAVTNQNWPYOUSPVAVBMQHDLC
XFGQOJIALHWWAINTAGJRVMDGKKLLYZHPOGQWKBJ
XMYEDNOWESMKTBAYUUNZOSYYCIDGCETXQZEPYMA
XUICSCJAVJHPJAIWHMTHTQDZDERPZYQEMLBYVRA
XWBMFGWFBIMXBKWOLJPIVRYRHUGINDRSZBJPQJH
XDENPFTDZGFFVEFYJQASIBLULPMZPEXJMHIEMGT
XIQTYWXGUMJRGRZEMKCJQSCVYJLRVHIBWVJOJQI
```
The generating code:
```
import sys
class b:
def __init__(s,l,ws):
s.d=[' ']*(l*l)
s.x,s.y=l//2,l//2
s.l=l
s.dir=1j
s.ws=ws[:]
# last char pos, remaining word part, used positions
s.wx,s.wy,s.wp,s.wu=None,None,None,None
def copy(s):
#print('copy',s.x,s.y,s.wp)
c=b(s.l,s.ws)
c.d=s.d[:]
c.x,c.y=s.x,s.y
c.dir=s.dir*1
c.wx,c.wy=s.wx,s.wy
c.wp=s.wp[:] if s.wp!=None else None
c.wu=s.wu[:] if s.wu!=None else None
return c#copy.deepcopy(s) is very slow
def score(s):
placed_chars=allwlen-sum([len(w) for w in s.ws])
used_cells=0
for i in range(s.l):
for j in range(s.l):
if s.d[i*s.l+j]!=' ':
used_cells+=1
return placed_chars/used_cells
def get_next_bs(s):
bl=[]
for wi in range(len(s.ws)):
bl+=s.get_b_for_w(wi)
return bl
def get_b_for_w(s,wi):
w=s.ws[wi]
bl=[]
for i in range(1,s.l-1,3):
for j in range(1,s.l-1,3):
for reversed in True,False:
if abs(i-s.x)+abs(j-s.y)>5:
continue
bn=s.copy()
bn.wx,bn.wy=i,j
bn.wp=w if not reversed else w[::-1]
del bn.ws[wi]
bn.wu=[]
bnr=bn.get_bs_for_wp()
bl+=bnr
# only use the best for a given word
best_b=max(bl,key=lambda b:b.score())
return [best_b]
def get_bs_for_wp(s):
if len(s.wp)==0:
return [s]
bl=[]
for ir in -1,0,1:
for jr in -1,0,1:
i=s.wx+ir
j=s.wy+jr
if (i,j) not in s.wu and (s.d[i*s.l+j]==s.wp[0] or (i==s.x and j==s.y)):
bn=s.copy()
assert bn.d[i*bn.l+j] in (bn.wp[0],' ')
#add/owerwrite char
bn.d[i*bn.l+j]=bn.wp[0]
bn.wp=bn.wp[1:]
bn.wu+=[(i,j)]
bn.wx,bn.wy=i,j
if (i==bn.x and j==bn.y):
spiraling=not (bn.x==bn.l//2 and bn.l//2+nonspiral_length>bn.y>=bn.l//2 )
#turn
nd=bn.dir*1j
if bn.d[int(bn.x+nd.real)*bn.l+int(bn.y+nd.imag)]==' ' and spiraling:
bn.dir=nd
#move
bn.x+=bn.dir.real
bn.y+=bn.dir.imag
#add bs from new state
bl+=bn.get_bs_for_wp()
return bl
def __repr__(s):
#borders
x1,x2,y1,y2=s.l,0,s.l,0
for i in range(s.l):
for j in range(s.l):
if s.d[i*s.l+j]!=' ':
x1=min(i,x1)
x2=max(i,x2)
y1=min(j,y1)
y2=max(j,y2)
r=''
for i in range(x1,x2+1):
for j in range(y1,y2+1):
r+=s.d[i*s.l+j] if s.d[i*s.l+j]!=' ' else 'X'
r+='\n'
return r
progress_info=False # toggle to print progress info
allws=[w.rstrip() for w in sys.stdin.readlines()]
allws=allws[:]
allwlen=sum([len(w) for w in allws])
max_nonspiral_length=16
best_score=allwlen*2+1 # maxint
best_b=None
for nonspiral_length in range(1,max_nonspiral_length+1,3):
length=int(allwlen**0.5)+nonspiral_length*2+5 #size with generous padding
bl=[b(length,allws)]
for wc in range(len(allws)):
bln=[]
for be in bl:
bln+=be.get_next_bs()
bln.sort(key=lambda b:b.score(),reverse=True)
bl=bln[:10]
if progress_info:
print(wc,end=' ')
sys.stdout.flush()
#print(bl[0].score(),wc)
real_score=len(repr(bl[0]))-repr(bl[0]).count('\n')
#print(bl[0])
if progress_info:
print()
print(nonspiral_length,'score =',real_score)
if real_score<best_score:
best_b=bl[0]
best_score=real_score
if progress_info:
print()
print(best_b)
if progress_info:
print('score =',best_score)
```
] |
[Question]
[
Given two rectangles, which are possibly not in the orthogonal direction, find the area of their intersection.
[](https://i.stack.imgur.com/CmqsU.png)
## Input
You may take the rectangles as input in one of the following ways:
* The coordinates of the four vertices of the rectangle. These coordinates are guaranteed to represent a rectangle.
* The coordinates of the center of the rectangle, the width, the height, and the angle of rotation.
* The coordinates of the center of the rectangle, half the width, half the height, and the angle of rotation.
* The coordinates of the four vertices of the unrotated rectangle, and the angle of rotation. Since the unrotated rectangle is in the orthogonal direction, its coordinates can be represented by four numbers instead of eight. You may choose to rotate about either the center of the rectangle or the origin.
The angle can be either in degrees or radians. It can be either counterclockwise or clockwise.
You don't need to take the two rectangles in the same way.
## Output
The area of the intersection of the two rectangles.
The output must be within a relative or absolute error of \$10^{-3}\$ of the expected answer for the given test cases.
This means that, if the expected answer is \$x\$, and your answer is \$y\$, then \$y\$ must satisfy \$|x - y| \leq \max(10^{-3}, 10^{-3} x)\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
In the test cases, the rectangles will be given in the format `[x, y, w, h, a]`, where `(x, y)` is the center of the rectangle, `w` is the width, `h` is the height, and `a` is the angle of rotation in radians. The angle is measured counterclockwise from the positive x-axis.
```
[[0.0,0.0,1.0,1.0,0.0], [0.0,0.0,1.0,1.0,0.0]] -> 1.0
[[0.0,0.0,1.0,1.0,0.0], [0.0,0.0,1.0,1.0,0.785398]] -> 0.828427
[[-3.04363,2.24972,4.58546,9.13518,2.46245], [-3.2214,4.88133,9.71924,8.41894,-2.95077]] -> 31.9172
[[-0.121604,-0.968191,4.37972,3.76739,0.378918], [-2.64606,4.07074,5.22199,0.847033,-0.785007]] -> 0.0
[[-2.00903,-0.801126,9.90998,6.7441,-1.69896] ,[-2.6075,4.35779,4.29303,8.99664,-0.644758]] -> 14.5163
[[-3.29334,-1.24609,8.73904,3.86844,-2.90883], [-3.77132,-0.751654,1.14319,6.62548,0.806614]] -> 5.26269
[[3.74777,3.13039,1.94813,6.56605,1.53073], [1.20541,4.38287,5.16402,3.75463,-1.66412]] -> 4.89221
[[2.40846,1.71749,7.71957,0.416597,-2.4268], [-0.696347,-2.3767,5.75712,2.90767,3.05614]] -> 0.000584885
[[3.56139,-2.87304,8.19849,8.33166,1.00892], [3.03548,-2.46197,8.74573,7.43495,-2.88278]] -> 54.0515
[[3.49495,2.59436,8.45799,5.83319,0.365058], [3.02722,1.64742,1.14493,2.96577,-2.9405]] -> 3.3956
```
[Answer]
# [Python](https://www.python.org) + [Shapely](https://shapely.readthedocs.io), 88 bytes
```
lambda x,y:Polygon(x).intersection(Polygon(y)).area
from shapely.geometry import Polygon
```
Takes a list of ordered vertex coordinates for both rectangles (or any polygons) as input.
A solution using [Shapely 2.0](https://shapely.readthedocs.io/en/stable/manual.html), but I'm working on golfing an awfully long solution which uses line-line intersection and the shoelace formula.
[Answer]
# Mathematica ~~60~~ 36 or ~~222~~ 175 bytes
**Pure coordinate input:**
```
Area@RegionIntersection[Polygon/@#]&
```
Thanks to @alephalpha and @att!
**`{x,y,w,h,a}` - input:**
```
Area@RegionIntersection[Polygon/@((s=Sin@#5;c=Cos@#5;v1=#4s;v2=#3c;v3=#4c;v4=#3s;
.5{{v1+v2,v4-v3},{v2-v1,v3+v4},{-v1-v2,v3-v4},{v1-v2,-v3-v4}}+Table[{#1,#2},4])&@@@#)]&;
```
Expanded version self-explained:
```
Area@RegionIntersection[
Polygon /@
(
With[
{v1 = Sin@#[[5]] #[[4]],
v2 = Cos@#[[5]] #[[3]],
v3 = Cos@#[[5]] #[[4]],
v4 = Sin@#[[5]] #[[3]]},
.5 {{v1 + v2, v4 - v3}, {v2 - v1, v3 + v4 }, {- v1 - v2,
v3 - v4 }, {v1 - v2, -v3 - v4}} +
Table[{#[[1]], #[[2]]}, 4]] & /@ ##
)
]&
```
A bit non-code golf, cause `Area` and `RegionIntersection` are extra-power built-ins. But this is working answer anyway =)
[Answer]
# [Desmos](https://www.desmos.com/calculator), 229 bytes (non-competing)
```
u(x)=\frac{\operatorname{sign}(x)+1}{2}
t(a,b,c,d,x,y)=u(c-abs((x-a.x)\cos(b)-(y-a.y)\sin(b)))u(d-abs((x-a.x)sin(b)+(y-a.y)cos(b)))
f(a,b,c,d,g,h,i,j)=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}t(a,b,c,d,x,y)t(g,h,i,j,x,y)dxdy
```
[Try it online!](https://www.desmos.com/calculator/k6g2causi8)
Takes input as center point, rotation angle (radians), half width, half height, and then the same for the second rectangle.
First we define `u` to be the step function, then we define `t` to take a rectangle and coordinates x, y, and using transformations and the step function return 1 if the point is in the rectangle and 0 if it isn't. Then for `f` we simply multiply `t` applied to each rectangle, giving us a function which is 1 in the intersection and 0 otherwise. The we simply integrate this over x and y and we have the area.
So why non-competing? It doesn't meet the accuracy requirement. The theory here is sound, and I'm not enough of an expert in Desmos to know the technical reasons it isn't accurate, but in general Desmos is only so good at integrals. You may think it has to do with the bounds being \$-\infty\$ to \$\infty\$, but I tried finite (\$-5\$ to \$5\$) bounds as well and it made no difference. I *think* if the requirement was \$10^{-2}\$, it would actually pass, but alas.
[Answer]
# [MATLAB](https://www.mathworks.com/products/matlab.html), 344 bytes
344 bytes, maybe golfed more.
```
R=@(r1,r2)polyshape((r1(3)/2*[-1 1 1 -1])'*cos(r1(5))-(r1(4)/2*[-1 -1 1 1])'*sin(r1(5))+r1(1), (r1(3)/2*[-1 1 1 -1])'*sin(r1(5))+(r1(4)/2*[-1 -1 1 1])'*cos(r1(5))+r1(2)).intersect(polyshape((r2(3)/2*[-1 1 1 -1])'*cos(r2(5))-(r2(4)/2*[-1 -1 1 1])'*sin(r2(5))+r2(1),(r2(3)/2*[-1 1 1 -1])'*sin(r2(5))+(r2(4)/2*[-1 -1 1 1])'*cos(r2(5))+r2(2))).area
```
---
Single file that can directly run:
```
%test_CGCC256396.m
R = @(r1, r2) polyshape((r1(3)/2*[-1 1 1 -1])'*cos(r1(5))-(r1(4)/2*[-1 -1 1 1])'*sin(r1(5))+r1(1), (r1(3)/2*[-1 1 1 -1])'*sin(r1(5))+(r1(4)/2*[-1 -1 1 1])'*cos(r1(5))+r1(2)).intersect(polyshape((r2(3)/2*[-1 1 1 -1])'*cos(r2(5))-(r2(4)/2*[-1 -1 1 1])'*sin(r2(5))+r2(1), (r2(3)/2*[-1 1 1 -1])'*sin(r2(5))+(r2(4)/2*[-1 -1 1 1])'*cos(r2(5))+r2(2))).area;
rectangle_intersection = @(rect1, rect2) R(rect1, rect2);
rectangles = [
[0.0,0.0,1.0,1.0,0.0],
[0.0,0.0,1.0,1.0,0.0],
[0.0,0.0,1.0,1.0,0.0],
[0.0,0.0,1.0,1.0,0.785398],
[-3.04363,2.24972,4.58546,9.13518,2.46245],
[-3.2214,4.88133,9.71924,8.41894,-2.95077],
[-0.121604,-0.968191,4.37972,3.76739,0.378918],
[-2.64606,4.07074,5.22199,0.847033,-0.785007],
[-2.00903,-0.801126,9.90998,6.7441,-1.69896] ,
[-2.6075,4.35779,4.29303,8.99664,-0.644758],
[-3.29334,-1.24609,8.73904,3.86844,-2.90883],
[-3.77132,-0.751654,1.14319,6.62548,0.806614],
[3.74777,3.13039,1.94813,6.56605,1.53073],
[1.20541,4.38287,5.16402,3.75463,-1.66412],
[2.40846,1.71749,7.71957,0.416597,-2.4268],
[-0.696347,-2.3767,5.75712,2.90767,3.05614],
[3.56139,-2.87304,8.19849,8.33166,1.00892],
[3.03548,-2.46197,8.74573,7.43495,-2.88278],
[3.49495,2.59436,8.45799,5.83319,0.365058],
[3.02722,1.64742,1.14493,2.96577,-2.9405]
];
for i = 1:2:size(rectangles,1)
rect1 = rectangles(i,:);
rect2 = rectangles(i+1,:);
area = rectangle_intersection(rect1, rect2);
fprintf("Intersection area of rectangle %d and %d: %f\n", i, i+1, area);
end
```
```
Intersection area of rectangle 1 and 2: 1.000000
Intersection area of rectangle 3 and 4: 0.828427
Intersection area of rectangle 5 and 6: 31.917167
Intersection area of rectangle 7 and 8: 0.000000
Intersection area of rectangle 9 and 10: 14.516304
Intersection area of rectangle 11 and 12: 5.262695
Intersection area of rectangle 13 and 14: 4.892207
Intersection area of rectangle 15 and 16: 0.000585
Intersection area of rectangle 17 and 18: 54.051499
Intersection area of rectangle 19 and 20: 3.395599
```
---
Ungolfed version, with detailed code comment
```
function area = rectangle_intersection(rect1, rect2)
% rect1 and rect2 are arrays of the form [x, y, w, h, a]
% where (x, y) is the center of the rectangle, w is the width,
% h is the height, and a is the angle of rotation in radians.
% create polygons representing the rectangles
poly1 = create_polygon(rect1);
poly2 = create_polygon(rect2);
% find the intersection of the polygons
poly_intersect = intersect(poly1, poly2);
% calculate the area of the intersection
area = poly_intersect.area;
end
function poly = create_polygon(rect)
% create a polygon representing the given rectangle
x = rect(1); y = rect(2); w = rect(3); h = rect(4); a = rect(5);
% calculate the coordinates of the corners of the rectangle
corners = [-w/2 -h/2; w/2 -h/2; w/2 h/2; -w/2 h/2];
% rotate the corners by the angle a
rot_mat = [cos(a) sin(a); -sin(a) cos(a)];
corners = corners * rot_mat;
% translate the corners to the center of the rectangle
corners(:,1) = corners(:,1) + x;
corners(:,2) = corners(:,2) + y;
% create the polygon
poly = polyshape(corners(:,1), corners(:,2));
end
```
] |
[Question]
[
This [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") is based on OEIS sequence [A261865](https://oeis.org/A261865).
>
> \$A261865(n)\$ is the least integer \$k\$ such that some multiple of \$\sqrt{k}\$ is in the interval \$(n,n+1)\$.
>
>
>
The goal of this challenge is to write a program that can find a value of \$n\$ that makes \$A261865(n)\$ as large as you can. A brute-force program can probably do okay, but there are other methods that you might use to do even better.
### Example
For example, \$A261865(3) = 3\$ because
* there is no multiple of \$\sqrt{1}\$ in \$(3,4)\$ (since \$3 \sqrt{1} \leq 3\$ and \$4 \sqrt{1} \geq 4\$);
* there is no multiple of \$\sqrt{2}\$ in \$(3,4)\$ (since \$2 \sqrt{2} \leq 3\$ and \$3 \sqrt{2} \geq 4\$);
* and there *is* a multiple of \$\sqrt{3}\$ in \$(3,4)\$, namely \$2\sqrt{3} \approx 3.464\$.
### Analysis
Large values in this sequence are rare!
* 70.7% of the values are \$2\$s,
* 16.9% of the values are \$3\$s,
* 5.5% of the values are \$5\$s,
* 2.8% of the values are \$6\$s,
* 1.5% of the values are \$7\$s,
* 0.8% of the values are \$10\$s, and
* 1.7% of the values are \$\geq 11\$.
### Challenge
The goal of this [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") is to write a program that finds a value of \$n\$ that makes \$A261865(n)\$ as large as possible. Your program should run for no more than one minute and should output a number \$n\$. Your score is given by \$A261865(n)\$. In the case of a close call, I will run all entries on my 2017 MacBook Pro with 8GB of RAM to determine the winner.
For example, you program might output \$A261865(257240414)=227\$ for a score of 227. If two entries get the same score, whichever does it faster on my machine is the winner.
(Your program should not rely on information about pre-computed values, unless you can justify that information with a heuristic or a proof.)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), Score 335 on TIO
```
#include <stdio.h>
#include <math.h>
int main() {
double n = 0, k;
while( n += 13 ) {
for(k = 2; ceil(sqrt((n + 1) * (n + 1) / k)) - floor(sqrt(n * n / k)) < 2; k++);
if( k > 250 ) printf("%.lf -> %.lf\n", n, k);
}
return 0;
}
```
[Try it online!](https://tio.run/##RU7LbsIwELz7K0agSnZDaKDqKZAv6SV1bGLZ2RTHUQ8Vv153QynsZVfz2tHlSeuc1450mDuDw5Q6N277RjygoU39gghHCUPrSCp8CwGebpw/ggHhiGoDX/@hX70LRjJaHLF7xV29jB2j9Czf19DGBTmdY5KSpdgpPOP/eoFXCiVsGNlwFRHTdCMOi98Xhaqvwfd0ZyU8GuzfKn77GbmxlaunbbAoGyz7nVYbEHe9WS@PgGjSHAlVLS45/2gb2tOUyzD8Ag "C (gcc) – Try It Online")
The algorithm to compute A(n) is took from the [OEIS](https://oeis.org/A261865) page.
The `n` for which A(n) is being computed, follows the heuristics below:
I computed these [first few A(n) greater than 100](https://tio.run/##fVG7csIwEOz1FRszzEgB80iTwsBMmnR8hCNLoLGQE1ueFAm/HkdnYyA8soV1uts93Z5lvJGyaQbGSVtnCovKZ6aYbFfslNqlfksZNsiUNk5hjfmsA2PGeexS47jAF2MIyIr6zSq4MfKkTbSf99pXPAqBo1u8wgt3AvjGayp9UVYoNFwkkjNy/D@I3LJ1UXKHJZ6S0HyBdThGo@M4PSPvGFIZy6uP0vOgGWEu8Ig@miIXAjG0LYKgJblQdofCgvR5aH1mi2A0R44VLQX0bJ8/Bq2lMmxK82j4PLGa/A/ppAVE43ZXh643xTQ/LdqQhzFkOFywQm8mMJ1ZXOAq8bk1VnE8cIkhjMAt0U3hn/EzmtdcDNtDYrqEua7t2f1b96@js45dfX9acql8XTrMErZvmh@pbbqpmtjufgE "C (gcc) – Try It Online")
```
n -> A(n) | Factors of n
-------------------------------
130375 -> 118 | 5 5 5 7 149
169819 -> 127 | 13 13063
902236 -> 103 | 2 2 211 1069
1227105 -> 106 | 3 3 5 11 37 67
1793759 -> 105 | 11 179 911
1940874 -> 103 | 2 3 13 149 167
1962875 -> 105 | 5 5 5 41 383
2135662 -> 130 | 2 1067831
2345213 -> 187 | 13 13 13877
2470326 -> 111 | 2 3 411721
3461537 -> 115 | 3461537
4221630 -> 105 | 2 3 3 5 7 6701
4576794 -> 103 | 2 3 229 3331
5021205 -> 114 | 3 5 7 17 29 97
5396362 -> 110 | 2 2698181
8567238 -> 102 | 2 3 29 53 929
9182575 -> 103 | 5 5 89 4127
9983754 -> 102 | 2 3 3 11 50423
```
Where there are two notable local maximum: **127** and **187**.
As you can see, in both cases the generating `n` is a multiple of **13**, and that seemed to me a good enough reason to conjecture that, on average, multiples of 13 may generate an higher A(n) than most numbers of the same magnitude.
So I made a program to compute the multiples of 13 and leaving it running for a minute on TIO, the maximum I get is
```
11145613453 -> 335
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), A261865(6600656102)=323 on TIO
This out this checks every `A(n)` sequentially (well, based on the small `CHUNKSIZE`, and it skips a lot of values based on optimization, see the How it works).
```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
//#define L unsigned __int128
//#define F __float128
#define L unsigned long long
#define F long double
#define MAXN (1024ull*1024ull*1024ull*1024ull)
#define CHUNKSIZE (1024ull*1024ull)
#define CHECKS 8
#define BUFFER 1024
int main() {
F steps[CHECKS + BUFFER], values[CHECKS + BUFFER];
steps[0] = sqrtl(2) / (sqrtl(2) - 1);
steps[1] = sqrtl(3) / (sqrtl(3) - 1);
int n=5, min_check;
for (int i = 2; i < CHECKS + BUFFER; n++) {
int ok = 1;
for (int tmp = 2; tmp < sqrtl(n) + 0.5; tmp++)
if (n % (tmp * tmp) == 0) ok = 0;
if (!ok)
continue;
values[i] = n;
steps[i++] = sqrtl(n);
if (i == CHECKS) min_check = i;
}
char chunk[CHUNKSIZE] = { 0 };
#pragma omp parallel for private(chunk) schedule(static, 1)
for (L chunki = 0; chunki < (MAXN / CHUNKSIZE); chunki++) {
L start = chunki * CHUNKSIZE, end = (chunki + 1) * CHUNKSIZE;
for (L i = start / steps[1] + 1; i < end / steps[1]; i++)
chunk[(L)(i * steps[1]) - start] = 1;
for (int k = 2; k < CHECKS; k++)
for (L i = start / steps[k] + 1; i < end / steps[k]; i++)
chunk[(L)(i * steps[k]) - start] = 0;
for (L i = start / steps[0] + 1; i < end / steps[0]; i++) {
L xi = (L)(i * steps[0]) - start;
if (chunk[xi] == 1) {
chunk[xi] = 0;
L x = xi + start;
int k = min_check;
while (++k) {
F sqrt_k = steps[k];
F try = sqrt_k * ceill(x/sqrt_k);
if (x < try && try < x + 1) break;
}
k = values[k];
if (k > 249)
printf("A261865(%llu)=%d\n", x, k), fflush(stdout);
}
}
}
}
```
[Try it online!](https://tio.run/##fVRrb9pAEPzuX7FNlOgOQzDkoVRApDQiahWaSo0iVU0j5NhnOPk4Uz9Sqoi/Xrp7PmNSQhGyzezs7OzemqA1CYLVal/qQBWhgH6WhzI5ml44NTTz8@lrBElKPm1hUueEOe32figiqQWMoNCZnGgRwniM4U73fCN6jWCkEt/Ab6SoRE/MxakzDBYmxZMSa/Tz5bdbYB2ve1Io1dhx52v61cf725u7T9@HWzmbnOHVzR3Utj7cX18PvwIRHQc7gZkvNePw4qCpLBfz7MHmuJb72IRnXxViO9BzbIb3CAPIfqa5Yl0ObWDr5xZ0@JrWqWnHG7TjNY386MFpE2ZSj4OpCGIEoyQFRhGJ2d0e3vrwj5MeaNc1PRiJJEZmB1Pr3Hw2L7PpoW9NaI4K3tGpQVEAE0BGwDQcACNigwIcBgPweKnqkSpx3iWx4QeJzqUuBOF2TJLa1ASUbUvXrRvXvFKQpFs2wuuGkSiRsXQcCKZ@ipdCxw/royahF/Bg2XOc/XnqT2Y@JOh07qe@UkKZjuepfPZzwUwuhwyFw0IJluV@LoMmztpOdVTKS9NY9dwHZhaxXS8Yr4LVlPE7wu78NMdUm9eo@U0QOsQIsyEXS27G0TxUDqh4qdSu1wQTyoMmnRpHzB5TORY24owKV3FaJKP1uLUAcXn88Xp58Nlq7TQS7zASbxh500n82on3/369HWU8W8ZMHOe9oNTXhby6UK/a3tLQgrZwQHN/2bBp0HKJjSL@WNDx1ApQDWvzFcTPr6lUApjrxpUi/V/gSo9j05CdSxXJ09925THegEBIpdiiXQLc0sjtApsm8uGhufXRk9mWp1T4tvTSXKmMfcGqOpQfwwV0T96XZ0Gbr/OI7V12zzrnZ6fsQKmCDw7CH3qvCYsmxLwJUaSKbIovA/775qUVqrCkl265Wv0JIuVPslUrSuZCz@ar1pfjVUvN/gI "C (gcc) – Try It Online")
### How it works
We sieve through the numbers: `floor(i * sqrt(n))` is a [Beatty sequence](https://en.wikipedia.org/wiki/Beatty_sequence). The nice thing about these is that their complement is easy to calculate. So if `floor(i * sqrt(2))` hits `1 2 4 5 7 8 9 …`, `floor(i * (sqrt(2) / (sqrt(2) - 1)))` hits `3 6 10 13 17 20 23 …` This alone saves us about two third calculation time.
For `n>4`, `sqrt(n)` is actually bigger than `(sqrt(2) / (sqrt(2) - 1)`. So we initialize an array of 0s, set every non-multiple of `sqrt(3)` to 1, and for every `n` between 3 and `CHECKS` we set every multiple of `sqrt(n)` back to 0. We then take the big steps of `(sqrt(2) / (sqrt(2) - 1)` and if there the array is set to 1, we know that `A(i)` is at least `CHECKS`.
`A(n)` must be a square free number, as the square of its square divisor (8 -> 4 -> 2) will already have hit the same numbers, so we can skip `4 8 9 12 16 …`, too.
The actual computation of `A(n)` is borrowed from @Noodle9. But we can start with `i = CHECKS`.
Bundled all of this with OpenMP for easy multithreading for the chunks and some performance testing to get a good value for `CHECKS`, we get to 383 on TIO. If you want to get further than `A(2^64)`, you need to define `L` and `F` to `unsigned __int128` and `__float128`.
[Answer]
# JavaScript (Node.js), score \$335\$
Pretty straight-forward algorithm. I made it multithreaded to be a bit faster.
```
// Run with: node ./square-root-multiples.js
const findMaxK = (fromN, toN) => {
let maxK = 0;
let maxN = 0;
for (let n = fromN; n < toN; n++) {
for (let k = 2, s = n * n; k < s; k++) {
const r = Math.sqrt(k);
const x = r * Math.ceil(n / r);
if (x > n && x < n + 1) {
if (k > maxK) {
maxK = k;
maxN = n;
}
break;
}
}
}
return { n: maxN, k: maxK };
};
const BATCH_SIZE = 10000000;
const cluster = require("cluster");
if (cluster.isMaster) {
const start = Date.now();
let nextBatch = 0;
let maxK = 0;
const numCpus = require("os").cpus().length;
for (let i = 0; i < numCpus; i++) {
const worker = cluster.fork();
worker.on("message", (msg) => {
if (msg.k > maxK) {
maxK = msg.k;
console.log(
`found A261865(${msg.n}) = ${msg.k} in ${
(Date.now() - start) / 1000
}s`
);
}
worker.send({ n: nextBatch, maxK });
nextBatch += BATCH_SIZE;
});
worker.send({ n: nextBatch });
nextBatch += BATCH_SIZE;
}
} else {
process.on("message", (msg) => {
process.send(findMaxK(msg.n, msg.n + BATCH_SIZE));
});
}
```
Output on my 2019 MacBook Pro:
```
found A261865(12779527) = 134 in 0.299s
found A261865(2345213) = 187 in 0.308s
found A261865(63856063) = 193 in 0.33s
found A261865(222125822) = 210 in 0.681s
found A261865(237941698) = 217 in 0.687s
found A261865(257240414) = 227 in 0.804s
found A261865(1217775885) = 230 in 2.704s
found A261865(1205703469) = 267 in 2.704s
found A261865(1558293414) = 299 in 3.306s
found A261865(4641799364) = 303 in 13.002s
found A261865(6600656102) = 323 in 20.045s
found A261865(11145613453) = 335 in 36.774s
found A261865(20641456345) = 354 in 73.047s
```
The highest K my machine found within 60s was `A261865(11145613453) = 335`.
[Answer]
# [C (clang)](http://clang.llvm.org/), score 210 on TIO
```
#include <stdio.h>
int main() {
unsigned long long x, i, j, k;
for (x = 2; x < 222125823ULL; x++) {
for (i = 1; ; i++) {
for (j = 2; j * j * i <= x * x; j *= 2);
for (k = j / 2; k /= 2; ) if ((j - k) * (j - k) * i > x * x) j -= k;
if (j * j * i < (x + 1) * (x + 1)) break;
}
if (i > 99) {
printf("A261865(%llu)=%llu\n", x, i);
fflush(stdout);
}
}
}
```
[Try it online!](https://tio.run/##TZDLasMwFET3/oohpSDFdoMVEhJsB7oPdNVdN65fubYqFz/AUPzrdWXJbbPQRYzOjIab@qlMVDnPD6RSOWQ5oq7PqHm6XRxSPT4SUozjy8GgOipVnkE2qrRj9EAeKg916KBoWrARMUSIERGEEIE4nMT@9XrViuuaFIuRxoIQIehXtnpl7RW25hCiWGdtMRpNv/Hwj601W2G38DV2xsdBBZhO8VFzbfu/ES42iGuPH5vCMPTdX0t9F4Fx2hvHe5snBp4cyy9J5/Na@rPVOyrY5lkcg9PxwB6lHHi8zDe18cx@1saFHLob06tthp6veZMzzfN3Wsik7Gb/Zf8D "C (clang) – Try It Online") Calculates all A261865 entries from 2 to 222,125,822 in just under 60s on TIO. Annoyingly, it doesn't seem to be possible to reach 250,000,000 within the time limit. In any case it is limited to about 2,000,000,000 due to the use of 64-bit integer arithmetic (no square root operations). By switching to `unsigned __int128` you could quickly calculate A261865 for specific higher values of course.
Edit: Just tried a threaded version on my local 16-core processor and it can reach 2,000,000,000 in just under 60 seconds, finding A261865(1558293414)=299. Soon after that it stops working because j reaches 4,294,967,296 and then j \* j overflows to zero.
Edit: I left the 128-bit single-threaded version running overnight and it found the following record values for A261865:
```
A261865(3)=3 (0s)
A261865(23)=7 (0s)
A261865(30)=15 (0s)
A261865(184)=38 (0s)
A261865(8091)=43 (0s)
A261865(16060)=46 (0s)
A261865(16907)=58 (0s)
A261865(20993)=61 (0s)
A261865(26286)=97 (0s)
A261865(130375)=118 (0s)
A261865(169819)=127 (0s)
A261865(2135662)=130 (0.7s)
A261865(2345213)=187 (0.8s)
A261865(46272966)=193 (17.8s)
A261865(222125822)=210 (91.7s)
A261865(237941698)=217 (98.6s)
A261865(257240414)=227 (1.8m)
A261865(1205703469)=267 (8.9m)
A261865(1558293414)=299 (11.6m)
A261865(4641799364)=303 (34.9m)
A261865(6600656102)=323 (49.9m)
A261865(11145613453)=335 (85m)
A261865(20641456345)=354 (2.7h)
A261865(47964301877)=358 (6.3h)
A261865(105991039757)=385 (14.2h)
A261865(119034690206)=397 (16h)
A261865(734197670805)=455 (4.4d)
```
[Answer]
# [C (clang)](http://clang.llvm.org/), score 299 on TIO
```
#include <stdio.h>
#define A261865 256
unsigned long long J[A261865], K[A261865];
int main() {
int i, m;
unsigned long long x, j, k;
for (i = 1; i < A261865; i++) J[i] = K[i] = i;
m = 2;
for (x = 1; x < 0x60000000ULL; x++) {
for (i = 1; ; i++) {
if (i < A261865) {
while (J[i] <= x * x) J[i] += K[i] += i + i;
if (J[i] < (x + 1) * (x + 1)) break;
} else {
for (j = k = i; j <= x * x; j += k += i + i);
if (j < (x + 1) * (x + 1)) break;
}
}
if (i > m) {
printf("A261865(%llu)=%d\n", x, i);
fflush(stdout);
m = i;
}
}
}
```
[Try it online!](https://tio.run/##hVJNa4NAEL3vr3gkBLSakqRECvmAXptATz21OVhdzZh1LTFSoeSv1866m5RCoYLO7NuZ9964m4wTFeu864akE9WkEsv6lFJ1u1@LYSoz0hIPs2h6H80xm0ei0TXlWqZQlc7t5/HFFexCbK75QpA@oYxJez4@BcyKQpQLgT842hBFiANvZtURHmGF6QKE5UWcF0HgsxbteG9jA3F9yXF26WttX8t9kzaa2Od5u2XIdLONX/yO1MCgzMBXPYfiY09Kwut1lytmvkHrbATOB0dC0JtxPLba2Akw9bnFZT7ejjI@9IVnSFVLp9KbKtjUoZ8KxVXL5IHBLyr@j0zxr4awr51tjdJN9X7k08i8gZvVGynV@KtR@qoHoTkKJ5Jlqqn3Ht@HqjlZqHR/3dCexbnrvpJMxXndjZ/uvgE "C (clang) – Try It Online") Takes under 60s to output:
```
A261865(3)=3
A261865(23)=7
A261865(30)=15
A261865(184)=38
A261865(8091)=43
A261865(16060)=46
A261865(16907)=58
A261865(20993)=61
A261865(26286)=97
A261865(130375)=118
A261865(169819)=127
A261865(2135662)=130
A261865(2345213)=187
A261865(46272966)=193
A261865(222125822)=210
A261865(237941698)=217
A261865(257240414)=227
A261865(1205703469)=267
A261865(1558293414)=299
```
Using a version with a 128-bit integer type and larger square root cache, this code has found the following values on my PC:
```
A261865(3)=3 (0s)
A261865(23)=7 (0s)
A261865(30)=15 (0s)
A261865(184)=38 (0s)
A261865(8091)=43 (0s)
A261865(16060)=46 (0s)
A261865(16907)=58 (0s)
A261865(20993)=61 (0s)
A261865(26286)=97 (0s)
A261865(130375)=118 (0s)
A261865(169819)=127 (0s)
A261865(2135662)=130 (0s)
A261865(2345213)=187 (0s)
A261865(46272966)=193 (1s)
A261865(222125822)=210 (5.2s)
A261865(237941698)=217 (5.7s)
A261865(257240414)=227 (6.2s)
A261865(1205703469)=267 (31s)
A261865(1558293414)=299 (41.8s)
A261865(4641799364)=303 (2.1m)
A261865(6600656102)=323 (3m)
A261865(11145613453)=335 (5.2m)
A261865(20641456345)=354 (9.8m)
A261865(47964301877)=358 (22.9m)
A261865(105991039757)=385 (52m)
A261865(119034690206)=397 (59.1m)
A261865(734197670865)=455 (6.4h)
A261865(931392113477)=501 (8.4h)
A261865(1560674332481)=505 (14.2h)
```
It also found `A261865(5928861186373)=509`, but I wasn't able to run it continuously for the ~2 days needed, so I don't know how long it took.
[Answer]
# [Python 3](https://docs.python.org/3/), score \$193\$
```
from math import ceil, floor, sqrt
def f(n):
k = 2
while ceil(sqrt((n + 1)**2/k)) - floor(sqrt(n**2/k)) < 2:
k += 1
return k
```
[Try it online!](https://tio.run/##nY/NCsIwEITveYo5Jm1EUhGk2IcpmtiQdlPXiPj0sT/05EnnsLCzzPDt@E5dpEPOjuOAoU0d/DBGTrhY32u4PkbWeNwn51tCXK2Dk6Rq/Cgxj4AG1V/JV@d7uzDKmU1KQgmjiqLaB6WwW8HXG23uGVUttpqAsoFZVrbpyYSQXWQQPIFbullptDkd1RoZ2dNUpZdvVf4A "Python 3 – Try It Online")
Straight forward port of the Mathematica code on [OEIS A261865](https://oeis.org/A261865) to get the ball rolling.
On my laptop (Intel(R) Core(TM) i7-8750H CPU @ 2.20 GHz with 16 GB RAM):
```
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
from math import ceil, floor, sqrt
@timeout(60)
def f():
n = 1
m = 1
while 1:
k = 2
while ceil(sqrt((n + 1)**2/k)) - floor(sqrt(n**2/k)) < 2:
k += 1
if k > m:
print(f'A({n}) -> {k}')
m = k
n += 1
f()
```
produces:
```
A(1) -> 2
A(3) -> 3
A(23) -> 7
A(30) -> 15
A(184) -> 38
A(8091) -> 43
A(16060) -> 46
A(16907) -> 58
A(20993) -> 61
A(26286) -> 97
A(130375) -> 118
A(169819) -> 127
A(2135662) -> 130
A(2345213) -> 187
A(46272966) -> 193
Traceback (most recent call last):
File "A261865_timeout.py", line 41, in <module>
f()
File "A261865_timeout.py", line 18, in wrapper
result = func(*args, **kwargs)
File "A261865_timeout.py", line 35, in f
while ceil(sqrt((n + 1)**2/k)) - floor(sqrt(n**2/k)) < 2:
File "A261865_timeout.py", line 12, in _handle_timeout
raise TimeoutError(error_message)
__main__.TimeoutError: Timer expired
```
[Answer]
# [C++ (clang)](http://clang.llvm.org/), score \$399\$
```
#include <iostream>
#include <cmath>
#include <vector>
#include <thread>
void f(unsigned long n)
{
unsigned int m = 0;
while (1) {
unsigned long k = 1;
while (++k) {
const double sqrt_k = std::sqrt(static_cast<double>(k));
const double x = sqrt_k * std::ceil(n/sqrt_k);
if (n < x && x < n + 1) break;
}
if (k > m) {
std::cout << "<" << k << "> for A261865(" << n << ")\n";
m = k;
}
++n;
}
}
int main()
{
const unsigned long block_size = 100000000000UL;
const unsigned long num_threads = 12;
std::vector<unsigned int> results(num_threads);
std::vector<std::thread> threads(num_threads - 1);
unsigned long start = 1UL;
for (int i = 0; i < num_threads - 1; ++i) {
threads[i] = std::thread(f, start);
start += block_size;
}
for (auto& entry: threads) {
entry.join();
}
}
```
[Try it online!](https://tio.run/##dVLbjtMwEH33V4y6UuUQAttFLKhxI/GOxBNPgKrUcVqTZFxiZ7mpv07wpWnd7q4fYmdmzlzOGb7fZ7wtcTuONxJ5O1QCmFTa9KLsCnK28a40u9jwILhRfWwxOwuqCkIelKygpgNquUVRQatwC5iQvwTsOZklGuhgBbe5t//cyVYAXSQQ4i5ifYrGBi/yk/MISNMmhrjDFWoDlRo2NkD/6M3aQbWplkv3R7UpjeRrXmrDQlRBmyTJn0/yy@FDohchEReypfg6GK@gsgaKwCxqPrcfBggp2ME2lqDmHHogMaCBArrrSUIpNRhgDGZs5q7GvwuoVQ8f7u4X7@/fUu9A70i@4uyyHUfyk2XTFIP5QA6EeD1KiXRSKjBwqcGmVbxZa/lHODFuz@fzx/xZEA7dOmyHdqi7EOlnC2vE4qUooBd6aI2mES55jPHv49LBMSyGQGY5z8njPbLy98Y1MvXsmKRufOnX0V4MrhLlliwZq3P0fZHfptUKFlq/DAWinQgF01XE3sT7qXw5GDUHgab/vZySx/W859V35fQ5iTaO/3jdlls9Zp/ejNk@4MbM9rPiabp49x8 "C++ (clang) – Try It Online")
Gets \$313\$ on TIO.
Gets \$399\$ on my laptop (Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz with 16 GB RAM):
```
#include <iostream>
#include <cmath>
#include <sys/time.h>
#include <vector>
#include <thread>
int sigTimerSet(int seconds)
{
std::cout << "Starting timer for " << seconds << " seconds.\n";
struct itimerval old_one, new_one;
new_one.it_interval.tv_usec = 0;
new_one.it_interval.tv_sec = 0;
new_one.it_value.tv_usec = 0;
new_one.it_value.tv_sec = static_cast<long int>(seconds);
if (setitimer (ITIMER_REAL, &new_one, &old_one) < 0)
return 0;
else
return old_one.it_value.tv_sec;
}
void f(unsigned long n)
{
unsigned int m = 0;
while (1) {
unsigned long k = 1;
while (++k) {
const double sqrt_k = std::sqrt(static_cast<double>(k));
const double x = sqrt_k * std::ceil(n/sqrt_k);
if (n < x && x < n + 1) break;
}
if (k > m) {
std::cout << "<" << k << "> for A261865(" << n << ")\n";
m = k;
}
++n;
}
}
int main()
{
sigTimerSet(60);
const unsigned long block_size = 100000000000UL;
const unsigned long num_threads = std::thread::hardware_concurrency();
std::vector<unsigned int> results(num_threads);
std::vector<std::thread> threads(num_threads - 1);
unsigned long start = 1UL;
for (int i = 0; i < num_threads - 1; ++i) {
threads[i] = std::thread(f, start);
start += block_size;
}
for (auto& entry: threads) {
entry.join();
}
}
```
produces:
```
Starting timer for 60 seconds.
<2> for A261865(1)
<3> for A261865(3)
<7> for A261865(23)
<15> for A261865(30)
<38> for A261865(184)
<3> for A261865(200000000001)
<2> for A261865(300000000001)
<3> for A261865(300000000003)
<<2> for A261865(60000000000143)
<<5> for A261865(3000000000065)
<<6> for A261865(300000000016)
<14> for A261865(300000000023)
<15> for A261865(300000000115)
<19> for A261865(300000000160)
<21> for A261865(300000000399)
<26> for A261865(300000000716)
<2> for A261865(400000000001)
<5> for A261865(400000000002)
<6> for A261865(400000000032)
<11> for A261865(400000000039)
<14> for A261865(400000000063)
<53> for A261865(400000000316)
<3> for A261865(600000000003)
<5> for A261865(600000000006)
<6> for A261865(600000000016)
<295> for A261865(400000002890)
<2> for A261865(900000000001)
<6> for A261865(900000000003)
<10> for A261865(900000000037)
<17> for A261865(900000000108)
<19> for A261865(900000000320)
<30> for A261865(900000000522)
<31> for A261865(900000001146)
<2> for A261865(800000000001)
<5> for A261865(800000000004)
<6> for A261865(800000000034)
<11> for A261865(800000000072)
<<39> for A261865(900000003574)
<35> for A261865(800000000079)
38<<> for A261865(300000002673)
> for A261865(<2> for A261865(100000000001)
<5> for A261865(100000000002)
> for A261865(<13> for A261865(100000000009)
<21> for A261865(100000000340)
<> for A261865(<29> for A261865(100000001644)
77> for A261865(<> for A261865(600000000027)
<10> for A261865(600000000037)
<15> for A261865(600000000068)
<21> for A261865(600000000139)
8091)
51> for A261865(900000008337)
<13> for A261865(1000000000001)
<15> for A261865(1000000000018)
<23> for A261865(1000000000124)
<46> for A261865(16060)
<<29> for A261865(1000000002029)
<38> for A261865(1000000002313)
200000000004)
<10> for A261865(200000000014)
<11> for A261865(200000000028)
<13> for A261865(200000000383)
<17> for A261865(200000000584)
<23> for A261865(200000000861)
71<46> for A261865(200000001329)
42> for A261865(300000003489)
<58> for A261865(200000003435)
<53> for A261865(300000004909)
<<62> for A261865(200000006771)
<30> for A261865(100000003880)
<37> for A261865(100000004041)
> for A261865(<38> for A261865(100000004980)
<<39> for A261865(100000005673)
700000000001)
<51> for A261865(100000008489)
<10> for A261865(700000000063)
<15> for A261865(700000000077)
<19> for A261865(700000000264)
500000000001<26> for A261865(700000001087)
39<30> for A261865(700000001941)
<<38> for A261865(700000002098)
800000005135<43> for A261865(700000002630)
29> for A261865(600000001409)
> for A261865()
<<5> for A261865(500000000004)
31> for A261865(600000003011)
)
1000000003259)
<42> for A261865(1000000005365)
<62> for A261865(300000022786)
<73> for A261865(700000007516)
<35> for A261865(600000003458)
<53> for A261865(1000000014642)
<58> for A261865(16907)
<67> for A261865(600000006910)
<55> for A261865(100000020333)
<79> for A261865(200000057626)
<21> for A261865(500000000018)
<<23> for A261865(500000001052)
<<33> for A261865(500000001414)
<35> for A261865(500000001568)
<<70> for A261865(300000025183)
62> for A261865(100000024519)
61> for A261865(20993)
65> for A261865(1000000025765)
85<74> for A261865(100000027954)
<97> for A261865(26286)
> for A261865(900000026060)
<66> for A261865(1000000037855)
<79> for A261865(100000035523)
<85> for A261865(200000088176)
<93> for A261865(900000037207)
<97> for A261865(300000061052)
<79> for A261865(600000074122)
<78> for A261865(800000098681)
<122> for A261865(400000213561)
<79> for A261865(700000110055)
<101> for A261865(900000115082)
<118> for A261865(130375)
<95> for A261865(600000136687)
<85> for A261865(700000175977)
<127> for A261865(169819)
<74> for A261865(1000000208668)
<95> for A261865(200000283049)
<95> for A261865(100000278291)
<79> for A261865(800000325129)
<83> for A261865(800000382758)
<101> for A261865(300000348034)
<82> for A261865(1000000377945)
<113> for A261865(600000368089)
<115> for A261865(600000388325)
<114> for A261865(900000458149)
<94> for A261865(800000523290)
<57> for A261865(500000002957)
<91> for A261865(500000020356)
<94> for A261865(500000086735)
<123> for A261865(1000000615915)
<139> for A261865(900000597046)
<113> for A261865(700000641956)
<122> for A261865(500000189745)
<138> for A261865(500000344679)
<109> for A261865(300000963142)
<129> for A261865(600001013758)
<139> for A261865(400001233496)
<177> for A261865(300001283249)
<107> for A261865(800001360974)
<110> for A261865(100001440670)
<119> for A261865(200001950373)
<127> for A261865(200002180270)
<119> for A261865(100001936762)
<130> for A261865(2135662)
<123> for A261865(700002323159)
<146> for A261865(600001831667)
<187> for A261865(2345213)
<109> for A261865(800002595588)
<145> for A261865(700002807851)
<155> for A261865(500003070679)
<194> for A261865(300003944386)
<127> for A261865(1000003765582)
<142> for A261865(1000003972101)
<165> for A261865(100003914551)
<110> for A261865(800004935331)
<141> for A261865(200005383478)
<186> for A261865(800005847131)
<157> for A261865(600005644046)
<185> for A261865(200006038768)
<178> for A261865(400008172024)
<183> for A261865(500008457011)
<163> for A261865(1000010164463)
<190> for A261865(800013713435)
<146> for A261865(900015388529)
<197> for A261865(600016805653)
<155> for A261865(700016980104)
<165> for A261865(1000017298685)
<185> for A261865(1000023033133)
<186> for A261865(100022787204)
<157> for A261865(700023653342)
<161> for A261865(700024255285)
<159> for A261865(900023644405)
<202> for A261865(900027523835)
<303> for A261865(700033230641)
<199> for A261865(300035412403)
<215> for A261865(500035617384)
<195> for A261865(800035729684)
<223> for A261865(600037942250)
<193> for A261865(46272966)
<221> for A261865(500060347857)
<197> for A261865(100072149460)
<226> for A261865(200071020948)
<219> for A261865(800096272342)
<273> for A261865(100096408342)
<195> for A261865(1000138255835)
<313> for A261865(600147859274)
<210> for A261865(300158020199)
<305> for A261865(300163012534)
<179> for A261865(400173203199)
<249> for A261865(500185649969)
<281> for A261865(900217000298)
<210> for A261865(222125822)
<222> for A261865(1000221604207)
<217> for A261865(237941698)
<227> for A261865(257240414)
<229> for A261865(1000299563639)
<191> for A261865(400330753112)
<237> for A261865(800371022066)
<197> for A261865(400388377102)
<222> for A261865(400519662337)
<247> for A261865(1000659372263)
<251> for A261865(400686850499)
<293> for A261865(900791054060)
<258> for A261865(201101992489)
<267> for A261865(1205703469)
<255> for A261865(501227521557)
<258> for A261865(501233713968)
<399> for A261865(1001313673399)
<299> for A261865(1558293414)
<271> for A261865(801556690220)
<286> for A261865(501665988151)
<257> for A261865(401963829763)
<357> for A261865(901991228083)
<290> for A261865(101979205483)
<293> for A261865(102084473850)
<282> for A261865(402539565301)
Alarm clock
```
Note the **<399> for A261865(1001313673399)**! :D
] |
[Question]
[
Inspired by [Make a Rectangle from a Triangle](https://codegolf.stackexchange.com/q/203135/78410).
## Task
There is a famous formula on the sum of first \$n\$ squares:
$$
1^2 + 2^2 + \dots + n^2 = \frac{n(n+1)(2n+1)}{6}
$$
It is known that this number is composite for any \$n \ge 3\$.
Now, imagine a collection of row tiles (a tile of shape \$1 \times k\$ with the number \$k\$ written on each cell), and you have 1 copy of size-1 tile, 2 copies of size-2 tiles, ... and \$n\$ copies of size-\$n\$ tiles.
```
[1] [2 2] [2 2] [3 3 3] [3 3 3] [3 3 3] ...
```
Then arrange them into a rectangle whose width and height are both \$ \ge 2\$. You can place each tile horizontally or vertically.
```
+-----+---+-+-+
|3 3 3|2 2|1|2|
+-----+---+-+ |
|3 3 3|3 3 3|2|
+-----+-----+-+
```
Output such a matrix if it exists. You don't need to indicate the boundaries; just output the resulting matrix of integers. Your program may do whatever you want if the solution doesn't exist.
I believe there exists a solution for any \$n \ge 3\$. Please let me know if you find a proof or counterexample!
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Examples
```
n = 3: (2x7 example)
3 3 3 3 3 3 1
3 3 3 2 2 2 2
n = 4: (3x10 example)
4 4 4 4 4 4 4 4 2 2
4 4 4 4 3 3 3 2 2 1
4 4 4 4 3 3 3 3 3 3
n = 5: (5x11 example)
5 5 5 5 5 4 4 4 3 3 3
5 5 5 5 5 4 4 4 3 3 1
5 5 5 5 5 4 4 4 3 3 2
5 5 5 5 5 4 4 4 3 3 2
5 5 5 5 5 4 4 4 4 2 2
n = 6: (7x13 example)
6 6 6 6 6 5 5 5 5 5 3 3 3
6 6 6 6 6 5 5 5 5 3 3 3 1
6 6 6 6 6 5 5 5 5 4 3 3 3
6 6 6 6 6 5 5 5 5 4 4 4 2
6 6 6 6 6 5 5 5 5 4 4 4 2
6 6 6 6 6 5 5 5 5 4 4 4 2
6 6 6 6 6 6 4 4 4 4 4 4 2
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~238 ...~~ 186 bytes
*-2 bytes thanks to @Arnauld!*
*-5 bytes thanks to @ovs!!*
*-6 bytes thanks to @Jonathan Allan!!*
```
n=input()
p=w=~n*n*(~n-n)/6
e=range(n+1)
def f(a,b,c,d=[]):1>a>exit(c);1>b>f(a-1,w,c+[d]);g=n;exec"e[g]-=1;g<=b>-1<e[g]>f(a,b-g,c,d+[g]*g);e[g]+=1;g-=1;"*n
while 1:1>p%w>f(p/w,w,[]);w-=1
```
[Try it online!](https://tio.run/##HY3LCoMwEEX3foUIhTyRdNFC4@RHxIXGGIUyDcUSu/HX06TLO3PuueG7ry@8poSwYfjshFYBIpzIkJETJdL2Vjl4j@gdQa5oNbulXsgoJmHFDP1AH8qMxh3bTizVykwmf6USUVjezwPVHlC7w9nG9X6QoLTvYDJSdSWbv0r6IuM5M091ufPCFbhhWMV1e7pa5aFwibkR2pj1eVrHjKR0/wE "Python 2 – Try It Online")
Notice that the above code only used horizontal tiles. To prove it's correct...
---
# [C++ (gcc)](https://gcc.gnu.org/), 4355 bytes
This code is an explicit construction using only horizontal tiles for \$n>6\$. It can produce correct solutions (at least) up to \$n=99\$.
```
#include <bits/stdc++.h>
using namespace std;
void dim(int x,int&p,int&q)
{
int u[]={x,x+1,x+x+1},o=0;
while(u[o]%2) ++o; u[o]/=2;
o=0; while(u[o]%3) ++o; u[o]/=3;
sort(u,u+3);if(x%3==1)swap(u[0],u[1]);
p=u[0];q=u[1]*u[2];
}
int o[100][99999],c[99999],g[99999];
void brute(int n,int& v,int& u,bool t)
{
for(int i=1;i<=n;++i) c[i]=i;
if(t)
{
u=n*(n+1)*(2*n+1)/6,v=2;
while(u%v) ++v;
if(n>=5) v=u/v;
u/=v; c[2]-=n==6;
}
for(int i=1;i<=v;++i)
{
int s=u,cnt=0;
for(int j=n;j>=1;--j) while(s>=j&&c[j])
{
s-=j, --c[j]; for(int k=j;k--;) o[i][++cnt]=j;
}
}
c[2]+=t&&n==6;
for(int i=u;i>=u-1&&i;--i)
for(int j=1;j<=v;++j) if(!o[j][i])
{
int x=0; while(!c[x]) ++x;
--c[x]; int l=x; --j;
while(l--) o[++j][i]=x;
}
}
int s0[99999],s1[99999];
//find a subset of a with sum b
//guaranteed b is half of a's sum
//guaranteed a is consecutive
pair<vector<int>,vector<int>> solve2(vector<int> a,int b)
{
if(!a.size()) return make_pair(a,a);
int w=0,s=0,as=a.size();
for(int i=0;i<as;++i)
s0[i+1]=s0[i]+a[i],
s1[i+1]=s1[i]+a[as-1-i];
while(w<a.size()&&s+a[w]<=b)
s+=a[w++];
assert(w!=a.size()&&w>0);
for(int l=0;l<w;++l)
{
int r=w-1-l;
int p=s0[l]+s1[r];
if(p>b) continue;
int q=b-p;
if(!(a[l]<=q&&q<=a[as-r-1]))
continue;
//first l, last r, q.
vector<int> A,B;
for(int j=0;j<l;++j) A.push_back(a[j]);
A.push_back(q);
for(int j=as-r;j<as;++j) A.push_back(a[j]);
for(int j=l;j<as-r;++j)
{
if(a[j]==q) q=-1;
else B.push_back(a[j]);
}
return make_pair(A,B);
}
assert(0);
}
int main()
{
int n,p,q;
cin>>n;
assert(n>=3);
if(n<=6) brute(n,p,q,1);
else
{
if(n%3==1)
{
int x=n%3,pp,qq;
dim(x,p,q);
brute(x,p,q,0);
while(n!=x)
{
//x+1...x+3
int xx=x+3; dim(xx,pp,qq);
assert(pp-p==2&&qq-q==x*3+6);
for(int i=x+1;i<=x+3;++i) c[i]=i;
int mr=x/6;
for(int i=1;i<=p;++i)
{
int cnt=q;
vector<int> rv;
if(i<=mr) rv=vector<int>{x+2,x+2,x+2};
else rv=vector<int>{x+1,x+2,x+3};
for(int j:rv)
{
assert(c[j]); --c[j];
for(int k=j;k--;) o[i][++cnt]=j;
}
}
vector<int> rv;
for(int i=x+1;i<=x+3;++i)
for(int j=c[i];j;--j) rv.push_back(i);
pair<vector<int>,vector<int>> s=solve2(rv,qq);
for(int i=p+1;i<=pp;++i)
{
int cnt=0;
for(auto j:(i==pp)?s.first:s.second)
{
assert(c[j]); --c[j];
for(int k=j;k--;) o[i][++cnt]=j;
}
}
p=pp; q=qq; x=xx;
}
}
else
{
int x=n%6,pp,qq;
dim(x,p,q);
brute(x,p,q,0);
while(n!=x)
{
int xx=x+6; dim(xx,pp,qq);
if(n%6==0)
assert(pp-p==1&&qq-q==24*x+90); //[1 2 3 4 5 6]*3+[2 3 5 5 6 6]
else if(n%6==2)
assert(pp-p==2&&qq-q==12*x+39); //[1 2 3 4 5 6]+[1 1 2 3 5 6]
else if(n%6==3)
assert(pp-p==2&&qq-q==12*x+45); //[1 2 3 4 5 6]+[1 2 4 5 6 6]
else if(n%6==5)
assert(pp-p==1&&qq-q==24*x+78); //[1 2 3 4 5 6]*3+[1 1 2 2 4 5]
else assert(0);
vector<int> uv;
if(n%6==0) uv=vector<int>{2,3,5,5,6,6};
else if(n%6==2) uv=vector<int>{1,1,2,3,5,6};
else if(n%6==3) uv=vector<int>{1,2,4,5,6,6};
else uv=vector<int>{1,1,2,2,4,5};
for(int j=1;j<4/(pp-p);++j)
for(int k=1;k<=6;++k) uv.push_back(k);
for(int i=x+1;i<=x+6;++i) c[i]=i;
for(int i=1;i<=p;++i)
{
int cnt=q;
for(auto j_:uv)
{
int j=j_+x;
assert(c[j]); --c[j];
for(int k=j;k--;) o[i][++cnt]=j;
}
}
vector<int> rv;
for(int i=x+1;i<=x+6;++i)
for(int j=c[i];j;--j) rv.push_back(i);
if(pp-p==2)
{
pair<vector<int>,vector<int>> s=solve2(rv,qq);
for(int i=p+1;i<=pp;++i)
{
int cnt=0;
for(auto j:(i==pp)?s.first:s.second)
{
assert(c[j]); --c[j];
for(int k=j;k--;) o[i][++cnt]=j;
}
}
}
else
{
int i=pp,cnt=0;
for(auto j:rv)
{
assert(c[j]); --c[j];
for(int k=j;k--;) o[i][++cnt]=j;
}
}
p=pp; q=qq; x=xx;
}
}
}
cerr<<p<<","<<q<<"\n";
for(int i=1;i<=p;++i,cout<<"\n")
for(int j=1;j<=q;++j)
cout<<setw(2)<<o[i][j]<<" ";
if(n>6)
{
for(int i=1;i<=n;++i) c[i]=i;
for(int i=1;i<=p;++i)
for(int j=1;j<=q;++j)
{
int u=o[i][j];
assert(u>=1&&u<=n);
for(int k=2;k<=u;++k)
assert(o[i][++j]==u);
--c[u];
}
for(int i=1;i<=n;++i) assert(!c[i]);
}
}
```
[Try it online!](https://tio.run/##xVdtc5s4EP5s/wolN/WZIGyDY@5akG/av@FjMpiQRDYGjBBmruPfnlu9YIODm7Y3nUvGgJZ9ebTaZyWiPLeeo@j19TeaRgl/jJG/piWbsvIxMs3Jy3LIGU2fURruYpaHUYzgjTesMvqIHuluTNMS1Riuo1xe98bw63AgpHwVkK81rk0bfnA94ozMvOHg8EKTeMxXWfDBMZBpZh4Sgylx4KVQQS2NeUdjDhosK8oxx9ycGx59Gtcf5oTYBjuEOVjMAsxXdmCAXk7E0NsTIbjjKyfwhsehAJat7NksWH0UfwGOmodn/aAnty54GcvppXJiqFI3jtdZlqBSzvMpK6QKJbZHfZJ6pkkNFK1oQChgAHygNwDFASfp3Tg1beNu7NyJ@9TFlZxyk5APlZhrJSRgly7JwkAV4VMp4VNSeeDYCSySEuKC7PgmfCXDq3hCzAjHUVrKrJ90N4ByswQDy9oYOtVsSTajUbTaBGAtzQfMIhuMLEsIPdQYb8nG21qWZ0ASabAyTXAfgAwsjhKRQGiScjTSIM8IuUeXhFv2aEQhtIDZgmR7GwUfIMHkbzKICgFOaGSVnUvjJlrVgchWLSIPBMoaUAqthNQewJaQdGYTyxJ4wbnwSWqFVtUCmzXLz@zT@k@nTzR9RCFifM1iKJgneD7Q8gUEO7SG9888LMK0jGOoE0QZegmTJ6n2OxM6XY1QaERZyuKIl7SKh3lIC7@KozIrfACxxK3nJWJZUsXOuCVDoSg9tFbUgvSEE0b/iceGgYq45EWKduE2fhBuxyEORfUL/QOZYQa/kJHGoLMiM6iZkOmaGUAmqGkHRNwDM4QLFlJbS20lDZllWzQ40fjgN65HIwbvD4FP1tKdSWBkmkI1ZCwG0h5uyFn5sJy10SSAJvEPACZpFXBBDhAu8fQwF@CSwAQwRaB5ki/XhkhuSVMeN4p7srZyrXAzDsHGJ/vRaO8TOYPCghYhQA7ahmLVCwZQMEpCuBcY7Scgby/EZ/yly6UZFG6i6vbzJOfs5WEdRlsIuZFNaNAW7o2urUAC5nIJrtmftROpChZC@cSLJ6lKyN6ASVu2rPo4YTH60ucNCDp4UzEwJ0O1E71OYmEUO3YhTcenhp7iHO9BM6Lpcpme1xVa1dxQ3S71iWvo1inVsS3eCER6VUFHdewutUGIc9DfyxmIjaUW5hL1QPmTAjwzWsxOb0gt11F6ghWEbWYymdTmXI6l65rA0JN7VV2rGMpFAx82wJwQB8pjb@0Jqe/mpqs1zlwBx6LDClfdFq/D7ApST91LK2mTNwxrYEoD0ZfVZLsVVlRaCJkC410BHK9IS@NrbTpY/45aV674GzVbq80btVMxfSoqBahB1ORCbgFe0/b1u@9o/gNVW821b0JXc3mBjYjUehu1PRVVq4ypXpV32ifRDbSozkt9Dp6r4Pn1VZm1shXyMoN0jSkBC@MvNpEt4hObQC/P0sdfmsRcgARWAyeAILXa6o6axYpRXQa5/51BJ8a4vYyR7HUJmemJdxhkNwxy7u9q8yOEQdPpykYOmqN7tEBuAMxaidFCjGA8PNVu49jpc3yipu2A4/nHt45NGKnxotft/H2394t@t4567nW7eD8Nf/zZnwaFVzpvOW414Esa8epyCUDUIbyD53gB/y52NeEvUntpYGMbK6Neg3mPgYPv30bodSs1j132qXPe/VRmymg2sg45bG8LWwi82oroLfJvr7dk921L/uEWfCb7wyd@2RwV9s2DPm7@X@3S/bl2KQ5JquA7GfiJLvrtNtpJV7uR/kAnPfn4Zoa/M8U6u51U677ZqQOYTY6vdP5fvFF@q8eLr6m4KHw/9/1bfOv7e7j/nd56w97yxlHGS6XR8221P7FNqcFnzWHsGL4vEW4CMES3@gy3dPUR/J2v2@ssuxr8vMtwoiN3zmJ8Kfonh1gXdN/CpzJ0Bi47Q6fr6hSLQzDXRmJVeHDKZf80tPmNmI46/x5fX@3Zvw "C++ (gcc) – Try It Online")
---
# How does the construction work?
It's an incremental construction. Consider \$n \bmod 6\$, we can have these values for height and width of rectangles:
* \$n/6\times (n+1)(2n+1)~(n\bmod 6=0)\$
* \$(2n+1)/3\times n(n+1)/2~(n\bmod 6=1)\$
* \$(n+1)/3\times n(2n+1)/2~(n\bmod 6=2)\$
* \$n/3\times (n+1)(2n+1)/2~(n\bmod 6=3)\$
* \$(2n+1)/3\times (n+1)n/2~(n\bmod 6=4)\$
* \$(n+1)/6\times n(2n+1)~(n\bmod 6=5)\$
(dimensions might be \$1\$ for \$n\leq 6\$ so these small cases are handled manually)
So the main idea of my construction is:
* We construct rectangles with the heights and widths as in above list.
* If \$n\bmod 3 \neq 1\$, construct the solution for \$n-6\$ recursively, add in \$n-5,n-4\cdots n\$. The height of the rectangle will only increase 1 or 2.
* If \$n\bmod 3=1\$, construct the solution for \$n-3\$ recursively and add in \$n-2,n-1,n\$. The height of the rectangle will only increase 2.
* We first carefully assign the new numbers to the added columns, and then put rest of the numbers into one or two added rows.
The rest of the job is some careful casework to pick the numbers. These details are left as an exercise to the readers (Be ready for some long and tedious casework!). If you complete all the details, this should become a formal proof for the existence of the solutions (and using only horizontal tiles!).
[Answer]
# JavaScript (ES6), 188 bytes
A shorter version inspired by [@newbie's answer](https://codegolf.stackexchange.com/a/203451/58563).
```
f=(n,w=2)=>(g=(h,a,m,r=[])=>h%1||r[w]?1:r[w-1]?--h*g(h,a,M=[...m,r]):a.every((_,j,[...a])=>a[j]++>j++||g(h,a,m,[...r,...Array(j).fill(j)])))(n*(~n-n)*~n/6/w,Array(n).fill(0),[])?f(n,w+1):M
```
[Try it online!](https://tio.run/##XU5LboMwEN3nFLOpmMHGKa2UBalBPUBOQFFlJfwsMo6cKigqzdWpSbPqZt7o/fSsuZjz3venr4TdoZ7nRiPLUb@QzrHV2Ekjj9LrsgpE95ROky/HqkizAElaFUnSxe3dtdOlUip4K8qMqi@1vyJ@SisX2ixxU9pKiNwKMU3to3kRvQzn3XtzRUuq6YchYEVEyDHeOGGKb7zerEf5Z@KH6ZlkmFU0y2CRUrabG@eRQcPrFhjeNGwCCkHwvQLYOz67oVaDazFiHYEApu0/oVnKj@aEHnQOXlnXM0YQET3eD44oJO@4@pl/AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, w = 2 // n = input, w = width of matrix
) => ( //
g = ( // g is a recursive function taking:
h, a, // h = height of matrix, a[] = array of counters
m, r = [] // m[] = matrix, r[] = current row
) => // (g returns 0 for success or 1 for failure)
h % 1 || // if h is not an integer or
r[w] ? // the length of r[] is w + 1 (i.e. r[] is too long):
1 // abort
: // else:
r[w - 1] ? // if the length of r[] is w:
--h * // decrement h and force success if h = 0
g( // do a recursive call with:
h, a, // h and a[] unchanged
M = [...m, r] // a new matrix M[] with r[] appended
) // end of recursive call
: // else:
a.every((_, j, [...a]) => // for each entry at position j in a[]:
a[j]++ > j++ || // unless a[j] is greater than j,
g( // do a recursive call with:
h, a, m, // h, a[] and m[] unchanged
[ ...r, // j added j times to the current row
...Array(j).fill(j) // NB1: both j and a[j] where incremented above
] // NB2: a[] is a local copy defined in this loop
) // end of recursive call
) // end of every()
)( // initial call to g with:
n * (~n - n) * ~n / 6 / w, // h = n(n+1)(2n+1) / 6 / w
Array(n).fill(0), // a[] initialized to n 0's
[] // an empty matrix
) ? f(n, w + 1) : M // return M[] on success, or try again with w + 1
```
---
# JavaScript (ES6), ~~297~~ 287 bytes
A brute-force search, which always try to put the biggest available rectangles first.
```
f=(n,i=2,k=n*(~n-n)*~n/6,A=n=>n?[0,...A(n-1)]:[])=>k%i||!(g=(m,a,x,y=m.findIndex(r=>r.some(v=>!v*~++x,x=-1)))=>~y?a.some((v,j)=>[0,1].some(r=>v<(o=n-j)&o<=(r?i-y:k/i-x)&&g(M=m.map(r=>[...r]),b=[...a],b[(h=p=>p--?h(p,M[y+r*p][x+!r*p]=o):j)(o)]++))):1)(A(i).map(_=>A(k/i)),A(n))?f(n,i+1):M
```
[Try it online!](https://tio.run/##PVDBboJAEL37FeuhOiMLlpp4oA6EYw@eeqSkQUVclFmyGgKp5dfpoklP72Vm3nszU2ZNdt0bVd9c1od8GI4ELBW9yTPxAnp2GRc9L9cyJqaQo@RVep4XA7s@pkGSIoXnF3W/T6EgqGQmW9lR5R0VHz74kLdgKDTeVVc5NBROm0XvOK1sycrRavsuyp5daGRpC9bfT58Vq2w2oIndEmd6Q2Ai5XbBeancFmezArY2qMrqcTCxS5kU5Y5GlqVyl8CJagpr141OUMtt0jlmUadJ60xHJI1BiaAxdRy7SeAjxKDw4fdNYQw2BlHaQxGj4/gTx8dgOxy1ARYkVu@CxUb4rxatg/iZCLHXfNWX3LvoAqzkaWYEhcI8KI@UvZv@vBnFBazWiF6pFcN8/s@@eI7CEQ@c/A5/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 148 bytes
finds random matrix with only horizontal tiles.
It is very slow for n>5 but this is code-golf...
```
(While@!MatrixQ[Join@@@(w=TakeList[d=RandomSample@Flatten[Table[#~Table~#,#]&/@Range@#,1],r=RandomChoice@IntegerPartitions[#(#+1)/2][[2;;-2]]])];w)&
```
[Try it online!](https://tio.run/##LY7NCoJAFEZfpRgQJUMUWokwEARFgf1Ai2EWN72Ml3SM8YKtfPVJqtXZnPPxdcANdsBUgTeFD@8NtSiXJ2BH77M69GSllOFY3OCJRxpY1cUFbN13V@hes7prgRmtusGjRSWmLycRCx0kcjYNShGnOnb/bNv0VKHcW0aDrgTHxNTbQYlQrNIoybRSWZ6vM611pPMxCnzpyHIiw98ZMe8ujNroyPsP "Wolfram Language (Mathematica) – Try It Online")
here is also a very quick random generator for test cases up to 6
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 97 bytes
```
(While@!MatrixQ[Join@@@(w=Partition[RandomSample@Flatten[Table[#~Table~#,#]&/@Range@#,1],3])];w)&
```
[Try it online!](https://tio.run/##JY29CsIwFEZfRRsoLQ0UEVxq4E4dBKH@gEPIcNXQXmgSCRfq1FePpU5n@M7HcciDdcj0wtSrVDwGGi1sz8iRvhd9CuQBoJhUh5GJKXh9Rf8O7obus5jtiMzW6zs@R6vFvHIWUpi8hsXsLQi5M3JvStNMZZ7aEDWpvaSjOkiqKtlF8lxD8U@J5bbpNZmyWQfIMpPSDw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Let's say you have some text, and you want it to send it to your friend, but you don't want anyone else to read it. That probably means you want to encrypt it so that only you and your friend can read it. But, there is a problem: you and your friend forgot to agree on an encryption method, so if you send them a message, they won't be able to decrypt it!
After thinking about this for a while, you decide to just send your friend the code to encrypt your message along with the message. Your friend is very smart, so they can probably figure out how to decrypt the message by studying the encryption method.
Of course, since other people might be reading the message, you want to choose an encryption scheme that makes it as hard as possible to crack (figure out the decryption scheme).
# Cops' Task
In this challenge, Cops will play the role of the writer: you will design an encryption scheme that converts strings to strings. However, this encryption scheme *must be **bijective***, meaning that no two strings must map to another string, and every string can be mapped to by an input. It must take only one input—the string to be encoded.
You will then post some code that performs the encryption, and a single message encrypted with the scheme detailed by your code.
Since you are paying by the byte to send messages, your score will be the length of your code *plus the length of the ciphertext*. If your answer is cracked, you will have a score of infinity.
After one week, you may reveal the text and mark your answer as **Safe**. Safe answers are those that cannot be cracked.
# Robbers' Task
Robbers will play either as the friend of the writer or the malicious middle man (there is no material difference, but you can role-play as either if it makes it more fun to do so). They will take the encryption schemes and the ciphertext and attempt to figure out the encrypted message. Once they figure out the encrypted message, they will post it in a comment. (There will not be a separate robbers' thread for this question.)
The winner will be the robber with the most cracks.
---
Here is an example of what a cracked solution might look like:
[](https://i.stack.imgur.com/8zESm.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 57 + 32 = 89 bytes ([cracked](https://codegolf.stackexchange.com/questions/133417/codebreakers-and-codewriters/133436?noredirect=1#comment327537_133436))
```
“¡ḟċ⁷Ḣṡ⁵ĊnɠñḂƇLƒg⁺QfȥẒṾ⁹+=?JṚWġ%Aȧ’
O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ
```
Encrypted message:
```
EªæBsÊ$ʳ¢?r×Q4e²?ò[Ý6
```
As a hex-string:
```
4518AAE6421973CA
9724CAB3A23F72D7
AD18855134651810
B23F1CF25BDD9036
```
Explanation:
```
O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ
O convert each into codepoint
‘ḅ256 convert from bijective base 256 to integer
b¢ convert from integer to base N
*21 map each to its 21th power
%¢ modulo N
ḅ¢ convert to integer from base N
ḃ256’ convert from integer to bijective base 256
Ọ convert each from codepoint
```
Where `N` is encoded by the string `“¡ḟċ⁷Ḣṡ⁵ĊnɠñḂƇLƒg⁺QfȥẒṾ⁹+=?JṚWġ%Aȧ’`, which is the number `105587021056759938494595233483151378724567978408381355454441180598980268016731`.
Also, this is the RSA method with `N` given above and public key `21`. Cracking this is equivalent to finding the two prime factors of `N`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 88 + 64 = 152 bytes
Encryption function:
```
“¥@ɦ⁺€€Ṅ`yȤDƁWĊ;Y^y⁻U ⁸ßɠƁXẹṡWZc'µ÷ḷỊ0ÇtṙA×Ḃß4©qV)iḷỊDƭ Mṛ+<ṛ_idðD’
O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ
```
Encrypted message:
```
AX!?ÖÍL¹ JÓ°û0àah4Û{µÌá`
^tÝrRÕù#êwðãTÓK"Íû´Ëß!øòOf«
```
As a hex-string:
```
9F419458213FD6CD4CB9094A10D3B0FB
8F30E0616834DB7BB517CCE1600A5E74
DD7252D5F923EA77F0E354D34B9F22CD
FB80B4CBDF21F80E94F24F9A66AB9112
```
Explanation:
```
O‘ḅ256b¢*13%¢ḅ¢ḃ256’Ọ
O convert each into codepoint
‘ḅ256 convert from bijective base 256 to integer
b¢ convert from integer to base N
*13 map each to its 13th power
%¢ modulo N
ḅ¢ convert to integer from base N
ḃ256’ convert from integer to bijective base 256
Ọ convert each from codepoint
```
Where `N` is encoded by the string:
```
“¥@ɦ⁺€€Ṅ`yȤDƁWĊ;Y^y⁻U ⁸ßɠƁXẹṡWZc'µ÷ḷỊ0ÇtṙA×Ḃß4©qV)iḷỊDƭ Mṛ+<ṛ_idðD’
```
which is the number
```
15465347049748408180402050551405372385300458901874153987195606642192077081674726470827949979631079014102900173229117045997489671500506945449681040725068819
```
Also, this is the RSA method with `N` given above and public key `13`. Cracking this is equivalent to finding the two prime factors of `N`, which has 512 bits.
[Answer]
## JavaScript (ES6), 43 + 33 = 76 bytes [Cracked by Leaky Nun](https://codegolf.stackexchange.com/questions/133417/codebreakers-and-codewriters#comment327390_133425)
Encryption function, 43 bytes:
```
s=>[...s].sort(_=>Math.cos(i++),i=0).join``
```
Encrypted message, 33 bytes:
*NB: This encryption method is browser-dependent.*
```
FireFox: "ty a)s kaasoeocr!hTt; o s -cwaoo"
Chrome : "oht aasoaoas e)tosr;oky c!-cw T"
Edge : "tskso ;- caroteoTha wa soo ay c!)"
```
[Answer]
# Braingolf, Cracked
```
(d1&,&g)&@
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/9fI8VQTUctXVPN4f///x6pOTn5Ogrh@UU5KYoA "Braingolf – Try It Online")
## Encrypted message, 45 bytes (UTF-8)
```
°Áݭїϳ{ًչםק{їϳэÁק{|э³קѡ|
```
## Hexcodes of encrypted message
```
C2 B0 C3 81 DD AD D1 97 CF
B3 C2 90 7B D9 8B D5 B9 D7
9D D7 A7 7B D1 97 CF B3 D1
8D C3 81 D7 A7 7B 7C D1 8D
C2 B3 D7 A7 D1 A1 7C C2 85
```
## Decrypted message
```
C'mon, this one's *easy*!
```
## Explanation
```
(d1&,&g)&@ Implicit input from commandline args
(......) Foreach loop, foreach codepoint of input
d Split into digits
1 Push 1
&, Reverse
&g Concatenate
&@ Print
```
## Decoder
A decoder can be made by changing only 3 characters. Simply remove the `1`, and insert `$_` inbetween `&,` and `&g`
```
(d&,$_&g)&@
```
[Answer]
# JavaScript (ES6), 96+9=105 bytes
```
q=>Buffer(q).map((a,i,d)=>d[i-1]^Math.abs(1e16*Math.sin(d[i]+i))%255).sort((a,i)=>Math.tan(a*i))
```
Ciphertext (hex-encoded): `7d111c74b99faff76a`
[Try it online!](https://tio.run/##HYtBCsIwEAD/UhB2axOIUG/twZMXXyAVNs1WIzFpk@j3Y@hxmJk3/SjN0a5ZaNLshA@GS5mDT8GxdOEJsA3j5bssHGFD@aEVgDrbGRxGc7dCTY8b5ZcknUCxOrc7Jeuh2uloEQ@nvkeZQsz7Wb89yeSB2uoRmis7FxrEUv4 "JavaScript (Babel Node) – Try It Online")
### Sample outputs (using V8 engine):
abc123 -> db48ea4f86b9
Hello -> 1b3420f5ab
] |
[Question]
[
*Tangentially inspired by the opening to the What-If book.*
The input is a rectangle of spaces as a string, list of string, etc., with objects made of `#`'s inside:
```
########
# #
########
### ####
### ####
###
```
The objects will always be non-intersecting, non-touching, rectangles. A soft object is defined as an object that isn't filled up with `#`'s in the middle and is only a border, a hard object is one that is filled up. An object with width or height `<=2` is considered hard. All objects are either hard or soft.
If there are more hard objects in the input, output `"Hard"`, if more soft, output `"Soft"`, if they are equal, output `"Equal"`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
# Test Cases
**These cases aren't full inputs, but rather what each object should be characterized as.** The actual input will be like the ascii-art at the top of the question.
## Hard
```
#
####
##
##
##########
##########
##########
```
## Soft
```
###
# #
###
###################
# #
# #
# #
###################
####
# #
# #
# #
# #
# #
# #
# #
####
```
## Actual Test Cases
```
########
# #
########
### ####
### ####
###
Hard
###
###
###
###################
# #
# #
# #
###################
Equal
######
# #
######
###
## # # #
###
########
# #
########
Soft
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~105~~ ~~104~~ ~~58~~ ~~50~~ 49 bytes
*Thanks to @Neil for a suggestion that allowed me to remove 46 bytes!*
```
2\TTYaEq4:HeqgEqZ+K/Zot0>+ss'Soft Hard Equal'Ybw)
```
Input is a 2D char array, with rows separated by `;`. The example in the challenge is
```
['######## ';'# # ';'######## ';' ';' ### ####';' ### ####';' ### ']
```
Here's another example:
```
['### ';'### ';'### ';' ';'###################';'# #';'# #';'# #';'###################']
```
This corresponds to
```
###
###
###
###################
# #
# #
# #
###################
```
and thus should give `'Equal'`.
As a third example, corresponding to `'Soft'`,
```
[' ###### ';' # # ';' ###### ';' ###';' ## # # #';' ###';' ';' ';' ######## ';' # # ';' ######## ']
```
that is,
```
######
# #
######
###
## # # #
###
########
# #
########
```
[**Try it online!**](http://matl.tryitonline.net/#code=MlxUVFlhRXE0OkhlcWdFcVorSy9ab3QwPitzcydTb2Z0IEhhcmQgRXF1YWwnWWJ3KQ&input=WycjIyMjIyMjIyAgICAgICAgICAnOycjICAgICAgIyAgICAgICAgICAnOycjIyMjIyMjIyAgICAgICAgICAnOycgICAgICAgICAgICAgICAgICAnOycgICAjIyMgICAgICAgICMjIyMnOycgICAjIyMgICAgICAgICMjIyMnOycgICAjIyMgICAgICAgICAgICAnXQ)
### Explanation
This uses 2D convolution to detect shapes. The input is converted to a 2D array with `1` indicating `#` and `-1` for space; and is padded with a frame of `-1` values. This assures that shapes at the edge of the original field are also detected.
A *soft object* is detected by the mask
```
1 1
1 -1
```
which corresponds to the object's upper-left corner with one empty interior point. Note that the convolution inverts the mask, so it is defined as `[-1 1; 1 1]` in the code. The number *S* of positions in which the convolution equals `4` is the total number of soft objects.
An *object* (soft or hard) is detected by the mask
```
-1 -1
-1 1
```
which correponds to the object's upper-left corner together with some empty exterior points. This mask is the negated version of the previous one, so the previous convolution result can be reused. Specifically, the number *T* of positions in which that result equals `-4` is the total number of objects.
The number *H* of hard objects is *T*−*S*. The output string is determined by the sign of *S*−*H* = 2\**S*−*T*.
```
2\ % Input. Modulo 2: '#' gives 1, ' ' gives 0
TTYa % Add a frame of zeros
Eq % Convert 0 to -1
4:HeqgEq % Generate mask [-1 1; 1 1], for soft objects
Z+ % 2D convolution, preserving size
K/Zo % Divide by 4 and round towards 0. Gives 1 or -1 for 4 or -4
t0> % Duplicate. 1 for positive entries (soft objects), 0 otherwise
+ % Add. This corresponds to the factor 2 that multiplies number S
ss % Sum of 2D array. Gives 2*S-T
'Soft Hard Equal' % Push this string
Yb % Split by spaces. Gives cell array
w) % Swap. Apply (modular) index to select one string
```
[Answer]
# JavaScript (ES6), ~~123~~ ~~121~~ 118 bytes
```
s=>s.replace(/#+/g,(m,i)=>s[i+l]>" "?0:n+=!m[1]|s[i-l+1]==s[i-l]||-1,n=l=~s.search`
|$`)|n>l?"Hard":n<l?"Soft":"Equal"
```
*Saved 2 bytes thanks to @edc65!*
Takes input as a multiline string padded with spaces to form a grid.
## Explanation / Test
~~Very close to MATL length!~~ Basically, it searches for the top line of `#`s of each object, and if the length of the top line is less than 2 or the first 2 characters below the top line are the same, it is hard, otherwise soft.
```
var solution =
s=>
s.replace(/#+/g,(m,i)=> // for each run of consecutive # characters
s[i+l]>" "? // if the position above the match contains a #
0 // do nothing (this object has already been counted)
:n+= // add 1 to the counter (hard) if
!m[1] // the match is only 1 # wide
|s[i-l+1]==s[i-l] // or the characters below are the same
||-1, // else decrement the counter (soft)
n= // n = counter, hard objects increase n, soft decrease
l=~s.search`\n|$` // l = (negative) line length
)
|n>l?"Hard":n<l?"Soft":"Equal" // return the result string
// Test
document.write("<pre>" + [`
########
# #
########
### ####
### ####
###
`,`
###
###
###
###################
# #
# #
# #
###################
`,`
######
# #
######
###
## # # #
###
########
# #
########
`,`
########
# #
########
### ####
# # ####
###
`,`
########
# #
########
### ### ####
### # # ####
### ###
`,`
#
`,`
##
`,`
#
#
`,`
###
# #
###
`].map((test) => solution(test.slice(2, -2))).join("\n")
)
```
[Answer]
# Jelly, ~~50~~ ~~49~~ ~~46~~ ~~43~~ ~~38~~ ~~34~~ ~~33~~ 32 bytes
```
Ḥ+ḊZ
>⁶ÇÇFµċ7_ċ4$Ṡị“¤Ỵf“¢*ɦ“¡⁺ƒ»
```
[Try it online!](http://jelly.tryitonline.net/#code=4bikK-G4iloKPuKBtsOHw4dGwrXEizdfxIs0JOG5oOG7i-KAnMKk4bu0ZuKAnMKiKsmm4oCcwqHigbrGksK7&input=&args=WycjIyMjIyMjIyAgICAgICAgICAnLCAnIyAgICAgICMgICAgICAgICAgJywgJyMjIyMjIyMjICAgICAgICAgICcsICcgICAgICAgICAgICAgICAgICAnLCAnICAgIyMjICAgICAgICAjIyMjJywgJyAgICMjIyAgICAgICAgIyMjIycsICcgICAjIyMgICAgICAgICAgICAnXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=4bikK-G4iloKPuKBtsOHw4dGwrXEizdfxIs0JOG5oOG7i-KAnMKk4bu0ZuKAnMKiKsmm4oCcwqHigbrGksK7CsOH4oKsauKBtw&input=&args=WwogWycjIyMjIyMjIyAgICAgICAgICAnLAogICcjICAgICAgIyAgICAgICAgICAnLAogICcjIyMjIyMjIyAgICAgICAgICAnLAogICcgICAgICAgICAgICAgICAgICAnLAogICcgICAjIyMgICAgICAgICMjIyMnLAogICcgICAjIyMgICAgICAgICMjIyMnLAogICcgICAjIyMgICAgICAgICAgICAnXSwKCiBbJyMjIyAgICAgICAgICAgICAgICAnLAogICcjIyMgICAgICAgICAgICAgICAgJywKICAnIyMjICAgICAgICAgICAgICAgICcsCiAgJyAgICAgICAgICAgICAgICAgICAnLAogICcjIyMjIyMjIyMjIyMjIyMjIyMjJywKICAnIyAgICAgICAgICAgICAgICAgIycsCiAgJyMgICAgICAgICAgICAgICAgICMnLAogICcjICAgICAgICAgICAgICAgICAjJywKICAnIyMjIyMjIyMjIyMjIyMjIyMjIyddLAoKIFsnICAgIyMjIyMjICAgICcsCiAgJyAgICMgICAgIyAgICAnLAogICcgICAjIyMjIyMgICAgJywKICAnICAgICAgICAgICMjIycsCiAgJyAgICMjICAjICAjICMnLAogICcgICAgICAgICAgIyMjJywKICAnICAgICAgICAgICAgICcsCiAgJyAgICAgICAgICAgICAnLAogICcgIyMjIyMjIyMgICAgJywKICAnICMgICAgICAjICAgICcsCiAgJyAjIyMjIyMjIyAgICAnXQpd).
### Background
There are **16** different **2×2** patterns of blocks and spaces:
```
| | | | #| | #| #|# | #|# |# |##|# |##|##|##|
| | #|# | |##| #|# | |##| #|# | |##| #|# |##|
```
Of these, since two objects will never touch,
```
| #|# |
|# | #|
```
will never occur in the input, leaving us with **14** possible patterns.
Assigning a value of **0** and `#` a value of **1**, we can encode a **2×2** pattern
```
|ab|
|cd|
```
as **2(2a + c) + (2b + d) = 4a + 2b + 2c + d**, leaving the following values for the **14** patterns.
```
| | | | #| | #|# | #|# |##|# |##|##|##|
| | #|# | |##| #| |##|# | |##| #|# |##|
0 1 2 2 3 3 4 5 6 6 7 7 8 9
```
For partial **2×1**, **1×2** or **1×1** patterns at the lower and/or right border, we'll treat them as if the were padded with spaces, encoding them as **4a + 2b**, **4a + 2c** and **4a**, respectively.
This way, each object (soft or hard) will have exactly one **4** pattern (its lower right corner); each soft object will have exactly two **7** patterns (its lower left and its upper right corner).
Thus, subtracting the amount of **4** patterns from the number of **7** patterns encountered in the input will yield **(s + h) - 2s = h - s := d**, where **h** and **s** are the amount of hard and soft objects they form.
We print *Hard* if **d > 0**, *Soft* if **d < 0** and *Equal* if **d = 0**.
### How it works
```
Ḥ+ḊZ Helper link. Input: M (n×m matrix)
Ḥ Unhalve; multiply all entries of M by 2.
Ḋ Dequeue; remove the first row of M.
+ Perform vectorized addition.
This returns 2 * M[i] + M[i + 1] for each row M[i].
Since the M[n] is unpaired, + will not affect it,
as if M[n + 1] were a zero vector.
Z Zip; transpose rows with columns.
>⁶ÇÇFµċ7_ċ4$Ṡị“¤Ỵf“¢*ɦ“¡⁺ƒ» Main link. Input: G (character grid)
>⁶ Compare each character with ' ', yielding 1 for '#'
and 0 for ' '.
Ç Call the helper link.
This will compute (2a + c) for each pattern, which is
equal to (2b + d) for the pattern to its left.
Ç This yields 2(2a + c) + (2b + d) for each pattern.
F Flatten; collect all encoded patterns in a flat list.
µ Begin a new, monadic link. Argument: A (list)
ċ7 Count the amount of 7's.
ċ4$ Count the amount of 4's.
_ Subtract the latter from the former.
Ṡ Yield the sign (1, -1 or 0) of the difference.
“¤Ỵf“¢*ɦ“¡⁺ƒ» Yield ['Hard', 'Soft', Equal'] by indexing into a
built-in dictionary.
ị Retrieve the string at the corresponding index.
```
[Answer]
# Julia, ~~99~~ ~~95~~ 93 bytes
```
~=t->2t'+[t[2:end,:];0t[1,:]]'
!x=("Hard","Equal","Soft")[sign(~~(x.>32)∩(4,7)-5.5|>sum)+2]
```
`!` expects a two-dimensional Char array as argument. [Try it online!](http://julia.tryitonline.net/#code=fj10LT4ydCcrW3RbMjplbmQsOl07MHRbMSw6XV0nCiF4PSgiSGFyZCIsIkVxdWFsIiwiU29mdCIpW3NpZ24ofn4oeC4-MzIp4oipKDQsNyktNS41fD5zdW0pKzJdCgpmb3IgeCBpbiAoCgpbJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJwogJyMnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnIycgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJwogJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJwogJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJwogJyAnICAnICcgICcgJyAgJyMnICAnIycgICcjJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcjJyAgJyMnICAnIycgICcjJwogJyAnICAnICcgICcgJyAgJyMnICAnIycgICcjJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcjJyAgJyMnICAnIycgICcjJwogJyAnICAnICcgICcgJyAgJyMnICAnIycgICcjJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJ10sCgpbJyMnICAnIycgICcjJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnCiAnIycgICcjJyAgJyMnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcKICcjJyAgJyMnICAnIycgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJwogJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnCiAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycKICcjJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcjJwogJyMnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyMnCiAnIycgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnIycKICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJ10sCgpbJyAnICAnICcgICcgJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyAnICAnICcgICcgJyAgJyAnCiAnICcgICcgJyAgJyAnICAnIycgICcgJyAgJyAnICAnICcgICcgJyAgJyMnICAnICcgICcgJyAgJyAnICAnICcKICcgJyAgJyAnICAnICcgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcgJyAgJyAnICAnICcgICcgJwogJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnIycgICcjJyAgJyMnCiAnICcgICcgJyAgJyAnICAnIycgICcjJyAgJyAnICAnICcgICcjJyAgJyAnICAnICcgICcjJyAgJyAnICAnIycKICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyMnICAnIycgICcjJwogJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnCiAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcKICcgJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcgJyAgJyAnICAnICcgICcgJwogJyAnICAnIycgICcgJyAgJyAnICAnICcgICcgJyAgJyAnICAnICcgICcjJyAgJyAnICAnICcgICcgJyAgJyAnCiAnICcgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnIycgICcjJyAgJyMnICAnICcgICcgJyAgJyAnICAnICddCgopCiAgICBwcmludGxuKCF4KQplbmQ)
### How it works
This uses almost exactly the same idea as [my Jelly answer](https://codegolf.stackexchange.com/a/78055), with one improvement:
Instead of counting the amount of **4**'s and **7**'s, we remove all other numbers, then subtract **5.5** to map **(4, 7)** to **(-1.5, 1.5)**. This way, the sign of the sum of the resulting differences determines the correct output.
[Answer]
# TSQL, ~~328~~ 249 bytes
Declaring variables and test data:
```
DECLARE @l int = 20
DECLARE @ varchar(max)=''
SELECT @+=LEFT(x + replicate(' ', @l), @l)
FROM (values
(' xxxx'),
(' xxxx'),
(' xxxx'),
('x'),
(''),
('xxx'),
('x x xxx'),
('xxx x x'),
(' xxx ')) x(x)
```
Code:
```
SELECT substring('Soft EqualHard',sign(sum(iif(substring(@,N,@l+2)like'xx'+replicate('_', @l-2)+'x ',-1,1)))*5+6,5)FROM(SELECT row_number()OVER(ORDER BY Type)N FROM sys.all_objects)x WHERE n<=len(@)AND' x'=substring(@,N-1,2)AND''=substring(@,N-@l,1)
```
Code deflated:
```
SELECT
substring('Soft EqualHard',
sign(sum(iif(substring(@,N,@l+2)like'xx'+replicate('_', @l-2)+'x ',-1,1)))*5+6,5)
FROM(SELECT row_number()OVER(ORDER BY Type)N FROM sys.all_objects)x
WHERE n<=len(@)AND' x'=substring(@,N-1,2)AND''=substring(@,N-@l,1)
```
Explaination:
Script is scanning the text for the pattern:
```
space
space x
```
Each of those is the start of a box
For those positions, the script is then checking for the pattern, don't need to check for first x:
```
x
x space
```
When that exists it is a soft object, otherwise it is a hard object.
] |
[Question]
[
# Nuggets of Code
It's a hypothetical situation where it is Friday evening, and you've invited over the usual golfing buddies to participate in your favourite hobby: code golfing. However, as this is such a brain-draining task, you need to pick up some brain food for the group so you can golf as much as possible off your code.
Now, everyone's favourite snack is chicken nuggets, but there's a problem: There is no single pack of them which covers everyone's needs. So, since you're already in the golfing mood, you decide to create a program that figures out exactly what packs you must buy to be able to cover everyone's Nugget needs.
Chicken nugget pack sizes are all over the place, and depending on where you live in the world, the standard sizes change too. However, the closest *[place that serves nuggets]* stocks the following sizes of nugget packs:
`4, 6, 9, 10, 20, 40`
Now you may notice that you cannot order certain combinations of nuggets. For example, `11` nuggets is not possible, since there is no combination that equals `11` exactly. However, you can make `43` by getting 1 pack of `20`, 1 pack of `10`, 1 pack of `9` and 1 pack of `4`,
`20 + 10 + 9 + 4 = 43 (597)`
where `597` is each term squared and added together *(hint: the optimal solution has this as the highest value)*. There are of course other ways of making `43`, but as you know, the more nuggets per pack, the cheaper it gets per nugget. So, you want to ideally buy the least number of packs and in the greatest quantities to minimize your cost.
# The Task
You should create a *program* or *function* which takes a list of integers corresponding to each person's requirements. You should then calculate and *print* the most cost-efficientα order to buy the chicken nuggets. The most cost-efficientα order is the combination by which the sum of the squares of each quantity is the highest. If there is absolutely no way to buy the nuggets perfectly, you must *print* a falsy value such as `0`, `False`, `Impossible!`, or whatever is available in your language.
**Example I/O:**
```
[2 7 12 4 15 3] => [20 10 9 4]
1, 1, 2, 1 => False
6 5 5 5 5 5 9 => 40
[6, 4, 9] => 9 10
1 => 0
199 => 40, 40, 40, 40, 20, 10, 9
2 => Impossible!
```
[Here](https://gist.github.com/anonymous/e6f3576bfb3c4bb83837) is the list of ideal solutions for the first 400. Note these are not formatted how I would expect yours to be, each `tuple` is in the form `(N lots of M)`.
# Rules
1. [No standard loopholes.](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
2. No use of built-in functions that do all or the majority of the task, such as `FrobeniusSolve` in Mathematica.
---
α - To clarify this with an example, you could also make 43 by doing `4 + 6 + 6 + 9 + 9 + 9 = 43 (319)`, but this would not be optimal, and thus an incorrect output, as the sum of the squares is less than the combination I noted in the introduction. Essentially, higher sum of squares = lower cost = most cost-efficient.
[Answer]
# Pyth, ~~26~~ 25 bytes
```
e+Zo.aNf!-TCM"
("./sQ
```
Notice that there are some unprintable chars. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=e%2BZo.aNf!-TCM%22%14%09%0A%06%04(%22.%2FsQ&input=%5B1%2C2%2C11%5D&debug=0). It is quite slow (but not as slow as my 26 byte solution).
### Explanation:
```
implicit: Q = input list
sQ sum(Q)
./ generate all integer partitions
f filter for partitions T, which satisfy:
" (" string containing chars with the ASCII-values of 4,6,9,10,20,40
CM convert each char to the ASCII-value
-T remove this numbers from T
! and check, if the resulting list is empty
o order the remaining subsets N by:
.aN the vector length of N (sqrt of sum of squares)
+Z insert 0 at the beginning
e print the last element
```
# Pyth, 32 bytes
```
e+Zo.aNfqsTsQysm*]d/sQdCM"
(
```
Notice that there are some unprintable chars. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=e%2BZo.aNfqsTsQysm*%5Dd%2FsQdCM%22%14%09%0A%06%04(&input=%5B6%2C7%2C8%5D&debug=0)
This version is way faster. It finds the solution for the input `[6,7,8]` in about one second and the solution for the input `[30]` in about 90 seconds.
### Explanation:
```
implicit: Q = input list
"...( the string containing chars with the ASCII-values of 4,6,9,10,20,40
CM convert each char to the ASCII-value
m map each number d to:
]d create the list [d]
* /sQd and repeat it sum(Q)/d times
s unfold
y generate all subsets
f filter for subsets T, which satisfy:
qsTsQ sum(Q) == sum(T)
o order the remaining subsets N by:
.aN the vector length of N (sqrt of sum of squares)
+Z insert 0 at the beginning
e print the last element
```
[Answer]
## Perl, 175 153
```
sub f{my$n=$_[0];if(!$n){return 1;}foreach$o(40,20,9,10,6,4){if($n>=$o&&f($n-$o)){print"$o ";return 1;}}return 0;}$n+=$_ for@ARGV;if(!f($n)){print":(";}
```
Takes it's input from the program arguments. Prints a **:(** if it can't find a perfect solution.
### Ungolfed Code:
```
sub f
{
my $n = $_[0];
if(!$n)
{
return 1;
}
foreach $o(40,20,9,10,6,4)
{
if($n>=$o&&f($n-$o))
{
print "$o ";
return 1;
}
}
return 0;
}
$n += $_ for @ARGV;
if(!f($n))
{
print ":(";
}
```
P.S.: This is probably the first entry that doesn't take 10 minutes for `1 2` ;)
[Check it out here.](http://ideone.com/dIE9QK)
[Answer]
# CJam, ~~45~~ ~~29~~ 28 bytes
```
q~:+_[40K9A6Z)U]m*_::+@#=0-p
```
Note that this approach is *very* slow and memory-intensive.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%3A%2B_%5B40K9A6Z)U%5Dm*_%3A%3A%2B%40%23%3D0-p&input=%5B2%202%202%5D).
It can be sped up significantly at the cost of 5 bytes:
```
q~:+_40/4+[40K9A6Z)U]m*_::+@#=0-p
```
Complexity is still exponential in the sum of the input, but this should handle test cases up to 159 with the online interpreter and up to 199 with the Java interpreter in a couple of seconds.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%3A%2B_40%2F4%2B%5B40K9A6Z)U%5Dm*_%3A%3A%2B%40%23%3D0-p&input=%5B49%2049%5D).
### Idea
An optimal purchase (maximal sum of squares) is a valid purchase (correct number of nuggets) that has as many **40**'s as possible, then as many **20**'s as possible, then as many **9**'s as possible (e.g., `9 9` is preferable over `10 4 4`) and so forth for **10**'s, **6**'s and **4**'s.
In this approach, we generate the Cartesian product of **N** copies of the array **[40 20 9 10 6 4 0]**, where **N** is the desired number of nuggets. **N** is a (bad) upper bound for the number of purchases we have to make. In the sped up version of the code, we use **N/40 + 4** instead.
Because of how the array is ordered, the Cartesian product will start with the vector **[40 ... 40]** and end with the vector **[0 ... 0]**. We compute the index of the first vector that has the correct sum (which will also have the optimal sum of squares), retrieve the corresponding array element, remove the zeroes that served as placeholders and print the result.
If no vector could be found, the index will be **-1**, so we retrieve **[0 ... 0]**, which will print an empty array instead.
### Code
```
q~ e# Read from STDIN and evaluate the input.
:+ e# Push N, the sum of all elements of the resulting array.
[40K9A6Z)U] e# Push B := [40 20 9 10 6 4 0].
_ m* e# Push B**N, the array of all vectors of dimension N
e# and coordinates in B.
_::+ e# Copy and replace each vector by its sum.
@# e# Get the first index of N.
= e# Retrieve the corresponding element.
0-p e# Remove 0's and print.
```
[Answer]
# Julia, 126 bytes
```
r->(t=filter(i->all(j->j∈[4,6,9,10,20,40],i),partitions(sum(r)));show(!isempty(t)&&collect(t)[indmax(map(k->sum(k.^2),t))]))
```
This creates an unnamed function that accepts an array as input and prints an array or boolean to STDOUT, depending on whether a solution exists. To call it, give it a name, e.g. `f=n->...`.
Ungolfed + explanation:
```
function f(r)
# Nugget pack sizes
packs = [4, 6, 9, 10, 20, 40]
# Filter the set of arrays which sum to the required number of nuggets
# to those for which each element is a nugget pack
t = filter(i -> all(j -> j ∈ packs, i), partitions(sum(r)))
# Print the boolean false if t is empty, otherwise print the array of
# necessary nugget packs for which the sum of squares is maximal
show(!isempty(t) && collect(t)[indmax(map(k -> sum(k.^2), t))])
end
```
Examples:
```
julia> f([1])
false
julia> f([2,7,12,4,15,3])
[20,10,9,4]
```
[Answer]
# Python 3 - 265 characters
```
import itertools as i
n=list(map(int,input().split(',')));m=[]
for f in range(1,9):
for j in range(6*f):
for x in i.combinations((4,6,9,10,20,40,)*f,j+1):
if sum(n)==sum(x):m.append(x)
if m!=[]:v=[sum(l**2for l in q)for q in m];print(m[v.index(max(v))])
else:print(0)
```
Showing spacing:
```
import itertools as i
n=list(map(int,input().split(',')));m=[]
for f in range(1,5):
for j in range(6*f):
\tfor x in i.combinations((4,6,9,10,20,40,)*f,j+1):
\t if sum(n)==sum(x):m.append(x)
\t\tif m!=[]:v=[sum(l**2for l in q)for q in m];print(m[v.index(max(v))])
else:print(0)
```
Passes all test cases
**Note:** I don't know if this will pass all cases because it is so slow... But it *should*...
[Answer]
# JavaScript, ~~261~~ ~~256~~ 261
```
d="length";function g(a){for(z=y=0;y<a[d];z+=+a[y++]);return z}x=[40,20,10,9,6,4];l=prompt().split(",");o=g(l);p=[];for(i=0;i<x[d];i++)r=g(p),s=r+x[i],(s<o-3||s==o)&&p.push(x[i]),(i==x[d]-1||40<o-r)&&r+x[i]<o-3&&(i=-1,0==i||o-r<p[p[d]-1]&&p.pop());g(p)==o&&p||0
```
I'm not sure if this is alright, it seems to work but I'm surely missing things.
It doesn't seem to be slow though, up to `123456` it outputs `[40 x 3086, 10, 6]` almost immediatly.
Explanation:
Iterating over the nugget sizes (biggest first)
* If the sum of the stack plus the nugget size is less than the goal - 3 -> push it on a stack
* If there is more than 40 left -> reset the loop counter
* If the sum of the stack is more than the goal when the last nugget-size was reached -> pop the last element, reset the loop counter
* If the sum of the stack adds up, return it, otherwise return 0
For 199 | 1 the stack built looks like this
```
i | stack
0 [40]
0 [40, 40]
0 [40, 40, 40]
0 [40, 40, 40, 40]
0 [40, 40, 40, 40]
1 [40, 40, 40, 40, 20]
2 [40, 40, 40, 40, 20, 10]
3 [40, 40, 40, 40, 20, 10, 9]
4 [40, 40, 40, 40, 20, 10, 9]
5 [40, 40, 40, 40, 20, 10, 9]
==> [40, 40, 40, 40, 20, 10, 9]
```
For 1
```
i | stack
0 []
1 []
2 []
3 []
4 []
5 []
==> 0
```
] |
[Question]
[
Task: Have your program randomly choose one of the following two quotes at runtime and print that one quote, exactly as shown.
1:
```
Under the spreading chestnut tree
I sold you and you sold me.
There lie they, and here lie we
Under the spreading chestnut tree.
```
2:
```
WAR IS PEACE.
FREEDOM IS SLAVERY.
IGNORANCE IS STRENGTH.
```
Restrictions: The words `spreading`, `chestnut`, `PEACE`, `FREEDOM`, and `STRENGTH` **must** appear in your code. No word from the above two quotes may appear in your code **more than once**.
Shortest solution wins.
[Answer]
# Perl (~~191~~ 184 characters)
```
$_=$$&1?"0
I12321me6T4they,34we
06":"WAR5PEACE6FREEDOM5SLAVERY6IGNORANCE5STRENGTH6";s/\d/("Under the spreading chestnut tree"," sold ",you," and ","here lie "," IS ",".
")[$&]/ge;print
```
Thanks @core1024 for tips on golfing this.
[Answer]
# PHP 179
Inspired by [es1024's](https://codegolf.stackexchange.com/a/35591/21202) answer.
```
<?=strtr(rand()%2?"0
I 1 232 1 me.
T5 they,35 we
0.
":"WAR4PEACE.
FREEDOM4SLAVERY.
IGNORANCE4STRENGTH.
",["Under the spreading chestnut tree",sold,you," and "," IS ","here lie"]);
```
[Answer]
# Java, 338
I can't get it below 338...
```
class B{public static void main(String[]a){String b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=".\n",i=" IS ";if(Math.random()>.5)System.out.print(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+h);else System.out.print("WAR"+i+"PEACE"+h+"FREEDOM"+i+"SLAVERY"+h+"IGNORANCE"+i+"STRENGTH"+h);}}
```
Bit ungolfed:
```
class B{public static void main(String[]a){String b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=".\n",i=" IS ";
if(Math.random()>.5)System.out.print(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+h);
else System.out.print("WAR"+i+"PEACE"+h+"FREEDOM"+i+"SLAVERY"+h+"IGNORANCE"+i+"STRENGTH"+h);}}
```
[Answer]
# Javascript 229 ~~254 256~~
**Edit 1** using `new Date` as suggested by @Doorknob - still unclear to me how javascript Dates morph to strings or integers or whatever
**Edit 2** simplified. A lot.
```
t=(new Date&1
?'0WAR0 IS 0PEACE0.\n0FREEDOM020SLAVERY040IGNORANCE020STRENGTH.'
:'0Under the spreading chestnut tree0\nI 0sold 0you 0and 04030me.\nT0here lie 0they, 05090we\n010.'
).split(0);
for(i=o='';j=t[++i];)o+=t[j|0||i];alert(o)
```
[Answer]
# C# (268)(260) (256)
This is executable in LINQPad, using the `Dump()` method:
```
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";if(new Random().Next(9)>4)(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+".").Dump();else("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.").Dump();
```
Ungolfed:
```
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";
if(new Random().Next(9)>4)
(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+".").Dump();
else
("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.").Dump();
```
**Update:**
Using the ternary operator and 1 extra variable, I was able to cut another 6 characters:
```
string a,b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";a=new Random().Next(9)>4?(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+"."):("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.");a.Dump();
```
Ungolfed:
```
string a,b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";
a=new Random().Next(9)>4 ?
(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+".") :
("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.");
a.Dump();
```
**Update2:**
Thanks to the ingenious suggestion of `tsavinho` I was able to save 4 more chars by placing braces around the ternary operation:
```
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";(new Random().Next(9)>4?(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+"."):("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.")).Dump();
```
Ungolfed:
```
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";
(new Random().Next(9)>4?
(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+"."):
("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.")
).Dump();
```
[Answer]
# Python 3 - 228
```
for x in[b"AB:87078@624>049BA6",b"?;<61;=63;56"][id(id)%3-1]:print("and |FREEDOM|T|IGNORANCE|here lie |STRENGTH|.\n|you |sold |we|I | IS |PEACE|SLAVERY|they, |WAR|me|Under the spreading chestnut tree|\n".split("|")[x-48],end="")
```
Slightly ungolfed:
```
# id(id) returns an even number based on memory address of id
# id(id)%3-1 gives -1, 0 or 1
randomNumber = id(id)%3-1
# Word list
words = "and |FREEDOM|T|IGNORANCE|here lie |STRENGTH|.\n|you |sold |we|I | IS |PEACE|SLAVERY|they, |WAR|me|Under the spreading chestnut tree|\n".split("|")
# Byte Literals for Under the chestnut and WAR IS PEACE
# each byte correspond to the word's index in the word list
byteLiterals = [b"AB:87078@624>049BA6", b"?;<61;=63;56"]
choice = byteLiterals[randomNumber]
for x in choice:
print(words[x-48], end="") # Print each word out
```
[Answer]
# PowerShell 205
```
("{0}.`nI{1}{2}{3}{2}{1} me.`nT{4}they,{3} {4}we`n{0}."-f"Under the spreading chestnut tree"," sold"," you"," and","here lie "),("WAR","PEACE.`nFREEDOM","SLAVERY.`nIGNORANCE","STRENGTH."-join" IS ")|Random
```
Uses the `-f` operator to put strings on the first quote, and the second one is joined by `IS`, after that it selects a random element of those 2 quotes and prints it...
[Answer]
## JavaScript / jQuery 396
```
var B={
U:"Under the spreading chestnut tree",
s:"sold ",
y:"you ",
l:"lie ",
a:"and ",
i:"IS ",
b:"</br>"
};
var A={
P:B.U+B.b+"I "+B.s+B.y+B.a+B.y+B.s+"me."+B.b
+"There "+B.l+"they, "+B.a+"here "+B.l+"we."+B.b+B.U,
Q:"WAR "+B.i+"PEACE."+B.b+"FREEDOM "+B.i+"SLAVERY."+B.b
+"IGNORANCE "+B.i+"STRENGTH."
};
$(function(){
var z=(Math.random()<0.5)?A.P:A.Q;
$('#d').append(z);
});
```
[Answer]
# T-SQL, ~~337~~ 327
Just for fun, I've made another solution in T-SQL, which is one byte shorter than my Java 8 solution:
```
DECLARE @b char(33)='Under the spreading chestnut tree',@c char(5)='sold',@d char(4)='you',@e char(4)='and',@f char(9)='here lie',@ char='
',@h char(4)=' IS'IF rand()>.5PRINT @b+@+'I '+@c+@d+@e+@d+@c+'me.'+@+'T'+@f+'they, '+@e+@f+'we'+@+@b+'.'ELSE PRINT'WAR'+@h+'PEACE.'+@+'FREEDOM'+@h+'SLAVERY.'+@+'IGNORANCE'+@h+'STRENGTH.'
```
By declaring the `char`s one too long, you can add an 'automatic' space, saving up a few bytes.
Using the code in the proposed edit by user PenutReaper, you can indeed shave off 10 bytes.
[Answer]
# JavaScript, 233 bytes
```
Math.random()>0.5?(a="Under the spreading chestnut tree")+"\nI "+(s="sold")+(y=" you ")+(n="and")+y+s+" me.\nT"+(h="here ")+(l="lie ")+"they "+n+" "+h+l+"we\n"+a+".":["WAR","PEACE.\nFREEDOM","SLAVERY.\nIGNORANCE","STRENGTH."].join(" IS ")
```
Wrote this without looking at other answers. Makes good use of assignments as expressions.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 119 bytes
```
“‚  spreading chestnutíÍ““Iïê€î€ƒ€îïê€á.““€Çº¤€»,€ƒ€Îº¤€¦“).ªĆ»‘‡î€ˆ PEACE.
FREEDOM€ˆÃÒRY.
IGNORANCE€ˆ STRENGTH‘)'.«Ω
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcOcRw2zDi961LQGiBSKC4pSE1My89IVkjNSi0vySksOrz3cC1Y0x/Pw@sOrgIoOrwMSxyaBWTChhXoQNSB2@6Fdh5YAGYd268AV9sHElgEVaeodWnWk7dDuRw0zHjUsBBt3uk0hwNXR2VWPyy3I1dXF3xcsdrj58KSgSD0uT3c//yBHP2dXiMrgkCBXP/cQD6B@TXW9Q6vPrfz/HwA "05AB1E – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 222 bytes
```
a,b,c,d,e,f='Under the spreading chestnut tree',' you ',' lie ','and','sold',' IS '
print({f'{a}\nI {e}{b}{d}{b}{e} me.\nThere{c}they, {d} here{c}we\n{a}.',f'WAR{f}PEACE.\nFREEDOM{f}SLAVERY.\nIGNORANCE{f}STRENGTH.'}.pop())
```
[Try it online!](https://tio.run/##LY3BCsIwEETvfsXeohB68eyhaNSCVolVEXqpzdYWdBvSiJSQb6@peJkHbxhG97ZuaT4MBb/zkiuOvFqwMyk0YGuEThssVEMPKGvsLL0tWIPIOIO@fcPIZ4MjC1Ihu/Y5ApITsIk2Ddmpq5grfE4JOPTu7p36JXp4YZRTVqNBV/rw1nMIJfzFB3MKw4jxil1j6Sp/FPFShMlaCrE67IM57eKLkLfgkk16kHG6FKPNpEg32TZiPtKtns5mw/AF "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~307~~ ~~289~~ ~~271~~ 270 bytes
-37 bytes thanks to ceilingcat
```
*y=" IS ";main(){int*r[]={"WAR",y,"PEACE.\nFREEDOM",y,"SLAVERY.\nIGNORANCE",y,"STRENGTH.",0,"Under the spreading chestnut tree","\nI"," sold ","you"," and ",r[11],r[10],"me.\n","T","here lie ","they,",r[12],r[17],"we\n",r[8],".",0},z=r;for(z=z/2&8;r[z];)printf(r[z++]);}
```
[Try it online!](https://tio.run/##JU/BbsIwDP2VKIephYwBlyFFPVQsY0hbmUK3aepyqFpDK0GK3KCpRXx757CDLb/n52e7uN8XxTCMuoiz9ZZxecxrG4SX2roRZia68K9Yc9EJ/q7ipZr82Get1NPm7cZtX@NPpb@JXa@SjY6TpfrnU62SVfoy4WIq@IctAZmrgLUnhLys7Z4VFbTOnh1zCMAFJwfKrG0OJaOia84e5tYjzGYz4/PUCH4E2ka9lKICBHaowU@QPS32qvlN@0jaX/BSzBZU@1Ouoo9Q7hoM@qh/mN8tJGa9keEJ6d1dQGA8NqG8DsMf "C (gcc) – Try It Online")
] |
[Question]
[
The challenge is to create the classic Snake game using as few bytes as possible.
Here are the requirements:
* The game must be implemented in a typical 2-dimensional layout. The snake should be able to grow significantly within the bounds of the map (this really means, don't make your map too small, use your discretion here).
* A user may move the snake using keys of your choosing, however, the snake cannot double back on itself (e.g. if it is going West it cannot go East without first going North or South). A snake ought to be able to travel in all 4 directions: up, down, left, right (North, South, West, East).
* Snake starts off as length 1, each time it eats a "food" object it grows +1 in length
* Food objects are randomly placed in locations other than those occupied by the snake
* If the Snake hits itself or a wall the game is ended
* When the game has been ended the literal "Score: [score]" is displayed where [score] is the number of food items eaten during the game. So, for example, if the snake has eaten 4 "foods" (and therefore has a length of 5) when the game ends, "Score: 4" will be printed.
* No compression algorithms unless they are explicitly defined in your code.
Here's my solution, 908 Bytes, Python 2.7
```
import random as r
import curses as c
def g(s,w,l):
while 1:
p=[r.randrange(0,w),r.randrange(0,l)]
for l in s:
if l==p:continue
return p
s=[]
d=[0,1]
p=k=n=0
e=100
v={65:[-1,0],66:[1,0],68:[0,-1],67:[0,1]}
z=c.initscr()
w,l=z.getmaxyx()[0],z.getmaxyx()[1]
c.noecho()
z.clear()
x=g(s,w,l)
s.append([w/2,l/2])
z.nodelay(1)
q=lambda h,i:range(h,len(i))
while k!=101:
k=z.getch()
if k in v and not (d[0]==(v[k][0]*-1) and d[1]==(v[k][1]*-1)):d=v[k]
f=[0,0]
for i in q(0,s):
if i == 0:
f=[s[i][0],s[i][1]]
s[i][0]+=d[0]
s[i][1]+=d[1]
else:s[i],f=f,s[i]
if s[0]==x:
n+=1
s.append(f)
x=g(s,w,l)
z.clear()
if s[0][0]>=w or s[0][1]>=l or s[0][0]<0 or s[0][1]<0:break
for i in q(1,s):
if s[0] == s[i]: k = 101
for i in q(0,s):z.addch(s[i][0],s[i][1],"X")
z.addch(x[0],x[1],"O")
z.move(0,0)
z.refresh()
if d[1]!=0:c.napms(e/2)
else:c.napms(e)
c.endwin()
print 'Score: %s'%n
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~244~~ 233 bytes
```
s←2⌿⊂2⌿25
d←?x←2⌿50
o←⍳2
G←P5.G
P5.draw←{G.bg¯1
G.fill←0
s⊢←(1↓s),⊂o+f←⊃⌽s
((⊢≢∪)s)∨~f⊂⍛∊a←⍳x:P5.exit 0⊣⍞←'Score: ',⍕2-⍨≢s
d≡f:s⊢←s,⊂f+2×o⊣d⊢←?x
(t←'center'G.rect,∘2 2)¨2×s
G.fill←'f00'
t+⍨d}
P5.kp←{o≢-n←('sdwa'⍳⍵)⊃1-↓⍬2⍴3⊤2320:o⊢←n}
```
Golfed from 294 → 244 bytes with the help of dzaima.
Uses `WASD` controls.
Uses `⎕IO←0` (0-indexing).
The grid is `50x50`, on the default `100x100` canvas Processing uses.
Displays score to the console.
Explanation done!
## Explanation
`s←2⌿⊂2⌿25` snake starts at \$(25,25)\$
`d←?x←2⌿50` first food position: 2 random ints in (0,50)
`x←2⌿50` save (50,50) in x
`o←⍳2` initial snake direction: (0,1)
`G←P5.G` save namespace as `G`
`P5.draw←{` execute the following each frame:
`G.bg¯1` display white background
`G.fill←0` set fill to black
`s⊢←(1↓s),⊂o+f←⊃⌽s` calculate next snake position:
`(1↓s)` remove the last tail segment
`,⊂o+f←⊃⌽s` add direction to the front, and append that
`f←⊃⌽s` assign head coordinates to f
`((⊢≢∪)s)∨~f⊂⍛∊a←⍳x:(...)` check if the player has lost:
`((⊢≢∪)s)∨` if snake does not match itself uniquified, or
`~f⊂⍛∊a←⍳x:` head is not within 50x50 grid:
`⍞←'Score: ',⍕2-⍨≢s` display the score in console, and
`P5.exit 0⊣` exit, displaying nothing
`d≡f:s⊢←s,⊂f+2×o⊣d⊢←?x` if head matches food, then change food position and increase snake length.
`(t←'center'G.rect,∘2 2)¨2×s` draw each position of the snake
`t←'center'G.rect,∘2 2` create function `t` for drawing the blocks
`G.fill←'f00'` set fill to red`
`t+⍨d` draw the food
`}` close draw loop
`P5.kp←{...}` execute the following each time a key is pressed (⍵ is key name):
`1-↓⍬2⍴3⊤2320` array of directions `│0 1│1 0│0 ¯1│¯1 0│`
`('sdwa'⍳⍵)⊃` get key number, index into directions
`n←` store direction in n
`o≢-` if snake direction is not the opposite of n,(prevents moving backward)
`o⊢←n` then change snake direction
## Gameplay
(recorded at low fps)
[](https://i.stack.imgur.com/ByLkS.gif)
[Answer]
# JavaScript, 609 bytes
```
document.write`<canvas id=C width=40 height=40 style='width:180px;height:180px;border:4px solid'`
s=[l={x:9,y:9}]
h=t=0,v=1
r=(x,y,w,h,f)=>{c.fillStyle=f,c.fillRect(x,y,w,h)}
m=n=>{g=4,i=0|38*(R=Math.random)()+1,j=0|38*R()+1,s.map(b=>b.x^i|b.y^j?0:m())},m()
onkeydown=k=>{f={d:[0,1],a:[0,-1],w:[-1,0],s:[1,0]}[k.key],f?(v=f[0],h=f[1]):0}
z=setInterval(w=>z?(focus(),c=C.getContext`2d`,r(0,0,80,80,'#fff'),s.push(l={x:l.x+h,y:l.y+v}),s.splice(0,0>g--),l.x^i|l.y^j?0:t+=!m(),s.map(b=>z&&(0>l.x||0>l.y||39<l.x||39<l.y||b!=l&&b.x==l.x&&b.y==l.y)?z=alert('Score:'+t):r(b.x,b.y,1,1,'#000')),r(i,j,1,1,'#f0f')):0,75)
```
Use WASD for controls.
[JSFiddle](https://jsfiddle.net/9agd6tx4/1/)
[Answer]
## Ruby 1.9 + SDL (~~341~~ ~~324~~ 316)
Here's a first attempt at a Ruby version using the SDL library. I can save 6 characters if I'm allowed to load the SDL library using `-rsdl` on the command line instead of the require statement.
```
require'sdl'
f=o=d=3
s=SDL::Screen.open l=32,l,0,0
r=*0..l*l
loop{f==o ?f=(r-$*).sample: $*.shift
/yU/=~"#{e=SDL::Event.poll}"&&(v=e.sym%4)&&d+v!=3&&d=v
$><<"Score #{$*.size}"&&exit if$*.index(n=o+[-1,-l,l,1][d])||n<0||n>=l*l||d%3<1&&n/l!=o/l
$*<<o=n
r.map{|i|s[i%l,i/l]=[[f,*$*].index(i)?0:255]*3}
s.flip
sleep 0.1}
```
The snake segments and food pieces are represented using black pixels, the grid size is currently 32\*32. You can control with the arrow keys (or any keys really, the keycode mod 4 indexes the direction array [LEFT, UP, DOWN, RIGHT]). I think there's definitely room for improvement here, especially in the death-checking IF statement.
I've vastly improved this over the previous version, hopefully it more closely matches the spirit of the question now. ~~There's one thing I need to fix to comply with the spec, which is that food can currently spawn inside the tail.~~ Fixed!
Prints the score to stdout after the game is completed.
[Answer]
# Bash: ~~537~~ ~~533~~ 507 characters
```
C=$COLUMNS;L=$LINES;D=-1;c=9;r=9;z=(9\ 9);l=;h=1;v=;s=1;d=1
t(){ echo -en "\e[$2;$1H$3";}
b(){ ((f=RANDOM%C+1));((g=RANDOM%L+1));for i in "${z[@]}";do [[ $f\ $g = $i ]]&&b;done;t $f $g F;}
echo $'\e[2J';b
while :;do
read -sn1 -t.1 k
case $k in
w|s)((h))&&h=&&v=${D:$k};;
a|d)((v))&&v=&&h=${D:$k};;
esac
((c+=h));((r+=v))
((c==f&&r==g&&++l))&&b
((c<1||r<1||c>C||r>L))&&break
for i in "${z[@]}";do [[ $c\ $r = $i ]]&&break 2;done
t ${z[-1]} \ ;t $c $r X
z=($c\ $r "${z[@]::l}")
done
echo $'\e[2J\e[H'Score: $l
```
As it uses the `$COLUMNS` and `$LINES` shell variables, it must be run sourced: `. snake.sh`. The snake can be controlled with the `w`/`a`/`s`/`d` keys.
I know, it can be easily reduced to 493 characters by using `clear` to clear the screen, but I prefer to keep it pure `bash`, without using any external tool.
[Answer]
## Python 2.7: 869 816 818 817 816 Characters
I hacked this together in the last few hours. It should meet the requirements and is a few characters shorter than mjgpy3's solution (Tried hard, but couldn't get it much shorter. Now I'm tired). Surprisingly, using a game development library like pygame didn't get the python-snake much shorter. Suggestions and tips how to make it shorter are highly appreciated. I hope it's not too cryptic.
This is the result:
```
import pygame as p
from random import randint as r
p.init();l=20
c=p.time.Clock()
dp=p.display;w=p.display.set_mode((500,)*2)
C=p.Color;b=C(0,0,0);g=C(0,99,0)
D=(0,1);U=(0,-1);L=(-1,0);R=(1,0)
S=[R];d=R;n=[]
O=lambda t:{U:D,R:L,D:U,L:R}[t]
def Q(e):print "Score: %i"%(len(S)-1);p.quit()
def K(e):global d;_={276:L,273:U,274:D,275:R}.get(e.key,(0,0));d=not _==O(d) and _ or d
def N(S):[p.draw.rect(w,g,[x[0]*l,x[1]*l,l,l]) for x in S+n]
def M():n=(r(0,24),r(0,24));return n not in S and n or M()
A=lambda s,o:tuple(x+y for x,y in zip(s,o))
n=[M()]
while True:
w.fill(b);[{12:Q,2:K}.get(e.type,lambda e:e)(e) for e in p.event.get()]
if not (0<=S[-1][0]<25 and 0<=S[-1][1]<25) or A(S[-1],d) in S: Q(e)
if A(S[-1],d) in n: S.append(A(S[-1],d));n=[M()]
else: S.append(A(S[-1],d));S.pop(0)
N(S);dp.update();c.tick(6)
```
EDIT: I could reduce it to 816 Bytes, yay! :) Fixed the score
EDIT2: Pasted the wrong version accidentally
Here is a commented version:
```
import pygame as p
from random import randint as r
# initialize pygame
p.init()
# the game consists of 25*25 blocks,with each block 20*20 pixels
l=20
# initialize the main loop clock
c=p.time.Clock()
# open the window
dp=p.display;w=p.display.set_mode((500,)*2)
# define black and green colors
C=p.Color;b=C(0,0,0);g=C(0,99,0)
# Directions of the snake: down, up, left, right
D=(0,1);U=(0,-1);L=(-1,0);R=(1,0)
# S is the snake, d is the current direction and n is the array of foods
S=[R];d=R;n=[]
# get the opposite direction of a direction to forbid double backing
O=lambda t:{U:D,R:L,D:U,L:R}[t]
# print the score and quit
def Q(e):print "Score: %i"%(len(S)-1);p.quit()
# update the direction (this is a key press handler)
def K(e):global d;_={276:L,273:U,274:D,275:R}.get(e.key,(0,0));d=not _==O(d) and _ or d
# draw the snake and food boxes
def N(S):[p.draw.rect(w,g,[x[0]*l,x[1]*l,l,l]) for x in S+n]
# place new food on the map not colliding with the snake
def M():n=(r(0,24),r(0,24));return n not in S and n or M()
# A((1,1), (-2, 1)) -> (-1,2)
A=lambda s,o:tuple(x+y for x,y in zip(s,o))
# initialize food array
n=[M()]
while True:
# fill the screen black
w.fill(b)
# get quit or key press events and execute the event handlers
[{12:Q,2:K}.get(e.type,lambda e:e)(e) for e in p.event.get()]
# check if snake hits map boundaries or itself
if not (0<=S[-1][0]<25 and 0<=S[-1][1]<25) or A(S[-1],d) in S: Q(e)
# check if snake is eating food at the moment and append one to the snake's length
if A(S[-1],d) in n: S.append(A(S[-1],d));n=[M()]
# move the snake in the current direction
else: S.append(A(S[-1],d));S.pop(0)
# draw the map and limit the main loop to 6 frames per second
N(S);dp.update();c.tick(6)
```
[Answer]
# Java, ~~2343~~ 2239
Not exactly concise, but I believe it follows all the requirements.
### Snake class
```
import javax.swing.*;
public class S extends JFrame{
S(){add(new B());setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(320,340);setVisible(true);}
public static void main(String[]a){new S();}}
```
---
### Board class
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class B extends JPanel implements ActionListener{
int W=300;int H=300;int DS=10;int AD=900;int RP=29;int D=140;int x[]=new int[AD];int y[]=new int[AD];int d;int ax;int ay;boolean l=false;boolean r=true;boolean u=false;boolean dn=false;boolean ig=true;Timer t;Image b;Image a;Image h;
B(){addKeyListener(new T());setBackground(Color.black);ImageIcon id=new ImageIcon(this.getClass().getResource("d.png"));b=id.getImage();ImageIcon ia=new ImageIcon(this.getClass().getResource("a.png"));a=ia.getImage();ImageIcon ih=new ImageIcon(this.getClass().getResource("h.png"));h=ih.getImage();setFocusable(true);i();}
void i(){d=3;for(int z=0;z<d;z++){x[z]=50-z*10;y[z]=50;}l();t=new Timer(D,this);t.start();}
public void p(Graphics g){super.paint(g);if(i){g.drawImage(a,ax,ay,this);for(int z=0;z<d;z++){if(z==0)g.drawImage(h,x[z],y[z],this);else g.drawImage(b,x[z],y[z],this);}Toolkit.getDefaultToolkit().sync();g.dispose();}else{g(g);}}
void g(Graphics g){String ms="Score:";Font sm=new Font("Courier",Font.PLAIN,12);FontMetrics me=this.getFontMetrics(sm);g.setColor(Color.white);g.setFont(sm);g.drawString(ms+d,(W-me.stringWidth(ms)),H);}
void c(){if((x[0]==ax)&&(y[0]==ay)){d++;l();}}
void m(){for(int z=d;z>0;z--){x[z]=x[(z-1)]; y[z]=y[(z-1)];}if(l){x[0]-=DS;}if (r){x[0]+=DS;}if(u){y[0]-=DS;}if(dn){y[0]+=DS;}}
void cc(){for(int z=d;z>0;z--){if((z>4)&&(x[0]==x[z])&&(y[0]==y[z])){ig=false;}}if(y[0]>H){ig=false;}if(y[0]<0){ig=false;}if(x[0]> W){ig=false;}if(x[0]<0){ig=false;}}
void l(){int r=(int)(Math.random()*RP);ax=((r*DS));r=(int)(Math.random()*RP);ay=((r*DS));}
public void actionPerformed(ActionEvent e){if(ig){c();cc();m();}repaint();}
class T extends KeyAdapter{public void keyPressed(KeyEvent e){int k=e.getKeyCode();if((k==KeyEvent.VK_LEFT)&&(!r)){l=true;u=false;dn=false;}if((k==KeyEvent.VK_RIGHT)&&(!l)){r=true;u=false;dn=false;}if((k==KeyEvent.VK_UP)&&(!dn)){u=true;r=false;l=false;}if((k==KeyEvent.VK_DOWN)&&(!u)){dn=true;r=false;l=false;}}}}
```
---
### Screenshot

---
### Commentary
A while back I visited a website called [zetcode](http://www.zetcode.com) which provided some tutorials for creating classic 2D games in Java. The code provided is strongly influenced by [the tutorial](http://zetcode.com/tutorials/javagamestutorial/snake/) that was provided for the Snake game... I think at this time I just started coding classic games and followed the tutorial to a 'T'.
I'll make an edit later and add a link to an executable so people can play the game.
---
### EDITS
* 9/9/12: I am unable to properly load the images from the resource folder. I'll continue to work through this issue in an attempt to prove that my code works and meets all criteria of the question.
* 9/11/12: I am going to continue working on getting the pictures to load from the resource file. I added a picture provided from the ZetCode tutorial.
] |
[Question]
[
We have 3 dice in a square dish. The dish is 8 units wide and tall and each die is 3 units wide and tall. The dice are facing up each with a different number on their top face.
```
111..222
111..222
111..222
........
........
333.....
333.....
333.....
```
Then we play a game. At each step we can slide any 1 die in any cardinal direction until it meets either another die or a boundary. We are not allowed to stop sliding it before it hits an obstacle, we must go all the way.
For example from the position above the following are valid next moves:
```
111222.. 111.....
111222.. 111.....
111222.. 111.....
........ ........
........ ........
333..... 333..222
333..... 333..222
333..... 333..222
```
but these are not:
```
111.222. 111.....
111.222. 111.....
111.222. 111.....
........ .....222
........ .....222
333..... 333..222
333..... 333.....
333..... 333.....
```
The goal of the game is to choose a potential position and see if you can get to it from the starting position.
For example, if our goal is:
```
........
........
..111222
..111222
..111222
..333...
..333...
..333...
```
We can do these moves:
```
111..222 111..... 111..... ........ .....222 ...222.. ........ ........ ........
111..222 111..... 111..... ........ .....222 ...222.. ........ ........ ........
111..222 111..... 111..... 111..... 111..222 111222.. 111222.. 111..222 ..111222
........ ........ ........ 111..... 111..... 111..... 111222.. 111..222 ..111222
........ ........ ........ 111..... 111..... 111..... 111222.. 111..222 ..111222
333..... 333..222 ..333222 ..333222 ..333... ..333... ..333... ..333... ..333...
333..... 333..222 ..333222 ..333222 ..333... ..333... ..333... ..333... ..333...
333..... 333..222 ..333222 ..333222 ..333... ..333... ..333... ..333... ..333...
```
Not every game is winnable though, for example:
```
222..111
222..111
222..111
........
........
333.....
333.....
333.....
```
## Task
You will take as input a board, and you should output whether that board can be reached from the above starting position using these moves.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") answers will be scored in bytes with fewer bytes being better.
## IO
You can take input as an 2D array containing 4 distinct symbols representing the 3 dice and the background. You can also take it as a list of a specified corner (e.g. upper left corner) of each of the dice.
You should give output as 1 of two distinct values with both corresponding to either true and false.
[Answer]
# [PHP](https://php.net/), ~~157~~ ~~123~~ ~~111~~ 89 bytes
```
function f($b){$o=$c=9;foreach($b as$p){$o*=$p%3-1;$c^=$p>2;$c*=2;}return$o&&$c%46%14<5;}
```
[Try it online!](https://tio.run/##vZLfboMgFMbvfQpisGkbRwTqkoayPciyJR3RuBs1rr1q@uzueMCqU9c/F5Pk8PkdfhA4p8zKevdaQkyPuTl8FTlJl/RzdaKFpkZvVVpUyd5k4JH9Ny2bxFrTMpBPXFHzAfJFgFhroc5VcjhWOS0WC2qCzXPAN7tYnevEZIXvMfcRAkEI0SicOOfodVnGpJQ3A/BrARStNQFYdw7oH@/UAIDvZqD1PDzHWaBwmZ0t0Hrugv8BaE18li7folCEMQyI7yvmEw0J0k/KMBolbTaGTDNgHqMC9xUzaBRyd@4F9bxfxWfDwo0f/X7A3n2uNSDgM10B@o/JHNB69wMoXGd2y3oAVsx5oGaAwUN0zfcQ0CtwjMX/ozfkld6ANZPlj7D4QE9tHLmOvKC@qn8A "PHP – Try It Online")
### Some deductions
I've first noted that, on each axes, if we consider the *shorter* distance of a dice from a wall, it can never be \$1\$.
Each movement aims towards a wall or a dice:
* hitting a wall we reset the dice shorter distance to \$0\$.
* hitting a dice we set the dice shortest distance to either \$1\$ or \$2\$.
+ \$2\$ iff the dice we hit has distance \$0\$ from the wall
+ \$1\$ iff the dice we hit has distance \$1\$ from the wall
Hence why, since in the starting configuration there are no dices at distance \$1\$ from a wall, *they can never pop up*.
***Putting momentarily aside the dices labeling***, we want to know if any configuration having no dice at distance \$1\$ from a wall is reachable. Note that if one particular configuration is reachable so do all its rotations and reflections since the starting one can be easily rotated (or reflected).
Now I don't have yet any simple argument so I've checked them all.
Unlabeled, net of symmetries, ***there are 21 configurations*** and I've grouped them in this way:
* **1** dice with shortest distances from the walls \$\{2,2\}\$ (there can't be more than one)
[](https://i.stack.imgur.com/HSJPw.png)
* **3** dices with shortest distances from the walls \$\{0,0\}\$ (the starting configuration)
[](https://i.stack.imgur.com/toXx7.png)
* **2** dices with shortest distances from the walls \$\{0,0\}\$
[](https://i.stack.imgur.com/Kl3AV.png)
* **1** dice with shortest distances from the walls \$\{0,0\}\$
[](https://i.stack.imgur.com/h0rwC.png)
* **0** dices with shortest distances from the walls \$\{0,0\}\$
[](https://i.stack.imgur.com/X67C1.png)
And here's an Hamiltonian cycle through all of them! [*thin air*](https://tio.run/##VZNfi@IwFMXf/RTBgcUZqtKOdmaQBdum7rDswzDMW@lDaKMGNJE0yyIyn91N7m1Sfalyzv2d@6d6ZGbPj8yIhl2vkyeSTfNpMaXTkjRKa96dlGyJUcRWkRPTRhihJFFbEBolt2L3VzMndoR1REhyPBMmu39cz0geE9FBZWccK3f3yIw8PY5GjPwkl8s4i8fRuHi2j2wx/o6skLjvbyhE6FPn0xR9qH299x1Dl@gvAu@sbOnyoUmC/tKjSMWopgEIPE2xNfgvIdVRZU/BGDBQ6v3ShZR9r2GNFHvZx2JIzZ2QhwsUmFoMZcHCot5PwvDPfsyhqD8jBiZ@eRpulWMIjW8sEBIPwEJlQAuclYbALPWt7/xFCExvRgdr6e@SDVP1VuqHK5MbC5o4Hyjg4Q0MC@NCr1iUeBVeCJ7GbvW9GvHW/sw2B2YMl9XXXnPWVlRo3hjelu2OVxuhO1M91NEnh8@6/jFfsyiuV6Pm3Fh4shGyfWdHcTBKCiaLc3Pg61@anfZr3s7nEPBYVatVlNSW@tBCmvVvJWR1wWN/KsMM/8O3prKREQAfqoP/FCiuzDa@Xv8D "Wolfram Language (Mathematica) – Try It Online")
[](https://i.stack.imgur.com/QegjL.png)
So as wished... Yes:
\$A)\$ Assuming the correct dice labeling, any configuration having no dice at distance \$1\$ from a wall is reachable.
Speaking of dices labeling... The board is small enough to keep the dices from permutating one another, they can only rotate like a nano version of the [15 puzzle](https://www.youtube.com/watch?v=YI1WqYKHi78).
Furthermore *from every configuration we can always scatter the dices to their nearest corner* and using these as dices clips we can say:
\$B)\$ The "clockwise order" is always retained.
### Former approach digression
Check for \$A)\$ is quite straightforward, but check for \$B)\$ can be fancy.
My former approach *(≥ 111 bytes answers)* was to calculate the two vectors connecting respectively dices `1->2` and `2->3` using their nearest corners as points.
For example in the starting position these vectors would be `(0,0)->(1,0), (1,0)->(1,1)`, read as binary numbers `0010, 1011 = 2, 11`
```
(0,0)________(1,0)
| < | Out of 12 possible vectors only 4 violate the clockwise order
|v | they form the numbers 1, 7, 8, 14
| ^ | all satisfying v%7<2
|__>_____|
(0,1) (1,1)
```
Fun fact: **former code was blundered**, it put together correctly only the first vector.
Good news I was already thinking of a way to collapse this operation into a single check instead of two.
### How
There are 24 sets (4 choose 3) of corners, 12 in clockwise order, 12 in counterclockwise order.
Combining them into one single binary number (instead of analyzing two vectors) give us the opportunity to execute a single check.
*Inspired by [this answer](https://codegolf.stackexchange.com/a/181718/94346)* I wrote a C program to brute-force the decision problem out of these numbers.
```
corners c | (9*32^c)*2 | c%46 | c%14 | <5 Examples
------------+---------------+------+------+-------
000110 6 | 588 | 36 | 8 | no
000111 7 | 590 | 38 | 10 | no 3 ________ 2
001001 9 | 594 | 42 | 0 | yes | |
001011 11 | 598 | 0 | 0 | yes | 011000 |
001101 13 | 602 | 4 | 4 | yes | |
001110 14 | 604 | 6 | 6 | no |________|
010010 18 | 612 | 14 | 0 | yes 1
010011 19 | 614 | 16 | 2 | yes
011000 24 | 624 | 26 | 12 | no
011011 27 | 630 | 32 | 4 | yes ________ 1
011100 28 | 632 | 34 | 6 | no | |
011110 30 | 636 | 38 | 10 | no | 101101 |
100001 33 | 514 | 8 | 8 | no | |
100011 35 | 518 | 12 | 12 | no |________|
100100 36 | 520 | 14 | 0 | yes 3 2
100111 39 | 526 | 20 | 6 | no
101100 44 | 536 | 30 | 2 | yes
101101 45 | 538 | 32 | 4 | yes 3 ________
110001 49 | 546 | 40 | 12 | no | |
110010 50 | 548 | 42 | 0 | yes | 011100 |
110100 52 | 552 | 0 | 0 | yes | |
110110 54 | 556 | 4 | 4 | yes |________|
111000 56 | 560 | 8 | 8 | no 1 2
111001 57 | 562 | 10 | 10 | no
```
[Answer]
# [Python 3](https://docs.python.org/3/), 209 bytes
```
B=[[0,0,5,0,0,5]];exec("B+=[b[:D]+[d*min([-5*~d/2]+[b[x]*d-3 for x in((D+2)%6,(D-2)%6)if d*b[x]>d*b[D]and-3<b[D+1-D%2*2]-b[x+1-D%2*2]<3])]+b[D+1:]for D in range(6)for d in(-1,1)for b in B];"*12)
B.__contains__
```
Takes a list of six numbers, where the 1st and 2nd numbers are the x and y coordinates (0-indexed) of the upper left corner of the first dice, etc.
**Explanation**
This is *extremely* inefficient as `B` will theoretically be a list of length 9.7e12
The brute force code
```
def overlap(corner1, corner2):
return -3 < corner1 - corner2 < 3
def move(board, direction, dice):
other_dice_pos = [board[i] for i in [0, 1, 2] if i != dice]
dice_x, dice_y = board[dice]
new_board = board.copy()
if direction in "EW":
if direction == "E":
new_pos = 5
for (x, y) in other_dice_pos:
if overlap(y, dice_y) and x > dice_x:
new_pos = min(new_pos, x - 3)
else:
new_pos = 0
for (x, y) in other_dice_pos:
if overlap(y, dice_y) and x < dice_x:
new_pos = max(new_pos, x + 3)
new_board[dice] = (new_pos, dice_y)
else:
if direction == "S":
new_pos = 5
for (x, y) in other_dice_pos:
if overlap(x, dice_x) and y > dice_y:
new_pos = min(new_pos, y - 3)
else:
new_pos = 0
for (x, y) in other_dice_pos:
if overlap(x, dice_x) and y < dice_y:
new_pos = max(new_pos, y + 3)
new_board[dice] = (dice_x, new_pos)
return new_board
initial_board = [(0, 0), (5, 0), (0, 5)]
possible_boards = [initial_board]
previous_length = 0
iteration = 0
while len(possible_boards) > previous_length:
previous_length = len(possible_boards)
new_boards = []
for board in possible_boards:
for dice in (0, 1, 2):
for direction in "ENSW":
new_board = move(board, direction, dice)
if new_board not in possible_boards:
new_boards.append(new_board)
possible_boards += new_boards
iteration += 1
print(iteration)
```
shows that every reachable board is at most 12 steps away. In the code, we use six numbers to represent each board state and each move changes exactly one of them. To unify the four cases in the `move` function, we encoded the moves slightly differently.
`D` represents the index of the changing number and `d` is `-1` if the move is towards the top or the left and is `1` otherwise.
Then `(D+2)%6` and `(D-2)%6` are the indices of the coordinates in the moving direction for the stationary dice. moves from the index. Adding `1-D%2*2` shifts to the coordinates for the stationary direction. We also use the fact that `max(a,b,c)=-min(-a,-b,-c)` and `a>b` iff `-a<-b`. (The implementation has been checked to agree with `move` function up to a difference in encoding the move for all possible board positions)
The rest of the code is just simply generating all board states reachable in 12 steps and checking if the given one is one of those.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~75~~ 65 bytes
```
ÄṪ€µŒcạ/€<3¬aÆi%7Ȧ
⁴Dp`ṖÆịW,þ@⁹¦ı*Ɱ4¤¹WŒḊ?€ŒpÄÇ¿Ṫ€$€ʋⱮ3$€ẎẎQƲƬẎQċ
```
[Try it online!](https://tio.run/##y0rNyan8//9wy8Odqx41rTm09eik5Ie7FuoD2TbGh9YkHm7LVDU/sYzrUeMWl4KEhzunHW57uLs7XOfwPodHjTsPLTuyUevRxnUmh5Yc2hl@dNLDHV32QJ1HJxUcbjncfmg/xFAVID7VDVRmDGI93NUHRIHHNh0DMQOPdP9/uHOf9aOGOQq6dgqPGuZaH27XjPz/Pzpaw1jbOEtTRwFIm4FpMxA/VkchWsMQKmKobQiVAdKxsQA "Jelly – Try It Online")
A pair of links that takes a list of three complex numbers as its argument (indicating upper left position of the dice, with the top left of the grid being `(1+1i)`) and returns `1` for valid final positions and `0` for invalid positions. Brute force is used to find all possible reachable positions and then the list of positions is checked. The first 7 bytes of the main link are spent constructing the initial position - removing this would allow this pair of links to be supplied with two arguments, an initial and final position, and would determine if you can reach one from the other.
] |
[Question]
[
A quote from [MO.SE answer](https://mathoverflow.net/a/357249):
>
> Although it is well known that Conway was able to quickly calculate the day of the week of any given date, it is less well known that one part of the algorithm is easy to remember and useful in practice: In any given year, the following dates all fall on the same day of the week: **4/4, 6/6, 8/8, 10/10, 12/12, 5/9, 9/5, 7/11, 11/7, and the last day of February**. For example, in 2020, all these dates fall on a Saturday. Conway, in his characteristically colorful way, would say that the **Doomsday** of 2020 is Saturday. Knowing this fact allows you to calculate fairly quickly in your head, with no special training, the day of the week for any date in 2020.
>
>
>
Well, it sounds easy, but then we need to check which doomsday is the closest from the given date in order to quickly calculate the day of week. Now *that* sounds hard.
Practically, we'd just compare a given date with the Doomsday in the same month (or adjacent month in case of January and March).
## Task
Given a date consisting of full year, month, and day, output the closest Conway's Doomsday (i.e. one of **4/4, 6/6, 8/8, 10/10, 12/12, 5/9, 9/5, 7/11, 11/7, and the last day of February**) from the given date.
The closest Doomsday can be in the same month, a different month, or even a different year. If the given date has two nearest Doomsdays, output any one or both of them. Also note that the last day of February can be either 28th or 29th (depending on leap-year-ness).
You can take input and produce output in any suitable format, e.g. three integers, a formatted string, or even a built-in Date object (if your language has one). You can assume the given date is valid, and the **input year is between 1901 and 2099 inclusive**. Gregorian calendar is assumed in this challenge.
## Test cases
```
YYYY-MM-DD => YYYY-MM-DD, ...
-------------------------------
2020-05-18 => 2020-05-09
2020-05-30 => 2020-06-06
2020-10-31 => 2020-11-07
2020-10-24 => 2020-10-10 or 2020-11-07
2020-01-20 => 2019-12-12
2020-01-21 => 2020-02-29
2019-01-20 => 2018-12-12 or 2019-02-28
```
[Reference implementation in Python.](https://tio.run/##TU/LjoQgELz7FX2EtScR1BmdxC8xHphFsiSCRr04P@82Mut6qaK6in5M2/oz@nzfzTw60GrtV@t6sG4a5/UrOarfaui9VvNZTXRvwLANHWr@TECPlGpgUO6lFWzPNvT52GacgRisb5lEWaV2GXo1sY1zZAUWhCXWhHe8Ez5QCKIKK8IaS0KRocgCC3wEkigk77o4dqG5gdl2EzyNrz9OBaeQNSaEWvVa2GUvuB3/OIQFjwOsjx2p8zRbv7JWu@hS3gT7bSd2RDC25WANkNU04Kxnsdbx3TCZyQxLFBVPTpFnp6CTcnFVsvhXKLOr@OREHZ39Fw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~138~~ ~~110~~ 98 bytes
```
≔§⪪”)¶⊟eΦO∨ü&-T[¿Q№i⧴⊕%⁰q”⁴LΦ⪪”)¶ »R≦PH↘{⎚″4χχβ´ΣP”⁴›ι✂θ⁴χ¹η¿⁼Iη¹²⁺⊖…θ⁴1212«…θ⁴¿⁻Ση³η«022§9888I…θ⁴
```
[Try it online!](https://tio.run/##XZDfaoMwFMav9SmCVwk4ODnaqnhV3B8GGxR8ArFpDaRpa@LYGH12d3S1F81HAvmS8/uS03ZN354aM44b5/TB8o1/tzv1zeuz0Z5HEkkSMgkSoIAV5KSMnDVpRU5KSoCGxChmqYjZh7IH3/FXbbzqFw4dAyQygxQlrDCBNc0MiYcIBZKJqZSY3hhvvWqmah2z2uhW8Qv5MZNAU0wjZp0oQ71n/OUyNMbxqnGed@RLFIJte20935rB8WfV9uqorFc7Xv20RlXd6TzzJsr8wUgQSxmn2G8Y/Jc@3izDYAr71JaQ9XCco5J70vSYYCHcEBEgkcv7fulsVOR5Tv@cX/yYMyddw@s4IlDHaBmfvswf "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 28 bytes by switching I/O to compact ISO format (yyyymmdd). Saved 12 bytes when the supported year range was restricted to 1901 to 2099. Explanation:
```
≔§⪪”)¶⊟eΦO∨ü&-T[¿Q№i⧴⊕%⁰q”⁴LΦ⪪”)¶ »R≦PH↘{⎚″4χχβ´ΣP”⁴›ι✂θ⁴χ¹η
```
Take the dates (in mmdd format) `0120`, `0317`, `0421`, `0523`, `0623`, `0725`, `0822`, `0922`, `1024`, `1124`. These represent the cutoff points above which the next Doomsday is nearer. (In some cases the Doomsday is equidistant but in particular for `0120` that is not true on leap years.) Work out which cutoff point applies by counting the number of dates that fall before the input date. Then look up the relevant Doomsday date from the list (in mmdd format) `1212`, `1107`, `1010`, `0905`, `0808`, `0711`, `0606`, `0509`, `0404`, `0300`, `0012`.
If I had access to a date library I could then ask it to fix up my date, but unfortunately I have to do that manually:
```
¿⁼Iη¹²
```
Is this the `0012` date, meaning the 12th of month 0, i.e. last December?
```
⁺⊖…θ⁴1212«
```
If so then output the previous year and a month and day of 12.
```
…θ⁴
```
Otherwise the year is at least correct...
```
¿⁻Ση³
```
Is this the `0300` date, meaning the 0th of March, i.e. the last day of February?
```
η«
```
If not then this is the date we seek.
```
022
```
Output February the 2?th.
```
§9888I…θ⁴
```
Output `9` if the year is a multiple of 4, otherwise `8`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 102 bytes
```
aMinimalBy[DateObject@{a[[1,1]],##}&@@@36^^3cx83c24e4aw06er~IntegerDigits~13~Partition~2,Abs[#-a]&]
```
[Try it online!](https://tio.run/##Rc1NisJAEIbhqzRpyKob@yeKwyC04mYWouCyaaEMbSwxcYgFMyKTQ8wNPKFHiIp/u@crXqgSaB1LIMyhXbFBC@f/0wQrLGE7OvgxUJwuNzEndwTvtdAhCM7/Uuec7S0WNv/t29xkMYMf1Yt181VRLGI9xgJp32jbzKAmJNxVjRHD5d5zCSEN7azGijwXLGGJYCvPQ2Ap6zj2/nhbc7p2xfx7i@QTo4ySqit1nz1p1Z1aSatfNNkj0NKoN2@B/rhfk/DZXgA "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a `DateObject` as input and returns a list of `DateObject`s as output. The Unicode character is U+F4A1 (`\[Function]`). I'd use `Nearest` here, but its default `DistanceFunction` refuses to compare `Quantity` values. Note that the function emits a few warnings on TIO due to its sandboxing.
[Answer]
# JavaScript (ES7), ~~125 ... 114~~ 113 bytes
Takes and returns a Date object.
```
D=>[25,-15,...'108088080'].map(b=d=>(v=(q=new Date(D.getFullYear(x+=21-d),x>>4,x&15))-D)*v>b||(b=v*v,o=q),x=0)&&o
```
[Try it online!](https://tio.run/##dZBPT8IwHIbvfIrfCVrWlrYwHTHtaXrwoAdPZtlhrAUxg8KYExPiV58dqPyJJm97aJ8@b9vXrM42eTlfVXTpjG2mqomVTmRIqAgJY6wneMQjH95L2SJboYkySqNaobVa2neIs8qimM1sdfdWFM82K9E2UFJQg8lW6xHZdkWIMY1xv9aT3c6fr/s1cWrt9xXH3a5rbpIOQAKSS04AQgIigpTAYLBfojykfHxBDPkZceVzQgg/huKUEILy6wtCjs6INuDKv3kQnj92ijEV0ueSOOvkksqfe4vx0QHfjujgOHR6Y8tHnbTDpq68zfIXhJIPAgsCJsWgNORuuXGFZYWbIWRAwe//txjQ1m8wZpW7f3p8QJhtinlu0f61GALowaf2UwBTZP6hMG6@AA "JavaScript (Node.js) – Try It Online")
### How?
The array `[25,-15,...'108088080']` encodes the following pairs \$(m,d)\$ where \$m\$ is a 0-indexed month and \$d\$ is a day:
```
[-1,12], [2,0], [3,4], [4,9], [5,6], [6,11], [7,8], [8,5], [9,10], [10,7], [11,12]
```
Special cases:
* `[-1,12]` is the 12th of December of the previous year
* `[2,0]` (literally "March 0") is the last day of February
It is decoded as follows:
```
[25, -15, ...'108088080'] // array of delta values
.map(d => // for each value d in this list:
[ // build the pair (month, day):
(x += 21 - d) >> 4, // add 21 - d to x; the month is floor(x / 16)
x & 15 // the day is (x + 16) mod 16
], // end of pair
x = 0 // start with x = 0
) // end of map()
```
[Try it online!](https://tio.run/##fZDBboMwEETvfMWcGqwCgaipolbwI1EOW2yKIwcj20nJ19M1TS9V0pVlHzxvZnePdCHfOj2GfLBSza0dvDWqMPYznfebbYa84qsoilVV7sodn3J1wHoNco6usB2kMoFwIXNWPilONKYSdYO/xUhnHRS1/Y8YEnpA6LWH0T68JcAe94tZ4OOsjWS9wkjaIT3ZIfQZJF1FZIF0wnONTYUcUqBp8JL9sgBJeftCsJjeF6PFAtxAZ6x1zK9RvYrFbMITqu3dRrCwnBvJGBoh9pL8MnvI/hlCDTLuLE6QxJAa5SOpD@QCvjR3uOgSATzez804rl/MYv4G "JavaScript (Node.js) – Try It Online")
For each pair \$(m,d)\$ we compute the square of the difference (in milliseconds) between the input date \$D\$ and a new date \$q\$ generated with this month and this day.
```
(v = (q = new Date(D.getFullYear(), m, d)) - D) * v
```
We eventually return the date that leads to the smallest squared difference.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~115 99~~ 91 bytes
```
{u/⍨(⊢=⌊/)|(1∆DT⊂⍵)-1∘∆DT¨⊂¨u←(,y∘.,(2/¨2+2×⍳5),(⊢,⌽¨)0 2+⊂5 9),↓y,↑2∘,¨28+0=4|y←(2-⍳3)+⊃⍵}
```
[Try it online!](https://tio.run/##TU@xTsMwFNzzFW9rrDjEdhqpRcpUBlhpF8ZIISwVIJUOVstSUIRCXYEQgpkpA1IHYKnUxfzJ@5Hw6oqqy/Pd@e70XnY9DHOdDa8uGg8Xr70zaOXF5ajl4UN5NMDyaSJTNKvDPNMjW6P54TSrmQQJ@HgPeXZz7uTbZjKO0NQ@Vh8pzquITX257ahm9M9CYu9OcAW2HlO5zzWpB9xXka1VoH7f0HwljG9aOM7XtmYCVED@BLqMY/miaTwrCtEeqhOItD3VmyIVUjJmZL1z2xQkolk4@onm2y5jCtKF/dMezcHxSb8pQAklIAHZ8XY4Fv9YCojlHlHtHaFnD29Nsuv0Pw "APL (Dyalog Unicode) – Try It Online")
Takes a date array `yyyy mm dd`, and returns all the closest doomsdays. If that is not allowed, then +1 byte.
-16 bytes from Bubbler(simplifying leap year check)
-8 bytes from Bubbler(compressing doomsdays)
`⎕DT` is polyfilled as `∆DT` here(Courtesy of Adám) since tio's version doesn't allow it's usage.
## Explanation
`(2-⍳3)` array (-1,0,1)
`y←(2-⍳3)+⊃⍵` add that to the year and store it as y.
`0=4|` check if each of those is a leap year(This works due to the year range.)
`28+` add 28 to those booleans to get the correct february dates
`↓y,↑2∘,¨` add the respective years, and months(2) to them to get the appropriate dates
`(...),` concatenate with:
`(⊢,⌽¨)0 2` generate array `(5 9)(7 11)(9 5)(11 7)`
`(2/¨2+2×⍳5)` and the numbers 4 6 8 10 12 repeated twice
`,y∘.,` join with the years and flatten to a list to get all the dates
`u←` save all the dates together as u
`1∘∆DT¨⊂¨` get each of their date numbers
`(1∆DT⊂⍵)` and subtract from the input's date number.
`|` convert to their absolute values:
`(⊢=⌊/)` tacit fn: array = minimum? (generates bitmask)
`u/⍨` filter the dates by that (get the dates with minimum distance)
[Answer]
# [Red](http://www.red-lang.org), ~~234~~ ~~182~~ 176 bytes
```
func[n][y: n/2 t: to-date[y 3]second sort/skip
collect[foreach[d m]reduce[4 4 6 6 8 8 10 10 12 12 5 9 9 5 7 11 11 7 t/4 2 -19 1][a:
to-date[d m y]keep absolute a - n keep a]]2]
```
[Try it online!](https://tio.run/##VY3BboMwEETv/opR7ha2A01Aaj@iV2sP1F7UKMRGYA58PXUgVYtnDn7jXc/Ifv1kb0l0zdrNwdlAdmkQCoPUIEXp28R2wZkmdjF4THFMxXS/DcLFvmeXbBdHbt239XjQyH52bEuUeMu6Zmm12Txdoc6qcIHWT1@QihIGUtfQZNtG/Dbmz7DQnXlA@zXFfk6MFhIBe0ZkaH0147kBK5CPvkpVSaOM2vCsjqilVn9oyiPmYf0P9RFfr7oWZLFFw3gLCXbvP71/nNDtdxK0/gA "Red – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 84 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4Ö¹тÖ_²3@PU•ΘÏF•5°X*+ºS₂+©²<£O+•23õ₄ƶ₃-¹å•60в.¥X+¦19(šs.xDVdi®ηODY‹O©£θYα®>¹)ë12D¹<)
```
Can definitely be golfed some more.. 05AB1E doesn't have any date builtins, so everything is done manually.
Input as three loose inputs in the order `year,month,day`, output as a triplet in the format `[day,month,year]`.
[Try it online.](https://tio.run/##AZYAaf9vc2FiaWX//zTDlsK50YLDll/CsjNAUFXigKLOmMOPRuKAojXCsFgqK8K6U@KCgivCqcKyPMKjTyvigKIyM8O14oKExrbigoMtwrnDpeKAojYw0LIuwqVYK8KmMTkoxaFzLnhEVmRpwq7Ot09EWeKAuU/CqcKjzrhZzrHCrj7CuSnDqzEyRMK5PCn//zIwMTkKMDUKMTg)
**Explanation:**
Determine if the input is a leap year, and if the input-month is NOT January nor February:
```
4Ö # Check if the (implicit) first input-year is divisible by 4
¹тÖ_ # Check that the first input-year is NOT divisible by 100
²3@ # Check that the second input-month is >= 3
P # Check if all three are truthy by taking the product of the stack
# (1 if truthy; 0 if falsey)
U # Pop and store this in variable `X`
```
Convert the input to an integer \$n\$, being the (1-based) \$n^{th}\$ day of the year:
```
•ΘÏF• # Push compressed integer 5254545
5° # Push 10 to the power 5: 100000
X* # Multiply it by `X`
+ # Add it to the integer (5354545 if `X` is truthy; 5254545 if falsey)
º # Mirror it: 5354545454535 or 5254545454525
S # Convert it to a list of digits
₂+ # Add 26 to each: [31,28 or 29,31,30,31,30,31,31,30,31,30,31,28 or 29,31]
© # Store this list in variable `®` (without popping)
²< # Push the second input-month, and decrease it by 1
£ # Leave that many leading values of the list
O # Sum them
+ # And add them to the (implicit) third input-day
```
Create a list of values \$k\$, representing the \$k^{th}\$ day of the year for the dates `[prevYear-12-12, year-02-28 or 29, year-04-04, year-05-09, year-06-06, year-07-11, year-08-08, year-09-05, year-10-10, year-11-07, year-12-12]`:
```
•23õ₄ƶ₃-¹å• # Push compressed integer 36033721893183342948
60в # Convert it to base-60 as list: [59,35,35,28,35,28,28,35,28,35,48]
.¥ # Undelta it with leading 0: [0,59,94,129,157,192,220,248,283,311,346,394]
X+ # Add `X` to each
¦ # Remove the leading 0 (or 1)
19(š # And prepend -19 instead
```
Get \$k\$ closest to \$n\$:
```
s # Swap so `n` is at the top of the stack
.x # And get the value of the list closest to it
DV # And store a copy in variable `Y`
```
And convert that result back into a date to output:
```
di # If the result is non-negative (>=0):
® # Push the list from variable `®`
η # Get its prefixes
O # And sum each prefix: [31,60,91,121,152,182,213,244,274,305,335,366,395,426]
D # Duplicate it
Y‹ # Check for each whether it's smaller than `Y` (1 if truthy; 0 if falsey)
O # Sum those checks
© # Store it in variable `®` (without popping)
£ # Leave that many leading values from the list
θ # Then only leave its last value
Yα # And take its absolute difference with `Y`
®> # Push `®` + 1
¹ # Push the first input-year
) # And wrap all three values on the stack into a list
ë # Else:
12D # Push two 12s
¹< # Push the first input-year - 1
) # And wrap all three values on the stack into a list
# (after which it is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•ΘÏF•` is `5254545`; `•23õ₄ƶ₃-¹å•` is `36033721893183342948`; and `•23õ₄ƶ₃-¹å•60в` is `[59,35,35,28,35,28,28,35,28,35,48]`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~173~~ 169 bytes
```
y=${1%%-*}
for E in {4..12} {3/1/{$y,$[y+1]}-,1/2/$y-2}1day
{
((E))&&E+=/$[E%2?12^E:E]/$y
a=date\ -d;k=$[(`$a$1 +%s`-`$a$E +%s`)**2];((k<n|!n))&&{ n=$k;D=$E;}
}
$a$D +%F
```
[Try the test cases online!](https://tio.run/##TZDBToNAEIbv8xQjWRoK3cIsNVHp1ku3Vx8Aa7oCCmm7GFqjBHl2hNqql8mXP99MZuZZH/Iu0UdcvFXla6X3OJ9b6mFldbVkDdk2d1t4KStUWBhsZtMpiRab0Ce/YfWExbVH65ZPyBc@q7loKdU1NOA4ajwejZQnfRYrW9yTeFJ3at1LoGWqj9kj8jTaShY7G6YZoWcfNnxAdcKx64p15Djbufm6MsOsBo1k22gpmYpaaKFXl7266vp1AZJ8X6b47n3i@RCAj7zYZVhlOsVdYTJATMu@IGZJXiI3aLEhR7lA65RP/csT2G@DyToRiIAH15xuEC4cBmemgIf0x2J2cYiL4B@fHLr9yeEb "Bash – Try It Online")
This is a full program. Input is passed as an argument in yyyy-mm-dd format. Output is on stdout in the same format.
This uses several tricks:
* For each month `E` from April to December, the Doomsday day in that month is computed as `E` for even months and `E xor 12` for odd months.
* The last day of February is computed as 1 day before March 1. (This applies to both the current year and the next year.)
* December 12 of the previous year is computed as 21 days before January 2 of the current year.
* The last two computations (ending with `-1day` and `-21day`) are combined using bash's brace expansion).
* The `date` command with first option `-d` is saved in a variable for use like a macro.
* Some spurious error messages are written to stderr.
] |
[Question]
[
[Life-like cellular automaton](https://en.wikipedia.org/wiki/Life-like_cellular_automaton) are cellular automaton that are similar to Conway's Game of Life, in that they operate on a (theoretically) infinitely large square grid, where each cell has exactly 8 neighbours, and is one of 2 states, namely alive and dead.
However, these Like-like versions are different in a crucial way: the rules for a given cell to come alive and the rules for a given cell to survive to the next generation.
For example, classic Game of Life uses the rule `B3/S23`, meaning that it takes 3 alive cells to birth a new one, and either 2 or 3 living neighbours to survive. For this challenge, we will assume that neighbours do not include itself, so each cell has exactly 8 neighbours.
Your task is, given a starting configuration, a birth rule, a survival rule and a positive integer (the number of generations to be run), simulate the Life-like automaton using those rules for the number of generations given in the shortest code possible. The starting configuration will be a square matrix/2-dimensional array or a multiline string, you may choose. The others may be given in any reasonable format and method.
For example, if the birth rule was `12345678` (any living neighbours), the survival rule was `2357` and the starting configuration was
```
0 0 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
```
the next two generations would be
```
Generation 1: Generation 2:
0 0 0 0 0 1 1 1 1 1
0 1 1 1 0 1 1 0 1 1
0 1 0 1 0 1 0 1 0 1
0 1 1 1 0 1 1 0 1 1
0 0 0 0 0 1 1 1 1 1
```
If the number of generations given was 10, the output would be something along the lines of
```
0 1 1 1 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
0 1 1 1 0
```
You do not have to handle changes that happen outside of the bounds given by the input matrix, however, all cells outside the matrix begin dead. Therefore, the input matrix may be any size, up to the maximum value your language can support. You do not have to output the board between generations.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
## Test cases
These use the `B/S` notation to indicate the rules used
`B2/S2`, `generations = 100`, configuration:
```
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
```
Output:
```
0 0 0 0 0 0 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
```
---
`B1357/S2468`, `generations = 12`, configuration:
```
1 0 1 0 1 0
0 1 1 0 1 0
1 0 0 0 0 0
0 0 0 0 0 1
1 1 1 1 1 0
0 1 1 0 0 1
```
Output:
```
0 1 0 0 0 0
0 1 1 1 1 0
0 1 0 1 1 0
1 1 1 0 0 0
0 0 1 1 1 0
0 1 1 0 0 0
```
If you need to generate more test cases, you can use [this](http://play.starmaninnovations.com/varlife/) wonderful simulator. Please make sure to limit the board size
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~24~~ 23 bytes
```
xx:"tt3Y6Z+1Gm<8M2Gmb*+
```
Inputs are:
* Array with birth rule
* Array with survival rule
* Number of generations
* Matrix with initial cell configuration, using `;` as row separator.
[**Try it online!**](https://tio.run/##y00syfn/v6LCSqmkxDjSLErb0D3XxsLXyD03SUv7//9oQwUjBWMFEwVTBTMFcwWLWK5oEN9UwTyWy4gr2kABCq0V0JiGWEXBMBYA) Or see test cases: [**1**](https://tio.run/##y00syfn/v6LCSqmkxDjSLErb0D3XxsLXyD03SUv7//9oo1guEDY0MOCKNlRAgdYKBqjQWoEeKmIB), [**2**](https://tio.run/##y00syfn/v6LCSqmkxDjSLErb0D3XxsLXyD03SUv7//9oQwVjBVMF81iuaCMFEwUzBYtYLkMjLqCwgQIUW4MpOAfEgEJrBFPB0BqsCAKR9ADpWAA).
For a few bytes more you can see the [**evolution in ASCII art**](http://matl.suever.net/?code=xx%3A%221%26Xxtt3Y6Z%2B1Gm%3C8M2Gmb%2a%2BtZcD%5Dx&inputs=%5B2%5D%0A%5B2%5D%0A100%0A%5B1+1+1+1+1+1+1+1%3B+0+0+0+0+0+0+0+0%3B+1+1+1+1+1+1+1+1%3B+0+0+0+0+0+0+0+0%3B+1+1+1+1+1+1+1+1%3B+0+0+0+0+0+0+0+0%3B+1+1+1+1+1+1+1+1%3B+0+0+0+0+0+0+0+0%5D&version=20.4.2).
### Explanation
```
xx % Take two inputs implicitly: birth and survival rules. Delete them
% (but they get copied into clipboard G)
:" % Take third input implicitly: number of generations. Loop that many times
tt % Duplicate twice. This implicitly takes the initial cell configuration
% as input the first time. In subsequent iterations it uses the cell
% configuration from the previous iteration
3Y6 % Push Moore neighbourhood: [1 1 1; 1 0 1; 1 1 1]
Z+ % 2D convolution, maintaining size
1G % Push first input from clipboard G: birth rule
m % Ismember: gives true for cells that fulfill the birth rule
< % Less than (element-wise): a cell is born if it fulfills the birth rule
% *and* was dead
8M % Push result of convolution again, from clipboard M
2G % Push second input from clipboard G: survival rule
m % Ismember: gives true for cells that fulfill the survival rule
b % Bubble up the starting cell configuration
* % Multiply (element-wise): a cell survives if it fulfills the survival
% rule *and* was alive
+ % Add: a cell is alive if it has been born or has survived, and those
% are exclusive cases. This produces the new cell configuration
% Implicit end loop. Implicit display
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~144~~ 122 bytes
```
CellularAutomaton[{Tr[2^#&/@Flatten@MapIndexed[2#+2-#2[[1]]&,{#2,#3},{2}]],{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},#,{{#4}}]&
```
[Try it online!](https://tio.run/##LU3LCsIwELz7FYFAL67YRD0KFUHoQRDxFlZYbKqFNJUQQQj59rgFGXZeDOxI8WVHisODSr8vR@vcx1E4fOLE7eRNugWj77JaNydHMVrfnOnd@s5@bWe0XOqV1MYoxAqS1CA3GZLOiMyQ@BhzA@qvc87sFCgWyRu5zRmrcgmDj01vruS7aWx9tE8bjAKRVA1C1RnZahD8QKSZdrgoPw "Wolfram Language (Mathematica) – Try It Online")
Example usage:
```
%[RandomInteger[1, {10, 10}], {2, 3}, {3}, 5]
```
uses a 10x10 random grid as a start, survives with either 2 or 3 neighbors, births with 3 neighbors, plot result at 5 iterations.
[Answer]
# [R](https://www.r-project.org/), 256 bytes
```
function(x,B,S,r){y=cbind(0,rbind(0,x,0),0)
n=dim(y)[1]
z=c(1,n)
f=function(h){w=-1:1
b=h%%n+1
a=(h-b+1)/n+1
'if'(a%in%z|b%in%z,0,sum(x[w+b,w+a])-x[b,a])}
while(r){x=y
for(i in 1:n^2){u=f(i-1)
y[i]=u%in%B
y[i]=(y[i]&!x[i])|(x[i]&(u%in%S))}
r=r-1}
y[-z,-z]}
```
[Try it online!](https://tio.run/##bVHbboMwDH3PV7AH2lg4GumuquSX/kIfEZMKhRJpTSsGItD221nSAuumyYlvOT52krLfUZ/XOq3UQXODK1xjCaeW0kTpLQ@xHKzBEOximrZqz1uIZMw6SrlEDSyniaKAU0NCLiVLqPB9HUi2IV6IJJDw6KK5yud84yvtd@fkajDEr3rPTdQECTbBJgZhogStvbCmUJ8ZtxMZall@KLnylPbkUn8s4FRTzpWQwNpIxVQ7stXN507PHozVcObOzPj1fA2WtKRSyItFig5FF1/61fUiT/iCb8DWNljgM77iOzBDtwdgnkOEOGxAl3Dur4QLBhkRo8gRMcofDoewF6Hd8AlyAYxl5pilVbb1yBvHGEruukwkE@uEuc/IqdEPJvynasTY9sdS6Yq3YhwD@m8 "R – Try It Online")
Sadly, this does not look as golfed as I'd hoped.
**Input**: an R matrix, and the challenge parameters. **Output**: the matrix after R generations.
The algorithm pads the matrix with zeros to handle the boundaries. Then, iteratively: 1st) it applies the Birth rule and 2nd) it kills the pre-existing cells that did not pass the Survival rule. Padding is removed when returning.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~156~~ ~~149~~ 146 bytes
```
lambda R,g,c:g and f(R,g-1,[[`sum(sum(l[y+y/~y:y+2])for l in c[x+x/~x:x+2])-c[x][y]`in R[c[x][y]]for y,_ in e(c)]for x,_ in e(c)])or c
e=enumerate
```
[Try it online!](https://tio.run/##vY/PisIwEMbv8xS5mdARm666S8GX8Dob1lhTFdpYuhWSi6/eTVRWA55lGMLvmz@Zr/PD4WSLsV59j41utzvN1rjHqtwzbXes5oGmEok2v@eWx2zIZ3528aXPCiXqU88adrSsIpe52cWVLsrTgIq82oTKmu6gYrPHn9hueCWu7J5YBK7ArIw9t6bXgxn/19ecJsUEQyqUeY4EJDEJhUA5JhGlN3eBEiWwrj/agbW64@HFRgBcFYDEj/xYfEZL8@VXdFXcTOV4z9t6@YwyvefxsUzPS2Zj9fVZ4x8 "Python 2 – Try It Online")
Takes input:
* `R`ules: `[birth,survial]` rules as list of `string`. eg.(`['135','246']`)
* `g`enerations: `int`
* `c`onfiguration: Square 2D array of `1/0` or `True/False`
Returns 2d array of `True/False`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~38~~ ~~36~~ 34 bytes (SBCS)
* Saved ~~2~~ 4 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)!
```
{(((1⊥,)∊⍺(⍵+1)⊃⍨4⊃,)⍤⊢⌺3 3⍣⍵⍵)⍺⍺}
```
[Try it online!](https://tio.run/##JU07CsJAFOxziuncxSjZfEyuYOUZAhIRVhLUJkgqQSQkYmNp4wc8gB9I603eRdYXA/PewAwzE2d6MM1jnc7M902744bqhoHuXoyWCn5nZKnOk7nWSNIlVDR0eivWbyZpc0IIReXdlrQvOSw41VeSyi3VD5/JltxfXqhqPHhUX7ty2c0VxtDhNJ5wkWMt4jVzgIDqp2MJFy5VHxYlq8pScOHBR4ARQkQQ7CCBcuTfCBD@AA "APL (Dyalog Unicode) – Try It Online")
Can be invoked with `birth_rule (start_grid f epochs) survival_rule`, where `f` is the operator. Requires 0-indexing.
~~For some reason, using the trains `(+/,)` and `(4⊃,)` to make it 36 bytes [doesn't work](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqDQ0NbX0dzUcdXRqPencB8VZtQ81HXc2PeldomABpHU1NzUc9u4wVjB/1LgbKApEmUCEQ1f5/1DsXZMaj3j6gwkPrjR@1TXzUNzU4yBlIhnh4Bv8H0p7@QBUGXLmJJUDaVMH0Ue8WAy4NIwWjRz3bgYKaQFFDLkMFIwVjBRMFUwUzBXMFCwUNoIxCmoKhgSZYwlTBHAA).~~ As ovs explained, it's because `⌺` calls functions dyadically. Anyway, their new solution is 34 bytes.
---
`⍣` can repeatedly apply a function some number of times, given a starting value. In this case, the starting value is the left operand, and the right operand tells it how many times to repeat.
`((1⊥,)∊⍺(⍵+1)⊃⍨4⊃,)⍤⊢⌺3 3` computes the next generation. The stencil operator (`⌺`) creates windows of a given shape (a 3x3 square here), applies a function on each of them, and puts them back together into a matrix. For cells on the edge of the grid, it will use zeroes, which works well with this challenge.
The train `((1⊥,)∊⍺(⍵+1)⊃⍨4⊃,)⍤⊢` is applied to each of those windows. `⍤⊢` applies the stuff before it to the second argument. `1⊥,` calculates the number of neighbors (including the cell) by turning the 2D window into a vector (`,`) and then summing it (`1⊥`). `∊` checks if that the number of neighbors is in either the birth rule or survival rule vector. Whether the birth rule or survival rule is chosen depends on the train `⍺(⍵+1)⊃⍨4⊃,`.
`4⊃,` turns the window into a vector and chooses the 5th cell, which is the cell we are calculating the next generation of. `⍺(⍵+1)` is an array where the first element is the birth rule and the second element is the survival rule, but with its elements increased by one (because we're including the current cell). Then `⊃⍨` uses the current cell/5th cell/middle cell to index into this array, so if the cell's dead (0) the birth rule will be used, and if the cell is alive (1) the survival rule will be used.
] |
[Question]
[
This is going to be relatively challenging code-golf challenge.
**Input:** Any URL, must have the protocol attached, e.g. <http://codegolf.stackexchange.com> (which will be our test case)
**Output:** A generated QR Code that represents this URL, which, when scanned by a smart device will take you to that URL on the smart device's browser.
Rules for this Code-Golf
1. As usual, smallest code wins.
2. No external web resources, libraries or plugins to generate the code for you. Your code must calculate the QR code image.
3. Output can be presented by an image, generated by HTML5/CSS3, or even using appropriate Unicode blocks, or if your platform's ASCII has it available, through ASCII characters that can form the QR code (this last one is directed at Commodore 64 Basic, Amiga QBasic, Amstrad Basic, etc users), but it must generate a QR code output such that I can scan the code.
4. Entries of the code must be followed with the generated output, either by a screen shot of the output after executing your code, or with a link showing the output (whichever suits the situation best)
5. You are to test your code with the URL "<http://codegolf.stackexchange.com>", and report the output in accordance to Rules 3 to 4.
6. You are to also test your code with a URL of your choice, and report the output in accordance to Rules 3 to 4.
References:
1) <http://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders>
2) <http://www.pclviewer.com/rs2/calculator.html>
3) <http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction>
4) <http://en.wikipedia.org/wiki/QR_code>
5) <http://www.qrstuff.com/> for inspiration... ;)
[Answer]
# Python 3: 974 chars [[nb]](https://gist.github.com/nicktimko/b57b489515a4521500dc)
Further beat with the ugly stick, [see notebook on GH-Gist](https://gist.github.com/nicktimko/b57b489515a4521500dc). Python 3 has built-in ASCII-85 encoding, which helps with the zipped saus. 3's more advanced built-in compression algorithms (LZMA) don't seem to work well with such small things.
Zipping is very fickle about changing characters around, was almost tempted to write something that would randomly try different 1-letter names for variables to minimize the zipped size.
# Python 2: 1420 1356 1085 1077 characters

I read the first argument passed when called, which can be a string up to 106-ish characters long. The output is always a version 5-L QR code and mask 4 which means it's 37x37 modules large and can only handle ~5% damage.
The program's only dependencies are `numpy` (array manipulations) and `matplotlib` (display only); **all Reed-Solomon encoding, data packing, and module layout is handled within the provided code**. For RS, I basically robbed the [Wikiversity functions](https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#RS_generator_polynomial)...it's still kind of a black-box for me. Learned a ton about QR in any event.
Here's the code before I beat it with the ugly stick:
```
import sys
import numpy as np
import matplotlib.pyplot as plt
# version 5-L ! = 108 data code words (bytes), 106 after metadata/packing
### RS code stolen from https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#RS_generator_polynomial
gf_exp = [1] + [0] * 511
gf_log = [0] * 256
x = 1
for i in range(1,255):
x <<= 1
if x & 0x100:
x ^= 0x11d
gf_exp[i] = x
gf_log[x] = i
for i in range(255,512):
gf_exp[i] = gf_exp[i-255]
def gf_mul(x,y):
if x==0 or y==0:
return 0
return gf_exp[gf_log[x] + gf_log[y]]
def main():
s = sys.argv[1]
version = 5
mode = 4 # byte mode
dim = 17 + 4 * version
datamatrix = 0.5 * np.ones((dim, dim))
nsym = 26
# PACK
msg = [mode * 16, len(s) * 16] + [ord(c) << 4 for c in s]
for i in range(1, len(msg)):
msg[i-1] += msg[i] // 256
msg[i] = msg[i] % 256
pad = [236, 17]
msg = (msg + pad * 54)[:108]
# MAGIC (encoding)
gen = [1]
for i in range(0, nsym):
q = [1, gf_exp[i]]
r = [0] * (len(gen)+len(q)-1)
for j in range(0, len(q)):
for i in range(0, len(gen)):
r[i+j] ^= gf_mul(gen[i], q[j])
gen = r
msg_enc = [0] * (len(msg) + nsym)
for i in range(0, len(msg)):
msg_enc[i] = msg[i]
for i in range(0, len(msg)):
coef = msg_enc[i]
if coef != 0:
for j in range(0, len(gen)):
msg_enc[i+j] ^= gf_mul(gen[j], coef)
for i in range(0, len(msg)):
msg_enc[i] = msg[i]
# PATTERN
# position marks
for _ in range(3):
datamatrix = np.rot90(datamatrix)
for i in range(4):
datamatrix[max(0, i-1):8-i, max(0, i-1):8-i] = i%2
datamatrix = np.rot90(datamatrix.T)
# alignment
for i in range(3):
datamatrix[28+i:33-i, 28+i:33-i] = (i+1)%2
# timing
for i in range(7, dim-7):
datamatrix[i, 6] = datamatrix[6, i] = (i+1)%2
# the "dark module"
datamatrix[dim-8, 8] = 1
# FORMAT INFO
L4 = '110011000101111' # Low/Mask4
ptr_ul = np.array([8, -1])
steps_ul = [0, 1] * 8 + [-1, 0] * 7
steps_ul[13] = 2 # hop over vertical timing
steps_ul[18] = -2 # then horizontal
ptr_x = np.array([dim, 8])
steps_x = [-1, 0] * 7 + [15-dim, dim-16] + [0, 1] * 7
for bit, step_ul, step_x in zip(L4, np.array(steps_ul).reshape(-1,2), np.array(steps_x).reshape(-1,2)):
ptr_ul += step_ul
ptr_x += step_x
datamatrix[tuple(ptr_ul)] = int(bit)
datamatrix[tuple(ptr_x)] = int(bit)
# FILL
dmask = datamatrix == 0.5
cols = (dim-1)/2
cursor = np.array([dim-1, dim]) # starting off the matrix
up_col = [-1, 1, 0, -1] * dim
down_col = [1, 1, 0, -1] * dim
steps = ([0, -1] + up_col[2:] + [0, -1] + down_col[2:]) * (cols/2)
steps = np.array(steps).reshape(-1, 2)
steps = iter(steps)
# bit-ify everything
msg_enc = ''.join('{:08b}'.format(x) for x in msg_enc) + '0' * 7 # 7 0's are for padding
for bit in msg_enc:
collision = 'maybe'
while collision:
cursor += steps.next()
# skip vertical timing
if cursor[1] == 6:
cursor[1] = 5
collision = not dmask[tuple(cursor)]
datamatrix[tuple(cursor)] = int(bit)
# COOK
mask4 = lambda i, j: (i//2 + j//3)%2 == 0
for i in range(dim):
for j in range(dim):
if dmask[i, j]:
datamatrix[i, j] = int(datamatrix[i, j]) ^ (1 if mask4(i, j) else 0)
# THE PRESTIGE
plt.figure(facecolor='white')
plt.imshow(datamatrix, cmap=plt.cm.gray_r, interpolation='nearest')
plt.axis('off')
plt.show()
if __name__ == '__main__':
main()
```
After:
```
import sys
from pylab import*
n=range
l=len
E=[1]+[0]*511
L=[0]*256
x=1
for i in n(1,255):
x<<=1
if x&256:x^=285
E[i]=x;L[x]=i
for i in n(255,512):E[i]=E[i-255]
def f(x,y):
if x*y==0:return 0
return E[L[x]+L[y]]
m=sys.argv[1]
m=[ord(c)*16 for c in'\4'+chr(l(m))+m]
for i in n(1,l(m)):m[i-1]+=m[i]/256;m[i]=m[i]%256
m=(m+[236,17]*54)[:108]
g=[1]
for i in n(26):
q=[1,E[i]]
r=[0]*(l(g)+l(q)-1)
for j in n(l(q)):
for i in n(l(g)):r[i+j]^=f(g[i],q[j])
g=r
e=[0]*134
for i in n(108):
e[i]=m[i]
for i in n(108):
c=e[i]
if c:
for j in n(l(g)):e[i+j]^=f(g[j],c)
for i in n(108):e[i]=m[i]
m=.1*ones((37,)*2)
for _ in n(3):
m=rot90(m)
for i in n(4):m[max(0,i-1):8-i,max(0,i-1):8-i]=i%2
m=rot90(m.T)
for i in n(3):m[28+i:33-i,28+i:33-i]=(i+1)%2
for i in n(7,30):m[i,6]=m[6,i]=(i+1)%2
m[29,8]=1
a=array
t=tuple
g=int
r=lambda x:iter(a(x).reshape(-1,2))
p=a([8,-1])
s=[0,1]*8+[-1,0]*7
s[13]=2
s[18]=-2
P=a([37,8])
S=[-1,0]*7+[-22,21]+[0,1]*7
for b,q,Q in zip(bin(32170)[2:],r(s),r(S)):p+=q;P+=Q;m[t(p)]=g(b);m[t(P)]=g(b)
D=m==0.1
c=a([36,37])
s=r(([0,-1]+([-1,1,0,-1]*37)[2:]+[0,-1]+([1,1,0,-1]*37)[2:])*9)
for b in ''.join('{:08b}'.format(x) for x in e):
k=3
while k:
c+=s.next()
if c[1]==6:c[1]=5
k=not D[t(c)]
m[t(c)]=g(b)
a=n(37)
for i in a:
for j in a:
if D[i,j]:m[i,j]=g(m[i,j])^(j%3==0)
imshow(m,cmap=cm.gray_r);show()
```
(relying on a tab to count as 4/8/whatever number of spaces >= 2., not sure how well it will copy)
Because it's so long, we can zip it (saw someone do this somewhere else, forgot who though :( ) to save some more characters, bringing the total down to **1085** **1077** because `pylab` is filthy:
```
import zlib,base64
exec zlib.decompress(base64.b64decode('eJxtU0tzmzAQvvSkX6FLaglkyiM2hHRvyS2HZNobo3QwwY6IBVjQFrfT/96V3KR4Wg5I+/6+3ZXSfWdGOhwHsjWdpv1xX26oclqPtGDKdleTPezrltxCEUm/CKW3iiJyB/YWr9ZkgohsO0MVVS1tWSTi1YrnhE4fP6KFqi2d3qNfPj1CnK0IvS2UhOn6rpgkqHkkxolVFPPceeBviRpJnuot3bJJHG1Sm807AoS5qcevpqUhoX9ut4VN6d8VRymJBuQUlGb3DUGjVHTmiVXci9bUVqyw4uLdwq+eDdszzbmv5TkJp801gkDSgKf8gCSu7cVJF5a6Bqb9Ik7WIkqxLZe8yKMwk2RnW3VGbW3BH1AtLDmJoF3/sPiO+3t24MuIEwetOUVYnY3Bb5bHuvPcFMpv5CNs2Q6TiUPRSAzegSG1yxoll2dkwsxmql+h/8dWgbW69lY5favazKvWs6qNFBX/J8/fChqCyOvaemAsSQX34pPzl5NzYktqMN14FWKbyZzhpW26LicWCmw9z7OlEucibs1FTN7Cg89nQBIbH2e+ypMEQ99uEpjyI46RM+dUJKEbslhb4Gsxc8MsVyKTuMIllMaURzLC+LXf1zhd1Y7EwL7Um6eSTrkaa8NKNvHA1MNz2ddsia+Ac9JDyYpM4ApxMuBoRCS9zC/QilNKyVBEiYTYnlhoGZN7648Ny9D/E7z6YUAci9g9PpshdRQ24iAeLI0fqmcbhczjKA15EedSGDZw/H3CqfU+HK7vfXjA1R1ZzyXs2IY74f6PQG5A44sKIlK5+muRpA6wYQwr2gfALBZEYwUvSV0V/832j4l7V6ehbCzAxSJoOgS4+JmH2ebXIkCLLkfslxv8ZH1quxIvkBD6/Vnta/pyWv3KhyFo62lk3Ml2P/FpAaxzd66c9gXabqQ3SKniuMT6dDlxKwE7k85WpMxn76zMX9Pe4BI00u1CY0NPF/7ImosEm8OJ0sNz951pUemyh0oHO9yJL4ZfOzX/DQ2mdSs='))
```

If you replace the last line with the following (it adds 62 chars), you get nearly-perfect output, but the other still scans, so whatever.
```
figure(facecolor='white');imshow(m,cmap=cm.gray_r,interpolation='nearest');axis('off');show()
```

] |
[Question]
[
**Challenge**
The goal of this challenge is to make a function that takes an input string, a start keyword and a end keyword. The output extracted result is from (but excluded) the given start keyword to (but excluded) end keyword. The output sub-string follows the rules as below.
* In all cases, the leading/trailing spaces in output sub-string should be removed.
* If the given start keyword is an empty string, it means that the anchor is at the start of the input string. Otherwise, the first occurrence of the given start keyword is an start anchor. If there is no any occurrence of the given start keyword, the output is an empty string.
* If the given end keyword is an empty string, it means that the anchor is at the end of the input string. Otherwise, the first occurrence of the given end keyword is an end anchor. If there is no any occurrence of the given end keyword, the output is an empty string.
* If the location of start anchor is after than the location of end anchor, or a part of the first occurrence of the given start keyword and a part of the first occurrence of the given end keyword are overlapped, the output is an empty string.
Similar but different from [Extract a string from a given string](https://codegolf.stackexchange.com/q/50379/100303), the given start and end anchors are multiple characters.
Here's an ungolfed reference implementation in C#
```
private static string GetTargetString(string stringInput, string startKeywordInput, string endKeywordInput)
{
int startIndex;
if (String.IsNullOrEmpty(startKeywordInput))
{
startIndex = 0;
}
else
{
if (stringInput.IndexOf(startKeywordInput) >= 0)
{
startIndex = stringInput.IndexOf(startKeywordInput) + startKeywordInput.Length;
}
else
{
return "";
}
}
int endIndex;
if (String.IsNullOrEmpty(endKeywordInput))
{
endIndex = stringInput.Length;
}
else
{
if (stringInput.IndexOf(endKeywordInput) > startIndex)
{
endIndex = stringInput.IndexOf(endKeywordInput);
}
else
{
return "";
}
}
// Check startIndex and endIndex
if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex)
{
return "";
}
if (endIndex.Equals(0).Equals(true))
{
endIndex = stringInput.Length;
}
int TargetStringLength = endIndex - startIndex;
return stringInput.Substring(startIndex, TargetStringLength).Trim();
}
```
**Example Input and Output**
The example input and output is listed as below.
| Input String | Start Keyword | End Keyword | Output |
| --- | --- | --- | --- |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ""(empty string) | ""(empty string) | "C# was developed around 2000 by Microsoft as part of its .NET initiative" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ""(empty string) | ".NET" | "C# was developed around 2000 by Microsoft as part of its" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | "C#" | ""(empty string) | "was developed around 2000 by Microsoft as part of its .NET initiative" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | "C#" | ".NET" | "was developed around 2000 by Microsoft as part of its" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ".NET" | ""(empty string) | "initiative" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ""(empty string) | "C#" | ""(empty string) |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ".NET" | "C#" | ""(empty string) |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | "ABC" | "C#" | ""(empty string) |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ".NET" | "XYZ" | ""(empty string) |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | "ABC" | "XYZ" | ""(empty string) |
**Rules**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The answer with the fewest bytes wins.
[Answer]
# JavaScript (ES6), ~~80~~ 75 bytes
This contains some unprintable characters which are escaped below.
```
(s,a,b)=>s.replace(b||/$/,"").replace(a,"").match(/ *(.*?) *|$/)[1]||""
```
[Try it online!](https://tio.run/##tZHLTsMwEEWldtevGE27sKMQB/YBQcQSVix4iMUkccAoxJFtUiHl30NCo7aIPhBQS17YujrHd/xCNdnUqModlTqTbR61zPrkJzw6tYGRVUGpZEnTiJnwcYx8eUc@jrrjK7n0mYkReCzwzjh442Ym@MPxY9MgttYZiADjKczJQiZrWehKZkBGv5UZnIRhCMk7XKnUaKtzB12qIuNA56CcheD68gZUqZwip2qJk0mqS6sLGRT6ieWs4/uA2G/OYVhC/Kdxm7APDtK/CDcL4umXTr3ggHUWtmWhX9s20z@5qzY9/Sfz7R61Xn83ewhvD55fxOvQ/cTbu/s@upc45HYEyX77ywP945xw4VtNGtsP "JavaScript (Node.js) – Try It Online")
### Commented
```
(s, a, b) => // s = input string, a = start keyword, b = end keyword
s.replace( // replace in s:
b || /$/, // look for the end keyword, or the regex /$/ if it's empty
"\3" // and replace it with ETX (end of text)
) //
.replace( // replace in the resulting string:
a, // look for the start keyword
"\2" // and replace it with STX (start of text)
) //
.match( // attempt to match:
/\2 *(.*?) *\3|$/ // "\2" STX
) // " *" followed by optional whitespace
// "(.*?)" followed by a non-greedy string (the payload)
// " *" followed by optional whitespace
// "\3" followed by ETX
// "|$" OR match an empty string to make sure that
// match() doesn't return null
[1] || "" // return the payload string, or an empty string if undefined
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~86~~ ~~77~~ 75 bytes
Saved 9 bytes thanks to [movatica](https://codegolf.stackexchange.com/users/86751/movatica)!!!
Saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
lambda s,a,b:s[s.find(a):(b in s)*s.find(b)if b else None][len(a):].strip()
```
[Try it online!](https://tio.run/##rVLRTsIwFH3fV9yMh62mEkQTE5KZKPFRnnxQgZh2u5XGuS5tQZHw7bMdTCYhPihL2p7dtufce3vKpZ2p4rwSyaTK2RvPGBjKKB@YsekKWWQxI4OYgyzAkJNtiBMpgAPmBmGkCpyOcyz8wWnXWC3LmFQWjTXPQmpjIYE4HClbc7jt4iWkEDZj2NnN3dHtfRNv8PXN8MBvhgvMVYlZSIKNlMFUFVmttU@xj9uSm/nh8am1lExbx4sfJaYWd5zDDrwzA9/awLSaO81@r9cDvoQ7mWpllLDgTnkSUAKkNeDFXfXSSmblAv/D5e8eLYk/Z/CT5tD4hcy1Np1h@oradzaazPuXF2lEoUZn5xEJjNs4XrcDoTQ4S1P0Dvx09myZk0LbPhSaRyeDANznUxSxoe4@cFKHSudgG4soXJm1r3TFNgtfh3B65YB2YLWtcKyTBKfriFRf "Python 3 – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 24 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Full program that prompts for array of `[EndKeyword,StartKeyword,InputString]`. Requires 0-based indexing.
```
⌂deb⊃(⌽⊢↓⍨1⍳⍨⊣,⍷)/⌽¨@0⊢⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862gv@P@ppSklNetTVrPGoZ@@jrkWP2iY/6l1h@Kh3M5B61LVY51Hvdk19oNyhFQ4GIPm@qf@BGv8rgEEBl7q6Agg5KyuUJxYrpKSWpebkF6SmKCQW5ZfmpSgYGRgYKCRVKvhmJhflF@enlSgAVRUkFpUo5KcpZJYUK@j5uYYoZOZllmQmlmSWpapzwQ0GydDMcLCpNHU3rYwHmgq3geqGgx1NQ6Np7HJHJ2famB4RGUVT10PMp7LzAQ "APL (Dyalog Extended) – Try It Online")
`⎕` prompt for input
`⊢` on that…
`⌽¨@0` reverse all the elements that occur at offset 0
`(`…`)/` reduce from the right using the following tacit function:
`⍷` indicate with a Boolean list all the places where the left argument begins in the right argument
`⊣,` prepend the left argument to that
`1⍳⍨` find the offset of the first 1
`⊢↓⍨` drop that many leading elements from the right argument
`⌽` reverse (next time around, do this from the end, and after that, revert order)
`⊃` disclose the enclosure caused by the reduction from a 1-dimensional array to a 0-dimensional array
`⌂deb` **d**elete **e**nding (leading and trailing) **b**lanks
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
(s,a,b)=>s.substr(p=(s+a).indexOf(a)+a.length,b?s.indexOf(b)-p:1/0).trim()
```
[Try it online!](https://tio.run/##zVU9b8IwEJ3LrziFAbsYEzoWBdQixrZLh35KOIkTXBk7yhkKqvrbqVEJS2EqRAwe7vzk9/zupPchFgKTUhWuY2wq11m0JsgEi2k0QI7zGF1JiohgW1CuTCqXDxkRtC24liZ3UxYPcdePaae47nVDyl2pZoSunUSXCJQIEUwawagJnwIhlQupbSFTEKWdmxSuwjCEeAV3Kikt2syBRxWidGAzUA6B348fQRnllHBqIQO4CAIiZ4VbgdenTE73do7Gd2rpG1DwD8FHFjhq7pd5jmb@aq0MPAf3Ki1//atxo/aO8DT/rIHq5nZUL9OBGZ5idZ@eX2obVR1cWwcPUE36jV0obFOCY6GVI60306I8s@VYJFOilZEQDeCrAaClg1dkIBjEDOS7D5PNNZ8J55HdgF8Og25OfV2QZTRYctQqkaTHOj1K@/6BxBq0WnJtc5JV8RZJBlXhUd/@rH8A "JavaScript (Node.js) – Try It Online")
Quite straightforward...
[Answer]
# [Ruby](https://www.ruby-lang.org/), 66 bytes
```
->w,s,e,r=Regexp{"#{w[/#{r.quote s}\K.+(?=#{r.quote e})/]}".strip}
```
[Try it online!](https://tio.run/##rZBND8FAEIbvfsVkeyGqGvfV0DgJB3HweSidlU3Ert2tkqa/vb4VQSQc5jLPzPvOOyqa7TJGs0o9trWNtqI9XOBWJsRK4nHVSpSzjoRB0Omk7ZSLHs1bmJaq05Q42igu00wDBeJbEAcaQtzgUkgMIVAiWoVQc10XZjvo8LkSWjADhykZKAOCATcanG6rD3zFDQ8M3yApFGR0aLOxBpuQU02B/tXhyeDIfzV5JerdVB@ob92n@n@ks/59qN8TndXyqz9882j/IvVV4Q1uNP0vlgfD0aftd5gJcTr@grI9 "Ruby – Try It Online")
Another method without the use of regex,
# [Ruby](https://www.ruby-lang.org/), 72 bytes
```
->w,s,e{"#{w[((w+s).index(s)+s.size rescue 0)...w.rindex(e)||0]}".strip}
```
[Try it online!](https://tio.run/##rZA9b8IwEIZ3fsXJWRKRWhZ7qNqoI0wMBcQQyFk6qYojn4OhwG8PHwFKK0CVYPDix/e899pW02Wtk/ql62OOcSWClR@HoW9zJKnIcRFy1GbJ9I1gkWcVgoqklF7aBmO0XqvJRkh2lspNzZCASAPwGUOOc/wyJeaQWVMVOXSUUjBdQo9m1rDRDnavysw6MBrIMcj@xwCoIEeZozmKVqusdtd6zBALcTgTSJ6a8Cdgzx8NuSZ9PVt/0TS4bPX8So3/stTjjRrbz9Z3fnMff6X1yXADv72n/xj@HI7uTd/C2pjD8kdUbwE "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~100~~ 85 bytes
Regex version, still cannot beat the [slicing algorithm](https://codegolf.stackexchange.com/a/217448/).
```
from re import*
r=escape
f=lambda s,b,e:(search(r(b)+'(.+)'+r(e),s)or' ')[1].strip()
```
[Try it online!](https://tio.run/##fYw/b4NADEd3PoVFBu4KQrTdIjE0KGM7MfSPOhzgUywFfPK5qfLpadJsTejg5f3eczjqjqfHefbCIwgCjYFF7xKpMfYuYOLrvRu7wUEsugLXJqKTfmfEdDbPTJnbLBeDtoiWJQPI7Mf9ZxlVKBg7t3XarODbRRjwgHsOOIAT/poGeKiqCrojPFMvHNkrnKzgRIE9kEYoX7Yt0ERKTumAaZIEoUmNN20BaXo@a6/YufrLm9Ut@0Jv@b9s4f@pWrCvl6dN83/y@va@0FyW@Qc "Python 3 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes
```
(.*)¶(.+)?¶.*?\1 *(.*?) *(?<!(?=\2).*)(?(2)\2.*|$)|(.|¶)+
$3
```
[Try it online!](https://tio.run/##rZDPCoJAEIfvPsWEBrsqi27XYinpWJc6VHhoyxUWwhXdjMDn8gF8MVsPvcFc5s@P4eNjGmV1JaclOd1jj7CQjoOr4@AmL@DjEKTTP42omHORpxC6TFDXxHpBxCbn1N0QQTjNOQv7gPaE9eNAIy9YTVPmw0e2UKhOvUytCpCNeVcF8CRJ4PGFg342pjWlBXdVy8aCKUHbFthxfwZdaaul1Z2KYw8PNQd4uMyPUWG4dvOO@bvMR3bDBG53Gb7g5XrDNXTAHw "Retina 0.8.2 – Try It Online") Takes input as start, end, string on separate lines but link is to test suite with header that converts from comma separated string, end, start for convenience. Explanation:
```
(.*)¶
```
Match the start keyword.
```
(.+)?¶
```
Optionally match a non-empty end keyword.
```
.*?\1
```
Find the start keyword as early as possible in the string, plus optional spaces.
```
*(.*?) *
```
Match as short a result as possible (so that the end keyword is found as early as possible in the string) but also trim spaces around it.
```
(?<!(?=\2).*)
```
Ensure that the end keyword hasn't already been passed at this point.
```
(?(2)\2.*|$)
```
If the end keyword was empty then only match at the end of the string otherwise match the end keyword and the rest of the string.
```
|(.|¶)+
```
If it wasn't possible to match anything, delete everything.
```
$3
```
Keep the desired result.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 93 bytes
```
sStringTrim@StringTake[s,i=1;If[i*=-1;#=="",0,StringPosition[s,#][[1,i]]]-i&/@#]/._@_:>""&
```
[Try it online!](https://tio.run/##tZLRSsMwFEDf9xUhgT5IurV73OiIFoU9KBP74CyhxDXVi7YpSbohpT/hH/iFfkKNq59g3i7h5HBuSC3sq6yFhYMYq2Q0359fD1ZD85JpqNnfKN5kbigk8Xpb5XCRhPGaJAnGNKITsVMGLKjGUYTneUyBcx5CsGCEL@YFK1YbjIPxvgNp2c7dsHlPyBBuqtzxZOkgU0yq1SZT0@Rk26bt7I3SNecBY6yf9Tgl6CQMKuVRvqtWlkho1TUlWkZRhJ4/0C0ctDKqsshRrdAWqQqBNWh@d50haFyn2/YoMe3dAhgPA/1/6@@pB3NK/BSfvZ6az1pf7@zCvRV7cV9epZ6zH/dP3rr9uIXx8z9OwnmdfBhmw/gD "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 90 bytes
```
func[t s e][p:""if""<> s[append s" "]if e =""[e:[end]]parse t[thru s copy p to[opt" "e]]p]
```
[Try it online!](https://tio.run/##XVA9T8MwEN3zK57cmSpijKASRIwwIAbA8mDis2qpxJZ9aemvD5cUlIDl4X3cezo7kxufyWlT@QajH/pOMwrI6NQoFbxSNzsUbVOi3qEoKBM8CLdKaWq0iMYkmwuBNe/zINkupjMSOOqYWAIkE2Zk@uIGqt3gZAscHekQEznYHAdpvq7rGh9nPIYuxxI9Q6akmBE9Ahdsnx5eEPrAwXI4kvROt/Ixk@320PPOFeRcjF805X5Yu1mcGa@8Ga5zMrA427Vwd9/@94W/vr3/8Rd@skJtUZXRSDn0DI3pN6Cudgqf8eDgL4K8AQZm/AY "Red – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~168~~ ~~152~~ ~~143~~ ~~132~~ 112 bytes
An enormous **-38** thanks to @ceilingcat
```
#define r strstr(c
*f(c,s,e)int*c,*s,*e;{return*e&&r,s)>r,e)|!r,s)|!r,e)||*e&&(*r,e)=0)?"":r,s)+strlen(s)+!!*s;}
```
[Try it online!](https://tio.run/##ZVLRToMwFH3nK@5KZoDVhS0xJmOb0cVHffJBZTxgKa4JFtKWmWXj2@ctzI1oQ3rPPef2tL2FXX8ydnSFZEWdcZhrk4lyvFke3YznQnJQoI3Cz2NOkHuMasp9IU3AaKBpwKO94qZWMuBXV4pqf6lQPwwstDPig5W8wOJF6N8RMrPiCC0LLj1Eg0Ggo@aIpvCVCun5sHccwME2qQIhq9rECSyArFz4TjVkfMuLsuIZpKqsZQbTMAzhYwdPgqlSl7kBrKpSZaDMQRgN4@fHFzQSRqRGbDmJLvasrHbxJAyTHme4Nsgl8TSJb@zO@z0hlJCGQgusXZes3DPfwovSot4alPv8b3r/sPovvr6999U2haY7YDvlpfJsuwSeLYwwzGFi42hkewencQbYalbtPHtV2rbTj85apdAo98jwVsNQr@XfuJaEAtEGuzlD1LZGJHGYIMtl1ucmllNc10Vbmncb9lZcCv3TCZruobtfCK/iNMcf "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6) ~~95~~ 92 Bytes, No Regex!
```
(i,s,e,t=i.indexOf(s),r=i.lastIndexOf(e))=>t!=-1&r!=-1?(i.substring(t+s.length,r)).trim():''
```
### How to try it:
Open your browser's JavaScript Console and paste the following.
```
((i,s,e,t=i.indexOf(s),r=i.lastIndexOf(e))=>t!=-1&r!=-1?(i.substring(t+s.length,r)).trim():'')('C# was developed around 2000 by Microsoft as part of its .NET initiative', 'C#', '.NET')
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
≔⎇ζ…θ⌕θζθθ≔⎇η⪫Φ⪪θηκηθθ≔⌕AEθ›ι ¹ε¿ε✂θ⌊ε⊕⌈ε
```
[Try it online!](https://tio.run/##XU3LasMwELz7K5bkIoNanFxzCqYpLaQEkh9QpXW9VJacleLG@XlVSnvKwjAwOw/dK9Ze2ZS2IdCXEydkp3gWNwntrC22vR/FWcKOnCl8q2sJ5zs21UOml/DuyYkd2YgsjqOlWDJ9tn/Xf/wQLbVba8Ve3VdeGVWJkoQFLMrUKgOznzoQWMOByUVxtKSx@PfkaLgM@SPhzWnGAV1Ek@uu/3q@TUrtEn5UAIMTWj@iAcX@4gysm6aBzzn3aPbBdxGya1QcwXdAMcDzx8sJ8kgkFWnCql1WRUpPk/0F "Charcoal – Try It Online") Link is to verbose version of code. Take care to include sufficient newlines in the input even if one of the keywords is empty. Explanation:
```
≔⎇ζ…θ⌕θζθθ
```
If the end keyword is not empty then truncate the string at its first appearance. (Fortunately `CycleChop` truncates the string to empty if its input is negative.)
```
≔⎇η⪫Φ⪪θηκηθθ
```
If the start keyword is not empty then split the string on the keyword, discard the first element, and join the string again. This results in an empty string if the start keyword does not appear in the string.
```
≔⌕AEθ›ι ¹ε
```
Check whether the string has any non-spaces.
```
¿ε✂θ⌊ε⊕⌈ε
```
If so then print from the first to the last non-space.
[Answer]
# [R](https://www.r-project.org/), 111 bytes
```
function(s,a,b,c=?s,`?`=nchar,r=regexpr)trimws(substr(s,`if`((d=r(a,s,f=T))>0,d+?a,c),`if`(?b,r(b,s,f=T)-1,c)))
```
[Try it online!](https://tio.run/##dY@xTsQwDIZ3nsLqLYkIqLCHCipGmG4ApjppckSCpLLTKzx9CcctSI2U6f/@z7FpNS4vzkXOFOJBr36ONocUBStURlndsRq6QUf7jqRIkzu4r4lkqX8uLHg2xSzlIfhBiFGTQMXK672Ud60aLztUVv7RzigS5kyvbkou5cq66XewIMPoju4jTW4EpDTHEW7btgXzDU/BUuLkM5TWhJQheQiZ4fr5cQ8hhhwwh6NrLv7dUpZqmvLkZvzrbqF@V3FOoGad8upfRd0A9w99lZ3nvby@1c0KXLAw5ILWHw "R – Try It Online")
Straightforward approach: finds bounding words using `regexpr` (with argument `f`ixed=`T`rue to ensure that the text string is not interpreted as a regex), gets the `substr`ing between them, and then `trim`s the `w`hite`s`pace from both ends.
Since the functions `nchar` and `regexpr` are each used twice, it's shorter to define single-character aliases. In the case of `nchar`, we can even redefine the unary operator `?` as its alias, so that we avoid the need for parentheses. Unfortunately, this trick isn't possible here for `regexpr` because of the need to feed it the additional argument `f`ixed=`T`rue.
[Answer]
## C# 114 bytes
```
(i,s,e)=>{int p=(i+(s??="")).IndexOf(s)+s.Length,q=$"{e}"==""?i.Length:i.IndexOf(e);return p<q?i[p..q].Trim():"";}
```
] |
[Question]
[
### Background
The [Burrows–Wheeler transform](http://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform) (BWT) is a reversible permutation of the characters of a string that results in large runs of similar characters for certain types of strings such as plain text. It is used, for example, in the [bzip2 compression algorithm](http://en.wikipedia.org/wiki/Bzip2).
The BWT is defined as follows:
Given an input string such as `codegolf`, compute all possible rotations of it and sort them in lexicographical order:
```
codegolf
degolfco
egolfcod
fcodegol
golfcode
lfcodego
odegolfc
olfcodeg
```
The BWT of the string `codegolf` is the string consisting of the last character of each string in that order, i.e., the last column of the block above. For `codegolf`, this yields `fodleocg`.
By itself, this transformation isn't reversible, since the strings `codegolf` and `golfcode` result in the same string. However, if we know that the string ends with an `f`, there is only one possible preimage.
### Task
Implement an involutive program or function that reads a single string from STDIN or as command-line or function argument and prints or returns either the BWT or its inverse of the input string.
If the input string contains no spaces, your submission should append a single space to the input and compute the BWT.
If the input string already contains a space, it should compute the preimage of the BWT that has a trailing space and strip that space.
### Examples
```
INPUT: ProgrammingPuzzles&CodeGolf
OUTPUT: fs&e grodllnomzomaiCrGgPePzu
```
```
INPUT: fs&e grodllnomzomaiCrGgPePzu
OUTPUT: ProgrammingPuzzles&CodeGolf
```
```
INPUT: bt4{2UK<({ZyJ>LqQQDL6!d,@:~L"#Da\6%EYp%y_{ed2GNmF"1<PkB3tFbyk@u0#^UZ<52-@bw@n%m5xge2w0HeoM#4zaT:OrI1I<|f#jy`V9tGZA5su*b7X:Xn%L|9MX@\2W_NwQ^)2Yc*1b7W<^iY2i2Kr[mB;,c>^}Z]>kT6_c(4}hIJAR~x^HW?l1+^5\VW'\)`h{6:TZ)^#lJyH|J2Jzn=V6cyp&eXo4]el1W`AQpHCCYpc;5Tu@$[P?)_a?-RV82[):[@94{*#!;m8k"LXT~5EYyD<z=n`Gfn/;%}did\fw+/AzVuz]7^N%vm1lJ)PK*-]H~I5ixZ1*Cn]k%dxiQ!UR48<U/fbT\P(!z5l<AefL=q"mx_%C:2=w3rrIL|nghm1i\;Ho7q+44D<74y/l/A)-R5zJx@(h8~KK1H6v/{N8nB)vPgI$\WI;%,DY<#fz>is"eB(/gvvP{7q*$M4@U,AhX=JmZ}L^%*uv=#L#S|4D#<
OUTPUT: <#Q6(LFksq*MD"=L0<f^*@I^;_6nknNp;pWPBc@<A^[JZ?\B{qKc1u%wq1dU%;2)?*nl+U(yvuwZl"KIl*mm5:dJi{\)8YewB+RM|4o7#9t(<~;^IzAmRL\{TVH<bb]{oV4mNh@|VCT6X)@I/Bc\!#YKZDl18WDIvXnzL2Jcz]PaWux[,4X-wk/Z`J<,/enkm%HC*44yQ,#%5mt2t`1p^0;y]gr~W1hrl|yI=zl2PKU~2~#Df"}>%Io$9^{G_:\[)v<viQqwAU--A#ka:b5X@<2!^=R`\zV7H\217hML:eiD2ECETxUG}{m2:$r'@aiT5$dzZ-4n)LQ+x7#<>xW)6yWny)_zD1*f @F_Yp,6!ei}%g"&{A]H|e/G\#Pxn/(}Ag`2x^1d>5#8]yP>/?e51#hv%;[NJ"X@fz8C=|XHeYyQY=77LOrK3i5b39s@T*V6u)v%gf2=bNJi~m5d4YJZ%jbc!<f5Au4J44hP/(_SLH<LZ^%4TH8:R
```
```
INPUT: <#Q6(LFksq*MD"=L0<f^*@I^;_6nknNp;pWPBc@<A^[JZ?\B{qKc1u%wq1dU%;2)?*nl+U(yvuwZl"KIl*mm5:dJi{\)8YewB+RM|4o7#9t(<~;^IzAmRL\{TVH<bb]{oV4mNh@|VCT6X)@I/Bc\!#YKZDl18WDIvXnzL2Jcz]PaWux[,4X-wk/Z`J<,/enkm%HC*44yQ,#%5mt2t`1p^0;y]gr~W1hrl|yI=zl2PKU~2~#Df"}>%Io$9^{G_:\[)v<viQqwAU--A#ka:b5X@<2!^=R`\zV7H\217hML:eiD2ECETxUG}{m2:$r'@aiT5$dzZ-4n)LQ+x7#<>xW)6yWny)_zD1*f @F_Yp,6!ei}%g"&{A]H|e/G\#Pxn/(}Ag`2x^1d>5#8]yP>/?e51#hv%;[NJ"X@fz8C=|XHeYyQY=77LOrK3i5b39s@T*V6u)v%gf2=bNJi~m5d4YJZ%jbc!<f5Au4J44hP/(_SLH<LZ^%4TH8:R
OUTPUT: bt4{2UK<({ZyJ>LqQQDL6!d,@:~L"#Da\6%EYp%y_{ed2GNmF"1<PkB3tFbyk@u0#^UZ<52-@bw@n%m5xge2w0HeoM#4zaT:OrI1I<|f#jy`V9tGZA5su*b7X:Xn%L|9MX@\2W_NwQ^)2Yc*1b7W<^iY2i2Kr[mB;,c>^}Z]>kT6_c(4}hIJAR~x^HW?l1+^5\VW'\)`h{6:TZ)^#lJyH|J2Jzn=V6cyp&eXo4]el1W`AQpHCCYpc;5Tu@$[P?)_a?-RV82[):[@94{*#!;m8k"LXT~5EYyD<z=n`Gfn/;%}did\fw+/AzVuz]7^N%vm1lJ)PK*-]H~I5ixZ1*Cn]k%dxiQ!UR48<U/fbT\P(!z5l<AefL=q"mx_%C:2=w3rrIL|nghm1i\;Ho7q+44D<74y/l/A)-R5zJx@(h8~KK1H6v/{N8nB)vPgI$\WI;%,DY<#fz>is"eB(/gvvP{7q*$M4@U,AhX=JmZ}L^%*uv=#L#S|4D#<
```
```
INPUT: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
OUTPUT: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
```
```
INPUT: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
OUTPUT: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
```
### Additional rules
* You cannot use any built-in operators that compute the BWT (or its inverse) of a string.
* You cannot use any built-in operators that invert functions.
* Your code may print a trailing newline if you choose STDOUT for output, even if it doesn't support trailing newlines in the input.
* Your code has to work for any input of 500 or less printable ASCII characters (0x20 to 0x7E), including at most one space.
* For any of the possible inputs described above, your code must finish in under ten minutes on my machine (Intel Core i7-3770, 16 GiB RAM). The last test case should be the slowest, so make sure you time your code with that one.
For most languages and approaches, it should be easy to comply with the time limit. This rule is solely meant to prevent implementing either transform as a brute-force inverse of the other.
* Standard code golf rules apply. The shortest submission in bytes wins.
[Answer]
# Pyth, 29 bytes
```
?tthu+VzSGzz}dzseMS.>L+z\ hlz
```
[Demonstration.](https://pyth.herokuapp.com/?code=%3Ftthu%2BVzSGzz%7DdzseMS.%3EL%2Bz%5C%20hlz&input=fs%26e%20grodllnomzomaiCrGgPePzu&debug=0) [Test harness.](https://pyth.herokuapp.com/?code=Fz%2Bz.z%3Ftthu%2BVzSGzz%7DdzseMS.%3EL%2Bz%5C%20hlz&input=ProgrammingPuzzles%26CodeGolf%0Afs%26e%20grodllnomzomaiCrGgPePzu%0Abt4%7B2UK%3C(%7BZyJ%3ELqQQDL6!d%2C%40%3A~L%22%23Da%5C6%25EYp%25y_%7Bed2GNmF%221%3CPkB3tFbyk%40u0%23%5EUZ%3C52-%40bw%40n%25m5xge2w0HeoM%234zaT%3AOrI1I%3C%7Cf%23jy%60V9tGZA5su*b7X%3AXn%25L%7C9MX%40%5C2W_NwQ%5E)2Yc*1b7W%3C%5EiY2i2Kr%5BmB%3B%2Cc%3E%5E%7DZ%5D%3EkT6_c(4%7DhIJAR~x%5EHW%3Fl1%2B%5E5%5CVW%27%5C)%60h%7B6%3ATZ)%5E%23lJyH%7CJ2Jzn%3DV6cyp%26eXo4%5Del1W%60AQpHCCYpc%3B5Tu%40%24%5BP%3F)_a%3F-RV82%5B)%3A%5B%4094%7B*%23!%3Bm8k%22LXT~5EYyD%3Cz%3Dn%60Gfn%2F%3B%25%7Ddid%5Cfw%2B%2FAzVuz%5D7%5EN%25vm1lJ)PK*-%5DH~I5ixZ1*Cn%5Dk%25dxiQ!UR48%3CU%2FfbT%5CP(!z5l%3CAefL%3Dq%22mx_%25C%3A2%3Dw3rrIL%7Cnghm1i%5C%3BHo7q%2B44D%3C74y%2Fl%2FA)-R5zJx%40(h8~KK1H6v%2F%7BN8nB)vPgI%24%5CWI%3B%25%2CDY%3C%23fz%3Eis%22eB(%2FgvvP%7B7q*%24M4%40U%2CAhX%3DJmZ%7DL%5E%25*uv%3D%23L%23S%7C4D%23%3C%0A%3C%23Q6(LFksq*MD%22%3DL0%3Cf%5E*%40I%5E%3B_6nknNp%3BpWPBc%40%3CA%5E%5BJZ%3F%5CB%7BqKc1u%25wq1dU%25%3B2)%3F*nl%2BU(yvuwZl%22KIl*mm5%3AdJi%7B%5C)8YewB%2BRM%7C4o7%239t(%3C~%3B%5EIzAmRL%5C%7BTVH%3Cbb%5D%7BoV4mNh%40%7CVCT6X)%40I%2FBc%5C!%23YKZDl18WDIvXnzL2Jcz%5DPaWux%5B%2C4X-wk%2FZ%60J%3C%2C%2Fenkm%25HC*44yQ%2C%23%255mt2t%601p%5E0%3By%5Dgr~W1hrl%7CyI%3Dzl2PKU~2~%23Df%22%7D%3E%25Io%249%5E%7BG_%3A%5C%5B)v%3CviQqwAU--A%23ka%3Ab5X%40%3C2!%5E%3DR%60%5CzV7H%5C217hML%3AeiD2ECETxUG%7D%7Bm2%3A%24r%27%40aiT5%24dzZ-4n)LQ%2Bx7%23%3C%3ExW)6yWny)_zD1*f%20%40F_Yp%2C6!ei%7D%25g%22%26%7BA%5DH%7Ce%2FG%5C%23Pxn%2F(%7DAg%602x%5E1d%3E5%238%5DyP%3E%2F%3Fe51%23hv%25%3B%5BNJ%22X%40fz8C%3D%7CXHeYyQY%3D77LOrK3i5b39s%40T*V6u)v%25gf2%3DbNJi~m5d4YJZ%25jbc!%3Cf5Au4J44hP%2F(_SLH%3CLZ%5E%254TH8%3AR%0Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa%0Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab%20aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&debug=0)
This straightforwardly divides into an encoding and decoding segment, with the code deciding which one to use with a ternary.
```
?tthu+VzSGzz}dzseMS.>L+z\ hlz
Implicit:
z = input()
d = ' '
? }dz If there is a space in the input,
u zz Update G to the result of the following,
with G starting as z and repeating len(z) times:
+V The vectorized sum of
zSG z and sorted(G)
h Take the first such result, which will consist of
the first character of z followed by the
first cyclic permuation of the pre-BWT string,
which must start with ' '.
tt Remove the first two characters and return.
L Otherwise, left-map (map with the variable as the
left parameter and a constant as the right)
.> cyclic right shift
+z\ of z + ' '
hlz over range(len(z)+1)
S Sort the shifted strings,
eM take their last charactes,
s combine into one string and return.
```
[Answer]
# CJam, ~~41~~ ~~36~~ 35 bytes
```
q:XS&LX,{X\.+$}*0=1>XS+_,,\fm<$zW>?
```
[Test it here.](http://cjam.aditsu.net/#code=q%3AXS%26LX%2C%7BX%5C.%2B%24%7D*0%3D1%3EXS%2B_%2C%2C%5Cfm%3C%24zW%3E%3F&input=ProgrammingPuzzles%26CodeGolf)
## Explanation
```
q:X e# Read STDIN and store it in X.
S& e# Take the set intersection with " ". We'll use this as a truthy/falsy value to
e# select the correct output later.
# Compute the iBWT:
LX, e# Push an empty array, compute the length of X.
{ e# Run the following block that many times:
X\ e# Push X and pull the other array on top.
.+ e# Add the characters of X to the corresponding line of the other array,
e# i.e. prepend X as a new column.
$ e# Sort the rows.
}*
0= e# Since we just sorted the rows, the first permutation of the output will be
e# one starting with a space, followed by the string we actually want. So just
e# pick the first permutation.
1> e# Remove the leading space.
# Compute the BWT:
XS+ e# Push X and append a space.
_, e# Get that string's length N.
,\ e# Turn it into a range [0 .. N-1], swap it with the string.
fm< e# Map each value in the range to the string shifted left by that many characters.
$ e# Sort the permutations.
zW> e# Transpose the grid and discard all lines but the last.
? e# Choose between the iBWT and the BWT based on whether the input had a space.
```
[Answer]
# Perl 5, 179
Another not-so-good one from me. There are probably some gains to be had in this one, but it's not going to compete with the purpose-built golf languages.
```
$_=<>;@y=/./g;if(/ /){@x=sort@y;for(1..$#y){@x=sort map$y[$_].$x[$_],0..$#x}
say$x[0]=~/^ (.*)/}else{push@y," ";say map/(.)$/,sort map{$i=$_;join"",
map$y[($_+$i)%@y],0..$#y}0..$#y}
```
Un-golfed:
```
# Read input
$_ = <>;
# Get all the chars of the input
my @chars = /./g;
if (/ /) {
# If there's a space, run the IBWT:
# Make the first column of the table
my @working = sort @chars;
# For each remaining character
for (1 .. $#chars) {
# Add the input as a new column to the left of @working,
# then sort @working again
@working = sort map {
$chars[$_] . $working[$_]
} 0 .. $#working;
}
# Print the first element of @working (the one beginning with space), sans space
say $working[0] =~ /^ (.*)/;
} else {
# BWT
# Add a space to the end of the string
push @chars, " ";
# Get all the rotations of the string and sort them
@rows = sort map {
my $offset = $_;
join "", map {
$chars[($_ + $offset) % @chars]
} 0 .. $#chars
} 0 .. $#chars;
# Print all the last characters
say map /(.)$/, @rows;
}
```
] |
[Question]
[
Almost the polar opposite if [this](https://codegolf.stackexchange.com/questions/17907/convert-a-repeated-decimal-to-a-fraction) challenge, and I suspect it will be slightly easier.
Your task is to take two integers in the format `a/b` (Forming a rational number) then output the number in decimal exactly.
For example, if you were to input `1/3`, it would output:
```
0.33333333333333333
```
And would keep on printing 3s until the end of time, with an optional leading 0. (You could also print *one* character per line if and *only if* your language does not allow printing on the same line.)
The behaviour for `x/0` will be undefined. For a number that looks like it doesn't repeat (Like, say `5/4`) it actually does repeat. Either of the following two forms would be acceptable for `5/4`:
```
1.25000000000000000
1.24999999999999999
```
(The same with whole numbers, `1.9999999` or `2.000000`)
The fraction may not be in its simplest form, and `a` or `b` may be negative (Note `-a/b = -(a/b)`, `-a/-b = a/b`, `a/-b = -a/b`, and `-.6249999` is invalid, but `-0.6249999` is acceptable, but you still can use.
[Answer]
# C, 108 ~~79~~
**Edit** Modified to work with negative numbers.
Input from stdin. Old K&R style.
```
main(a,b){char*s="-%d.";scanf("%d/%d",&a,&b);for(a*b<0?(a<0?a=-a:(b=-b)):++s;printf(s,a/b);s="%d")a=a%b*10;}
```
[Answer]
# Ruby, ~~83~~ ~~69~~ ~~102~~ ~~91~~ 89 bytes
```
->s{a,b=s.scan(/\d+/).map &:to_i
eval(s+?r)<0&&$><<?-
$><<a/b<<?.
loop{a=a%b*10
$><<a/b}}
```
Simple implementation of manual integer division based on the computer's integer division.
Thanks to @blutorange for the help in golfing.
Edit: Fixed the solution to include negative numbers.
[Answer]
# CJam, ~~38~~ 37 bytes
```
l'/%:i2*~*0<'-*o:Dmd\zo'.{oA*Dmd\z1}g
```
### How it works
```
l e# Read line from STDIN. STACK '17/-13'
'/% e# Split at '/'. STACK ['17' '-13']
:i e# Cast each element to int. STACK [17 -13]
2*~ e# Duplicate and dump the array. STACK 17 -13 17 -13
* e# Multiply. STACK 17 -13 -221
0< e# Compare with zero. STACK 17 -13 1
'-*o e# Print '-' that many times. STACK 17 -13
:D e# Save the topmost integer in D. STACK 17 -13
md e# Perform modular division. STACK -1 4
\z e# Swap and take absolute value. STACK 4 1
o'. e# Print and push '.'. STACK 4 '.'
{ e# do:
o e# Print. STACK 4
A* e# Multiply by 10. STACK 40
Dmd e# Divide modulo D. STACK -3 1
\z e# Swap and take absolute value. STACK 1 3
o e# Print. STACK 1
1}g e# while(1)
```
[Answer]
# Java, ~~177~~ ~~176~~ 170
```
s->{try{int x=new Integer(s.split("/")[0]),y=new Integer(s.split("/")[1]),z=1;for(;;x=x%y*10,Thread.sleep(999))System.out.print(x/y+(z-->0?".":""));}catch(Exception e){}}
```
The algorithm is straightforward; the tricky part was getting the printing to work. In the end, I had the computer sleep for a second between each step so it could print.
## Expanded, runnable version
```
public class RepeatedDecimal {
public static void main(String[] args) {
java.util.function.Consumer<String> f = s -> {
try {
int x = new Integer(s.split("/")[0]),
y = new Integer(s.split("/")[1]),
z = 1;
for (;; x = x % y * 10, Thread.sleep(999)) {
System.out.print(x / y + (z-- > 0 ? "." : ""));
}
} catch (Exception e) { }
};
f.accept("5/7");
}
}
```
[Answer]
# R, ~~103~~ ~~137~~ ~~109~~ 103
Bit happier with this now. Using scan with a separator save a lot of bytes. May still have some room for improvement.
Replaced `<-` with `=`. Haven't always had the best of luck with this, but it worked this time.
```
cat(if(prod(i=scan(sep='/'))<0)'-',(n=(i=abs(i))[1])%/%(d=i[2]),'.',sep='');repeat cat((n=n%%d*10)%/%d)
```
Test runs
```
> cat(if(prod(i=scan(sep='/'))<0)'-',(n=(i=abs(i))[1])%/%(d=i[2]),'.',sep='');repeat cat((n=n%%d*10)%/%d)
1: -1/3
3:
Read 2 items
-0.33333333333333333333...
> cat(if(prod(i=scan(sep='/'))<0)'-',(n=(i=abs(i))[1])%/%(d=i[2]),'.',sep='');repeat cat((n=n%%d*10)%/%d)
1: -5/-4
3:
Read 2 items
1.250000000000000000000...
```
[Answer]
# Python 3, ~~107~~ 115 bytes
```
a,b=map(int,input().split("/"))
print(("%.1f"%(a/b))[:-1],end="")
b=abs(b)
while 1:a=abs(a)%b*10;print(a//b,end="")
```
Pretty straightforward:
* Input the numerator and denominator
* Output the the quotient with 1 digit after the decimal point, then take off the last digit (e.g. `-1/3` -> `-0.`)
* Take absolute values\*
* Loop:
+ Numerator is remainder after dividing out denominator
+ Multiply numerator by 10
+ Output integer quotient as next digit
\* (Though the calculation for `a` was moved inside the loop to save a few bytes.)
**Edit:** Fixed bug with negative fractions > -1.
[Answer]
# Python 2.7, 209 bytes
```
from sys import*;m,o=1,lambda x:stdout.write(str(x));a,b=[int(x)for x in argv[1].split('/')]
o(str(a*b)[0]);a,b=abs(a),abs(b);o('0'*(b>a))
while 1:
while not((m*a)/b):o('0.'[m==1]);m*=10
o((m*a)/b);a=(m*a)%b
```
## edit:
Now outputs all characters on the same line, as asked.
## edit2:
Now reads the fraction from commandline argument, as requested :)
] |
[Question]
[
Write a program, that determines whether the multiplication table of the given finite magma represents a group.
A magma is a set with a binary operation that is closed, that means
* for all \$a,b\$ in \$G\$, \$a\*b\$ is again in \$G\$ (Closedness)
Let \$(G, \* )\$ be a magma. \$(G, \* )\$ is a group if
* for all \$a,b,c\$ in \$G\$, \$(a\*b) \* c = a \* (b\*c)\$ (Associativity)
* there exists an element \$e\$ in \$G\$ such that \$e \* a = a \* e = a\$ for all \$a\$ in \$G\$ (Existence of neutral Element)
* for all \$a\$ in \$G\$ there is a \$b\$ in \$G\$ such that \$a \* b = b \* a = e\$ where \$e\$ is the neutral element (Existence of Inverse)
## Specs
The input is of a string of \$n^2-1\$ characters (one character for each element of the magma, allowed are `0-9`,`a-z`) and just represents the table read row by row, omitting the operator name. You can assume that the input represents a valid magma (that means each of the elements appears exactly once in the header row/column).
Example:
Here we have the table of \$\mathbb Z\_4\$
```
+ | 0 1 2 3
-----------
0 | 0 1 2 3
1 | 1 2 3 0
2 | 2 3 0 1
3 | 3 0 1 2
```
The input string will be `012300123112302230133012`. (Or if we use symbols it could also be `nezdnnezdeezdnzzdneddnez`). Be aware that the sequence of the elements in the row and in the column do not have to be the same, so the table of \$\mathbb Z\_4\$ could also look like so:
```
+ | 1 3 2 0
-----------
1 | 2 0 3 1
0 | 1 3 2 0
2 | 3 1 0 2
3 | 0 2 1 3
```
This also means that the neutral element is not necessarily in the first column or first row.
If it is a group, the program has to return the character representing the neutral element. If not it has to return a falsy (distinct from the values `0-9a-z`) value
# Test cases
Non-groups can easily be constructed by just altering one digit of the string or by artificially altering the tables defining a operation that contradicts one of the group axioms.
## Groups
### Trivial
```
* | x
-----
x | x
xxx
Neutral Element: x
```
### \$\mathbb H\$ (quaternion group)
```
* | p t d k g b n m
-------------------
m | b d t g k p m n
p | m k g d t n p b
n | p t d k g b n m
b | n g k t d m b p
t | g m n p b k t d
d | k n m b p g d t
k | t b p m n d k g
g | d p b n m t g k
ptdkgbnmmbdtgkpmnpmkgdtnpbnptdkgbnmbngktdmbptgmnpbktddknmbpgdtktbpmndkggdpbnmtgk
Neutral Element: n
```
### \$D\_4\$
```
* | y r s t u v w x
-------------------
u | u x w v y t s r
v | v u x w r y t s
w | w v u x s r y t
x | x w v u t s r y
y | y r s t u v w x
r | r s t y v w x u
s | s t y r w x u v
t | t y r s x u v w
yrstuvwxuuxwvytsrvvuxwrytswwvuxsrytxxwvutsryyyrstuvwxrrstyvwxusstyrwxuvttyrsxuvw
Neutral Element: y
```
### \$\mathbb Z\_6 \times \mathbb Z\_2\$
```
x | 0 1 2 3 5 7 8 9 a b 4 6
---------------------------
0 | 0 1 2 3 5 7 8 9 a b 4 6
1 | 1 2 3 4 0 8 9 a b 6 5 7
2 | 2 3 4 5 1 9 a b 6 7 0 8
7 | 7 8 9 a 6 2 3 4 5 0 b 1
8 | 8 9 a b 7 3 4 5 0 1 6 2
9 | 9 a b 6 8 4 5 0 1 2 7 3
a | a b 6 7 9 5 0 1 2 3 8 4
b | b 6 7 8 a 0 1 2 3 4 9 5
3 | 3 4 5 0 2 a b 6 7 8 1 9
4 | 4 5 0 1 3 b 6 7 8 9 2 a
5 | 5 0 1 2 4 6 7 8 9 a 3 b
6 | 6 7 8 9 b 1 2 3 4 5 a 0
01235789ab46001235789ab4611234089ab6572234519ab67087789a623450b1889ab7345016299ab684501273aab6795012384bb678a0123495334502ab67819445013b67892a5501246789a3b66789b12345a0
Neutral Element: 0
```
### \$A\_4\$
```
* | i a b c d e f g h j k l
---------------------------
i | i a b c d e f g h j k l
a | a b i e c d g h f l j k
b | b i a d e c h f g k l j
c | c f j i g k a d l b e h
d | d h k b f l i e j a c g
e | e g l a h j b c k i d f
f | f j c k i g d l a h b e
g | g l e j a h c k b f i d
h | h k d l b f e j i g a c
j | j c f g k i l a d e h b
k | k d h f l b j i e c g a
l | l e g h j a k b c d f i
iabcdefghjkliiabcdefghjklaabiecdghfljkbbiadechfgkljccfjigkadlbehddhkbfliejacgeeglahjbckidfffjckigdlahbegglejahckbfidhhkdlbfejigacjjcfgkiladehbkkdhflbjiecgalleghjakbcdfi
Neutral Element: i
```
## Non-Groups
### A loop (Group missing associativity, or a Quasi-Group with neutral element)
```
* | 1 2 3 4 5
-------------
1 | 1 2 3 4 5
2 | 2 4 1 5 3
3 | 3 5 4 2 1
4 | 4 1 5 3 2
5 | 5 3 2 1 4
12345112345224153335421441532553214
Neutral Element: 1
(2*2)*3 = 4*3 = 5 != 2 = 2*1 = 2*(2*3)
```
An IP-loop
(from <http://www.quasigroups.eu/contents/download/2008/16_2.pdf>)
```
* | 1 2 3 4 5 6 7
-----------------
1 | 1 2 3 4 5 6 7
2 | 2 3 1 6 7 5 4
3 | 3 1 2 7 6 4 5
4 | 4 7 6 5 1 2 3
5 | 5 6 7 1 4 3 2
6 | 6 4 5 3 2 7 1
7 | 7 5 4 2 3 1 6
123456711234567223167543312764544765123556714326645327177542316
Neutral Element: 1
2*(2*4) = 2*6 = 5 != 7 = 3*4 = (2*2)*4
```
## Monoid (by Quincunx, thanks!)
Monoids are Magmas with associativity and a neutral element.
```
* | 0 1 2 3
-----------
0 | 0 1 2 3
1 | 1 3 1 3
2 | 2 1 0 3
3 | 3 3 3 3
012300123113132210333333
Neutral Element: 0
```
### Another Monoid
(Multiplication mod 10, without the 5)
We obviously do not have inverses, and the associativity is given by the multiplication modulo 10.
```
* | 1 2 3 4 6 7 8 9
-------------------
1 | 1 2 3 4 6 7 8 9
2 | 2 4 6 8 2 4 6 8
3 | 3 6 9 2 8 1 4 7
4 | 4 8 2 6 4 8 2 6
6 | 6 2 8 4 6 2 8 4
7 | 7 4 1 8 2 9 6 3
8 | 8 6 4 2 8 6 4 2
9 | 9 8 7 6 4 3 2 1
Neutral Element: 1 12346789112346789224682468336928147448264826662846284774182963886428642998764321
```
[Answer]
# Ruby, ~~401~~ ... 272
```
f=->s{n=(s.size+1)**0.5
w=n.to_i-1
e=s[0,w].split''
s=s[w,n*n]
m={}
w.times{(1..w).each{|i|m[s[0]+e[i-1]]=s[i]}
s=s[n,n*n]}
s=e.find{|a|e.all?{|b|x=m[a+b]
x==m[b+a]&&x==b}}
e.all?{|a|t=!0
e.all?{|b|x=m[a+b]
t||=x==m[b+a]&&x==s
e.all?{|c|m[m[a+b]+c]==m[a+m[b+c]]}}&&t}&&s}
```
This is my first ruby program! This defines a lambda function that we can test by doing `puts f[gets.chomp]`. I return `false` for my false value. The first half of the function is simply parsing the input into a map, then the second half checks the possibilities.
```
f=->s{
n=((s.size+1)**0.5).to_i
w=n-1
e=s[0,w].split'' # create an array of elements of the potential group
s=s[w,n*n]
m={} # this map is what defines our operation
w.times{
(1..w).each{ # for each element in the row of the table
|i|m[s[0]+e[i-1]]=s[i] # put the value into the map
}
s=s[n,n*n]
}
s=e.find{|a| # s is the identity
e.all?{|b|
x=m[a+b]
x==m[b+a]&&x==b # is a the identity?
}
}
e.all?{|a| # implicit return statement
t = !0 # t = false
e.all?{|b| # check for inverses
x=m[a+b]
t ||= x==m[b+a]&&x==s # t is now true if b was a's inverse
e.all?{|c|
m[m[a+b]+c]==m[a+m[b+c]] # check associativity
}
} && t
}&&s
}
```
[Answer]
# Octave, 298 290 270 265 chars
```
function e=g(s)
c=@sortrows;d=a=c(c(reshape(a=[0 s],b=numel(a)^.5,b)')');
for i=2:b a(a==a(i))=i-1;end;
a=a(2:b,2:b--);u=1:b;
e=(isscalar(e=find(all(a==u')))&&a(e,:)==u&&sum(t=a==e)==1&&t==t')*e;
for x=u for y=u for z=u e*=a(a(x,y),z)==a(x,a(y,z));end;end;end;e=d(e+1);
```
**265:** Removed unnecessary function handle.
**270:** After all, the check that `e==h` for **e** always satisfying **e·a=a** and **h** always satisfying **a·h=a** was not necessary. This is not possible for them to be different (**e·h=?**).
The details from the explanation for solution below are still relevant.
---
**290:**
```
function e=g(s)
c=@sortrows;d=a=c(c(reshape(a=[0 s],b=numel(a)^.5,b)')');
for i=2:b a(a==a(i))=i-1;end;
a=a(2:b,2:b--);u=1:b;
s=@isscalar;e=(s(e=find(all(a==u')))&&s(h=find(all(a'==u')'))&&sum(t=a==e)==1&&t==t')*e;
for x=u for y=u for z=u e*=a(a(x,y),z)==a(x,a(y,z));end;end;end;e=d(e+1);
```
The first line
`c=@sortrows;d=a=c(c(reshape(a=[0 s],b=numel(a)^.5,b)')');` just stores the input into n x n table (with zero character at the place of operation mark), and then lexicographically sorts columns and rows, so that rows and columns receive the same order:
```
+ | z a t b + | a b t z
----------- -----------
z | t b a z becomes a | t a z b
b | z a t b ============> b | a b t z
t | a z b t t | z t b a
a | b t z a z | b z a t
```
Now, I remap `"a","b","t","z"` to standard `1, 2, 3, 4` , so that I can index the table efficiently. This is done by the line `for i=2:b a(a==a(i))=i-1;end;`. It yields table like
```
0 1 2 3 4
1 3 1 4 2
2 1 2 3 4
3 4 3 2 1
4 2 4 1 3
```
, where we can get rid of the first row and column with `a=a(2:b,2:b--);u=1:b;`:
```
3 1 4 2
1 2 3 4
4 3 2 1
2 4 1 3
```
This table has the given properties:
* if the neutral element **e** exists, **exactly one** (`isscalar`) row and one column have the value of row vector `u=[1 2 3 ... number-of-elements]`:
`s=@isscalar;e=(s(e=find(all(a==u')))&&s(h=find(all(a'==u')'))&&...`
* if each element **a** has a reverse element **a'**, two things hold:
the neutral element **e** occurs only once each column and only once each row (`sum(t=a==e)==1`) and, to satisfy **a'·a = a·a'**, the occurences of **e** are symmetrical in respect to translation `t==t'`
* a·b can be retrieved by simple `t(a,b)` indexing. Then we check the associativity in the boring loop:
`for x=u for y=u for z=u e*=a(a(x,y),z)==a(x,a(y,z));end;end;end;`
The function returns the neutral element the way it appeared in original table (`e=d(e+1)`) or nil character if the table does not describe a group.
[Answer]
# JavaScript (ES6) 285 ~~243 278~~
Run snippet to test (being ES6 it works only on Firefox)
**Edit 2** Bug fix. I was wrong in finding the neutral element, checking just one way. (Need better test cases!!!)
**Edit** Using simpler string concatenation instead of double index (like @Quincunx), I don't know what I was thinking. Also, simplified inverse check, it should still work.
```
F=t=>(
e=t.slice(0,d=Math.sqrt(t.length)|0),
t=t.slice(d).match('.'.repeat(d+1),'g'),
t.map(r=>{
for(v=r[i=0],
j=e.search(v)+1, // column for current row element
r!=v+e|t.some(r=>r[j]!=r[0])?0:n=v; // find neutral
c=r[++i];
)h[v+e[i-1]]=c
},h={},n=''),
e=[...e],!e.some(a=>e.some(b=>(
h[a+b]==n&&--d, // inverse
e.some(c=>h[h[a+b]+c]!=h[a+h[b+c]]) // associativity
)
))&&!d&&n
)
```
```
input { width: 400px; font-size:10px }
```
```
Click on textbox to test - Result : <span id=O></span><br>
<input value='...' onclick='O.innerHTML=F(this.value)'> (?)
<br>Groups<br>
<input value='nezdnnezdeezdnzzdneddnez' onclick='O.innerHTML=F(this.value)'> (n)<br>
<input value='ptdkgbnmmbdtgkpmnpmkgdtnpbnptdkgbnmbngktdmbptgmnpbktddknmbpgdtktbpmndkggdpbnmtgk' onclick='O.innerHTML=F(this.value)'> (n)<br>
<input value='yrstuvwxuuxwvytsrvvuxwrytswwvuxsrytxxwvutsryyyrstuvwxrrstyvwxusstyrwxuvttyrsxuvw' onclick='O.innerHTML=F(this.value)'> (y)<br>
<input value='01235789ab46001235789ab4611234089ab6572234519ab67087789a623450b1889ab7345016299ab684501273aab6795012384bb678a0123495334502ab67819445013b67892a5501246789a3b66789b12345a0'onclick='O.innerHTML=F(this.value)'> (0)<br>
Non groups <br>
<input value='12345112345224153335421441532553214' onclick='O.innerHTML=F(this.value)'> (FAIL)<br>
<input value='123456711234567223167543312764544765123556714326645327177542316' onclick='O.innerHTML=F(this.value)'> (FAIL)<br>
<input value='012300123113132210333333' onclick='O.innerHTML=F(this.value)'> (FAIL)<br>
```
[Answer]
# Haskell 391B
```
import Data.Maybe
import Data.List
o a b=elemIndex b a
l£a=fromJust.o a$l
a§b=[a!!i|i<-b]
f s|isJust j&&and(map(isJust.o h)s)&&and[or[p%q==e|q<-h]&&and[p%(q%r)==(p%q)%r|q<-h,r<-h]|p<-h]=[e]|True="!"where n=floor$(sqrt(fromIntegral$length s+1))-1;h=take n s;g=[s§[a..b]|(a,b)<-zip[1+n,2+n+n..][n+n,3*n+1..(n+1)^2]];v=s§[n,1+2*n..n+n*n];a%b=g!!(b£v)!!(a£h);j=o g h;e=v!!fromJust j
```
Curse those `import`s!
```
import Data.Maybe
import Data.List
{- rename elemIndex to save characters -}
o a b=elemIndex b a
{- get the index of l in a -}
l£a=fromJust.o a$l
{- extract a sublist of a with indices b -}
a§b=[a!!i|i<-b]
f s |isJust j {-Identity-}
&&and (map (isJust.o h) s) {-Closure-}
&&and[
or [p%q==e|q<-h] {-Inverse-}
&& and [ p%(q%r)==(p%q)%r | q<-h,r<-h ] {-Associativity-}
|
p<-h
]=[e]
|True="!"
where
{-size-} n=floor$(sqrt(fromIntegral$length s+1))-1
{-horiz-} h=take n s
{-table-} g=[s§[a..b]|(a,b)<-zip[1+n,2+n+n..][n+n,3*n+1..(n+1)^2]]
{-vert-} v=s§[n,1+2*n..n+n*n]
{-operate-} a%b=g!!(b£v)!!(a£h)
j=o g h {-index of the first row identical to the top-}
{-ident-} e=v!!fromJust j
```
## Explanation
`f::String->String` maps the string to either `e::Char`, the identity element, or `!`.
The `where` clause creates a bunch of variables and functions, which I've commented; `v::[Int]` is the vertical list of elements, `h::[Int]` the horizontal one.
`%::Char->Char->Char` applies the group operation to its arguments.
`g::[[Int]]` is the group table (for dereferencing using `%`)
`j::Maybe Int` contains the index of the identity in `v` if it exists, otherwise `Nothing`, which is why `isJust j` is the condition in `f` for identity.
] |
[Question]
[
(Based on [this Math.SE problem](https://math.stackexchange.com/questions/472908/given-a-desired-coloring-scheme-for-a-stick-how-can-i-brush-it-with-the-fewest), which also provides some graphics)
I have a stick which looks kinda like this:

I want it to look kinda like this:

I'm not an expert painter, however, so before I start such an ambitious DIY project, I want to make sure that I'm not in over my head.
Your program should tell me how how many steps are involved in painting this stick. Each step involves painting a continuous area with a solid color, which covers up previous layers of paint. For the above example, I could paint the left half blue, the right half red, and then the two separate green areas for a total of 4 steps (the green is not continuously painted).

Here it is in ASCII:
```
------
bbb---
bbbrrr
bgbrrr
bgbrgr
```
There are a couple different ways to paint this stick and end up with the same result. I'm only interested in the time estimate, however, which is four steps.
## Goal
Your program should output the minimum number of steps needed to paint a stick with a given color scheme. The paint scheme will be in the form of a string of characters, while output will be a number. This is code golf. Shortest program wins.
## Input
Your program will receive the coloring scheme for a stick in the form of a string of letters. Each unique letter (case sensitive) represents a unique color.
```
YRYGR
grG
GyRyGyG
pbgbrgrp
hyghgy
```
## Output
These numbers are the least number of steps needed to paint the sticks.
```
4
3
4
5
4
```
## Explanations
This is how I arrived at the above numbers. Your program does not need to output this:
```
-----
YYY--
YRY--
YRYG-
YRYGR
---
g--
gr-
grG
-------
GGGGGGG
GyyyGGG
GyRyGGG
GyRyGyG
--------
pppppppp
pbbbpppp
pbbbrrrp
pbgbrrrp
pbgbrgrp
------
-yyyyy
-ygggy
hygggy
hyghgy
```
Edit: I'll add more test cases if they prove to be more difficult test cases.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~60~~ 59 bytes
```
p=lambda s:len(s)and-~min(sum(map(p,s.split(c)))for c in s)
```
[Try it online!](https://tio.run/##HcaxDsIgEADQWb@CMN0l1cWtiTM7W9M4QKtAAvQCONzir6M4vUfc/JFvvdM9mmR3I@ocnxkqmrxfPin8@k6QDAFN9VophgYbIr6OIjYRsqjYx834Khe9KC0nIV1RA8WaFf9L1tniCo17dt6xfMznE5WQGxAYxP4F "Python 3 – Try It Online")
Ungolfed:
```
def paint(stick):
if not stick:
return 0
return 1 + min(
sum(paint(part) for part in stick.split(c))
for c in stick
)
```
[Answer]
### GolfScript, 82 72 67 characters
```
.,n*{:c,,{[).2$1<*\c>+1$.,,{).2$<\3$<=},,.@>@@>]}%\;{~S)}%$0+0=}:S~
```
Reasonably fast for a GolfScript program, examples:
```
> hyghgy
4
> pbgbrgrp
5
```
The algorithm used works through the colors left-to-right recursively, according to the following statements:
* Ignore all parts from the left which already have the required color. Overpainting them again will not provide a better answer.
* If the complete stick already has the desired color, return 0 steps as result.
* Otherwise, take the target color of the now leftmost part (i.e. the first not in the desired color).
+ Paint 1 part with the target color and recurse.
+ Paint 2 parts with this color and recurse....
+ Paint the whole remaining stick with this color and recurse.Take the minimum of all those numbers and add 1 (for the current step). Return this as the optimal number of steps.
This algorithm works, because the leftmost part has to be painted at one time anyways, so why not do it immediately - in any possible fashion.
```
.,n* # prepare the initial situation (target stick, unpainted stick)
# used n instead of '-' for the unpainted parts, because it is shorter
{ # Define the operator S which does t c S -> n
# - t: the desired target colors
# - c: the stick as it is colored currently
# - n: minimum number of steps required to go from c to t
:c # Assign the current configuration to the variable c
,,{[ # Map the list [0 1 2 .. L-1]
# We will build a list of all possible configurations if we paint
# the stick with the 0th part's color (either 1 or 2 or 3 or ... parts)
). # Increase the number, i.e. we paint 1, 2, 3, ... L parts, copy
2$1< # Take the first color of the target configuration
* # ...paint as many parts
\c>+ # ...and keep the rest as with the current stick
1$ # take the target configuration
# Top of stack now e.g. reads
# h----- hyghgy (for i=0)
# hh---- hyghgy (for i=1)
# Next, we strip the common leading characters from both strings:
.,, # Make list [0 1 2 ... L-1]
{ # Filter {}, all the numbers for which the first j+1 parts are the same
). # incr j
2$< # take leftmost j parts of stick A
\3$< # take leftmost j parts of stick B
= # are they equal?
},, # The length of the result is the number of common parts.
.@> # cut parts from A
@@> # cut parts from B
]}%
\; # Remove the target from the stack (not needed anymore)
# We now have a list of possible paintings where 1, 2, ..., L parts were
# painted from the left with the same color.
# All configurations were reduced by the common parts (they won't be
# painted over anyways)
{~S)}% # Call the method S recursively on the previously prepared configurations
$0+0= # $0= -> sort and take first, i.e. take the minimum, 0+ is a workaround
# if the list was empty (i.e. the operator was called with a stick of length 0).
}:S
~ # Execute S
```
[Answer]
**JavaScript: 187 Bytes**
Assuming we're allowed to just have the input and output to a function (please)!
```
function p(w){var j,l,s=-1,i,m=i=w.length;if(m<2)return m;for(;i--;){l = 1;for(var k=-1;(j=k)!=m;){if((k=w.indexOf(w[i],++j))==-1)k=m;l+=p(w.substring(j,k));}if(s==-1||l<s)s=l;}return s;}
```
**157 Bytes** by doing further ugly optimization (Which is part of the point, and I found incredibly fun):
```
function p(w){var j,l,s=-1,i,m=i=w.length;if(m<2)return m;for(;i--;s<0|l<s?s=l:1)for(l=1,j=0;~j;)l+=p(w.substring(j,(j=w.indexOf(w[i],j))<0?m:j++));return s}
```
**135 Bytes** I realised that the length of the input is an upper bound and I don't need to handle trivial cases separately now.
```
function p(w){var j,l,s,i,m=s=i=w.length;for(;i--;l<s?s=l:1)for(l=1,j=0;~j;)l+=p(w.substring(j,~(j=w.indexOf(w[i],j))?j++:m));return s}
```
Test cases:
```
p("YRYGR")
4
p("grG")
3
p("GyRyGyG")
4
p("pbgbrgrp")
5
p("hyghgy")
4
```
Expanded version:
```
function paint(word) {
var smallest = -1;
if(word.length < 2) return word.length;
for(var i = word.length; i-->0;) {
var length = 1;
for(var left, right = -1;(left = right) != m;) {
if((right = word.indexOf(word[i],++left)) == -1) right = word.length;
if(left != right) length += paint(word.substring(left , right));
}
if(smallest == -1 || length < smallest) smallest = l;
}
return smallest;
}
```
For every character of the input, calculate the length of the pattern if we paint that colour first. This is done by pretending we paint that colour and then making sub sections out of the bits that aren't that colour, and recursively calling the paint method on them. The shortest path is returned.
Example (`YRYGR`):
Initially, try `R`. This gives us the sub groups `Y` and `YG`. `Y` is trivially painted in one go.
For `YG`:
Try `G`, `Y` is trivial, length `2`. Try `Y`, `G` is trivial, length 2. `YG` is therefore length `2`.
Painting `R` first therefore gives us `1 + 1 + 2 = 4`
Then try `G`. This gives us the sub groups `YRY` and `R`. `R` is trivial.
For `YRY`:
Try `Y`: `R` is trivial, length `2`. Try `R`: `Y` and `Y` are the two groups, length `3`.
`YRY` is length `2`.
Painting `G` first gives `1 + 1 + 2 = 4`
Then try `Y`. This gives the sub groups `R` and `GR`. `R` trivial, `GR` is length `2`. `Y` is length `4`
This implementation would then check R and Y again to reduce code length. The result for `YRYGR` is therefore `4`.
[Answer]
## Python, 149 chars
```
D=lambda s:0 if s=='?'*len(s)else min(1+D(s[:i]+'?'*(j-i)+s[j:])for i in range(len(s))for j in range(i+1,len(s)+1)if set(s[i:j])-set('?')==set(s[i]))
```
I use `?` to mark an area that may be any color. `D` picks a contiguous region of the stick that contains only a single color (plus maybe some `?`s), colors that region last, replaces that region with `?`s, and recurses to find all the previous steps.
Exponential running time. Just barely fast enough to do the examples in a reasonable time (a few minutes). I bet with memoization it could be much faster.
[Answer]
## Python 3 - 122
```
def r(s,a):c=s[0];z=c in a;return s[1:]and min([1+r(s[1:],a+c)]+[r(s[1:],a[:a.rfind(c)+1])]*z)or(1-z)
print(r(input(),''))
```
It seems to work, but I'm still not 100% sure that this method will always find the minimum number of steps.
[Answer]
## CoffeeScript - 183 247 224 215 207
```
x=(s,c='')->return 0if !s[0]?;return x s[1..],c if s[0]is c;l=s.length;return x s[1...l],c if s[l-1]is c;i=s.lastIndexOf s[0];1+(x s[1...i],s[0])+x s[i+1..],c
y=(z)->z=z.split "";Math.min (x z),x z.reverse()
```
[Demo on JSFiddle.net](http://jsfiddle.net/TimWolla/DJpe9/5/)
Ungolfed version including debug code and comments:
```
paintSubstring = (substring, color = '####') ->
console.log 'Substring and color', substring, color, substring[0]
# no need to color here
if !substring[0]?
return 0
# no need to recolor the first part
if substring[0] is color
return paintSubstring (substring[1..]), color
l = substring.length
# no need to recolor the last part
if substring[l-1] is color
return paintSubstring substring[0...l], color
# cover as much as possible
index = substring.lastIndexOf substring[0]
part1 = substring[1...index]
part2 = substring[index+1..]
console.log 'Part 1:', part1
console.log 'Part 2:', part2
# color the rest of the first half
p1 = paintSubstring part1, substring[0]
# color the rest of the second half, note that the color did not change!
p2 = paintSubstring part2, color
# sum up the cost of the substick + this color action
return p1+p2+1
paintSubstringX=(x)->Math.min (paintSubstring x.split("")), paintSubstring x.split("").reverse()
console.clear()
input = """YRYGR
grG
GyRyGyG
pbgbrgrp
aaaaaaaa
hyghgy""".split /\n/
for stick in input
console.log paintSubstringX stick
```
[Answer]
## Haskell, ~~118~~ 86 characters
```
p""=0
p(a:s)=1+minimum(map(sum.map p.words)$sequence$map(a%)s)
a%b|a==b=b:" "|1<3=[b]
```
Test runs:
```
λ: p "YRYGR"
4
λ: p "grG"
3
λ: p "GyRyGyG"
4
λ: p "pbgbrgrp"
5
λ: p "hyghgy"
4
λ: p "abcacba"
4
```
This method isn't even all that inefficient!
[Answer]
Haskell, 143 chars
```
f s=g(r n ' ')0where{r=replicate;n=length s;g p l=minimum$n:[0|p==s]++[1+g(take i p++r(j-i)(s!!i)++drop j p)(l+1)|l<n,i<-[0..n-1],j<-[i+1..n]]}
```
This tries all possible rewritings up to the length of the string, and goes until it finds one that constructs the input pattern. Needless to say, exponential time (and then some).
[Answer]
A simple breadth first search. It doesn't put anything on the queue that's already been seen. It works in under a second for all of the examples but 'pbgbrgrp' which actually takes a full minute :(
Now that I have something that *works* I'll be working on finding something faster and shorter.
**Python - ~~300~~ 296**
```
def f(c):
k=len(c);q=['0'*99];m={};m[q[0]]=1
while q:
u=q.pop(0)
for x in ['0'*j+h*i+'0'*(k-j-i) for h in set(c) for j in range(1+k) for i in range(1,1+k-j)]:
n=''.join([r if r!='0' else l for l,r in zip(u,x)])
if n == c:
return m[u]
if not n in m:
m[n]=m[u]+1;q.append(n)
```
] |
[Question]
[
I have a combination padlock which has letters instead of numbers. It looks like this: <http://pictures.picpedia.com/2012/09/Word_Combination_Padlock.jpg> There are 5 reels, each of which has 10 different letters on it.
Most people like to use a word for their combination rather than an arbitrary string of letters. (Less secure, of course, but easier to remember.) So when manufacturing the lock, it would be good to build it to have a combination of letters which can be used to create as many 5-letter English words as possible.
Your task, should you choose to accept it, is to find an assignment of letters to reels which will allow as many words as possible to be created. For example, your solution might be
ABCDEFGHIJ DEFGHIJKLM ZYXWVUTSR ABCDEFGHIJ ABCDEFGHIJ
(If you weren't feeling too imaginative, that is).
For consistency, please use the word list at <http://www.cs.duke.edu/~ola/ap/linuxwords>
Any 5-letter word in that list is OK, including proper names. Ignore Sino- and L'vov and any other words in the list which contain a non a-z character.
The winning program is the one which produces the largest set of words. In the event that multiple programs find the same result, the first one to be posted wins. The program should run in under 5 minutes.
Edit: since activity has died down, and no better solutions have come out, I declare Peter Taylor the winner! Thanks everyone for your inventive solutions.
[Answer]
## 1275 words by simple greedy hill-climbing
Code is C#. Solution produced is
```
Score 1275 from ^[bcdfgmpstw][aehiloprtu][aeilnorstu][acdeklnrst][adehklrsty]$
```
I'm using that output format because it's really easy to test:
```
grep -iE "^[bcdfgmpstw][aehiloprtu][aeilnorstu][acdeklnrst][adehklrsty]$" linuxwords.txt | wc
```
---
```
namespace Sandbox {
class Launcher {
public static void Main(string[] args)
{
string[] lines = _Read5s();
int[][] asMasks = lines.Select(line => line.ToCharArray().Select(ch => 1 << (ch - 'a')).ToArray()).ToArray();
Console.WriteLine(string.Format("{0} words found", lines.Length));
// Don't even bother starting with a good mapping.
int[] combos = _AllCombinations().ToArray();
int[] best = new int[]{0x3ff, 0x3ff, 0x3ff, 0x3ff, 0x3ff};
int bestSc = 0;
while (true)
{
Console.WriteLine(string.Format("Score {0} from {1}", bestSc, _DialsToString(best)));
int[] prevBest = best;
int prevBestSc = bestSc;
// Greedy hill-climbing approach
for (int off = 0; off < 5; off++)
{
int[] dials = (int[])prevBest.Clone();
dials[off] = (1 << 26) - 1;
int[][] filtered = asMasks.Where(mask => _Permitted(dials, mask)).ToArray();
int sc;
dials[off] = _TopTen(filtered, off, out sc);
if (sc > bestSc)
{
best = (int[])dials.Clone();
bestSc = sc;
}
}
if (bestSc == prevBestSc) break;
}
Console.WriteLine("Done");
Console.ReadKey();
}
private static int _TopTen(int[][] masks, int off, out int sc)
{
IDictionary<int, int> scores = new Dictionary<int, int>();
for (int k = 0; k < 26; k++) scores[1 << k] = 0;
foreach (int[] mask in masks) scores[mask[off]]++;
int rv = 0;
sc = 0;
foreach (KeyValuePair<int, int> kvp in scores.OrderByDescending(kvp => kvp.Value).Take(10))
{
rv |= kvp.Key;
sc += kvp.Value;
}
return rv;
}
private static string _DialsToString(int[] dials)
{
StringBuilder sb = new StringBuilder("^");
foreach (int dial in dials)
{
sb.Append('[');
for (int i = 0; i < 26; i++)
{
if ((dial & (1 << i)) != 0) sb.Append((char)('a' + i));
}
sb.Append(']');
}
sb.Append('$');
return sb.ToString();
}
private static IEnumerable<int> _AllCombinations()
{
// \binom{26}{10}
int set = (1 << 10) - 1;
int limit = (1 << 26);
while (set < limit)
{
yield return set;
// Gosper's hack:
int c = set & -set;
int r = set + c;
set = (((r ^ set) >> 2) / c) | r;
}
}
private static bool _Permitted(int[] dials, int[] mask)
{
for (int i = 0; i < dials.Length; i++)
{
if ((dials[i] & mask[i]) == 0) return false;
}
return true;
}
private static string[] _Read5s()
{
System.Text.RegularExpressions.Regex word5 = new System.Text.RegularExpressions.Regex("^[a-z][a-z][a-z][a-z][a-z]$", System.Text.RegularExpressions.RegexOptions.Compiled);
return File.ReadAllLines(@"d:\tmp\linuxwords.txt").Select(line => line.ToLowerInvariant()).Where(line => word5.IsMatch(line)).ToArray();
}
}
}
```
[Answer]
# Python (3), 1273 ≈ 30.5%
This is a really naïve approach: keep a tally of the frequency of each letter in each position, then eliminate the "worst" letter until the remaining letters will fit on the reels. I'm surprised it seems to do so well.
What's most interesting is that I have almost exactly the same output as the C# 1275 solution, except I have an `N` on my last reel instead of `A`. That `A` was my 11th-to-last elimination, too, even before throwing away a `V` and a `G`.
```
from collections import Counter
def main(fn, num_reels, letters_per_reel):
# Read ye words
words = []
with open(fn) as f:
for line in f:
word = line.strip().upper()
if len(word) == num_reels and word.isalpha():
words.append(word)
word_pool_size = len(words)
# Populate a structure of freq[reel_number][letter] -> count
freq = [Counter() for _ in range(num_reels)]
for word in words:
for r, letter in enumerate(word):
freq[r][letter] += 1
while True:
worst_reelidx = None
worst_letter = None
worst_count = len(words)
for r, reel in enumerate(freq):
# Skip reels that already have too-few letters left
if len(reel) <= letters_per_reel:
continue
for letter, count in reel.items():
if count < worst_count:
worst_reelidx = r
worst_letter = letter
worst_count = count
if worst_letter is None:
# All the reels are done
break
# Discard any words containing this worst letter, and update counters
# accordingly
filtered_words = []
for word in words:
if word[worst_reelidx] == worst_letter:
for r, letter in enumerate(word):
freq[r][letter] -= 1
if freq[r][letter] == 0:
del freq[r][letter]
else:
filtered_words.append(word)
words = filtered_words
for reel in freq:
print(''.join(sorted(reel)))
print("{} words found (~{:.1f}%)".format(
len(words), len(words) / word_pool_size * 100))
```
Produces:
```
BCDFGMPSTW
AEHILOPRTU
AEILNORSTU
ACDEKLNRST
DEHKLNRSTY
1273 words found (~30.5%)
```
[Answer]
## *Mathematica*, 1275 words again and again...
This code is not Golfed as the question does not appear to call for that.
```
wordlist = Flatten @ Import @ "http://www.cs.duke.edu/~ola/ap/linuxwords";
shortlist = Select[ToLowerCase@wordlist, StringMatchQ[#, Repeated[LetterCharacter, {5}]] &];
string = "" <> Riffle[shortlist, ","];
set = "a" ~CharacterRange~ "z";
gb = RandomChoice[set, {5, 10}];
best = 0;
While[True,
pos = Sequence @@ RandomInteger /@ {{1, 5}, {1, 10}};
old = gb[[pos]];
gb[[pos]] = RandomChoice @ set;
If[best < #,
best = #; Print[#, " ", StringJoin /@ gb],
gb[[pos]] = old
] & @ StringCount[string, StringExpression @@ Alternatives @@@ gb]
]
```
The word count quickly (less than 10 seconds) evolves to 1275 on most runs but never gets beyond that. I tried perturbing the letters by more than one at a time in an attempt to get out of a theoretical local maximum but it never helped. I strongly suspect that 1275 is the limit for the given word list. Here is a complete run:
>
>
> ```
> 36 {tphcehmqkt,agvkqxtnpy,nkehuaakri,nsibxpctio,iafwdyhone}
>
> 37 {tpicehmqkt,agvkqxtnpy,nkehuaakri,nsibxpctio,iafwdyhone}
>
> 40 {tpicehmqkt,agvkqxtnpy,nkehuaakri,nsibxpctio,iafldyhone}
>
> 42 {tpicehmqkt,agvkqxtnpy,nkehuaakri,nsfbxpctio,iafldyhone}
>
> 45 {tpicehmrkt,agvkqxtnpy,nkehuaakri,nsfbxpctio,iafldyhone}
>
> 48 {tpicehmrkt,agvkwxtnpy,nkehuaakri,nsfbxpctio,iafldyhone}
>
> 79 {tpicehmskt,agvkwxtnpy,nkehuaakri,nsfbxpctio,iafldyhone}
>
> 86 {tpicehmskt,agvkwxtnpy,nkehuaakri,esfbxpctio,iafldyhone}
>
> 96 {tpicehmskt,agvkwxtnpy,nkehuaokri,esfbxpctio,iafldyhone}
>
> 97 {tpicehmskt,agvkwxtnpy,nkehuaokri,esfbxpctio,ipfldyhone}
>
> 98 {tpicehmskv,agvkwxtnpy,nkehuaokri,esfbxpctio,ipfldyhone}
>
> 99 {tpicehmskv,agvkwxtnpy,nkehuaokri,esfbzpctio,ipfldyhone}
>
> 101 {tpicehmskv,agvkwxtnpy,nkehuaokri,esfhzpctio,ipfldyhone}
>
> 102 {tpicehmskv,agvkwxtnpy,nkehuaokri,esfhzpctno,ipfldyhone}
>
> 105 {tpicehmskv,agvkwxtnpy,nkehuaokri,esfhzmctno,ipfldyhone}
>
> 107 {tpicehmskn,agvkwxtnpy,nkehuaokri,esfhzmctno,ipfldyhone}
>
> 109 {tpgcehmskn,agvkwxtnpy,nkehuaokri,esfhzmctno,ipfldyhone}
>
> 115 {tpgcehmsan,agvkwxtnpy,nkehuaokri,esfhzmctno,ipfldyhone}
>
> 130 {tpgcehmsan,agvkwxtnpy,nkehuaokri,esfhzmctno,ipfldyhons}
>
> 138 {tpgcehmsan,agvkwxtnpy,nkehuaokri,esfhzmctno,ipfldytons}
>
> 143 {tpgcehmsab,agvkwxtnpy,nkehuaokri,esfhzmctno,ipfldytons}
>
> 163 {tpgcehmsab,auvkwxtnpy,nkehuaokri,esfhzmctno,ipfldytons}
>
> 169 {tpgcehmsab,auvkwctnpy,nkehuaokri,esfhzmctno,ipfldytons}
>
> 176 {tpgcehmsab,auvkwctnpy,nkehuaokri,esfhzmctno,ihfldytons}
>
> 189 {tpgcehmsab,auvkwchnpy,nkehuaokri,esfhzmctno,ihfldytons}
>
> 216 {tpgcehmsab,auvkwchnpy,nkehtaokri,esfhzmctno,ihfldytons}
>
> 220 {tpgcehmsab,auvkwthnpy,nkehtaokri,esfhzmctno,ihfldytons}
>
> 223 {tpgcehmsab,auvkwthnpy,nkehtaokri,esfhbmctno,ihfldytons}
>
> 234 {tpgcehmsab,auvkwthnpy,nkegtaokri,esfhbmctno,ihfldytons}
>
> 283 {tpgcehmsab,auvkwthnpy,nkegtaokri,esfhbrctno,ihfldytons}
>
> 285 {tpdcehmsab,auvkwthnpy,nkegtaokri,esfhbrctno,ihfldytons}
>
> 313 {tpdcehmsab,auvkwthnly,nkegtaokri,esfhbrctno,ihfldytons}
>
> 371 {tpdcehmsab,auvkethnly,nkegtaokri,esfhbrctno,ihfldytons}
>
> 446 {tpdcehmsab,auvoethnly,nkegtaokri,esfhbrctno,ihfldytons}
>
> 451 {tpdcehmslb,auvoethnly,nkegtaokri,esfhbrctno,ihfldytons}
>
> 465 {tpdcwhmslb,auvoethnly,nkegtaokri,esfhbrctno,ihfldytons}
>
> 545 {tpdcwhmslb,auioethnly,nkegtaokri,esfhbrctno,ihfldytons}
>
> 565 {tpdcwhmslb,auioethnly,nkegtaocri,esfhbrctno,ihfldytons}
>
> 571 {tpdcwhmslb,auioethnly,nkegtaocri,esfhwrctno,ihfldytons}
>
> 654 {tpdcwhmslb,auioethnly,nkegtaocri,esfhwrctno,ihfedytons}
>
> 671 {tpdcwhmslb,auioethnly,nkegtaocri,esfhirctno,ihfedytons}
>
> 731 {tpdcwhmslb,auioethnly,nkegtaocri,esfhirctno,ihredytons}
>
> 746 {tpdcwhmslb,arioethnly,nkegtaocri,esfhirctno,ihredytons}
>
> 755 {tpdcwhmslb,arioethnuy,nkegtaocri,esfhirctno,ihredytons}
>
> 772 {tpdcwhmslb,arioethnuy,nkegtaocri,ekfhirctno,ihredytons}
>
> 786 {tpdcwhmslb,arioethnuy,nkegtaocri,ekfhirctno,lhredytons}
>
> 796 {tpdcwhmslb,arioethnuy,nkegtaocri,ekfhgrctno,lhredytons}
>
> 804 {tpdcwhmslb,arioethwuy,nkegtaocri,ekfhgrctno,lhredytons}
>
> 817 {tpdcwhmslb,arioethwuy,nklgtaocri,ekfhgrctno,lhredytons}
>
> 834 {tpdcwhmslb,arioethwuy,nklgtaocri,ekfhdrctno,lhredytons}
>
> 844 {tpdcwhmslb,arioethwup,nklgtaocri,ekfhdrctno,lhredytons}
>
> 887 {tpdcwhmslb,arioethwup,nklgtaocri,ekshdrctno,lhredytons}
>
> 901 {tpdcwhmslb,arioethwup,nklgtaouri,ekshdrctno,lhredytons}
>
> 966 {tpdcwhmslb,arioethwup,nklgtaouri,elshdrctno,lhredytons}
>
> 986 {tpdcwhmsfb,arioethwup,nklgtaouri,elshdrctno,lhredytons}
>
> 1015 {tpdcwhmsfb,arioethwup,nklgtaouri,elsidrctno,lhredytons}
>
> 1039 {tpdcwhmsfb,arioethwup,nklgtaouri,elsidrctno,khredytons}
>
> 1051 {tpdcwhmsfb,arioethwup,nklgtaouri,elskdrctno,khredytons}
>
> 1055 {tpdcwhmsfb,arioethwup,nklgtaouri,elskdrctno,khredytlns}
>
> 1115 {tpdcwhmsfb,arioethwup,nelgtaouri,elskdrctno,khredytlns}
>
> 1131 {tpdcwhmsfb,arioethwup,nelwtaouri,elskdrctno,khredytlns}
>
> 1149 {tpdcwhmsfb,arioethwup,nelwtaouri,elskdrctna,khredytlns}
>
> 1212 {tpdcwhmsfb,arioelhwup,nelwtaouri,elskdrctna,khredytlns}
>
> 1249 {tpdcwhmsfb,arioelhwup,nelstaouri,elskdrctna,khredytlns}
>
> 1251 {tpgcwhmsfb,arioelhwup,nelstaouri,elskdrctna,khredytlns}
>
> 1255 {tpgcwdmsfb,arioelhwup,nelstaouri,elskdrctna,khredytlns}
>
> 1258 {tpgcwdmsfb,arioelhwup,nelstaouri,elskdrctna,khredytlas}
>
> 1262 {tpgcwdmsfb,arioelhwut,nelstaouri,elskdrctna,khredytlas}
>
> 1275 {tpgcwdmsfb,arioelhput,nelstaouri,elskdrctna,khredytlas}
>
> ```
>
>
Here are some other "winning" selections:
```
{"cbpmsftgwd", "hriuoepatl", "euosrtanli", "clknsaredt", "yhlkdstare"}
{"wptdsgcbmf", "ohlutraeip", "erotauinls", "lknectdasr", "sytrhklaed"}
{"cftsbwgmpd", "ropilhtaue", "niauseltor", "clstnkdrea", "esdrakthly"}
{"smgbwtdcfp", "ihulpreota", "ianrsouetl", "ekndasctlr", "kehardytls"}
```
As Peter comments these are actually the same solution in different orders. Sorted:
```
{"bcdfgmpstw", "aehiloprtu", "aeilnorstu", "acdeklnrst", "adehklrsty"}
```
[Answer]
## Python, 1210 words (~ 29%)
Assuming I counted the words correctly this time, this is slightly better than
FakeRainBrigand's solution. The only difference is I add each reel in order, and then remove all words from the list that don't match the reel so I get a slightly better distribution for the next reels. Because of this, it gives the exact same first reel.
```
word_list = [line.upper()[:-1] for line in open('linuxwords.txt','r').readlines() if len(line) == 6]
cur_list = word_list
s = ['']*5
for i in range(5):
count = [0]*26
for j in range(26):
c = chr(j+ord('A'))
count[j] = len([x for x in cur_list if x[i] == c])
s[i] = [chr(x+ord('A')) for x in sorted(range(26),lambda a,b: count[b] - count[a])[:10]]
cur_list = filter(lambda x:x[i] in s[i],cur_list)
for e in s:
print ''.join(e)
print len(cur_list)
```
The program outputs
```
SBCAPFDTMG
AOREILUHTP
ARIOLENUTS
ENTLRCSAID
SEYDTKHRNL
1210
```
[Answer]
# iPython (273 210 Bytes, 1115 words)
### 1115/4176\* ~ 27%
I calculated these in iPython, but my history (trimmed to remove debugging) looked like this.
```
with open("linuxwords") as fin: d = fin.readlines()
x = [w.lower().strip() for w in d if len(w) == 6]
# Saving for later use:
# with open("5letter", "w") as fout: fout.write("\n".join(x))
from string import lowercase as low
low=lowercase + "'"
c = [{a:0 for a in low} for q in range(5)]
for w in x:
for i, ch in enumerate(w):
c[i][ch] += 1
[''.join(sorted(q, key=q.get, reverse=True)[:10]) for q in c]
```
If we're going for short; I could trim it to this.
```
x = [w.lower().strip() for w in open("l") if len(w)==6]
c=[{a:0 for a in"abcdefghijklmnopqrstuvwxyz'-"}for q in range(5)]
for w in[w.lower().strip()for w in open("l") if len(w)==6]:
for i in range(5):c[i][w[i]]+=1
[''.join(sorted(q,key=q.get,reverse=True)[:10])for q in c]
```
Shortened:
```
c=[{a:0 for a in"abcdefghijklmnopqrstuvwxyz'-"}for q in range(5)]
for w in[w.lower() for w in open("l")if len(w)==6]:
for i in range(5):c[i][w[i]]+=1
[''.join(sorted(q,key=q.get,reverse=True)[:10])for q in c]
```
My results were: `['sbcapfdtmg', 'aoeirulhnt', 'aironeluts', 'etnlriaosc', 'seyrdtnlah']`.
\*My math on the 4176 may be a little short due to words with hyphens or apostrophes being omitted
[Answer]
# Q
**? (todo) words**
Words should be stored in a file called `words`
```
(!:')10#/:(desc')(#:'')(=:')(+:)w@(&:)(5=(#:')w)&(&/')(w:(_:)(0:)`:words)in\:.Q.a
```
Runs in about 170 ms on my i7. It analyses the wordlist, looking for the most common letter in each position (obviously filtering out any non-candidates). It's a lazy naive solution but produces a reasonably good result with minimal code.
Results:
```
"sbcapfdtmg"
"aoeirulhnt"
"aironeluts"
"etnlriaosc"
"seyrdtnlah"
```
[Answer]
**Edit:** Now that the rules have been modified, this approach is disqualified. I'm going to leave it here in case anyone is interested until I eventually getting around to modifying it for the new rules.
# Python: 277 Characters
I'm pretty sure that the generalized version of this problem is NP-Hard, and the question didn't require finding the *fastest* solution, so here's a brute-force method of doing it:
```
import itertools,string
w=[w.lower()[:-1] for w in open('w') if len(w)==6]
v=-1
for l in itertools.product(itertools.combinations(string.ascii_lowercase,10),repeat=5):
c=sum(map(lambda d:sum(map(lambda i:i[0] in i[1],zip(d,l)))==5,w))
if c>v:
v=c
print str(c)+" "+str(l)
```
Note that I renamed the word list file to just "w" to save a few characters.
The output is the number of words that are possible from a given configuration followed by the configuration itself:
```
34 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'))
38 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'))
42 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'l'))
45 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'n'))
50 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'r'))
57 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 's'))
60 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k', 's'))
64 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'l', 's'))
67 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'n', 's'))
72 (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'r', 's'))
...
```
The last line of output before the program terminates is guaranteed to be the optimal solution.
] |
[Question]
[
Out of all of the ASCII characters, it is easy to tell that some of them form groups that are rotations of the same basic character. For example, `V > ^ <`. This allows the possibility to construct ASCII art that can be rotated by multiples of 90 degrees and still remain ASCII art.
# The Challenge
Your goal is to golf a program that accepts ASCII art and the number of degrees to rotate it from STDIN, and prints the rotated ASCII art to STDOUT.
On the first line of input, your program will receive a number N. This number represents the width and height of the ASCII art.
You will then receive N more lines of exactly N characters each (the newline is not counted in this number). The size of the art will always be a square, although it may have padding in the form of spaces to make it a square.
You will then receive one more number on a final line: 90, 180, or 270. This represents how many degrees clockwise the picture should be rotated.
Note: The inputted image will only contain characters that can be rotated by the correct amount. If the input does not match these requirements exactly, no specific behavior is required.
As output, your program should print exactly N lines of N characters, with newlines after each line. The image should be rotated so that each character in the original has been replaced by a rotated version and has been moved to the correct place in the image.
## Examples (not very beautiful ASCII art)
Input
```
5
<- ||
| |V
+->+
|O
<--+
90
```
Output
```
^ +-^
| | |
| V
+-+--
O <-
```
(Rotations by 90 and 270 won't look very good because the characters are not squares)
Input
```
6
+ /\ +
| \ \|
( \/|
\ )
I \ /
:) V $
180
```
Output
```
$ ^ (:
/ \ I
( \
|/\ )
|\ \ |
+ \/ +
```
## Required Supported Characters
For all rotations (90, 180, and 270), the program should be able to rotate:
* Spaces, `+`, `@`, `X` and `O` which never change
* `V` `>` `<` `^`
* `|` `-` and `\` `/` (rotated by 180 they stay the same)
For 180 degree rotation, these additional characters must be supported
* `I` `N` `Z` `%` `:` `0` `=` `S` `~` `$` `#` which stay the same
* `P` `d`, `(` `)`, `[` `]`, `{` `}`, `M` `W`, and `9` `6`
[Answer]
## C, 336 chars
I'm sure there's room for improvement.
```
char*a="<^>V|-|-/\\/\\ppdd(())[[]]{{}}MMWW9966",*p,*q;
n,x,y,r;
z(c){
return(q=strchr(a,c))?a[(q-a&-4)+(q-a+r&3)]:c;
}
#define A(r)(r&3^3?1-r%4:0)*
f(r){
return A(r)x+A(~-r)y+(r&2)/2*~-n;
}
main(){
scanf("%d\n",&n);
p=q=malloc(n*n+1);
for(y=n;y--;q+=n)gets(q);
scanf("%d",&r);
for(r/=90;++y<n;puts(""))for(x=0;x<n;x++)putchar(z(p[f(r)+n*f(r+1)],r));
}
```
[Answer]
## GolfScript, ~~79~~ ~~75~~ ~~73~~ 67 chars
```
n%(;)~90/{-1%zip{{.'V<^>P(d)[{]}M9W6/\/\|-|'4/\+{.}%n+.@?)=}%}%}*n*
```
Looks like my and [Peter Taylor's](https://codegolf.stackexchange.com/a/5205) solutions are experiencing a certain amount of convergence. Anyway, looks like I'm still a few chars ahead for now. :-) Thanks (and +1) to both Peter and [copy](https://codegolf.stackexchange.com/a/5207) for ideas that I've shamelessly stolen.
This code completely ignores the size given on the first line, since it's redundant information. It should even handle inputs with non-square dimensions, but it very much depends on all the input lines being padded to the same length. Trying to rotate the characters `P`, `d`, `(`, `)`, `[`, `]`, `{`, `}`, `M`, `W`, `9`, or `6` by 90 or 270 degrees may produce unexpected output; all other characters that are not explicitly remapped are retained unchanged.
Ps. Here's my original 79-char solution:
```
n%(;)~90/:z{-1%zip}*n*z'V<^>/|-\V>^<'{:c;{{.c?~.c=@if}%}*}:s~2z='P([{M96W}])d's
```
[Answer]
## javascript (181 chars)
```
a=prompt(f="V<^>V|-|/\\/P(d)P([{]}[}M9W6M9").split(n="\n");c=a.pop()/90;for(
b=a[0];c--;a=d.split(n))for(e=d=n;e<b*b;++e%b||(d+=n))d+=f[f.indexOf(g=a[b-e
%b][e/b|0])+1||a]||g;alert(d)
```
Requires every line to be padded to the given length.
[Answer]
## Golfscript (80 79 78 77 76 chars)
```
n%(;)~90/{zip{-1%{'V<^>V|-|/\/''Pd()[]{}MW96'{.4*}%4/128,+{.}%+.@?)=}%}%}*n*
```
NB Entering the "undefined behaviour" permitted by invalid input can produce somewhat curious output, because of placeholder characters (outside ASCII) used for certain characters whose rotation by 90 degrees is not defined. For example, `(` would be mapped to code point 160, which in ISO-8859-1 and Unicode is a non-breaking space.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 7 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
╶╶90┤÷↷
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTc2JXUyNTc2OTAldTI1MjQlRjcldTIxQjc_,i=JTIyJTNDLSUyMCU3QyU3QyU1Q24lN0MlMjAlMjAlN0NWJTVDbistJTNFKyUyMCU1Q24lMjAlMjAlMjAlN0NPJTVDbiUzQy0tKyUyMCUyMiUwQTkw,v=8)
~~basically cheating~~
] |
[Question]
[
# Context :
Suppose you have a sheet of paper measuring `8 x 10`. You want to cut it exactly in half while maintaining its rectangular shape. You can do this in two ways.
* You can cut it in half preserving its long dimension of 10 (for our purpose we will refer to this as long cut from now on).
Example :
$$
[8, 10] \rightarrow {long cut} \rightarrow [4, 10]
$$
Or you can cut it in half preserving its short dimension (we will refer to it as short cut).
Example :
$$
[8,10]→short cut→[5,8]
$$
For a square, the short and long cut are same. i.e :
$$
[12,12]→long cut→[6,12]
$$
$$
[12,12]→short cut→[6,12]
$$
# Task :
For this challenge you are given two arguments.
* The first is a string containing the cuts to be made to a sheet of paper in sequence from first to last. A long cut is designated by "L" and a short cut by "S".
* The second is dimension of paper after said cuts were made (an array)
Given that devise a function that will find the all the possible original dimensions of the sheet of paper before any cuts were made.
The dimensions of a sheet are given as an array `[x,y]` (\$y\geq x\$)
Return all possible orignial paper measures : `[x, y]` for (\$y\geq x\$)
If input make it so that an output is not possible return a falsey value (be it empty array , false, 0, empty string, nil/null/Null). You may not give an error though
# Examples :
```
cuttingPaper("S", [3, 7]) --> [[3, 14]]
cuttingPaper("L", [5, 7]) --> []
cuttingPaper("", [3, 7]) --> [[3, 7]]
cuttingPaper("S", [5, 7]) --> [[5, 14], [7, 10]]
cuttingPaper("LSSSSS", [1, 2]) --> [[2, 64], [4, 32], [8, 16]]
```
# Explanation :
### For example 2 :
`L` for `[5, 7]` gives empty array since if it started `[5, 14]` then the long cut would result in `[2.5, 14]` and if it started with `[10, 7]` then the long cut would result in `[10, 3.5]`. so in this case the cut is simply not possible
### For example 4 :
`[5, 7]` for `S` cut gives 2 solutions since it could start as `[5, 14]` and then short cut would yield `[5, 7]` which is possible solution 1.
Alternately you can start with `[7, 10]` and then cut and you would end up with `[5, 7]` which is possible solution 2. B
ecause of that you get 2 possible solutions. (you output both)
**In such a case you will return an array of array / list of list / etc...**
# I/O :
You take 2 inputs :
* A String containing the cuts made.
* The array after said cuts were made
You can take it as the following :
* an array/set (or equivalents) containing 3 inputs (in following order `[cuts, x, y]` or `[x, y, cut]`
* Three inputs `cut, x, y` or `x, y, cut`
* 2 input `cut, [x, y]` or `[x, y], cut`
* A string consisting of all 3 `cuts x y` (space seperated, you may choose your separator)
# Notes :
* The string will either be empty or contain some combination of S and/or L.
* The array will always contain two Positive integers.
* This is code-golf so shortest answer in bytes will win (note : I won't be selecting any answer as accepted).
* Standard loopholes apply.
For those that solve it kindly if you can give a small explanation so others (mainly me) can learn/understand your code (if you have the time and patience)
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~115~~ 110 bytes
```
f=lambda s,d:{k for a,b in[d,d[::-1]]if(x:=(2*a,b)[::s[-1]<'S'or-1])[0]<=x[1]for k in f(s[:-1],x)}if s else{d}
```
[Try it online!](https://tio.run/##TY7BCoMwEETv/YqlF5OyhaqUlqB/4C3HkIMSQ4NWxXiwiN@ebqAF97Qzs4/Z6bO8xiF/TnMItuzrd2Nq8GjE1oEdZ6ixATcog0YJcU21dpatomTZhRJOnlfkFolMxpkWrm66KFeV6gh3hIJlXkUSV747Cx7a3reb2UO88PhrAHWWZ4Qc4aGRREXi/hfHQB6DSsYhJ0XItDgBTLMbFkadyOKDnIcv "Python 3.8 (pre-release) – Try It Online")
---
# [Python 3.8](https://docs.python.org/3.8/), 104 bytes
Takes some inspiration from Arnauld's answer.
```
f=lambda s,d:s==''!=print(d)or[f(s[:-1],x)for a,b in{d,d[::-1]}if(x:=(2*a,b)[::s[-1]<'S'or-1])[0]<=x[1]]
```
[Try it online!](https://tio.run/##TY5NCsIwEEb3nmLsJolMwFZECc0NussyZNESggVtS9JFRTx7naBCZzXvfczP9Jxv43C6TnFdg763j863kNCrpDVjez3Ffpi5F2O0gSerZOlwEWGM0GIH/fDy6K3K@t0HvijNqwMlglyyZGtm2BipEfboar3Y0rk1jyf8bQBbmALhhHBxSNAQnP@wDcw2aEwuMiVC5dQOgN5Dnk8Lgu/bTErJxPoB "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~94~~ 91 bytes
Expects `(list, width, height)`, where `list` is either a string or an array of characters. Prints the solutions.
```
f=([...c],w,h)=>c+c?c.pop(W=w*2)>"L"?f(c,w,h*2,W<h|w==h||f(c,h,W)):W>h||f(c,W,h):print(w,h)
```
[Try it online!](https://tio.run/##bZC9rsIwDIV3nsLKlIAbIPwUASnT3dg6ZIgyVJF6wx2gKogOlGfvdSgwIDz52N85VvJXXIuzrw/VJbmuuq7U3EopvcMGg9CZH/mdl9Wp4kY3QyUytme7kvu4Hio029A2Woe2jbOARoi1yZ7SUMK6qg/HC49h3cYOACywnCHMEFJwCLHGY7CWBtO5cz2xJ2LxQTxXH963OX158y9eu3ikI9iUmsn7TB6L@CmCAtejCmH5QOd0ScVmRcCSPG4gy1P9U/jAi/oXdAY3KDn9Fimxgf6lLEkSRuouun8 "JavaScript (V8) – Try It Online")
### How?
Given an operation and the resulting dimensions \$(w,h)\$ (with \$w\le h\$), we look for the possible solutions for the original dimensions.
If the operation was a long cut:
* If \$2w\le h\$, the only possible solution is \$(2w,h)\$. Otherwise, this is invalid.
If the operation was a short cut:
* \$(w,2h)\$ is always a solution.
* If \$2w\ge h\$, \$(h,2w)\$ is another solution.
* If \$w=h\$, both solutions are identical so we make sure to try only one of them to avoid duplicate results.
We attempt to apply these rules, starting with the last operation and going backwards. Whenever we successfully process the entire chain, we print the final result.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
Takes `[x, y]` on the first and the (unquoted) cut sequence on the second line.
```
¸sRv€ÂÙ€ƶyCÉií}ʒD{Q
```
[Try it online!](https://tio.run/##yy9OTMpM/V9WeaT9UcMs26CE/4d2FAeVPWpac7jp8EwgdWxbpfPhzszDa2tPTXKpDvxfW6ukoGunoGSvo6QLBEo6/6OjlYKVdBSMdRTMY3UUopV8gBxTGAdZIhhZwicYBIAihjoKRrGxAA "05AB1E – Try It Online")
```
¸ # wrap the pair into a list [[x,y]]
sR # swap to the string and reverse it
v # for each character y in the reversed string:
€Â # extend the list by all pairs reversed
Ù # remove duplicate pairs
€ƶ # "Lift" each pair; multiply first element by 1, second by 2
yCÉ # is y equal to 'L'?
ií} # if so, reverse each pair
ʒ # only keep resulting pairs, that are ...
D{Q # equal when sorted
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~73~~ 43 bytes
```
⊞υE²NF⮌S≔ΦE⁺υEυ⮌κEκ×μ⊕⁼ν⁼ιS¬›⁰↨κ±¹υIΦυ⁼κ⌕υι
```
[Try it online!](https://tio.run/##PU5LDoIwEN1ziomrIamJsnWlRoyJEiJeoOIIjaVgP1y/tijOZiZv3q9uua57Lr0vnWnRMbjwATMGJzU4W7juThrTNN0kz14DXmkkbQinb2W1UE38wtYY0SjMhbSBHy1K6cxsF9YsfAX2F3wxuImODHYxrNbUkbL0wMPbcWlQMfhdgsGiWqTTMCh6i0dNPOasGOx4NA0wNQHC9Y/lQuEytLO458bOvdzfMyhyoR4REZNk4/06yZJzFccvR/kB "Charcoal – Try It Online") Link is to verbose version of code. Takes `x`, `y`, `cuts` on separate lines and outputs pairs of `x`, `y` on separate lines with double-spacing between each pair. Explanation: Now inspired by @ovs's answer.
```
⊞υE²N
```
Push the target pair to the predefined empty list.
```
F⮌S
```
Loop over the cuts in reverse order.
```
≔ΦE⁺υEυ⮌κEκ×μ⊕⁼ν⁼ιS¬›⁰↨κ±¹υ
```
Take the list of sizes and reverse each size. Take both lists and double either the width or length depending on the cut. Filter out those sizes where the width is larger than the length.
```
IΦυ⁼κ⌕υι
```
Deduplicate and output the final sizes.
] |
[Question]
[
# Game of Game of Life
[Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life "Conway's Game of Life") is a 0-player game. But that's okay! We can make it a multi-player game.
This game is played on the smallest square grid that will accommodate a 6x6 square for each player (12x12 for 2-4 players, 18x18 for 5-9 players, etc). This grid is actually a torus, so it wraps in both directions. The rules of Life are:
* If a cell has exactly 3 neighbours, it comes to life (or remains alive) in the next generation.
* If a cell has exactly 2 neighbours, it does not change in the next generation.
* If it does not have exactly 2 or 3 neighbours, it dies in the next generation.
A cell's neighbours are those cells adjacent to it orthogonally or diagonally; each cell has 8 neighbours.
In this game, there are only a few differences from the standard Game of Life:
* Each player has a different colour of life, with dead cells being white and neutral living cells being black.
* When a cell becomes alive, it takes on the colour of its most common neighbour, or black (no player) if there are three different colours. Cells do not change colour as long as they are alive.
* Each generation, each bot can cause one nearby cell to come alive in their colour or one of their own cells to die. This happens before a generation is processed; a cell that is killed may come back to life and a cell brought to life may die in the subsequent generation.
# Winning the game
The game lasts 1000 generations, or until there is only one colour of living cells remaining. If all coloured cells die on the same generation, the game is a draw, and no bot receives points. Each bot scores points equal to the percentage of living coloured cells it has at that time (out of the total number of coloured cells). 10000 games will be run, and the winner is the bot with the highest average score. Ties are broken with a 1v1 cage match.
# Starting conditions
Each bot will start with the following layout of living cells:
```
......
......
..##..
..##..
......
......
```
These will be randomly arranged into the square playing area. Each 6x6 area without a bot will have the same configuration, but with black living cells.
# Bot parameters
Your bot will be written in Javascript, and will not have an average call time of over 50ms (bots that do may be disqualified, but bots may use `performance.now()` to police their own time). It will accept as parameters:
```
grid - The grid on which the game is played. This should not be modified.
botId - The bot's ID, corresponding to the colour on the grid.
lastMoves - An array of each bot's most recent move, as it's (usually) possible but computationally intensive to get this information otherwise.
```
Your bot will return an array with two elements, x and y. This is the cell that your bot wishes to play. It must be within 2 cells of one of your living cells. If the selected cell is alive and not one of your cells, it does nothing unless the bot whose colour it is removes it on the same generation, in which case it causes it to be your colour. If it is alive and one of your cells, that cell is killed before the next generation. If it is a dead cell, it comes alive before the next generation (it comes alive as your bot's colour unless some other bot also picks it, in which case it comes alive black).
A play too far away from one of your cells is a pass. Alternately, [-1,-1] is an explicit pass. A play off of the board in any other way is illegal and grounds for disqualification.
On the grid, -1 is black (neutral living), 0 is white (dead), and all other numbers are the id of the bot whose life is in that cell.
# Other Restrictions
* You may make a maximum of 3 bots.
* If your bots uses random numbers you can use `Math.random`.
* Your bot may, if it wishes, store data on `this`. It will be cleared between games.
* You may not make a bot which targets a single, prechosen bot. Your bot may target the tactics of a class of bots.
* Cooperation is legal between bots, but communication is not - you can cooperate with a strategy, but not attempt to make a specific sequence of moves which identifies your bot. For example, identifying a bot based on specific starting sequence is not allowed, but knowing "target bot prefers moving up and left, all else equal" is okay. IDs are randomized and bots will not know in advance what other bots' IDs are.
# Controller
This isn't quite complete, but it's a good start. I plan to keep track of scores, add a box so it's easy to test a new bot, etc. Of course, some of that is hard to test without real competitors, but I'll get around to it.
It seems that I made x the major axis and y the minor one, so if your bot is going a different way than you expect, that might be why. Sorry.
[Code](https://github.com/Nucaranlaeg/Nucaranlaeg.github.io/tree/master/KotH/GoGoL) [Run it here](https://nucaranlaeg.github.io/KotH/GoGoL/)
# Example bot
It seems traditional to include a bad bot in the competition to get things started. This bot is *bad*. It chooses uniformly at random from cells in the grid and tries to move there. I haven't yet had it survive 1000 generations.
```
function randomMovesBot(grid, botId, lastMoves){
return [Math.floor(Math.random() * grid.length), Math.floor(Math.random() * grid.length)];
}
```
# Winner
Two weeks after the last new submission (or a significant change to a bot), I'll close this by running 10000 games (number subject to possible revision). I'll leave the controller up afterward if someone wants to make a new submission, but official standings won't change.
# [Chat](https://chat.stackexchange.com/rooms/104667/game-of-game-of-life)
[Answer]
# Do-nothing
```
function rgs_do_nothing(grid, id, last_moves) {
return [-1, -1];
}
```
As of the time of posting, this wins against all other bots in the competition fairly consistently.
This bot is funny because in the branch of numerical analysis where I did some research, sometimes we have *partial differential equations* with these *do-nothing boundary conditions* and for a method I implemented, it **literally** amounted to doing nothing to handle the boundary conditions... My best type of work is when it is legit to do nothing :')
[Answer]
# planBbot
I took planBot as a blue print. With simple enhancements/changes:
### Version 1.1
* improved move selection: never delete own colour cells
* improved scoring
* improved time management: used a PD-Controller to stay at 50ms
* changed policy: dropped endgame mode
* result of playing 100 games:
```
Name Score
BestNowBot 0
planBbot v1.1 100
planBot 0
randomMovesBot 0
rgs_do_nothing 0
```
### Version 1.0
* simple time management:
Try to stay within 50 ms per move on average while using as much time as possible for lookaheads.
* some performance tweaks:
Undone caching of results. (Identical board states are too unlikely.)
* scoring: The idea: Stay sparse and don't feed the opponent.
* endgame aware: If planBbot survived until generation 990 it starts to look deep ahead to generation 1000.
* result of playing 100 games:
```
Name Score
BestNowBot 0.64
planBbot v1.0 85.40
planBot 13.94
randomMovesBot 0
rgs_do_nothing 0
```
```
// version 1.1
function planBbot(grid, botId, lastMoves) {
let t0=performance.now();
let best_cell = [-1, -1];
let max_score = -10000000;
let size = grid.length;
let possible_moves = new Set();
let dist = 1
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
if (grid[x][y] == botId) {
for (let dx = -dist; dx <= dist; dx++) {
for (let dy = -dist; dy <= dist; dy++) {
let x1 = (size + x + dx) % size;
let y1 = (size + y + dy) % size;
if (grid[x1][y1] == 0) {
possible_moves.add([x1, y1]);
}
}
}
}
}
}
if (possible_moves.size == 0) {
return best_cell;
}
let new_grid = Array(size).fill(0).map(() => new Array(size).fill(0));
if (typeof this.A == "undefined" || typeof this.A.dtime == "undefined") {
this.A={iters:4, dtime:49, count:0, e0:0};
this.A.lookahead=function(old_grid, new_grid){
let iscore = 0;
let oscore = 0;
let neighbours = [];
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
neighbours.length = 0;
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if ((dx == 0) && (dy == 0)) {
continue;
}
let cell = old_grid[(size + x + dx) % size][(size + y + dy) % size];
if (cell != 0) {
neighbours.push(cell);
}
}
}
let next=old_grid[x][y];
switch(neighbours.length) {
case 2: break;
case 3: if (next == 0) {
if (neighbours[0] == neighbours[1] || neighbours[0] == neighbours[2]) {
next = neighbours[0];
} else if (neighbours[1] == neighbours[2]) {
next = neighbours[1];
} else {
next = -1;
}
}
break;
default: next = 0;
}
new_grid[x][y] = next;
if (next == botId) {
iscore++;
} else if (next != 0) {
oscore++;
}
}
}
if (oscore==0) {
return 100000
}
return (iscore)-4*(oscore);
}
}
let me=this.A;
me.count++;
let e=49-me.dtime;
me.iters+=0.05*e+0.0005*(e-me.e0);
me.e0=e;
let iters=0.3*size*size*Math.max(me.iters, 2)/possible_moves.size;
iters=Math.min(Math.max(iters+0.5, 3), 7);
for (cell of possible_moves) {
let old_grid = grid.map(x => x.slice());
old_grid[cell[0]][cell[1]] = botId - old_grid[cell[0]][cell[1]];
let score = 0;
for (let i = 0; i < iters; i++) {
score += me.lookahead(old_grid, new_grid);
let tmp = new_grid;
new_grid = old_grid;
old_grid = tmp;
}
if (score >= max_score) {
max_score = score;
best_cell = cell;
}
}
me.dtime=performance.now() - t0;
return best_cell;
}
```
[Answer]
# Best Now Bot
```
function BestNowBot(grid, botId, lastMoves){
let wrap = coord => coord < 0 ? coord + grid.length : coord >= grid.length ? coord - grid.length : coord;
let adj_life = (x, y) => {
let sum = 0, sum_mine = 0;
for (let i = -1; i <= 1; i++){
for (let j = -1; j <= 1; j++){
if (!i && !j) continue;
if (grid[wrap(x+i)][wrap(y+j)]) sum++;
if (grid[wrap(x+i)][wrap(y+j)] == botId) sum_mine++;
}
}
return [sum, sum_mine];
}
let my_cells = [];
for (let i = 0; i < grid.length; i++){
for (let j = 0; j < grid.length; j++){
if (grid[i][j] == botId){
my_cells.push([i, j]);
}
}
}
let legal_moves = my_cells.slice();
my_cells.forEach(cell => {
for (let i = -2; i <= 2; i++){
for (let j = -2; j <= 2; j++){
let x = wrap(cell[0] + i),
y = wrap(cell[1] + j);
if (grid[x][y] == 0 && !legal_moves.some(m => m[0] == x && m[1] == y)){
legal_moves.push([x, y]);
}
}
}
});
// Calculate results of each move.
legal_moves.forEach(move => {
let move_score = 0;
if (grid[move[0]][move[1]] == botId) move_score--;
for (let i = -1; i <= 1; i++){
for (let j = -1; j <= 1; j++){
let x = wrap(move[0] + i),
y = wrap(move[1] + j);
let [adj, adj_mine] = adj_life(x, y);
if (grid[x][y] == botId && adj == 3){
move_score--;
} else if (grid[x][y] == 0 && adj == 2 && adj_mine > 0){
move_score++;
}
}
}
move.push(move_score);
});
let best = Math.max(...legal_moves.map(m => m[2]));
let good_moves = legal_moves.filter(m => m[2] == best);
return good_moves[Math.floor(Math.random() * good_moves.length)].slice(0, 2);
}
```
BestNowBot looks at all the available options and determines which of them are positive for it, and then selects randomly from them. Feel free to use BestNowBot as a basis for an answer - I figure it's kind of a baseline for an effective bot.
At time of posting, wins ~99% of games.
[Answer]
```
function advance(hash_grid, old_grid, new_grid){
let hash = 0;
let size = old_grid.length;
let neighbours = [];
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
neighbours.length = 0;
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if ((dx == 0) && (dy == 0)) {
continue;
}
let cell = old_grid[(size + x + dx) % size][(size + y + dy) % size];
if (cell != 0) {
neighbours.push(cell);
}
}
}
if (neighbours.length < 2 || neighbours.length > 3) {
new_grid[x][y] = 0;
} else if (neighbours.length == 3 && old_grid[x][y] == 0) {
if (neighbours[0] == neighbours[1] || neighbours[0] == neighbours[2]) {
new_grid[x][y] = neighbours[0];
} else if (neighbours[1] == neighbours[2]) {
new_grid[x][y] = neighbours[1];
} else {
new_grid[x][y] = -1;
}
} else {
new_grid[x][y] = old_grid[x][y];
}
hash += hash_grid[x][y] * new_grid[x][y];
}
}
return hash;
}
function planBot(grid, botId, lastMoves) {
let size = grid.length;
let possible_moves = new Set();
let count = 0;
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
if (grid[x][y] == botId) {
count++;
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
let x1 = (size + x + dx) % size;
let y1 = (size + y + dy) % size;
if ((grid[x1][y1] == 0) || (grid[x1][y1] == botId)) {
possible_moves.add([x1, y1]);
}
}
}
}
}
}
let possible_move_array = Array.from(possible_moves);
if (possible_move_array.length == 0) {
return [0,0];
}
let neighbor_scores = function(n) {
if ((n >= 2) && (n <= 3)) {
return 0;
}
return -1;
}
let best_cell = [0, 0];
let max_score = -10000;
let memo = new Map();
let hash_grid = Array(size).fill(0).map(() => new Array(size).fill(0).map(() => Math.random()));
let new_grid = Array(size).fill(0).map(() => new Array(size).fill(0));
let iters = 4;
for (cell of possible_move_array) {
let old_grid = grid.map(x => x.slice());
old_grid[cell[0]][cell[1]] = botId - old_grid[cell[0]][cell[1]];
let hashes = []
let score = 0;
let hit = false;
for (let i = 0; i < iters; i++) {
let hash = advance(hash_grid, old_grid, new_grid);
hashes.push(hash);
if (memo.has(hash)) {
score = memo[hash];
hit = true;
break;
}
let tmp = new_grid;
new_grid = old_grid;
old_grid = tmp;
}
if (!hit) {
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
if (old_grid[x][y] == botId) {
score++;
} else if (old_grid[x][y] > 0) {
score -= 1e-7;
}
}
}
}
for (hash of hashes) {
memo.set(hash, score);
}
score += 1e-9 * Math.random();
if (score >= max_score) {
max_score = score;
best_cell = cell;
}
}
return best_cell;
}
```
Rolls ahead a few steps for each potential move and picks the move which resulted in the greatest area for itself, breaking ties by total opponent area. It also caches the results to avoid simulating identical board states.
] |
[Question]
[
How can we depict a turned shape simply and nicely using ascii characters in 3D space?
I suggest this method :
Instead of a circle we use a square rotated by 45° for the cutting section so that we only need '/' and '\' characters to draw it.
```
/\
/ \
\ /
\/
```
And we use '\_' character for the profiles: upper, lower and median.
```
_________
/\ \
/ \________\
\ / /
\/________/
```
Isn't it Turning complete? Well, if you agree, write a full program or a function taking an unsigned integer value N , representing a number of steps , producing a 3d shape as described below.
The profile of this turned shape has the form of a stair step curve raising from 0 to N steps and lowering back to 0 where each step is 2 char('/') high and 5 char long ('\_').
Maybe some examples describes it more clearly.
For N = 0 you may output nothing but it's not mandatory to handle it.
```
N = 1
_____
/\ \
/ \____\
\ / /
\/____/
.
```
```
N = 2
_____
/\ \
___/_ \ \__
/\ \ \ \ \
/ \____\ \____\_\
\ / / / / /
\/____/ / /_/
\ / /
\/____/
.
```
```
N = 3
_____
/\ \
___/_ \ \__
/\ \ \ \ \
___/_ \ \ \ \ \__
/\ \ \ \ \ \ \ \
/ \____\ \____\ \____\_\_\
\ / / / / / / / /
\/____/ / / / / /_/
\ / / / / /
\/____/ / /_/
\ / /
\/____/
```
Rules :
- Margins are not specified.
- Standard loopholes are forbidden.
- Standard input/output methods.
- Shortest answer in bytes wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~70~~ 69 bytes
```
NθFθ«J⊕×⁷⊕ι⁰≔⊗⊕ιι↙ι↑←×⁵_P↖²→↗ι×⁴_↖ι←×⁵_↓P↙²→↘ιJ⁻×⁹θ⊗ι⊖ι__↗ι←P←__↖ι←__
```
[Try it online!](https://tio.run/##jZDBa8IwFMbP9q8IPSWQwdDJWD0NenFYGcOeRbuoD9okpkl3GPvbY9pkWjsc3h7vfe97v/cVh40qxKa0ds6l0UtTbZnCRzKLdkIhV6DvaPRmKrkSeM4LxSrGNfvEK6hYjZ8p6jeBEELRo1sevdY17DlOhdmWbjJQUQSt6F0B1zhJxRdfsJ0O3Uw0DCe57Cn81N@cUhSvY9IpTakhSHLpReOLxQfsD7rnksuuc3Xcez5dPAd2cAdFd6x94swkh4/9Q9WK@lwh7Ay4qQPeC0VHl9lvmF2AKbtK9OwXrx3WrZ89QYs0RPWYf5ZvhRCEP9ZO7ENTngA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθFθ«
```
Input `N` and loop that many times.
```
J⊕×⁷⊕ι⁰
```
Jump to the (middle) right corner of the front slice.
```
≔⊗⊕ιι
```
Get the size of the slice.
```
↙ι↑←×⁵_P↖²→↗ι×⁴_↖ι←×⁵_↓P↙²→↘ι
```
Draw the front slice.
```
J⁻×⁹θ⊗ι⊖ι
```
Jump to the bottom (that we can see) of the back slice.
```
__↗ι←P←__↖ι←__
```
Draw the back slice.
[Answer]
# JavaScript (ES8), ~~322 282 278~~ 272 bytes
Builds the output line by line.
```
f=(n,y=0,Y=(k=y>2*n)?4*n-y:y,S='___/_25__,/\\ \\25,\\/____/14_/,\\ 14,\\/____/,_____, \\____\\, / /, \\ \\,_\\, /, \\'.split`,`)=>~Y?(y-2*n?''.padEnd(n*5-(Y>>1)*5-3-y%2-k)+S[y?Y?k*2+y%2:4:5]:'/ 03').replace(/\d/g,n=>S[+n+6].repeat(Y-(n>2||-k)>>1))+`
`+f(n,y+1):''
```
[Try it online!](https://tio.run/##ZZDNioMwEMfvfQovSxKTmBq1ByHxtE/gSZoSxY/SKlGqFAJlX91NKCwsncN8/OY/wzD35tms7eO2bNTMXb/vg4CGWHEklYCjsJKHBhVpaKjNLSkF0FozzTOtCVMqcKYUz4hSTPtOnGrmiiBO/xDxXhOn81EpEjA/xjx5z5M39QBE6zLdtprUSMifqoCWugMKAKKl6b5NB02YUVhJGSOXJNR@cToiXJ5tURVjyLEDeZpnlxyw4JgAFD36ZWraHjLVsSsxQpZnbPDp4ht9s8GKQiP56@XW@K0I14caD/4HOEY5AHs7m3We@miar3CATnH4T/gHST5IitD@Cw "JavaScript (Node.js) – Try It Online")
### How?
For each row \$0 \le y \le 4n\$, we define:
$$k=\cases{
0,&\text{if $y \le 2n$}\\
1,&\text{if $y > 2n$}
}$$
$$Y=\cases{
y,&\text{if $k=0$}\\
4n-y,&\text{if $k=1$}
}$$
Each row is first converted into a main pattern. A main pattern may contain digits: they are placeholders for repeated sub-patterns that are expended afterwards.
The middle row (when \$y=2n\$) is a special case which is processed separately. For all other rows, we compute the main pattern ID \$p\$ with:
$$p=\cases{
5,&\text{if $y=0$}\\
4,&\text{if $y \neq 0, Y=0$}\\
2k+(y \bmod 2),&\text{otherwise}\\
}$$
There are no leading spaces for the middle row. For all other rows, the number \$s\$ of leading spaces is given by:
$$s=5n-5\left\lfloor\frac{Y}{2}\right\rfloor-3-(y\bmod 2)-k$$
There are inner sub-patterns (marked with a digit \$\le2\$) and outer sub-patterns (marked with a digit \$>2\$), which are repeated \$n\_1\$ and \$n\_2\$ times respectively:
$$n\_1=\left\lfloor\frac{Y+k}{2}\right\rfloor\\
n\_2=\left\lfloor\frac{Y-1}{2}\right\rfloor$$
The above formulae apply to the middle row as well, but are irrelevant for the first and last rows, which do not have sub-patterns.
Below is what we get for \$n=3\$:
```
y Y k | p | s | before .replace() | n1 | n2 | after .replace()
--------+-----+-----+----------------------+----+----+-----------------------------
0 0 0 | 5 | 12 | ............_____ | 0 | -1 | ............_____
1 1 0 | 1 | 11 | .........../\ \25 | 0 | 0 | .........../\ \
2 2 0 | 0 | 7 | .......___/_25__ | 1 | 0 | .......___/_ \ \__
3 3 0 | 1 | 6 | ....../\ \25 | 1 | 1 | ....../\ \ \ \ \
4 4 0 | 0 | 2 | ..___/_25__ | 2 | 1 | ..___/_ \ \ \ \ \__
5 5 0 | 1 | 1 | ./\ \25 | 2 | 2 | ./\ \ \ \ \ \ \ \
6 6 0 | n/a | n/a | / 03 | 3 | 2 | / \____\ \____\ \____\_\_\
7 5 1 | 3 | 0 | \ 14 | 3 | 2 | \ / / / / / / / /
8 4 1 | 2 | 1 | .\/____/14_/ | 2 | 1 | .\/____/ / / / / /_/
9 3 1 | 3 | 5 | .....\ 14 | 2 | 1 | .....\ / / / / /
10 2 1 | 2 | 6 | ......\/____/14_/ | 1 | 0 | ......\/____/ / /_/
11 1 1 | 3 | 10 | ..........\ 14 | 1 | 0 | ..........\ / /
12 0 1 | 4 | 11 | ...........\/____/ | 0 | -1 | ...........\/____/
```
] |
[Question]
[
**What is a Prime Square?**
A Prime Square is a square where all four edges are different prime numbers.
But which ones?
And how do we construct them?
**Here is an example of a 4x4 Prime Square**
```
1009
0 0
3 0
1021
```
First we start from the upper left corner. We are working **clockwise**.
We pick the smallest prime number having `4` digits which is **1009**.
Then we need the smallest prime number having `4` digits, which starts with a `9`. This is **9001**
The third (4-digits) prime number must have `1` as its last digit (because **9001** ends with `1`)
and also be the smallest 4-digit prime with this property that has **not been used before as an edge**.
This prime number is **1021**
The fourth prime number must have `4` digits, **start** with a `1` (because **1009** starts with a `1`) and **end** with a `1` (because **1021** starts with a `1`)
The smallest 4-digit prime number with this property that *has not been used before as an edge* is **1031**
**Your TASK**
You will be given an integer `n` from `3 to 100`
This number will be the dimensions of the `n x n` square
Then you must **output this square exactly in the form of the following test cases**
**Test Cases**
```
n=3
Output
101
3 0
113
n=5
Output
10007
0 0
0 0
9 0
10061
n=7
Output
1000003
0 0
0 0
0 0
0 0
8 1
1000037
n=10
Output
1000000007
0 0
0 0
0 0
0 0
0 0
0 0
1 0
8 0
1000000021
n=20
Output
10000000000000000051
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
9 8
10000000000000000097
```
* Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Any amount of extraneous whitespace is acceptable, so long as the numbers line up appropriately
* [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.
**EDIT**
This is possible for all `n`
Here are the primes for `n=100`
```
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000289
9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000091
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000711
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002191
```
And for those of you that you don't think this is possible [here are ALL the test cases][1]
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~64~~ ~~63~~ ~~56~~ ~~53~~ ~~48~~ 46 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
°ÅPIùćÐ4FˆθUKD.ΔθyXÅ?yXÅ¿)¯gè}ÐNĀiR}¦}I¯JŽ9¦SΛ
```
-1 byte thanks to *@Mr.Xcoder*
-5 bytes thanks to *@Grimy*.
[Try it online.](https://tio.run/##AU4Asf9vc2FiaWX//8Kww4VQScO5xIfDkDRGy4bOuFVLRC7OlM64eVjDhT95WMOFwr8pwq9nw6h9w5BOxIBpUn3Cpn1Jwq9Kxb05wqZTzpv//zQ) (Times out for \$n>4\$. [Here the slightly faster **53 bytes** version](https://tio.run/##yy9OTMpM/f//0IbDrQWeh3ceaT@08nSbsZtfmIveuSmR8ZmH1p3bcbjV/vDqSCjz0P7Dq8/tqK2tPbTS@9C6yCMNmUG1h5adbqv1PLTe6@hey0PLgs/N/v/fFAA) which times out for \$n>7\$ instead.)
**Explanation:**
```
° # Raise the (implicit) input to the power 10
ÅP # Get a list of primes within the range [2, n^10]
Iù # Only keep those of a length equal to the input
ć # Extract the head; push the remainder-list and first prime separately
Ð # Triplicate this first prime
4F # Loop 4 times:
ˆ # Add the (modified) prime at the top of the stack to the global array
θU # Pop and store the last digit of the prime in variable `X`
K # Remove this prime from the prime-list
D # Duplicate the prime-list
.Δ # Find the first prime `y` in the prime list which is truthy for:
θ # Get the last digit of prime `y`
yXÅ? # Check if prime `y` starts with variable `X`
yXÅ¿ # Check if prime `y` ends with variable `X`
) # Wrap the three results above into a list
¯g # Get the amount of items in the global array
è # And use it to index into these three checks
# (Note that only 1 is truthy for 05AB1E, so the `θ` basically checks
# if the last digit of prime `y` is 1)
}Ð # Triplicate the found prime
NĀi } # If the loop index is 1, 2, or 3:
R # Reverse the found prime
¦ # And then remove the first digit of the (potentially reversed) prime
} # After the loop:
I # Push the input as length
¯J # Push the global array joined together to a single string
Ž9¦S # Push compressed integer 2460 converted to a list of digits: [2,4,6,0]
Λ # Draw the joined string in the directions [2,4,6,0] (aka [→,↓,←,↑])
# of a length equal to the input
# (which is output immediately and implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž9¦` is `2460`. And [see this 05AB1E tip of mine](https://codegolf.stackexchange.com/a/175520/52210) to understand how the square is output with the `Λ` Canvas builtin.
The relevant code for printing the Canvas in a square is: `NĀiR}¦` and `I¯JŽ9¦SΛ`. Let's take `n=4` as example. The primes it will find with the rest of the code are `[1009,9001,1021,1031]`. The first code-part mentioned in this paragraph will save them as this instead: `[1009,"001","201","301"]`. The second code part of this paragraph will then use the Canvas builtin `Λ` with options:
- \$a\$ (side-length) = `I`: the input
- \$b\$ (string to print) = `¯J`: the global array joined together (so `"1009001201301"` for `n=4`)
- \$c\$ (direction) = `Ž9¦S`: the directions `[2,4,6,0]`, which will be `[→,↓,←,↑]` respectively
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ ~~33~~ ~~32~~ 31 bytes
*-1 byte thanks to Kevin Cruijssen*
```
°ÅPIùΔÐXθÅ?Ïн©KX®¦«UNií]IXŽ9¦SΛ
```
[Try it online!](https://tio.run/##ATsAxP9vc2FiaWX//8Kww4VQScO5zpTDkFjOuMOFP8OP0L3CqUtYwq7CpsKrVU5pw61dSVjFvTnCplPOm///NA)
Explanation:
```
° # 10 to the power of the input
ÅP # list of primes up to that
Iù # keep only those with the same length as the input
Δ # repeat until the list doesn't change
# This ends up doing a ton of unneeded work. 4F (to loop 4 times) would be
# enough, but Δ is shorter and the extra iterations don’t cause issues.
# At the start of each iteration, the stack only contains the list of primes,
# and the variable X contains the current list of digits we’ll want to print.
# Conveniently, X defaults to 1, which is our first digit.
Ð Ï # push a filtered copy of the list, keeping only…
Å? # numbers that start with…
Xθ # the last character of X
н # get the first element: this is our next prime
© # save this number to the register
K # remove it from the list of candidate primes
X # push X
® # restore the number from the register
¦ # remove its first character
« # concatenate it to X
U # save the result to X
Ni # if N == 1 (second time through the loop)
í # reverse all elements in the list of candidate primes
] # closes both this if and the main loop
Λ # Draw on a canvas…
I # using the input as length…
X # using X as the string to draw…
Ž9¦S # using [2,4,6,0] (aka [→,↓,←,↑]) as the directions to draw in
```
[Answer]
# JavaScript (ES8), ~~205 ... 185 177~~ 173 bytes
Times out on TIO for \$n>8\$ because of the very inefficient primality test.
```
n=>([a,b,c]=[0,-1,--n,0].map(p=o=i=>o[(g=n=>{for(k=n++;n%k--;);k|o[n]|p[i]-n%10?g(n):p=n+''})((~i?1:p%10)*10**n)|p]=p),[...p].map((d,i)=>i?i<n?d.padEnd(n)+b[i]:c:a).join`
`)
```
[Try it online!](https://tio.run/##XY69bsIwFEZ3nsILsm/8o0SdGnOTqWtfwETCJCQygWsLqi4EXj111a3THc7R@e7Zf/t7fwvpS1McTuuIK2EjnFdH1XfoSqUrpTWpsjNXn0TCiAGb6MSEWXyM8SZmJCktbWetLdh5iY66JbnQadpWZTsJgjplh/MnCPEKbVWnDKCoyqIgWFKHCZQzxqS/ETGoANiENuyoHUzywwcNuSKPOVr3tQdzjoEOmwOsvw8QQ/ZmGbEde89HSmCPDWN9pHu8nMwlToJ/ZoczyQjsPzTmcgZ8Tzyz5/oD "JavaScript (Node.js) – Try It Online")
## How?
### Step #1: computing the 4 primes
```
[a, b, c] = // save the 3 first primes into a, b and c
// (the 4th prime will be saved in p)
[ 0, -1, --n, 0 ] // decrement n and iterate over [ 0, -1, n, 0 ]
.map(p = // initialize p (previous prime) to a non-numeric value
o = // use o as a lookup table
i => // for each value i in the list defined above:
o[ // update o:
(g = n => { // g = recursive function taking n
for(k = n++; // set k = n and increment n
n % k--;); // decrement k until it's a divisor of n
// (notice that k is decremented *after* the test)
k | // if k is not equal to 0 (i.e. n is not prime)
o[n] | // or n was already used
p[i] - n % 10 ? // or the last digit of n does not match the connected
// digit (if any) with the previous prime:
g(n) // do a recursive call
: // else:
p = n + '' // stop recursion and save n coerced to a string into p
})( // initial call to g with:
(~i ? 1 : p % 10) // either 10 ** n if i is not equal to -1
* 10 ** n // or (p % 10) * 10 ** n if i = -1
) | p // yield p
] = p // set o[p] = p
) // end of map()
```
### Step #2: formatting the output
```
[...p].map((d, i) => // for each digit d at position i in the last prime:
i ? // if this is not the first digit:
i < n ? // if this is not the last digit:
d.padEnd(n) // append d, followed by n - 1 spaces
+ b[i] // append the corresponding digit in the 2nd prime
: // else (last digit):
c // append the 3rd prime
: // else (first digit):
a // append the first prime
).join`\n` // end of map(); join with carriage returns
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~89~~ 82 bytes
```
1ịÆn⁺f®$¿
’⁵*;Æn$©µDṪṪ×ḢÇ©;@©µ;Ç⁺;0ị®¤%⁵n/Ɗ¿$$©;Ç⁺%⁵’$¿$$µŒœṪDZUḊṖj€⁶x³¤ḊḊ¤;@Ḣ;2ị$
```
[Try it online!](https://tio.run/##y0rNyan8/9/w4e7uw215jxp3pR1ap3JoP9ejhpmPGrdqWQMFVQ6tPLTV5eHOVUB0ePrDHYsOtx9aae0AErU@3A7UYm0A1H1o3aElqkAtefrHug7tVwFqgkiCxICGqYDFth6ddHQy0BiXqNCHO7oe7pyW9ahpzaPGbRWHNh9aAhLZ0XVoibUD0A5rI6CZKv8Pt0f@/29sAAA "Jelly – Try It Online")
Could definitely be golfier, but works efficiently for big numbers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 59 bytes
```
DṪṪ=DZḢṪṪ3ƭƊ}Tịḟ@Ḣ
’;⁸⁵*æR/µḢ;ç¥⁺⁺µŒœṪDZUḊṖj€⁶x³¤ḊḊ¤;@Ḣ;2ị$
```
[Try it online!](https://tio.run/##y0rNyan8/9/l4c5VQGTrEvVwxyII2/jY2mNdtSEPd3c/3DHfASjM9ahhpvWjxh2PGrdqHV4WpH9oK1DQ@vDyQ0sfNe4CokNbj046Ohmo0yUq9OGOroc7p2U9alrzqHFbxaHNh5aARHZ0HVpiDTLK2ghorMr/w@2R//@bAQA "Jelly – Try It Online")
Shorter but much less efficient Jelly answer.
[Answer]
# JavaScript, 484 bytes
```
i=a=>a?(l=a=>a[(L=a=>a.length-1)(a)])(a)==9?i(r(a))+0:(r=a=>a.substr(0,L(a)))(a)+(+l(a)+1)%10:"1";s=(a,b)=>b?a==b?"":s(l(a)<l(b)?s(r(a),1):r(a),r(b))+Math.abs(l(a)-l(b)):a;m=(a,b)=>!a||!((c=L(a)-L(b))<0||!c&&a<b)&&m(s(a,b),b);p=(a,b="2")=>a/2<b||!(m(a,b)||!p(a,i(b)));a=>{for(M=1+(R=a=>"0".repeat(b))(z=a-1);!p(M=i(M)););for(N=M[z]+R(z);!p(N=i(N)););for(O=1+R(x=a-2);!p(O+n[z]);O=i(O));for(P=R(x);!p(m[0]+P+O[0]);P=i(P));for(S="\n",j=0;j<x;)S+=P[i]+R(x)+N[++i]+"\n";return M+S+O+N[z]}
```
The last unnamed function returns the ASCII art.
Original code
```
function inc(a){
if (!a) return "1";
if (a[a.length-1]=="9") return inc(a.substr(0,a.length-1))+"0";
return a.substr(0,a.length-1)+(+a[a.length-1]+1)%10;
}
function sub(a,b){
if (!b) return a;
if (a==b) return "";
var v=a.substr(0,a.length-1);
if (a[a.length-1]<b[b.length-1]) v=sub(v,1);
return sub(v,b.substr(0,b.length-1))+Math.abs(a[a.length-1]-b[b.length-1])
}
function multof(a,b){
if (!a) return true;
if (a.length<b.length||a.length==b.length&&a<b) return false;
return multof(sub(a,b),b);
}
function isprime(a){
for (var i="2";a/2>i;i=inc(i)){
if (multof(a,i)) return false;
}
return true;
}
function square(a){
for (var m="1"+"0".repeat(a-1);!isprime(m);m=inc(m)){}
for (var n=m[a-1]+"0".repeat(a-1);!isprime(n);n=inc(n)){}
for (var o="1"+"0".repeat(a-2);!isprime(o+n[a-1]);o=inc(o)){}
for (var p="0".repeat(a-2);!isprime(m[0]+p+o[0]);p=inc(p)){}
var s="";
for (var i=0;i<a-2;i++) s+=p[i]+"0".repeat(a-2)+n[i+1]+"\n";
return m+"\n"+s+o+n[a-1];
}
```
Best and average time complexity: Ω(100nn) in Knuth's big-omega notation(n steps for subtracting n digit numbers, 10n substractions per divisibility check, 10n divisibility check for prime check, and Ω(1) prime checks done).
Worst time complexity: Ω(1000nn) in Knuth's big-omega notation(n steps for subtracting n digit numbers, 10n substractions per divisibility check, 10n divisibility check for prime check, and 10n prime checks done).
I suspect `n=100` takes around 10203 calculations.
Sidenote: I validated syntax using UglifyJS 3, and it golfed it way better than I did, saving 47.13% more and earning 282 bytes. However, I decided not to make that my score since I feel like it is cheating.
```
i=(s=>s?9==(l=(l=>l[(L=(l=>l.length-1))(l)]))(s)?i(r(s))+0:(r=(l=>l.substr(0,L(l))))(s)+(+l(s)+1)%10:"1"),s=((L,i)=>i?L==i?"":s(l(L)<l(i)?s(r(L),1):r(L),r(i))+Math.abs(l(L)-l(i)):L),m=((l,r)=>!l||!((c=L(l)-L(r))<0||!c&&l<r)&&m(s(l,r),r)),p=((l,s="2")=>l/2<s||!(m(l,s)||!p(l,i(s))));
```
It just deleted the last function since they are never used. It actually became worse if it was assigned and not deleted, imcluding the additional code I added.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 222 bytes
```
n=>(g=(m,d=1n)=>((Q=(n,k)=>k?Q(n*n%m,k/2n)*n**(k%2n)%m:1n)(2n,m)==2)>(m in g)?(g[m]=m):g(m+d,d),c=10n**~-n,A=g(c),B=g(A%10n*c),C=g(c+B%10n,10n),[...g(-~c,10n)+''].map((c,i)=>i?i+1<n?c.padEnd(~-n+'')+(''+B)[i]:C:A).join`
`)
```
[Try it online!](https://tio.run/##bY7BasMwDIbvfYpeQqRY8ZJQdsjmhqSs955DoMEuxk0th3Xs2FfPnN4GPQjp@/gldB1/x7v@dvNPzsFclqNaWO3BKvBkVMkYAU4KmKY4Ts0JOOPE0/RWMWacZTAlcUp8HbNQMXlUqsI9@K3jrcUGbO8H5bG24IUhg6RVWcTFR87UKgsaqYutTVYb4bA60a1IsZB6KaWF/KGfKNJ0kH6cATS5@JJrnCg/udFyHs0XG4h3YwYFpKnosHdDfahblNfg@Lw546ID38PtIm/BwhF2jPix@e@q4oV8fyXL4mmXPw "JavaScript (Node.js) – Try It Online")
Reasonable time for large \$n\$, only check if \$2^n≡2\$ as prime test
] |
[Question]
[
We define \$V(x)\$ as the list of distinct powers of \$2\$ that sum to \$x\$. For instance, \$V(35)=[32,2,1]\$.
By convention, powers are sorted here from highest to lowest. But it does not affect the logic of the challenge, nor the expected solutions.
## Task
Given a [semiprime](https://en.wikipedia.org/wiki/Semiprime) \$N\$, replace each term in \$V(N)\$ with another list of powers of \$2\$ that sum to this term, in such a way that the union of all resulting sub-lists is an exact cover of the matrix \$M\$ defined as:
$$M\_{i,j}=V(P)\_i \times V(Q)\_j$$
where \$P\$ and \$Q\$ are the prime factors of \$N\$.
This is much easier to understand with some examples.
## Example #1
For \$N=21\$, we have:
* \$V(N)=[16,4,1]\$
* \$P=7\$ and \$V(P)=[4,2,1]\$
* \$Q=3\$ and \$V(Q)=[2,1]\$
* \$M=\pmatrix{8&4&2\\4&2&1}\$
To turn \$V(N)\$ into an exact cover of \$M\$, we may split \$16\$ into \$8+4+4\$ and \$4\$ into \$2+2\$, while \$1\$ is left unchanged. So a possible output is:
$$[ [ 8, 4, 4 ], [ 2, 2 ], [ 1 ] ]$$
Another valid output is:
$$[ [ 8, 4, 2, 2 ], [ 4 ], [ 1 ] ]$$
## Example #2
For \$N=851\$, we have:
* \$V(N)=[512,256,64,16,2,1]\$
* \$P=37\$ and \$V(P)=[32,4,1]\$
* \$Q=23\$ and \$V(Q)=[16,4,2,1]\$
* \$M=\pmatrix{512&64&16\\128&16&4\\64&8&2\\32&4&1}\$
A possible output is:
$$[ [ 512 ], [ 128, 64, 64 ], [ 32, 16, 16 ], [ 8, 4, 4 ], [ 2 ], [ 1 ] ]$$
## Rules
* Because factorizing \$N\$ is not the main part of the challenge, you may alternately take \$P\$ and \$Q\$ as input.
* When several possible solutions exist, you may either return just one of them or all of them.
* You may alternately return the exponents of the powers (e.g. \$[[3,2,2],[1,1],[0]]\$ instead of \$[[8,4,4],[2,2],[1]]\$).
* The order of the sub-lists doesn't matter, nor does the order of the terms in each sub-list.
* For some semiprimes, you won't have to split any term because \$V(N)\$ already is a perfect cover of \$M\$ (see [A235040](https://oeis.org/A235040)). But you still have to return a list of (singleton) lists such as \$[[8],[4],[2],[1]]\$ for \$N=15\$.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")!
### Test cases
```
Input | Possible output
-------+-----------------------------------------------------------------------------
9 | [ [ 4, 2, 2 ], [ 1 ] ]
15 | [ [ 8 ], [ 4 ], [ 2 ], [ 1 ] ]
21 | [ [ 8, 4, 4 ], [ 2, 2 ], [ 1 ] ]
51 | [ [ 32 ], [ 16 ], [ 2 ], [ 1 ] ]
129 | [ [ 64, 32, 16, 8, 4, 2, 2 ], [ 1 ] ]
159 | [ [ 64, 32, 32 ], [ 16 ], [ 8 ], [ 4 ], [ 2 ], [ 1 ] ]
161 | [ [ 64, 32, 16, 16 ], [ 8, 8, 4, 4, 4, 2, 2 ], [ 1 ] ]
201 | [ [ 128 ], [ 64 ], [ 4, 2, 2 ], [ 1 ] ]
403 | [ [ 128, 64, 64 ], [ 32, 32, 16, 16, 16, 8, 8 ], [ 8, 4, 4 ], [ 2 ], [ 1 ] ]
851 | [ [ 512 ], [ 128, 64, 64 ], [ 32, 16, 16 ], [ 8, 4, 4 ], [ 2 ], [ 1 ] ]
2307 | [ [ 1024, 512, 512 ], [ 256 ], [ 2 ], [ 1 ] ]
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~66~~ 63 bytes
```
{(&1,-1_~^(+\*|a)?+\b)_b:b@>b:,/*/:/2#a:{|*/'(&|2\x)#'2}'x,*/x}
```
[Try it online!](https://tio.run/##XVBLb4JAEL73V0yikV1cQ/fBQneStv9DfMCBptHYxHjAAP51Oguxdj3M5XvOzGF1@joNQ@1atpBiJXe3LVsWcVfyj2VR8V3lqs/3yokkTlyiZqVruziJ2KJTRcNnkeqjRsRJ0w8X187X19vZ1dDg/ueAbF@X30ds8IpnvulfLmsNGgCZAQUKheSbEUs9JnIUBsU/OPNwDgYMBnKZebn2iA0MRhNhDWgF0oJ3hjUP@m5@6sxABREkyccc85xlxx2kogBrMCAlHSmREQcUROzYN8VNe@U4XfUoplqdUWAqFQbG@xKhnH5j36jiVRkgix9i079vDL8 "K (ngn/k) – Try It Online")
accepts (P;Q) instead of N
algorithm:
* compute A as the partial sums of V(P\*Q)
* multiply each V(P) with each V(Q), sort the products in descending order (let's call that R), and compute their partial sums B
* find the positions of those elements in B that also occur in A; cut R right after those positions
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
BṚT’2*
Ç€×þ/FṢŒṖ§⁼Ç}ɗƇPḢ
```
A monadic link accepting a list of two integers `[P, Q]` which yields one possible list of lists as described in the question.
**[Try it online!](https://tio.run/##AUcAuP9qZWxsef//QuG5mlTigJkyKgrDh@KCrMOXw74vRuG5osWS4bmWwqfigbzDh33Jl8aHUOG4ov/Dh8WS4bmY//9bMTMsIDMxXQ "Jelly – Try It Online")** (footer prints a string representation to show the list as it really is)
Or see the [test-suite](https://tio.run/##y0rNyan8/9/p4c5ZIY8aZhppcR1uf9S05vD0w/v03R7uXHR00sOd0w4tf9S453B77cnpx9oDHu5Y9P9wW9rhdqCWUJD0jIc712Y9apijoGun8Khhrmbk//@WOgqGpjoKRoY6CqZAbGgEFgARZkCukQGQMDEw1lGwAMkaGRuYAwA "Jelly – Try It Online") (taking a list of N and reordering results to be like those in the question)
### How?
We may always slice up the elements of \$M\$ from lowest up, greedily (either there is a \$1\$ in \$M\$ or we had an input of \$4\$, when \$M=[[4]]\$) in order to find a solution.
Note: the code collects all (one!) such solutions in a list and then takes the head (only) result - i.e. the final head is necessary as the partitions are not of all possible orderings.
```
BṚT’2* - Link 1, powers of 2 that sum to N: integer, N e.g. 105
B - binary [1,1,0,1,0,0,1]
Ṛ - reverse [1,0,0,1,0,1,1]
T - truthy indices [1,4,6,7]
’ - decrement [0,3,5,6]
2 - literal two 2
* - exponentiate [1,8,32,64]
Ç€×þ/FṢŒṖ§⁼Ç}ɗƇPḢ - Main Link: list of two integers, [P,Q]
Ç€ - call last Link (1) as a monad for €ach
/ - reduce with:
þ - table with:
× - multiplication
F - flatten
Ṣ - sort
ŒṖ - all partitions
Ƈ - filter keep if:
ɗ - last three links as a dyad:
§ - sum each
} - use right...
P - ...value: product (i.e. P×Q)
Ç - ...do: call last Link (1) as a monad
⁼ - equal? (non-vectorising so "all equal?")
Ḣ - head
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~261~~ ~~233~~ ~~232~~ 231 bytes
```
g=lambda n,r=[],i=1:n and g(n/2,[i]*(n&1)+r,i*2)or r
def f(p,q):
V=[[v]for v in g(p*q)];i=j=0
for m in sorted(-a*b for a in g(p)for b in g(q)):
v=V[i]
while-m<v[j]:v[j:j+1]=[v[j]/2]*2
i,j=[i+1,i,0,j+1][j+1<len(v)::2]
return V
```
[Try it online!](https://tio.run/##NZBBcoMwDEXXcAqtGgzKJDZJmNK4x2Dj8YIMkJgBQ1xKp6enMqQb6f0v2bI1/k6PwYplucuu7G9VCRadVBqN5LmF0lZwj@xBoDI6juwbZ4lDEws2OHBhVTfQRCM@WR5CIZWadUOFGYylY2P8ZPrDyFYeQ/B@7/2vwU11Fe3L@Laa5auZeXHbxJPRhcEsC5oaBj8P09X7/jqrVucU8jbhWiovD0LHIgwMtlKZhKPBI/qqonDtahvNLM@FDsHV07ezUCx@Cj3Yz1FRiilDoHT2KdsUz/7d05rPr64Mxea/QKUIl0wTcKKUexKeVo8gu7xrTf8YnbET0DZwJ3e4rovoc4fb6pY/ "Python 2 – Try It Online")
1 byte from [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king); and another 1 byte due to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
Takes as input `p,q`. Pursues the greedy algorithm.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes
```
Œṗl2ĊƑ$Ƈ
PÇIP$ƇṪÇ€Œpµ³ÇIP$ƇṪƊ€ŒpZPṢ⁼FṢ$µƇ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7p@cYHek6NlHlWDtXwOF2zwAg4@HOVYfbHzWtOTqp4NDWQ5sRose6IKJRAQ93LnrUuMcNSKkc2nqs/f/hdpBZM/7/jzbWMY8FAA "Jelly – Try It Online")
Should probably be much shorter (some parts feel very repetitive; especially `ÇIP$Ƈ`, but I don't know how to golf it). Explanation to come after further golfing. Returns all possible solutions in case multiple exist and takes input as \$[P, Q]\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes
```
BṚT’2*
PÇŒṗæḟ2⁼ƊƇ€ŒpẎṢ⁼Ṣ}ʋƇÇ€×þ/ẎƊ
```
[Try it online!](https://tio.run/##y0rNyan8/9/p4c5ZIY8aZhppcQUcbj866eHO6YeXPdwx3@hR455jXcfaHzWtOTqp4OGuvoc7FwGFgGTtqe5j7YdBEoenH96nD5Q61vX/cFva4XZ3oFjWo8Z9h7Yd2vb/v5EhAA "Jelly – Try It Online")
Input format: `[P, Q]` (the TIO link above doesn't accept this, but a single number instead, to aid with the test cases).
Output format: List of all solutions (shown as grid representation of 3D list over TIO).
Speed: Turtle.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 27 bytes
Inspired by [Jonathan Allan's crushing of my Jelly solution](https://codegolf.stackexchange.com/a/170102/59487). Takes \$N\$ as input.
```
L^2x1jb2;hfqyQsMT./S*M*FyMP
```
[Try it here!](https://pyth.herokuapp.com/?code=L%5E2x1jb2%3BhfqyQsMT.%2FS%2aM%2aFyMP&input=21&debug=0)
[Answer]
# Haskell, ~~281~~ 195 bytes
```
import Data.List
r=reverse.sort
n#0=[]
n#x=[id,(n:)]!!mod x 2$(n*2)#div x 2
m!0=[]
m!x=m!!0:tail m!(x-m!!0)
m%[]=[]
m%n=m!head n:drop(length$m!head n)m%tail n
p&q=r[x*y|x<-1#p,y<-1#q]%r(1#(p*q))
```
] |
[Question]
[
Implement this [recurrence relation](https://en.m.wikipedia.org/wiki/Recurrence_relation) as a function or program that inputs and outputs a non-negative integer:
* F(0) = 0
* F(N) = the smallest integer greater than F(N-1) such that the sum and/or product of its base-10 digits is N
N is your program's input and F(N) its output.
To be clear, the sum of the digits in a number like 913 is 9+1+3=13. The product is 9×1×3=27. For single-digit numbers, the sum and product is the same number. Numbers that contain a 0 of course have product 0.
The results through F(70) are:
```
N F(N)
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 19
11 29
12 34
13 49
14 59
15 69
16 79
17 89
18 92
19 199
20 225
21 317
22 499
23 599
24 614
25 799
26 899
27 913
28 1147
29 2999
30 3125
31 4999
32 5999
33 6999
34 7999
35 8999
36 9114
37 19999
38 29999
39 39999
40 41125
41 59999
42 61117
43 79999
44 89999
45 91115
46 199999
47 299999
48 311128
49 499999
50 511125
51 699999
52 799999
53 899999
54 911116
55 1999999
56 2111147
57 3999999
58 4999999
59 5999999
60 6111125
61 7999999
62 8999999
63 9111117
64 11111188
65 29999999
66 39999999
67 49999999
68 59999999
69 69999999
70 71111125
```
The shortest code in bytes wins. Kudos if you can show that your code takes advantage of some efficiency.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~20~~ 12 bytes
Saved 8 bytes thanks to *Osable*!
```
µNSDOsP‚¾>å½
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wrVOU0RPc1DigJrCvj7DpcK9&input=MjE)
[Answer]
## Mathematica, 71 bytes, 68 characters
```
±0=0;±n_:=(For[x=±(n-1),FreeQ[{+##,1##}&@@IntegerDigits@x,n],x++];x)
```
For just 4 more bytes, here's a version that stores the values of `±n`:
```
±0=0;±n_:=(For[x=±(n-1),FreeQ[{+##,1##}&@@IntegerDigits@x,n],x++];±n=x)
```
With the latter version, before you evaluate `±n`, `PlusMinus` will have two down values:
```
In[2]:= DownValues@PlusMinus
Out[2]= {HoldPattern[±0] :> 0, HoldPattern[±n_] :> (For[x=±(n-1),FreeQ[{+##,1##}&@@IntegerDigits@x,n],x++];±n=x)}
```
Now if we evaluate `±20`:
```
In[3]:= ±20
In[3]:= 225
In[4]:= DownValues@PlusMinus
Out[4]= {HoldPattern[±0] :> 0, HoldPattern[±1] :> 1, HoldPattern[±2] :> 2, HoldPattern[±3] :> 3, HoldPattern[±4] :> 4, HoldPattern[±5] :> 5, HoldPattern[±6] :> 6, HoldPattern[±7] :> 7, HoldPattern[±8] :> 8, HoldPattern[±9] :> 9, HoldPattern[±10] :> 19, HoldPattern[±11] :> 29, HoldPattern[±12] :> 34, HoldPattern[±13] :> 49, HoldPattern[±14] :> 59, HoldPattern[±15] :> 69, HoldPattern[±16] :> 79, HoldPattern[±17] :> 89, HoldPattern[±18] :> 92, HoldPattern[±19] :> 199, HoldPattern[±20] :> 225, HoldPattern[±n_] :> (For[x=±(n-1),FreeQ[{+##,1##}&@@IntegerDigits@x,n],x++];±n=x)}
```
This dramatically speeds up future calculations since Mathematica will no longer calculate the values between `0` and `20` recursively. The time saved is more dramatic as `n` increases:
```
In[5]:= Quit[]
In[1]:= ±0=0;±n_:=(For[x=±(n-1),FreeQ[{+##,1##}&@@IntegerDigits@x,n],x++];±n=x)
In[2]:= AbsoluteTiming[±60]
Out[2]= {23.0563, 6111125}
In[3]:= AbsoluteTiming[±60]
Out[3]= {9.89694*10^-6, 6111125}
```
[Answer]
# C#, ~~155~~ ~~159~~ 135 bytes
```
a=n=>{if(n<1)return 0;int i=n,s=0,p=1,N=a(n-1);for(;;){s=0;p=1;foreach(var c in++i+""){s+=c-48;p*=c-48;}if(i>N&(s==n|p==n))return i;}};
```
~~Super inefficient, takes a long time for just `N>=14`. Gonna try to get a more efficient, but longer solution.~~
Okay, much better now, but 4 bytes longer. Oh well, I can do `N<=50` pretty quickly now. Thank you @milk for saving 24 bytes!
[Answer]
# Pyth - ~~18~~ 17 bytes
*One byte saved thanks to @Jakube!*
Uses reduce to do the recursive thing.
```
uf}HsM*FBjT;hGSQZ
```
[Test Suite](http://pyth.herokuapp.com/?code=uf%7DHsM%2aFBjT%3BhGSQZ&input=1&test_suite=1&test_suite_input=0%0A1%0A5%0A9%0A10%0A20%0A37&debug=0).
[Answer]
# R, ~~124~~ 112 bytes
```
f=function(N){y=x=`if`(N-1,f(N-1),0);while(N!=prod(y)&N!=sum(y)){x=x+1;y=as.double(el(strsplit(c(x,""),"")))};x}
```
Fails at N=45 because R insists on writing 10.000 as 1e+05, which isnt appreciated by `as.numeric()`, this is fixable by using `as.integer()` at the cost of 12 bytes:
```
f=function(N){y=x=`if`(N-1,f(N-1),0);while(N!=prod(y)&N!=sum(y)){x=x+1;y=as.double(el(strsplit(c(as.integer(x),""),"")))};x}
```
As a statistical programming language R has annoyingly wordy ways of splitting numbers into a vector of digits. Especially because everything has to be converted back from strings to numerical values explicitly.
12 bytes saved thanks to billywob.
[Answer]
# JavaScript (ES6) ~~109~~ ~~107~~ ~~105~~ ~~91~~ 89 Bytes
```
f=n=>n&&eval(`for(i=f(n-1);++i,${x="[...i+''].reduce((r,v)=>"}+r+ +v)-n&&${x}r*v)-n;);i`)
console.log(f.toString().length + 2);
console.log(f(25));
console.log(f(13));
console.log(f(8));
```
[Answer]
# JavaScript (ES6), 84 ~~86~~
Edit: 2 bytes saved thx @Arnauld
```
f=n=>eval("for(v=n&&f(n-1),p=s=n+1;s&&p-1;)[...++v+''].map(d=>(p/=d,s-=d),p=s=n);v")
```
**Test** Note above 50 it will use too much of your CPU, click 'Hide results' to stop before it's too late
```
f=n=>eval("for(v=n&&f(n-1),p=s=n+1;s&&p-1;)[...++v+''].map(d=>(p/=d,s-=d),p=s=n);v")
out=x=>O.textContent=x+'\n'+O.textContent
i=0
step=_=>out(i+' '+f(i),++i,setTimeout(step,i*10))
step()
```
```
<pre id=O></pre>
```
[Answer]
# Mathematica, 67 bytes
```
a@0=0;a@b_:=NestWhile[#+1&,a[b-1]+1,+##!=b&&1##!=b&@*IntegerDigits]
```
Function, named `a`. Takes a number as input and returns a number as output. Inspired by the previous Mathematica solution, but uses a different looping mechanism.
[Answer]
# C, 240 bytes
```
int f(char n){int q[19],i=19,r=n%9,j=9,*p=q,c=n/9;while(i)q[--i]=0;if(c){if(!r){r=9;c--;}q[9]=c;if(!(n%r)){n/=r;while((j-1)*(n-1)*c){if(n%j)j--;else{c--;q[9+j]++;n/=j;}}q[10]=c;if(1==n)p+=9;}while(++i<10){while(p[i]--)r=r*10+i;}}return(r);}
```
Trying to exploit some math properties of the sequence.
[Answer]
## PowerShell v3+, 114 bytes
```
param($n)$i=,0;$l=1;1..$n|%{for(;$_-notin((($b=[char[]]"$l")-join'+'|iex)),(($b-join'*'|iex))){$l++}$i+=$l};$i[$n]
```
Iterative solution, with no easy way to turn a number into the sum/product of its digits, so it's quite a bit longer than the JavaScript answers.
Takes input `$n`, sets `$i` to an array with just `0` (this is the collection of `F()`, and sets `$l` equal to `1` (this is the latest `F`). We then loop upward from `1` to `$n`, each iteration executing a `for` loop.
The `for` loop's conditional takes the `$l`atest number, in a string `"$l"`, then casts that as a `char`-array, and stores that array into temp variable `$b`. We then `-join` those digits together with `+` and pipe that to `iex` (short for `Invoke-Expression` and similar to `eval`). Additionally, we also do similar with `*`. Those two numbers are encapsulated in parens and treated as the array argument for the `-notin` operator against the current number `$_` of the outer loop (i.e., the `for` loop runs so long as either `+` and `*` are different than `$_`). The body of the `for` loop just increments `$l++`.
Once we're out of that inner `for` loop, we add our `$l` on as a new element of `$i`. Once we've fully completed the range loop, we just place `$i[$n]` on the pipeline, and output is implicit.
NB -- Gets pretty slow to execute above about `20`, simply because of the loop structure. For example, `N=40` takes about two minutes on my machine, and I've not even bothered testing `N>50`.
[Answer]
## Pyke, 17 bytes
```
t.fY'Bs]~ohR{Io(e
```
[Try it here!](http://pyke.catbus.co.uk/?code=t.fY%27Bs%5D%7EohR%7BIo%28e&input=12)
### Or 13 bytes noncompetitive
`first_n` now puts the amount of items already found plus one in `i` if used.
```
Q.fY'Bs]iR{)e
```
[Try it here!](http://pyke.catbus.co.uk/?code=Q.fY%27Bs%5DiR%7B%29e&input=12)
```
Q.f ) - first_n(input, start=1)
Y - digits(^)
'Bs] - [sum(^), product(^)]
R} - V in ^
i - len(results)+1
e - ^[-1]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
```
f=lambda n,k=0,r=0:-(k>n)or-~f(n,k+(k in[eval(c.join(`r`))for c in'+*']),r+1)
```
[Try it online!](https://tio.run/nexus/python2#Fc3BCsIwEATQu1@xl5KsSaTWixTSHxGhsWkkpm5kEY/@elzn@AZmWvJbeN5iALLF95Z9PzpdJsLK7pu0qNEFMl3WT9j0cnjUTHrmGTFVhkUaZfbqipbNEdvfSAw40H3VwxnHHUhenOkNqhsiuAm6U1TQgYyDPCC2Hw "Python 2 – TIO Nexus")
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 49 bytes
```
f\.{0\0@(:>@(| =#1sum#0)=#1prod#0)(dp +1f -#0 1)N
```
Pattern matching ftw! Usage:
```
f\.{0\0@(:>@(| =#1sum#0)=#1prod#0)(dp +1f -#0 1)N}; f 10
```
More readable:
```
f\.{
0\0
@(
find @(or = #1 sum #0) = #1 prod #0
) (dp + 1 (f -#0 1)) N
}
```
This is basically just a word-for-word implementation of the specs.
[Answer]
# BASH, 107 bytes
## with fold + paste + bc
```
for ((;n<=$1;z++)){
p(){ fold -1<<<$z|paste -sd$1|bc;}
[ `p +` = $n -o `p \*` = $n ]&&((z-->n++))
}
echo $z
```
[Answer]
# Befunge, 101 bytes
```
&20p>:000pv
>\1+^vp011<
| >.@>:55+%:00g+00p10g*v>10g-*
::\$_^#!:/+55p01*!`"~":<^\-g00
< |!-g02
+1< v\
```
[Try it online!](http://befunge.tryitonline.net/#code=JjIwcD46MDAwcHYKPlwxK152cDAxMTwKfCA-LkA-OjU1KyU6MDBnKzAwcDEwZyp2PjEwZy0qCjo6XCRfXiMhOi8rNTVwMDEqIWAifiI6PF5cLWcwMAo8IHwhLWcwMgorMTwgdlw&input=NDA) But note that it's going to get really slow once you get into the high forties. If you want to test the full range, you really need to be using a Befunge compiler.
**Explanation**
```
&20p Read N and save for later.
> Start of main loop; current target and test number on stack, initially 0.
: Duplicate the test number so we can manipulate it.
000p Initialise the sum to 0.
110p Initialise the product to 1.
> Start of inner loop.
:55+%: Modulo 10 of the test number to get the first digit.
00g+00p Add to the sum.
10g* Multiply by the product.
:"~"`!* If greater than 126, set to 0 to prevent overflows - it'll never match.
10p Update the product variable.
55+/ Divide the test number by 10 to get the next digit.
:!_ If not zero, repeat the inner loop
$ Drop the zero left over from the loop.
\::00g-\10g- Compare the sum and product with the current target.
*| Multiply the two diffs and branch; up if no match, down if either match.
\1+^ On no match, we increment the test number and repeat the main loop.
:>20g-!| With a match, we compare the current target with the saved N.
1+\v If that doesn't match, increment the current target and restart main loop.
\>.@ If it does match, we've got our result; output it and exit.
```
[Answer]
# [PHP](https://php.net/), 110 bytes
```
for(;$c<=$a=$argn;$c=count($r))array_product($s=str_split($n++))!=$c&&array_sum($s)!=$c?:$r[]=~-$n;echo$r[$a];
```
[Try it online!](https://tio.run/##JcqxCsIwFEDRvX9heZSGUhBH09BBOrjo4iYlhBibguaFl2Zw6V87x1DHe7je@tT13vrCECFJMh5pmd1Ur4O8XG/n08B4AYomJ8rDvuTpiVRz0J0AJTbPITRGt9RAjCki9ZGe8BF1liDCQjL415zDNQ1jOwG6qv5biO@8bNQfge6jWFtw3GiLuUCNPKWvw1Yrbc0P "PHP – Try It Online")
] |
[Question]
[
Last week, [we worked to create the shortest 1-D string using the top 10,000 words in the English language](https://codegolf.stackexchange.com/questions/87311/compounding-english). Now, lets try the same challenge in 2D!
What you need to do is to take all of the above words, and put them in a rectangle as small as possible, allowing for overlaps. For example, if your words were `["ape","pen","ab","be","pa"]`, then a possible rectangle would be:
```
.b..
apen
```
The above rectangle would give a score of 5.
Rules:
* Overlapping multiple letters in a word is allowed
* Words can go in any of the 8 directions
* Words cannot wrap around
* You can use any character for the empty locations
You need to create a word search that contains these [top 10,000 words in English](https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt) (according to Google). **Your score is equal to the number of characters in your word search** (excluding unused characters). If there is a tie, or if a submission is proven to be optimal, then the submission that is first posted wins.
[Answer]
# Rust, ~~31430~~ 30081 used characters
This is a greedy algorithm of sorts: we start with an empty grid, and repeatedly add the word that can be added with the fewest new letters, with ties broken by preferring longer words. To make this run quickly, we maintain a priority queue of candidate word placements (implemented as a vector of vectors of deques, with a vector for each number of new letters, containing a deque for each word length). For each newly added letter, we enqueue all candidate placements that run through that letter.
Compile and run with `rustc -O wordsearch.rs; ./wordsearch < google-10000-english.txt`. On my laptop, this runs in 70 seconds, using 531 MiB RAM.
[The output](https://glot.io/snippets/ehhcsqff88/raw) fits in a rectangle with 248 columns and 253 rows.
[](https://i.stack.imgur.com/J5vhZ.png)
### Code
```
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::prelude::*;
use std::iter::once;
use std::vec::Vec;
type Coord = i16;
type Pos = (Coord, Coord);
type Dir = u8;
type Word = u16;
struct Placement { word: Word, dir: Dir, pos: Pos }
static DIRS: [Pos; 8] =
[(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)];
fn fit(grid: &HashMap<Pos, u8>, (x, y): Pos, d: Dir, word: &String) -> Option<usize> {
let (dx, dy) = DIRS[d as usize];
let mut n = 0;
for (i, c) in word.bytes().enumerate() {
if let Some(c1) = grid.get(&(x + (i as Coord)*dx, y + (i as Coord)*dy)) {
if c != *c1 {
return None;
}
} else {
n += 1;
}
}
return Some(n)
}
struct PlacementQueue { queue: Vec<Vec<VecDeque<Placement>>>, extra: usize }
impl PlacementQueue {
fn new() -> PlacementQueue {
return PlacementQueue { queue: Vec::new(), extra: std::usize::MAX }
}
fn enqueue(self: &mut PlacementQueue, extra: usize, total: usize, placement: Placement) {
while self.queue.len() <= extra {
self.queue.push(Vec::new());
}
while self.queue[extra].len() <= total {
self.queue[extra].push(VecDeque::new());
}
self.queue[extra][total].push_back(placement);
if self.extra > extra {
self.extra = extra;
}
}
fn dequeue(self: &mut PlacementQueue) -> Option<Placement> {
while self.extra < self.queue.len() {
let mut subqueue = &mut self.queue[self.extra];
while !subqueue.is_empty() {
let total = subqueue.len() - 1;
if let Some(placement) = subqueue[total].pop_front() {
return Some(placement);
}
subqueue.pop();
}
self.extra += 1;
}
return None
}
}
fn main() {
let stdin = std::io::stdin();
let all_words: Vec<String> =
stdin.lock().lines().map(|l| l.unwrap()).collect();
let words: Vec<&String> = {
let subwords: HashSet<&str> =
all_words.iter().flat_map(|word| {
(0..word.len() - 1).flat_map(move |i| {
(i + 1..word.len() - (i == 0) as usize).map(move |j| {
&word[i..j]
})
})
}).collect();
all_words.iter().filter(|word| !subwords.contains(&word[..])).collect()
};
let letters: Vec<Vec<(usize, usize)>> =
(0..128).map(|c| {
words.iter().enumerate().flat_map(|(w, word)| {
word.bytes().enumerate().filter(|&(_, c1)| c == c1).map(move |(i, _)| (w, i))
}).collect()
}).collect();
let mut used = vec![false; words.len()];
let mut remaining = words.len();
let mut grids: Vec<HashMap<Pos, u8>> = Vec::new();
while remaining != 0 {
let mut grid: HashMap<Pos, u8> = HashMap::new();
let mut queue = PlacementQueue::new();
for (w, word) in words.iter().enumerate() {
if used[w] {
continue;
}
queue.enqueue(0, word.len(), Placement {
pos: (0, 0),
dir: 0,
word: w as Word
});
}
while let Some(placement) = queue.dequeue() {
if used[placement.word as usize] {
continue;
}
let word = words[placement.word as usize];
if let None = fit(&grid, placement.pos, placement.dir, word) {
continue;
}
let (x, y) = placement.pos;
let (dx, dy) = DIRS[placement.dir as usize];
let new_letters: Vec<(usize, u8)> = word.bytes().enumerate().filter(|&(i, _)| {
!grid.contains_key(&(x + (i as Coord)*dx, y + (i as Coord)*dy))
}).collect();
for (i, c) in word.bytes().enumerate() {
grid.insert((x + (i as Coord)*dx, y + (i as Coord)*dy), c);
}
used[placement.word as usize] = true;
remaining -= 1;
for (i, c) in new_letters {
for &(w1, j) in &letters[c as usize] {
if used[w1] {
continue;
}
let word1 = words[w1];
for (d1, &(dx1, dy1)) in DIRS.iter().enumerate() {
let pos1 = (
x + (i as Coord)*dx - (j as Coord)*dx1,
y + (i as Coord) - (j as Coord)*dy1);
if let Some(extra1) = fit(&grid, pos1, d1 as Dir, word1) {
queue.enqueue(extra1, word1.len(), Placement {
pos: pos1,
dir: d1 as Dir,
word: w1 as Word
});
}
}
}
}
}
grids.push(grid);
}
let width = grids.iter().map(|grid| {
grid.iter().map(|(&(x, _), _)| x).max().unwrap() -
grid.iter().map(|(&(x, _), _)| x).min().unwrap() + 1
}).max().unwrap();
print!(
"{}",
grids.iter().flat_map(|grid| {
let x0 = grid.iter().map(|(&(x, _), _)| x).min().unwrap();
let y0 = grid.iter().map(|(&(_, y), _)| y).min().unwrap();
let y1 = grid.iter().map(|(&(_, y), _)| y).max().unwrap();
(y0..y1 + 1).flat_map(move |y| {
(x0..x0 + width).map(move |x| {
*grid.get(&(x, y)).unwrap_or(&('.' as u8)) as char
}).chain(once('\n').take(1))
})
}).collect::<String>()
);
}
```
[Answer]
# C++, 27243 character grid (248x219, 50.2% filled)
(Posting this as a new answer because I'd like to keep the 1D bound I originally posted as a reference)
This ~~blatantly rips off~~ is heavily inspired by [@AndersKaseorg's answer](https://codegolf.stackexchange.com/a/89778/8927) in its main structure, but has a couple of tweaks. First, I use my original program to merge strings until the best available overlap is just 3 characters. Then I use the method AndersKaseorg describes to progressively fill a 2D grid using these generated strings. The constraints are a little different too: it still tries to add the fewest characters each time, but ties are broken by favouring square grids first, then small grids, and finally by adding the longest word.
The behaviour it displays is to alternate between periods of filling in space and rapidly expanding the grid (unfortunately it ran out of words just after a rapid expansion stage, so there's a lot of blank space around the edges). I suspect with some tweaking of the cost function it could be made to get better than 50% space filling.
There are 2 executables here (to avoid the need to re-run the whole process when iteratively improving the algorithm). The output of one can be piped directly into the other:
```
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
std::size_t calcOverlap(const std::string &a, const std::string &b, std::size_t limit, std::size_t minimal) {
std::size_t la = a.size();
for(std::size_t p = std::min(std::min(la, b.size()), limit + 1); -- p > minimal; ) {
if(a.compare(la - p, p, b, 0, p) == 0) {
return p;
}
}
return 0;
}
bool isSameReversed(const std::string &a, const std::string &b) {
std::size_t l = a.size();
if(b.size() != l) {
return false;
}
for(std::size_t i = 0; i < l; ++ i) {
if(a[i] != b[l-i-1]) {
return false;
}
}
return true;
}
int main(int argc, const char *const *argv) {
// Usage: prog [<stop_threshold>]
std::size_t stopThreshold = 3;
if(argc >= 2) {
char *check;
long v = std::strtol(argv[1], &check, 10);
if(check == argv[1] || v < 0) {
std::cerr
<< "Invalid stop threshold. Should be an integer >= 0"
<< std::endl;
return 1;
}
stopThreshold = v;
}
std::vector<std::string> words;
// Load all words from input and their reverses (words can be backwards now)
while(true) {
std::string word;
std::getline(std::cin, word);
if(word.empty()) {
break;
}
words.push_back(word);
std::reverse(word.begin(), word.end());
words.push_back(std::move(word));
}
std::cerr
<< "Input word count: " << words.size() << std::endl;
// Remove all fully subsumed words
for(auto p = words.begin(); p != words.end(); ) {
bool subsumed = false;
for(auto i = words.begin(); i != words.end(); ++ i) {
if(i == p) {
continue;
}
if(i->find(*p) != std::string::npos) {
subsumed = true;
break;
}
}
if(subsumed) {
p = words.erase(p);
} else {
++ p;
}
}
std::cerr
<< "After subsuming checks: " << words.size()
<< std::endl;
// Sort words longest-to-shortest (not necessary but doesn't hurt. Makes finding maxlen a tiny bit easier)
std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
return a.size() > b.size();
});
std::size_t maxlen = words.front().size();
// Repeatedly combine most-compatible words until we reach the threshold
std::size_t bestPossible = maxlen - 1;
while(words.size() > 2) {
auto bestA = words.begin();
auto bestB = -- words.end();
std::size_t bestOverlap = 0;
for(auto p = ++ words.begin(), e = words.end(); p != e; ++ p) {
if(p->size() - 1 <= bestOverlap) {
continue;
}
for(auto q = words.begin(); q != p; ++ q) {
std::size_t overlap = calcOverlap(*p, *q, bestPossible, bestOverlap);
if(overlap > bestOverlap && !isSameReversed(*p, *q)) {
bestA = p;
bestB = q;
bestOverlap = overlap;
}
overlap = calcOverlap(*q, *p, bestPossible, bestOverlap);
if(overlap > bestOverlap && !isSameReversed(*p, *q)) {
bestA = q;
bestB = p;
bestOverlap = overlap;
}
}
if(bestOverlap == bestPossible) {
break;
}
}
if(bestOverlap <= stopThreshold) {
break;
}
std::string newStr = std::move(*bestA);
newStr.append(*bestB, bestOverlap, std::string::npos);
if(bestA == -- words.end()) {
words.pop_back();
*bestB = std::move(words.back());
words.pop_back();
} else {
*bestB = std::move(words.back());
words.pop_back();
*bestA = std::move(words.back());
words.pop_back();
}
// Remove any words which are now in the result (forward or reverse)
// (would not be necessary if we didn't have the reversed forms too)
std::string newRev = newStr;
std::reverse(newRev.begin(), newRev.end());
for(auto p = words.begin(); p != words.end(); ) {
if(newStr.find(*p) != std::string::npos || newRev.find(*p) != std::string::npos) {
std::cerr << "Now subsumes: " << *p << std::endl;
p = words.erase(p);
} else {
++ p;
}
}
std::cerr
<< "Words remaining: " << (words.size() + 1)
<< " Latest combination: (" << bestOverlap << ") " << newStr
<< std::endl;
words.push_back(std::move(newStr));
words.push_back(std::move(newRev));
bestPossible = bestOverlap; // Merging existing words will never make longer merges possible
}
std::cerr
<< "After merging: " << words.size()
<< std::endl;
// Remove all fully subsumed words (i.e. reversed words)
for(auto p = words.begin(); p != words.end(); ) {
bool subsumed = false;
std::string rev = *p;
std::reverse(rev.begin(), rev.end());
for(auto i = words.begin(); i != words.end(); ++ i) {
if(i == p) {
continue;
}
if(i->find(*p) != std::string::npos || i->find(rev) != std::string::npos) {
subsumed = true;
break;
}
}
if(subsumed) {
p = words.erase(p);
} else {
++ p;
}
}
std::cerr
<< "After subsuming: " << words.size()
<< std::endl;
// Sort words longest-to-shortest for display
std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
return a.size() > b.size();
});
std::size_t len = 0;
for(const auto &word : words) {
std::cout
<< word
<< std::endl;
len += word.size();
}
std::cerr
<< "Total size: " << len
<< std::endl;
return 0;
}
```
```
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <limits>
class vec2 {
public:
int x;
int y;
vec2(void) : x(0), y(0) {};
vec2(int x, int y) : x(x), y(y) {}
bool operator ==(const vec2 &b) const {
return x == b.x && y == b.y;
}
vec2 &operator +=(const vec2 &b) {
x += b.x;
y += b.y;
return *this;
}
vec2 &operator -=(const vec2 &b) {
x -= b.x;
y -= b.y;
return *this;
}
vec2 operator +(const vec2 b) const {
return vec2(x + b.x, y + b.y);
}
vec2 operator *(const int b) const {
return vec2(x * b, y * b);
}
};
class box2 {
public:
vec2 tl;
vec2 br;
box2(void) : tl(), br() {};
box2(vec2 a, vec2 b)
: tl(std::min(a.x, b.x), std::min(a.y, b.y))
, br(std::max(a.x, b.x) + 1, std::max(a.y, b.y) + 1)
{}
void grow(const box2 &b) {
if(b.tl.x < tl.x) {
tl.x = b.tl.x;
}
if(b.br.x > br.x) {
br.x = b.br.x;
}
if(b.tl.y < tl.y) {
tl.y = b.tl.y;
}
if(b.br.y > br.y) {
br.y = b.br.y;
}
}
bool intersects(const box2 &b) const {
return (
((tl.x >= b.br.x) != (br.x > b.tl.x)) &&
((tl.y >= b.br.y) != (br.y > b.tl.y))
);
}
box2 &operator +=(const vec2 b) {
tl += b;
br += b;
return *this;
}
int width(void) const {
return br.x - tl.x;
}
int height(void) const {
return br.y - tl.y;
}
int maxdim(void) const {
return std::max(width(), height());
}
};
template <> struct std::hash<vec2> {
std::size_t operator ()(const vec2 &o) const {
return std::hash<int>()(o.x) + std::hash<int>()(o.y) * 997;
}
};
template <class A,class B> struct std::hash<std::pair<A,B>> {
std::size_t operator ()(const std::pair<A,B> &o) const {
return std::hash<A>()(o.first) + std::hash<B>()(o.second) * 31;
}
};
class word_placement {
public:
vec2 start;
vec2 dir;
box2 bounds;
const std::string *word;
word_placement(vec2 start, vec2 dir, const std::string *word)
: start(start)
, dir(dir)
, bounds(start, start + dir * (word->size() - 1))
, word(word)
{}
word_placement(vec2 start, const word_placement ©)
: start(copy.start + start)
, dir(copy.dir)
, bounds(copy.bounds)
, word(copy.word)
{
bounds += start;
}
word_placement(const word_placement ©)
: start(copy.start)
, dir(copy.dir)
, bounds(copy.bounds)
, word(copy.word)
{}
};
class word_placement_links {
public:
std::unordered_set<word_placement*> placements;
std::unordered_set<std::pair<char,word_placement*>> relativePlacements;
};
class grid {
public:
std::vector<std::string> wordCache; // Just a block of memory for our pointers to reference
std::unordered_map<vec2,char> state;
std::unordered_set<word_placement*> placements;
std::unordered_map<const std::string*,word_placement_links> wordPlacements;
std::unordered_map<char,std::unordered_set<word_placement*>> relativeWordPlacements;
box2 bound;
grid(const std::vector<std::string> &words) {
wordCache = words;
std::vector<vec2> directions;
directions.emplace_back(+1, 0);
directions.emplace_back(+1, +1);
directions.emplace_back( 0, +1);
directions.emplace_back(-1, +1);
directions.emplace_back(-1, 0);
directions.emplace_back(-1, -1);
directions.emplace_back( 0, -1);
directions.emplace_back(+1, -1);
wordPlacements.reserve(wordCache.size());
placements.reserve(wordCache.size());
relativeWordPlacements.reserve(64);
std::size_t total = 0;
for(const std::string &word : wordCache) {
word_placement_links &p = wordPlacements[&word];
p.placements.reserve(8);
auto &rp = p.relativePlacements;
std::size_t l = word.size();
rp.reserve(l * directions.size());
for(int i = 0; i < l; ++ i) {
for(const vec2 &d : directions) {
word_placement *rwp = new word_placement(d * -i, d, &word);
rp.emplace(word[i], rwp);
relativeWordPlacements[word[i]].insert(rwp);
}
}
total += l;
}
state.reserve(total);
}
const std::string *find_word(const std::string &word) const {
for(const std::string &w : wordCache) {
if(w == word) {
return &w;
}
}
throw std::string("Failed to find word in cache");
}
void remove_word(const std::string *word) {
const word_placement_links &links = wordPlacements[word];
for(word_placement *p : links.placements) {
placements.erase(p);
delete p;
}
for(auto &p : links.relativePlacements) {
relativeWordPlacements[p.first].erase(p.second);
delete p.second;
}
wordPlacements.erase(word);
}
void remove_placement(word_placement *placement) {
wordPlacements[placement->word].placements.erase(placement);
placements.erase(placement);
delete placement;
}
bool check_placement(const word_placement &placement) const {
vec2 p = placement.start;
for(const char c : *placement.word) {
auto i = state.find(p);
if(i != state.end() && i->second != c) {
return false;
}
p += placement.dir;
}
return true;
}
int check_new(const word_placement &placement) const {
int n = 0;
vec2 p = placement.start;
for(const char c : *placement.word) {
n += !state.count(p);
p += placement.dir;
}
return n;
}
void check_placements(const box2 &b) {
for(auto i = placements.begin(); i != placements.end(); ) {
if(!b.intersects((*i)->bounds) || check_placement(**i)) {
++ i;
} else {
i = placements.erase(i);
}
}
}
void add_placement(const vec2 p, const word_placement &relative) {
word_placement check(p, relative);
if(check_placement(check)) {
word_placement *wp = new word_placement(check);
placements.insert(wp);
wordPlacements[relative.word].placements.insert(wp);
}
}
void place(word_placement placement) {
remove_word(placement.word);
int overlap = 0;
for(const char c : *placement.word) {
char &g = state[placement.start];
if(g == '\0') {
g = c;
for(const word_placement *rp : relativeWordPlacements[c]) {
add_placement(placement.start, *rp);
}
} else if(g != c) {
throw std::string("New word changes an existing character!");
} else {
++ overlap;
}
placement.start += placement.dir;
}
bound.grow(placement.bounds);
check_placements(placement.bounds);
std::cerr
<< draw('.', "\n")
<< "Added " << *placement.word << " (overlap: " << overlap << ")"
<< ", Grid: " << bound.width() << "x" << bound.height() << " of " << state.size() << " chars"
<< ", Words remaining: " << wordPlacements.size()
<< std::endl;
}
int check_cost(box2 b) const {
b.grow(bound);
return (
((b.maxdim() - bound.maxdim()) << 16) |
(b.width() + b.height() - bound.width() - bound.height())
);
}
void add_next(void) {
int bestNew = std::numeric_limits<int>::max();
int bestCost = std::numeric_limits<int>::max();
int bestLen = 0;
word_placement *best = nullptr;
for(word_placement *p : placements) {
int n = check_new(*p);
if(n <= bestNew) {
int l = p->word->size();
int cost = check_cost(box2(p->start, p->start + p->dir * l));
if(n < bestNew || cost < bestCost || (cost == bestCost && l < bestLen)) {
bestNew = n;
bestCost = cost;
bestLen = l;
best = p;
}
}
}
if(best == nullptr) {
throw std::string("Failed to find join to existing blob");
}
place(*best);
}
void fill(void) {
while(!placements.empty()) {
add_next();
}
}
std::string draw(char blank, const std::string &linesep) const {
std::string result;
result.reserve((bound.width() + linesep.size()) * bound.height());
for(int y = bound.tl.y; y < bound.br.y; ++ y) {
for(int x = bound.tl.x; x < bound.br.x; ++ x) {
auto c = state.find(vec2(x, y));
result.push_back((c == state.end()) ? blank : c->second);
}
result.append(linesep);
}
return result;
}
box2 bounds(void) const {
return bound;
}
int chars(void) const {
return state.size();
}
};
int main(int argc, const char *const *argv) {
std::vector<std::string> words;
// Load all words from input
while(true) {
std::string word;
std::getline(std::cin, word);
if(word.empty()) {
break;
}
words.push_back(std::move(word));
}
std::cerr
<< "Input word count: " << words.size() << std::endl;
// initialise grid
grid g(words);
// add first word (order of input file means this is longest word)
g.place(word_placement(vec2(0, 0), vec2(1, 0), g.find_word(words.front())));
// add all other words
g.fill();
std::cout << g.draw('.', "\n");
int w = g.bounds().width();
int h = g.bounds().height();
int n = g.chars();
std::cerr
<< "Final grid: " << w << "x" << h
<< " with " << n << " characters"
<< " (" << (n * 100.0 / (w * h)) << "% filled)"
<< std::endl;
return 0;
}
```
And finally, the result:
[](https://i.stack.imgur.com/Pk4Ex.png)
---
Alternative result (after fixing a couple of bugs in the program which were biasing certain directions and tweaking the cost function, I got a more compact but less optimal solution): 29275 chars, 198x195 (75.8% filled):
[](https://i.stack.imgur.com/KS4mo.png)
Again I haven't done much to optimise these programs, so it takes a while. But you can watch as it fills in the grid, which is quite hypnotic.
[Answer]
# C++, 34191 character "grid" (with minimal human intervention, 6 or 7 can easily be saved)
This should be taken more as a bound for the 2D case, because the answer is still a 1D string. It's just my code from the previous challenge, but with the new ability to reverse any string. This gives us a lot more scope for combining words (particularly because it caps the worst case of non-overlapping superstrings to 26; one for each letter of the alphabet).
For some slight 2D visual appeal, it puts linebreaks in the result if it can do so for free (i.e. between 0-overlap words).
Pretty slow (still no caching). Here's the code:
```
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
std::size_t calcOverlap(const std::string &a, const std::string &b, std::size_t limit, std::size_t minimal) {
std::size_t la = a.size();
for(std::size_t p = std::min(std::min(la, b.size()), limit + 1); -- p > minimal; ) {
if(a.compare(la - p, p, b, 0, p) == 0) {
return p;
}
}
return 0;
}
bool isSameReversed(const std::string &a, const std::string &b) {
std::size_t l = a.size();
if(b.size() != l) {
return false;
}
for(std::size_t i = 0; i < l; ++ i) {
if(a[i] != b[l-i-1]) {
return false;
}
}
return true;
}
int main() {
std::vector<std::string> words;
// Load all words from input and their reverses (words can be backwards now)
while(true) {
std::string word;
std::getline(std::cin, word);
if(word.empty()) {
break;
}
words.push_back(word);
std::reverse(word.begin(), word.end());
words.push_back(std::move(word));
}
std::cerr
<< "Input word count: " << words.size() << std::endl;
// Remove all fully subsumed words
for(auto p = words.begin(); p != words.end(); ) {
bool subsumed = false;
for(auto i = words.begin(); i != words.end(); ++ i) {
if(i == p) {
continue;
}
if(i->find(*p) != std::string::npos) {
subsumed = true;
break;
}
}
if(subsumed) {
p = words.erase(p);
} else {
++ p;
}
}
std::cerr
<< "After subsuming checks: " << words.size()
<< std::endl;
// Sort words longest-to-shortest (not necessary but doesn't hurt. Makes finding maxlen a tiny bit easier)
std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
return a.size() > b.size();
});
std::size_t maxlen = words.front().size();
// Repeatedly combine most-compatible words until we have only 1 word left (+ its reverse)
std::size_t bestPossible = maxlen - 1;
while(words.size() > 2) {
auto bestA = words.begin();
auto bestB = -- words.end();
std::size_t bestOverlap = 0;
for(auto p = ++ words.begin(), e = words.end(); p != e; ++ p) {
if(p->size() - 1 <= bestOverlap) {
continue;
}
for(auto q = words.begin(); q != p; ++ q) {
std::size_t overlap = calcOverlap(*p, *q, bestPossible, bestOverlap);
if(overlap > bestOverlap && !isSameReversed(*p, *q)) {
bestA = p;
bestB = q;
bestOverlap = overlap;
}
overlap = calcOverlap(*q, *p, bestPossible, bestOverlap);
if(overlap > bestOverlap && !isSameReversed(*p, *q)) {
bestA = q;
bestB = p;
bestOverlap = overlap;
}
}
if(bestOverlap == bestPossible) {
break;
}
}
std::string newStr = std::move(*bestA);
if(bestOverlap == 0) {
newStr.push_back('\n');
}
newStr.append(*bestB, bestOverlap, std::string::npos);
if(bestA == -- words.end()) {
words.pop_back();
*bestB = std::move(words.back());
words.pop_back();
} else {
*bestB = std::move(words.back());
words.pop_back();
*bestA = std::move(words.back());
words.pop_back();
}
// Remove any words which are now in the result (forward or reverse)
// (would not be necessary if we didn't have the reversed forms too)
std::string newRev = newStr;
std::reverse(newRev.begin(), newRev.end());
for(auto p = words.begin(); p != words.end(); ) {
if(newStr.find(*p) != std::string::npos || newRev.find(*p) != std::string::npos) {
std::cerr << "Now subsumes: " << *p << std::endl;
p = words.erase(p);
} else {
++ p;
}
}
std::cerr
<< "Words remaining: " << (words.size() + 1)
<< " Latest combination: (" << bestOverlap << ") " << newStr
<< std::endl;
words.push_back(std::move(newStr));
words.push_back(std::move(newRev));
bestPossible = bestOverlap; // Merging existing words will never make longer merges possible
}
std::cerr
<< "After non-trivial merging: " << words.size()
<< std::endl;
if(words.size() == 2 && !isSameReversed(words.front(), words.back())) {
// must be 2 palindromes, so just join them
words.front().append(words.back());
}
std::string result = words.front();
std::cout
<< result
<< std::endl;
std::cerr
<< "Word size: " << result.size() // Note this number includes newlines, so to get the grid size according to the rules, subtract newlines manually
<< std::endl;
return 0;
}
```
Result: <http://pastebin.com/UTe2WMcz> (4081 characters less than the previous challenge)
It's pretty clear that some trivial savings can be made by putting the `xd` and `wv` lines vertical, intersecting the monster line. Then `hhidetautisbneudui` can intersect with the `d`, and `lxwwwowaxocnnaesdda` with `w`. This saves 4 characters. `nbcllilhn` can be substituted in to an existing `s` overlap (if one can be found) to save another 2 (or just 1 if no such overlap exists and it must be added vertically instead). Finally `mjjrajaytq` can be added vertically somewhere to save 1. This means with minimal human intervention, 6–7 characters can be saved from the result.
I would like to get this into 2D with the following method, but I'm struggling to find a way to implement it without making the algorithm O(n^4), which is quite impractical to compute!
1. Run the algorithm as above, but stop short when the overlaps reach 1 character
2. Repeatedly:
1. Find a group of 4 words which can be arranged into a rectangle
2. Add as many words as possible on top of this rectangle where each word overlaps at least 2 characters of the current shape (check all 8 directions) — this is the only stage where we can actually get an advantage over the current code
3. Combine the resulting grids and lone-words looking for single-letter overlaps each time
[Answer]
# PHP
this one does the job theroratically; but 10000 are probably too many words for recursion. The script is running now. (still ran 24 hours later)
works fine on small directories, but I may make an iterative version next week.
`$f=array("pen","op","po","ne","pro","aaa","abcd","dcba");
will output`abcdapenaropao..`although this is not an optimal result (scoring was changed ... I´m working on a generator). One optimal result is this:`open.r.a.o.adcba`
It is also not very fast; only removes substrings and sorts the remains by length,
the rest is brute force: try to fit the words into a rectangle, try on a larger rectangle if it fails.
btw: The substring part needs 4.5 minutes on my machine for the large directory
and cuts it down to 6,190 words; the sort on them takes 11 seconds.
```
$f=file('https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt');
// A: remove substrings - forward or reversed
$s=join(' ',$f);
$haystack="$s ".strrev($s);
foreach($f as$w)
{
$r=strrev($w=trim($w)); // remove trailing line break and create reverse word
if(!preg_match("%$w\w|\w$w%",$haystack)
// no substr match ... now: is the reverse word in the list?
// if so, keep only the lower one (ascii values)
&!($w>$r&&strstr($s,$r))
// strstr does NOT render the reverse substr regex obsolete:
// this is only executed for $w=abc, not for $w=bca!
)
$g[]=$w
;
}
// B: sort the words by length
usort($g,function($a,$b){return strlen($a)-strlen($b);});
// C1: function to fit $words into $map
function gomap($words,$map)
{
$h=count($map);$w=strlen($map[0]);
$len=strlen($word=array_pop($words));
// $x,$y=position; $d=0:horizontal, $d=1:vertical; $r=0: word, $r=1: reverse word
for($x=$w-$len;$x>=0;$x--)for($y=$h-$len;$y>=0;$y--)for($d=0;$d<2;$d++)for($r=0;$r<2;$r++)
{
// does the word fit there?
$drow=$r?strrev($word):$word;
for($ok=1,$i=0;$ok&$i<$len;$i++)
$ok=in_array($map[$y+$d*$i][$x+$i-$d*$i], [' ',$drow[$i]])
;
// it does, paint it
if($ok)
{
for($i=0;$i<$len;$i++)
$map[$y+$d*$i][$x+$i-$d*$i]=$drow[$i];
if(!count($words)) // this was the last word: return map
return $map;
else // there are more words: recurse
if ($ok=gomap($words,$map))
return $ok;
// no fit, try next position
}
}
return 0;
}
// C2: rectangle loop
for($h=0;++$h;)for($w=0;$w++<$h;) // define a rectangle
{
// and try to fit the words in there
if($map=gomap($g,
array_fill(0,$h,str_repeat(' ',$w))
))
{
// words fit; output and break loops
echo '<pre>',implode("\n",$map),'</pre>';
break 2;
}
}
```
] |
[Question]
[
In Canada, the penny is no longer circulated. Cash payments are rounded to the nearest 5 cents.
Money can be saved by splitting purchases. For example, two $1.02 items cost $2.04 which rounds up to $2.05, but when buying the items in separate purchases, each price rounds to $1.00 for a total of $2.00. However, when buying two items at $1.03 each, it is better to buy them in a single purchase.
Another way to save money is using a credit card when rounding is unfavourable, because credit payments are not rounded. If we want two $1.04 items, the total price will round up to $2.10 regardless of how we split the purchases. Therefore, we should pay for these items with a credit card.
Write a function or program which accepts a list of prices of items as integers in cents and outputs the lowest possible total price (in cents) for those items which can be achieved through a sequence of purchases, each either by cash or by credit.
Shortest code wins.
## Test cases
```
[] : 0
[48] : 48
[92, 20] : 110
[47, 56, 45] : 145
[55, 6, 98, 69] : 225
[6, 39, 85, 84, 7] : 218
[95, 14, 28, 49, 41, 39] : 263
[92, 6, 28, 30, 39, 93, 53] : 335
[83, 33, 62, 12, 34, 29, 18, 12] : 273
[23, 46, 54, 69, 64, 73, 58, 92, 26] : 495
[19, 56, 84, 23, 20, 53, 96, 92, 91, 58] : 583
[3, 3, 19, 56, 3, 84, 3, 23, 20, 53, 96, 92, 91, 58, 3, 3] : 598
[2, 3, 4, 4, 4, 4, 4] : 19
```
[Answer]
### Ruby, 119 105 characters (93 body)
```
def f s
a,b,c,d=(1..4).map{|i|s.count{|x|x%5==i}}
s.reduce(0,:+)-a-(c-m=c>d ?d:c)/2-2*(b+m+(d-m)/3)
end
```
Two characters may be saved if the algorithm is allowed to crash when fed an empty shopping list.
[Answer]
## GolfScript (54 chars)
```
~]4,{){\5%=}+1$\,,}%~.2$>$:m- 3/m+@+2*@@m- 2/++~)+{+}*
```
This is a program which takes input from stdin as space-separated values. One character could be saved by forcing the input format to instead be as GolfScript arrays.
[Test cases online](http://golfscript.apphb.com/?c=O1sKJycgIyAwCic0OCcgIyA0OAonOTIgMjAnICMgMTEwCic0NyA1NiA0NScgIyAxNDUKJzU1IDYgOTggNjknICMgMjI1Cic2IDM5IDg1IDg0IDcnICMgMjE4Cic5NSAxNCAyOCA0OSA0MSAzOScgIyAyNjMKJzkyIDYgMjggMzAgMzkgOTMgNTMnICMgMzM1Cic4MyAzMyA2MiAxMiAzNCAyOSAxOCAxMicgIyAyNzMKJzIzIDQ2IDU0IDY5IDY0IDczIDU4IDkyIDI2JyAjIDQ5NQonMTkgNTYgODQgMjMgMjAgNTMgOTYgOTIgOTEgNTgnICMgNTgzCiczIDMgMTkgNTYgMyA4NCAzIDIzIDIwIDUzIDk2IDkyIDkxIDU4IDMgMycgIyA1OTgKJzIgMyA0IDQgNCA0IDQnICMgMTkKXXsKCn5dNCx7KXtcNSU9fSsxJFwsLH0lfi4yJD4kOm0tIDMvbStAKzIqQEBtLSAyLysrfikreyt9KgoKcH0v)
The most interesting trick is `.2$>$` for a non-destructive `min` operator.
---
My analysis of the maths is essentially the same as Jan's and Ray's: considering values mod 5, the only saving is on transactions worth 1 or 2. The credit card option means that we never round up. So an item which costs 5n+2 cents can't benefit from bundling; nor can an item worth 5n+1 cents (because combining two 1-cent savings into a 2-cent saving doesn't give any benefit). 0 is the additive identity, so the only interesting cases involve values of 3 and 4. `3+3 = 1` and `3+4 = 4+4+4 = 2`; if we have mixed 3s and 4s then we optimise by preferring `3+4` over `3+3` (strictly better) or `4+4+4` (equivalent).
[Answer]
**C++: 126 character**
```
int P(int*m,int i){int t=0,h=0,d;while(i>-1){d=m[i]%5;t+=m[i--];d<3?t-=d:d==4?h++,t-=2:h--;}h<0?t+=h/2:t+=(h-h/3)*2;return t;}
```
Welcome to give guidance to put this program becomes shorter.Here is the test program,compile with tdm-gcc 4.7.1 compiler and run normally.
```
#include<iostream>
using namespace std;
//m[i]表示单个商品的价格,t表示所有商品总价格,
//d为单个商品价格取模后的值,h为单个商品价格取模后值为3的个数,
//f为单个商品价格取模后值为4的个数
int P(int*m,int i){int t=0,h=0,d;while(i>-1){d=m[i]%5;t+=m[i--];d<3?t-=d:d==4?h++,t-=2:h--;}h<0?t+=h/2:t+=(h-h/3)*2;return t;}
int main() {
int p1[1]={48};
int p2[2]={92,20};
int p3[3]={47,56,45};
int p4[4]={55,6,98,69};
int p5[5]={6,39,85,84,7};
int p6[6]={95,14,28,49,41,39};
int p7[7]={92,6,28,30,39,93,53};
int p8[8]={83,33,62,12,34,29,18,12};
int p9[9]={23,46,54,69,64,73,58,92,26};
int p10[10]={19,56,84,23,20,53,96,92,91,58};
int p11[10]={1,2,3,4,5,6,7,8,9,10};
cout<<P(p1,0)<<endl
<<P(p2,1)<<endl
<<P(p3,2)<<endl
<<P(p4,3)<<endl
<<P(p5,4)<<endl
<<P(p6,5)<<endl
<<P(p7,6)<<endl
<<P(p8,7)<<endl
<<P(p9,8)<<endl
<<P(p10,9)<<endl
<<P(p11,9)<<endl;
return 0;
}
```
[Answer]
## R 143
```
function(x)min(sapply(rapply(partitions::listParts(length(x)),
function(i)min(sum(x[i]),5*round(sum(x[i])/5)),h="l"),
function(x)sum(unlist(x))))
```
Tests (where `P` is an alias for the code above)
```
> P(c(48))
[1] 48
> P(c(92, 20))
[1] 110
> P(c(47, 56, 45))
[1] 145
> P(c(55, 6, 98, 69))
[1] 225
> P(c(6, 39, 85, 84, 7))
[1] 218
> P(c(95, 14, 28, 49, 41, 39))
[1] 263
> P(c(92, 6, 28, 30, 39, 93, 53))
[1] 335
> P(c(83, 33, 62, 12, 34, 29, 18, 12))
[1] 273
> P(c(23, 46, 54, 69, 64, 73, 58, 92, 26))
[1] 495
> P(c(19, 56, 84, 23, 20, 53, 96, 92, 91, 58))
[1] 583
```
[Answer]
# Mathematica 112 126 167 157
**Edit**: Cases of {3, 3} and {4,4,4} now handled thanks to Peter Taylor and cardboard\_box.
```
n_~g~o_ := {a___, Sequence @@ n, b___} :> {a, b, o};
f@s_ := Tr@Join[#[[2]], Sort@#[[1]] //. {1 -> 0, 2 -> 0, g[{3, 4}, 5], g[{3, 3}, 5],
g[{4, 4, 4}, 10]}] &[Transpose[{m = Mod[#, 5], # - m} & /@ s]]
```
Note: Non-purchases (test case #1) are entered as `f[{0}]`.
**How it works**
1. For each item, the greatest multiple of 5 less than the respective price will be paid regardless of form of payment. (No getting around that.)
2. The remainders of `Mod[n, 5]` are then processed: 1's and 2's become 0's. Zeros stay unchanged.
3. Each pair {3, 4} -> {5}; afterwards each pair {3, 3} -> {5}; then the triple, {4,4,4}-> {10}, if applicable.
4. The remaining 4's, if any, remain unchanged (paid by credit card).
5. Original multiples of 5 summed with remainders that were tweaked (or not) in steps (2) to (4).
**Testing**
`a12` adjusts for {3,3}
`a13` adjusts for {4,4,4}
```
a1={0};
a2={48};
a3={92,20};
a4={47,56,45};
a5={55,6,98,69} ;
a6={6,39,85,84,7};
a7={95,14,28,49,41,39};
a8={92,6,28,30,39,93,53};
a9={83,33,62,12,34,29,18,12};
a10={23,46,54,69,64,73,58,92,26};
a11={19,56,84,23,20,53,96,92,91,58};
a12={3,3,19,56,3,84,3,23,20,53,96,92,91,58,3,3};
a13={2,3,4,4,4,4,4};
f /@ {a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13}
```
>
> {0, 48, 110, 145, 225, 218, 263, 335, 273, 495, 583, 598, 19}
>
>
>
[Answer]
## Python 3 (115 chars)
```
m=eval(input());t=a=b=0
for v in m:d=v%5;t+=v-d*(d<3);a+=d==3;b+=d==4
d=min(a,b);a-=d;b-=d;print(t-d*2-a//2-b//3*2)
```
## Python 2 (106 chars)
```
m=input();t=a=b=0
for v in m:d=v%5;t+=v-d*(d<3);a+=d==3;b+=d==4
d=min(a,b);a-=d;b-=d;print t-d*2-a/2-b/3*2
```
[Answer]
## APL, 58 characters
```
{a b c d←+/(⍳4)∘.=5|⍵⋄(+/⍵)-a-(⌊2÷⍨c-m)-2×b+m+⌊3÷⍨d-m←c⌊d}
```
The program is essentially a direct translation of [Jan Dvorak's Ruby solution](https://codegolf.stackexchange.com/a/11784/7911).
---
```
{a b c d←+/(⍳4)∘.=5|⍵⋄(+/⍵)-a-(⌊2÷⍨c-m)-2×b+m+⌊3÷⍨d-m←c⌊d}⍬
0
{a b c d←+/(⍳4)∘.=5|⍵⋄(+/⍵)-a-(⌊2÷⍨c-m)-2×b+m+⌊3÷⍨d-m←c⌊d}95 14 28 49 41 39
263
{a b c d←+/(⍳4)∘.=5|⍵⋄(+/⍵)-a-(⌊2÷⍨c-m)-2×b+m+⌊3÷⍨d-m←c⌊d}19 56 84 23 20 53 96 92 91 58
583
```
`⍬` is the empty vector.
[Answer]
# Julia 83C
```
C=L->let
w,z,x,y=map(i->[i==x%5for x=L]|sum,1:4)
L|sum-(x+2w+3min(x,y)+4z)>>1
end
```
## Explaination:
In one purchase, you can save 2 cent at most. ~~So if you have a combination that can save you 2 cents, just buy it that way and it will be optimial~~. For example, if you have `x` items with price 3(mod 5) and `y` items with price 4(mod 5), you can make `min(x, y)` number of (3, 4) pairs, which save you `2 min(x, y)` cents. Then you use the rest 3's, if any, to save you `max(0, x-min(x,y)) / 2` cents. This can also be calculated by `(max(x,y)-y)/2`
```
w = sum(1 for p in prices if p % 5 == 1)
z = sum(1 for p in prices if p % 5 == 2)
x = sum(1 for p in prices if p % 5 == 3)
y = sum(1 for p in prices if p % 5 == 4)
ans = sum(prices) - (w + 2 z + 2 min(x, y) + div(max(x, y) - y, 2))
= sum(prices) - (2w + 4z + 4 min(x, y) + x + y - min(x, y) - y) `div` 2
= sum(prices) - (2w + 4z + 3 min(x, y) + x) `div` 2
```
## Edit
This solution is wrong.
] |
[Question]
[
Your program should compute the number of moves it takes a [chess knight](http://en.wikipedia.org/wiki/Knight_%28chess%29) to reach each square of the chess board. The input will be two space-separated integers representing coordinates of the starting square (horizontal then vertical coordinate, 0-7 inclusive each). Your program should output a number grid containing the minimum number of moves a chess knight needs to make to reach each square.
***examples***
**input**
```
0 0
```
**output**
```
03232345
34123434
21432345
32323434
23234345
34343454
43434545
54545456
```
**input**
```
3 1
```
**output**
```
21232123
32303232
21232123
34121432
23232323
32323234
43434343
34343434
```
Shortest code wins.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 55 bytes
```
{⍵⌊d⍴1+⌊/¨⌷∘⍵¨¨a/⍨¨Ö↓2=×/↑|∘.-⍨a←,⍳d}⍣≡0@(⊂⌽⎕)⊢9⍴⍨d←8 8
```
```
{⍵⌊d⍴1+⌊/¨⌷∘⍵¨¨a/⍨¨Ö↓2=×/↑|∘.-⍨a←,⍳d}⍣≡0@(⊂⌽⎕)⊢9⍴⍨d←8 8
0@(⊂⌽⎕)⊢9⍴⍨d←8 8 ⍝ create an 8x8 grid of 9s with a 0 at the start position
∘.-⍨a←,⍳d ⍝ all differences between coordinates
2=×/↑| ⍝ is 2 equal to the product of the absolute values?
a/⍨¨Ö↓ ⍝ filter where true (finds knight moves)
⌷∘⍵¨¨ ⍝ index into the board
1+⌊/¨ ⍝ 1 plus the minimum (finds minimum distance)
d⍴ ⍝ 8x8 reshape
⍵⌊ ⍝ the minimum of the new and old moves
{ }⍣≡ ⍝ apply until converged (minimum distances found)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/n942qO2CdUaj3q3ApHCo95dmkAMRAiRrZq1XI/6pnr6AxUacD3qaE/7Xw2S7OlKedS7xVAbyNA/tOJRz/ZHHTOA4odWHFqRqP@oF0iBzJ5sZHt4uv6jtok1QGk9XaB4ItAcnUe9m1NqH/UuftS50MBB41FX06OevUBLNB91LbIEmgpUlgJUZqFg8R8oCmSpq4Ns/p/GZaBgwJXGZaxgCAA "APL (Dyalog Classic) – Try It Online")
[Answer]
## Ruby 1.9, 146 ~~151~~ characters
```
g=(?9*8+".
")*8
r=->x,a=0{x<0||a<g[x].to_i&&(g[x]=a.to_s;[21,19,12,8].map{|i|r[x+i,a+1];r[x-i,a+1]})}
r[eval gets.split*?++"*10"]
puts g.tr(?.,"")
```
[Answer]
# [Haskell](https://www.haskell.org/), 255 236 231 229 bytes
```
import Data.List
k x y=unlines[[toEnum$findIndices(elem(i,j))(scanl(\s _->filter(\(z,w)->z`elem`n&&w`elem`n)$(\(a,b)->[(a+c,b+d)|(c,d)<-zip[1,1,-1,-1,-2,-2,2,2][2,-2,2,-2,1,-1,1,-1]])=<<s)[(x,y)]n)!!0+48|j<-n]|i<-n]where n=[0..7]
```
D:
This is my first attempt at golfing. Also somewhat new to Haskell.
Test suite:
```
import System.Environment
main :: IO ()
main = do
args <- getArgs
let readArgs = map read args
let out = k (readArgs !! 0) (readArgs !! 1)
putStr out
```
[Answer]
## Windows PowerShell, 178 ~~183~~ ~~188~~
```
filter f($n){if($d[($p=$_)]-gt$n){$d[$p]=$n
12,8,21,19|%{$p+$_
$p-$_}|f($n+1)}}$d=,0*20+(0..7|%{,9*8+0,0})+,0*20
$x,$y=-split$input
20+"$y$x"|f 0
2..9|%{-join$d[(10*$_).."$_`7"]}
```
Passes both test cases.
[Answer]
## JavaScript, ~~426~~ 408 bytes
```
for(a=[],i=0;i<8;i++){a[i]=[];for(j=0;j<8;j++)a[i][j]=99}m=[[2,1],[2,-1],
[-2,1],[-2,-1],[1,2],[-1,2],[1,-2],[-1,-2]];function s(f,g,e,b){b&&(a[f][g]=0);
for(var b=[],c=0;c<m.length;c++){var d=[f+m[c][0],g+m[c][1]];a[d[0]]&&
a[d[0]][d[1]]&&a[d[0]][d[1]]>e&&(a[d[0]][d[1]]=e,b.push(d))}for(c=0;c<b.length;c++)
s(b[c][0],b[c][1],e+1)}function _(f,g){s(g,f,1,1);for(e="",b=0;b<8;b++)e+=
a[b].join("")+"\n";return e}
```
JavaScript is not the most concise language out there... But my coding style is a little verbose too.
Usage: `_(0, 0)` etc.
] |
[Question]
[
## Problem
A fact you may have noticed about factorials is that as \$n\$ gets larger \$n!\$ will have an increasing number of \$0\$s at the end of it's base \$10\$ representation. In fact this is true for any base.
In this challenge you will be given a base \$b > 1\$ and an integer \$n > 0\$ and you will determine the smallest \$x\$ such that \$x!\$ has at least \$n\$ trailing \$0\$s in its base \$b\$ representation.
Of course you can easily do this by just checking larger and larger factorials. But this is super slow. The actual challenge is to do this quickly. So in order to be a valid answer you must have a worst case asymptotic complexity of \$O(\log(n)^3)\$ where \$n\$ is the number of trailing \$0\$s and \$b\$ is fixed. You should assume that *basic* arithmetic operations (addition, subtraction, multiplication, integer division, and modulo) are linear to the number of bits in the input.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code as measured in bytes.
## Examples
For a small example if \$b=2\$ and \$n=4\$ then the answer is \$6\$ since \$5!=120\$ which is not divisible by \$2^4=16\$, but \$6!=720\$ which is divisible by \$16\$.
For a bigger example if \$b=10\$ and \$n=1000\$ then the answer is \$4005\$, since \$4004!\$ has only \$999\$ trailing zeros in base 10, and multiplying by \$4005\$ is obviously going to introduce another \$0\$.
[Answer]
# [Python](https://www.python.org), 209 bytes
```
lambda b,n:max(h(g(b).count(s)*n,s,1)for s in g(b))
def h(n,s,*S,o=0):
while S[-1]<n:S+=S[-1]*s+1,
while S:*S,t=S;o+=n//t;o*=s;n%=t
return o
g=lambda b,p=2,m=0:(b-p)*[0]and g(b,p+1)if b%p else[p]+g(b//p,p)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY9BToUwFEXnXcWb_KQtRdofBz_FroIhMqDSfkigbWiJuhYnJEa34RocuhtB4h-9l3vu4Ny3z_Caeu_Wd6seP5Zk88vP99hOumtBMyen9gX3-Io1uXvyi0s4EupYZIJYP0OEwcEOCeqMhR7viFbMK04kgud-GA1UdS6aByerTP29NGaC3aDc6klVpc-UK4pUeqpi6U4qIZhNWmYHHl3VzSioM5sUl1jngdCaN63rdgMWMkEGC_oUwIzR1KHJtrgoAgsEHcO-wjxsCywWnAnO-Wb9n5zZPSFHa12P-ws)
Not very golfed yet. Hope to find time later.
`g` is based on one of @Lynn's neat [tips](https://codegolf.stackexchange.com/a/152433/107561) and does prime factor decomposition of `b`. As `b´ is fixed it is technically O(1).
The main function `f` goes through all prime factors and lets `h` compute the smallest `n` such that that prime factor occurs sufficiently often in the factorial. It then simply takes the max. As `b` is fixed the complexity is that of `h`.
`h` works on `p` the current prime factor and `n` where `n` is the requested number of trailing zeros times the multiplicity of `p` in `b`. It is easy to convince oneself that `p!` has `1` `p`,`p^2!` has `p+1` `p`s `p^3!` has `p(p+1)+1` etc. So what we want to do is something like writing `n` in the mixed base (1,p+1,p(p+1)+1,...) and then reinterpret the digits in base `p`.
Which is what `h` does, though I wish I had a few more test cases.
Complexity:
Disclaimer, I always get those wrong. But if I'm not mistaken this would be O(log(n)^2) (O(log(n)) steps in the while loop and O(log(n)) digits in the arithmetic operations.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~136~~ ~~128~~ 117 bytes
```
b=>n=>eval("h=x=>x&&x+h(x/p);p=2n;for(e=m=0n;b>1;)if(b%p)e=p-p++;else{b/=p;for(x=n*~-p*++e;h(x++/p)<n*e;)m=m<x?x:m}")
```
[Try it online!](https://tio.run/##bZDBbsIwDIbvfQoPCUhIGS2gHRbcSbvtMZoSaFhxo9Cxaoi9OnPZYBw4@Xf8@8ufbPJ9viuC882Y6qU9bfBkMCPM7D6vRK/EFrN2MGhVKdqJl9rjlPSqDsLiFhPSJku1dCth@l5a9GOvlLbVzh7MBP3Z2CKNvsd@pJTVDFGKMQsaWS23uF20L@3z9tiTJx1Fq7xo6uDyChAIMIND2LNMSQODQLi/xsGCDVyVksCWEYLTEGzzEYh7fYyakLvK0XrKG4JiI/9piYbP0lUWxIOgvpESDgQTBMOEPYc/3gXdcq5wcQ0sSMZgJL@hKG3x3rlNTL@3Rjnt@GAjXt36jRrBV14kSV4patrVlX2s6rWIhgaHTIphSJ0gFrzeSS5xNPyyobbn/pJCdAP4Z7PJB1vYZZf6vh3G/I23O5HUx0t2kT4lMcxm87TLdj6ZxjC/NilP0yRJpD79AA "JavaScript (Node.js) – Try It Online")
Shortened by @Cool guy.
I'm not entirely clear about Wheat Wizard's time bound, but I think this is within it. To explain the method: the number of zeroes at the end of \$n!\$ in base *b* is equal to the minimum number of zeroes at the end of \$n!\$ in any prime power base dividing *b*, so I look at all prime powers dividing *b*, find the minimum possible *x* for all of them and take the maximum. Counting up the factors of *p* in the factors of \$x!\$ shows you that the number of zeroes at the end of \$x!\$ in a prime base *p* is
$$\phi(x):=\sum\_{j\ge 1} \lfloor{\frac{x}{p^j}}\rfloor \le \frac{x}{p-1},$$
meaning that the smallest possible *x* in a prime power base \$p^e\$ definitely can't be any smaller than \$n e (p-1) \$. So, for each prime power factor \$p^e\$ of *b*, I start with \$n e (p-1)\$ and count up by ones until I find a working *x*. Since the difference between \$\phi(x)\$ and \$x/(p-1)\$ is logarithmic in *x*, and \$\phi(x)\$ increases by at least one when *x* is increased by *p*, only a logarithmic number of iterations are necessary. (Each iteration means recomputing \$\phi(x)\$, which uses \$O(\log{x})\$ additions and divisions by *p*.)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 118 bytes
```
n=>b=>(g=(p,k)=>b-!k?b%p?g(p+1,0,r=k&&(h=m=>H=N>=m&&(h(m*p+1)+(N-(N%=m))/m)*p)(1,N=n*k)>r?H:r):g(p,k+1,b/=p):r)(2,r=0)
```
[Try it online!](https://tio.run/##bYxLDoIwFAD33sIF5D0oUgxuSF7ZEVa9AyCpWvpJMV6/lqWJy5lJ5jV9pn0JT/@urLuvcaBoScwkQBF4pjFBddb9nPlegS8bxlkgnefwIENiJCnIHASmSBVLkBXIjAxibbDwCA2TZAuNIvRjF7BTxzZ95po8JgHXNOQYF2d3t62XzSkYoE0e8fQrG855GvI/AeHWtojxCw "JavaScript (Node.js) – Try It Online")
Maybe \$O(\log(n))\$?
1. For every \$p^k\$ where \$p\$ is prime, \$k\$ is an integer, \$p^k\$ is a factor of \$b\$. Calculate \$F\_p(k\cdot n)\$ using following steps; the answer is \$\max\$ of all results.
2. Convert \$k\cdot n\$ to a strange base \$\overline{d\_md\_{m-1}\dots d\_1}\$ where
$$ k\cdot n = \sum\_{i=1}^m\left(d\_i \cdot \frac{p^i-1}{p-1} \right) $$ $$ 0\le d\_i \le p $$ $$ d\_1=0 $$
3. Read the number \$\overline{d\_md\_{m-1}\dots d\_1}\$ as base \$p\$, while digits \$p\$ is treated as \$10\_{(p)}\$.
I know the code should be able to golf more. But the formula should just like this.
] |
[Question]
[
I'm trying to make a pointfree function `f` that can act like APL's dyadic forks/Husk's `§`, so `f g h i a b` equals `g (h a) (i b)`, where `g` is a binary function, `h` and `i` are unary functions, and `a` and `b` are integers (I'm only dealing with integers and not other types right now). I converted the function to pointfree in the following steps, but it's 26 bytes with a lot of parentheses and periods and even a `flip`, so I'd like to know how to golf it.
```
f g h i a b=g(h a)(i b)
f g h i=(.i).g.h
f g h=(.g.h).(.)
f g=(.(.)).(flip(.)).(g.)
f=((.(.)).).((flip(.)).).(.)
```
[Try it online!](https://tio.run/##hY6xDsIwDET3fsUNDLZQPABTpbDzGYkgiUUpFe3/BwNFGRiY7u6dT3IJ8/UyDDWh70GncYE7ogm/lP7kn1XnXEJGgSIgwmcqCEyKyK3yJMqSpXyRAUssJOuVAfMG0qDTx2XhmjythYHWvYf1FnSEx/neAdND7aUNEmjLCHEG7cyQ2zMO9Qk)
[Answer]
# 18 bytes
```
(flip.).(.).((.).)
```
[Try it online!](https://tio.run/##hY87EsIwDET7nGILCmkYuwCqzJieO9A4AX8GEzyE82MEDklBQaXd96RCwY6Xc0rFoW1Bh@EBtccy@D3pT/@5apRy8AiIsOhgPAVYpoiOF2VIR9Zehy8SII016WlLgGQBLsVck6/O0KQELXY@NRWKEzYLZ46l8k@fbLnaOMDgdGuAfI/yxAoOtGbYbgRtJJDaMnbl2btk/VhUn/ML "Haskell – Try It Online")
Since your function has no argument repetition and no argument deletion, it essentially becomes a BC calculus golf (in Haskell terms, a golf using just `B=(.)` and `C=flip`). I will use B and C combinators and convert to Haskell code later.
```
\g h i a b -> g (h a) (i b)
\g h i a -> B (g (h a)) i
\g h i -> C (\a -> B (g (h a))) i
\g h -> C (\a -> B (g (h a)))
-- choice 1
\g h -> C (B B (B g h))
-- choice 1.1
\g -> B C (B (B B) (B g))
B C.B (B B).B
(flip.).(((.).).).(.) -- 21 bytes
-- choice 1.2
\g -> B (B C (B B)) (B g)
B (B C (B B)).B
((flip.((.).)).).(.) -- 20 bytes; pointfree.io
-- choice 2
\g h -> C (B (B B g) h)
\g -> B C (B (B B g))
B C.B.B B
(flip.).(.).((.).) -- 18 bytes; shortest
```
As a bonus, if you can swap `i` and `a` in the definition of `f`, it becomes an ordered LC and allows a very short form using just `(.)`:
```
\g h a i b -> g (h a) (i b)
\g h a i -> B (g (h a)) i
\g h a -> B (g (h a))
\g h -> B (B B g) h
\g -> B (B B g)
B B (B B)
(.).((.).) -- 10 bytes
```
] |
[Question]
[
let `S`, `a` and `b` each represent a string
Goal: Write a standard string replace function where the you replace all occurrences of `a` in a string `S` with `b` so long as `a` is not already part of an instance of `b`
for example, if we have the string `S` = `My oh my that there is a big ol' that`
and we wanted to do a fancy replace with `a = that` and `b = that there` we would replace every instance of `that` with `that there` as long as the instance of `that` isn't already an instance of `that there`
So in this case the output would be: `My oh my that there is a big ol' that there`
The first `that` is not replaced because it is already part of an instance of `that there`
### Notes
* All 3 inputs must be strings containing only printable ascii characters
* Input may be given as 3 separate strings or a list of 3 strings
* Input will be in the order `S`, `a`, `b` unless otherwise specified in the answer
* In order for `a` to be considered a part of `b`, all of the instance of `a` must be part of an instance `b`
### Some Corner Cases Explained
```
Input: ["1222", "22", "122"]
Output: "12122"
```
In the case above example the latter `22` is replaced. Even though part of it is part of an instance of `b`, the entirety of it is NOT a part of the instance of `b`. Since the entire instance of `a` is not part of an instance of `b` it is replaced.
```
Input: ["123 ", "23", "12"]
Output: "112 "
```
This test case illustrates the same case as above but perhaps in a slightly more clear way. Again the `2` in the middle is both part of an instance of `a` as well as part of an instance of `b`, however since all of `a` is not part of the instance of `b` it is still replaced.
```
Input: ["Empty", "", "p"]
Output: "pEpmptpyp"
```
In the above test case both the empty string before and after the `p` are not replaced as the can wholly be considered part of the instance of `p`.
### Other Test Cases
```
Input: ["aabbaa", "aa", "aabb"]
Output: "aabbaabb"
Input: ["Hello World!", "o", " no"]
Output: "Hell no W norld!"
Input: ["Wow, oh wow, seriously WOW that's... wow", "wow", "WOW,"]
Output: "Wow, oh WOW,, seriously WOW that's... WOW,"
Input: ["Empty", "", "b"]
Output: "bEbmbpbtbyb"
Input: ["Empty", "b", "br"]
Output: "Empty"
Input: ["Empty", "pty", "Empty"]
Output: "Empty"
Input: ["aabbaaa", "aa", "PP"]
Output: "PPbbPPa"
Input: ["121212","1","121"]
Output: "121212"
```
---
This is a question for code-golf so the shortest answer in bytes wins.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 76 bytes
```
{$^b;$^a;&{S:g/$a<?{$!=$/;all m:ex/$b/>>.&{$!.to>.to||.from>$!.from}}>/$b/}}
```
[Try it online!](https://tio.run/##dVDBboJAEL3zFeNmY7WhWDDpQSumB5M2aeKhSTkoNrstVhNwt4CxBPl2O4NIMdGQeTP73rzHgg7i8OEQZdBewuiQ84Uc8oUYtvO3wXePi8dxzlsj3huKMIRoEPz2uOy5rtVG2kqVi7XfW8tYRS4S1IvCpZ2iOCxVDOF6EyRWJHQnjzBwzqzb8ZxRwuT96bXowp0LXJhcmvwTcgMgERnkjH/AaARcAjNxDH5wLDrLDhcz2zcRHb9Lh3u/2zWKw8tGb9MBwIwJIaUQzAR2QimZb0y3ablR6cgZxr/pOQhDBZ6Kw68WmRQBbFTTSDtIgYdQ7tUBM@apnQlqBTvqSRCv1TYJM/CmHqQrkd4klmWRSLFVQ81sxp8iiL@eUboaL55EOs0ojko38/REo6YzffahttMHWnX6hLbTdNi2A1ezz/6hnMhIapnKTF40yBLipuWoXVqu2vF8wYG3pIfhBakcm9VUKToklYBzpdVSrTFAAtk/ "Perl 6 – Try It Online")
Anonymous code block that takes input curried, like `f(a,b)(s)`.
I'm pretty sure this matches up with the intent of the question. Basically, it only makes the substitution if the position of `a` is not within any of the *overlapping* matches of `b`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
≔⁰εF⌕AθηF‹‹ιε⬤⌕Aθζ∨‹ικ›⁺ιLη⁺κLζ«≔⁺⁺ω✂θει¹ζω≔⁺ιLηε»⁺ω✂θε
```
[Try it online!](https://tio.run/##bY9BCsIwEEXX5hSzTCCCddtVN7optOAJQh3b0JBiUi1UPHucpFJUHMKQfN78P2k65ZpBmRAK73Vr@U4CipxdBgf8oO25MIZfJXRCQNJK9H5pOpISIvABziRVbiV6eh4dqhEdr80taSXaduw4WUpIWr9qs1gKHmzzXigRqU0STkY3GGNQAjll0SImTrTy18BPTPzSk9VO2/GPFwXmIWR7KkaHLmF7Ny8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰ε
```
Initialise a variable to show where the last replaced match ended.
```
F⌕Aθη
```
Find all overlapping matches of `a` in `S`.
```
F‹‹ιε
```
If the next match does not overlap the last successful replacement...
```
⬤⌕Aθζ∨‹ικ›⁺ιLη⁺κLζ«
```
... and it also overlaps no copy of `b` in `S`...
```
≔⁺⁺ω✂θει¹ζω
```
... then concatenate the intermediate substring between the last match and this match with `b` to the output string...
```
≔⁺ιLηε
```
... and update the last match end variable to the end of this new match.
```
»⁺ω✂θε
```
At the end, add on any remainder of `S` and output the result.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~43~~ ~~122~~ ~~96~~ 88 bytes
```
##2~StringReplacePart~Cases[#2~P~#,{a_,b_}/;And@@(#2<b||#>a&@@@P@##2)]&
P=StringPosition
```
[Try it online!](https://tio.run/##bY9Ra4MwFIXf/RVZAt0GmcP4uLVkjMHelm0PPhQpN206BTWiKaVY/esuMfallHDOTb6Te@GWYDJVgsm3MO6XIyFs@DVNXv39qLqArRLQmOEdWtWubSQGQjvYULnpn1/eqh3nD4S9yvOZrGDBORfcDnhMF4FY@ilCt7nJdTV@H3JluLDMrDtC@qfV3g6khJI4TV1rF3QYQEoATPFsUuKeWv6pikKjRDfF7s4G2gpV2meJPlKkM3R0tVVNrg9tcULJV4JMBua@DcPQhZgiPBebUd/8Udbm5JBTfYPJKyYna67oXPx7iiIWI4dY7Dxinvr9wCHvQly@u2PXipxYdKHMscnsHfdBP/4D "Wolfram Language (Mathematica) – Try It Online")
+79: should be fixed.
Call as `f[a,S,b]`.
```
& (* a function which finds *)
#2~P~#, (* the positions {start,end} where a occurs in S *)
Cases[ {a_,b_}/;And@@(#2<b||#>a&@@@ )] (* which are not a subrange of any of the *)
P@##2 (* positions of b in S, *)
##2~StringReplacePart~ (* and replaces those parts of the string with b *)
P=StringPosition
```
[Answer]
# Perl 5 (`-lpF/;/`), 41 bytes
```
($_,$a,$b)=@F;s/(?<!(?=$b).)(?!$b)$a/$b/g
```
[TIO](https://tio.run/##NY7BCsIwEETv@YoUArZQG5riaS31onjTW4@SxWILsRuaivjzxqRUdpZ5u3MZ201m530qbrnQucCsPpzAybTZJ2lTh7vI0iYJLrQUKB/el0opCArOtEbUGhYhsnNnDPGWJnNPgICPxFp655x6/o7uummglzMf3l5aPvd63riiKGIIccM3Z8ennT8A9g@4AgJOK8ZdiJWq4qCqUGbtspS5XkMQB8qQlF@y80Cj81tjTxLkDw)
] |
[Question]
[
The idea for this [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") is simple: given a matrix of integers, let's sort it by applying Rubik-style movements. This means that you can select a single row or column and rotate its elements in any direction:
```
[1, 3, 2, 4] => [3, 2, 4, 1] (rotate left for rows/up for columns)
[1, 3, 2, 4] => [4, 1, 3, 2] (rotate right for rows/down for columns)
```
So, given a matrix of integers of any dimension, sort its elements applying only these Rubik-style transformations. A matrix
$$ \begin{bmatrix}
a\_{11} & a\_{12} & a\_{13} & a\_{14} \\
a\_{21} & a\_{22} & a\_{23} & a\_{24} \\
a\_{31} & a\_{32} & a\_{33} & a\_{34}
\end{bmatrix} $$
will be considered sorted iff its elements comply with the following restriction:
$$ a\_{11} \leq a\_{12} \leq a\_{13} \leq a\_{14} \leq a\_{21} \leq a\_{22} \leq a\_{23} \leq a\_{24} \leq a\_{31} \leq a\_{32} \leq a\_{33} \leq a\_{34} $$
### I/O
* Input will be a matrix of positive integers with no repeated values.
* Output will be the movements needed to sort it. As this is not a code golf challenge and you don't need to worry about its length, the proposed format for every movement is `#[UDLR]` where `#` is the number of the row or column to move (0-indexed) and `[UDLR]` is a single character in that range that specifies if the movement is Up/Down (for columns) or Left/Right (for rows). So `1U` would mean "move the 1-th column upwards" but `1R` would be "move the 1-th row rightwards". Movements will be comma-separated, so a solution will be expressed like this: `1R,1U,0L,2D`.
### Scoring
Trying to sort a matrix this way can be costly as there are a lot of possible combinations of moves, and there are also a lot of possible lists of moves that can sort it, so the goal is to write some code that sorts the N\*N matrices below. **The score will be the greatest size N that you can solve in a reasonable amount of time1 without errors (the greater the size of the matrix solved, the better). In case of a tie, the tie-breaker will be the number of movements in your found path (the shorter the path, the better).**
Example: if a user A finds a solution for N=5 and B finds a solution for N=6, B wins regardless of the length of both paths. If they both find solutions for N=6 but the solution found by A has 50 steps and B's solution has 60 steps, A wins.
Explanations on how your code works are highly encouraged and please post the solutions found so we can [test them](https://tio.run/##rVbbjtowEH3PV4xQJRJhItLVturSbR9A6gsrraCoD5SHkPWyZklCHQOtonw7HccJuZBA9mJxcZKZ4/GZM544QdfxOT0ctgHzljD5Fwjq9rX8lTnw12vqCOZ7gfmDepQzp2QxYt6fvqZ5tkuDje1QGG8X7Hnir3eUa6EGOJy1HQRwz/0lt934jrovRyBswRzY@ewB7mzm6YHgiD6bg82XgXG0yzzk2NkcXBst/8IteHQPzBMzMocw/ETgM4HriEBoXROwCFzJ@RecXuHXiqJ@AWnPmaC6wjKKjyRuvJk7H/eiG2a8qcSWQMsakd6UWOozItaQfByn81FuMkwvx63SCgOk1V9T85cMAomkutEoukg7Tjec7WxBCzwqr4SSxLmGyEefg7QEhkT2@vj3NfHAdIsR9ZbiSe8Z@KDTMQqeRZwC1kphraqwLMRalbGq8U4Y0j@0QgU4YwRW8whCvWYR6IIF36FN2nADbWgbEZTJV0SeX7D12yu7Rc0zqEyTZG22izUmiHpbF4aMq6IqFcN0Q2Do7z0CI/ooCIzZ8knkQVQlZaIs@SdrxCJQYi2IgIAqLnDRNzgjCWo7T6DHRYaWWFzKw5xs1kzoSKpxSQsyumOlyEKSN1zqiYZ5Hw9QQxi8eW/zAJHQ25xsFyp@vYeVbBik0hO5RVfpMLPmcHsL7WkblXCk3JxuUBL558Pic5mAksWoaCGTgxbZjSxPBaXUKidfvyplSZ5i2ko5S5mLI6pLmiw74W6KCwZ7JmQiY/Yw2ktJc@yAFoi6qWQY15EMq0LEVMTw48G8X2ldOGGsl5ww5xUiR3oYyGrP4siCY5eCi7QzsBVRnix0wnk6FlhEz/1LFEutNSD5YiQNqK/BkAn5Fp/83e5r6a@kvkmAZ@nvvSfRsmSbEK0WJNB7i5qtN6n5GENM4bwiOPYqNafeNd3yHUiOj8GXsFwXymvkbL2XnHM0V3F/JsBm/PdeynSuW8jBqdhyL4GtedlQ7wmFnhtWtBzZZkNYUtGHQP6c9qVjcuO@et5WvpBw9kDTt4yf/kS167qmleyk1YKOjKQj1zAzr1m@CNPtRdrh8B8). You can use [Pastebin](https://pastebin.com/) or similar tools if the solutions are too big. Also, an estimation of the time spent by your code to find your solutions will be appreciated.
### Test cases
The following matrices ([Pastebin link](https://pastebin.com/N7isrc5t) for a more copy-pasteable version) have been created starting from already sorted matrices by scrambling them with 10K random, Rubik-style movements:
\begin{bmatrix}
8 & 5 & 6 \\
11 & 10 & 1 \\
3 & 15 & 13 \\
\end{bmatrix} \begin{bmatrix}
21 & 10 & 12 & 16 \\
17 & 6 & 22 & 14 \\
8 & 5 & 19 & 26 \\
13 & 24 & 3 & 1 \\
\end{bmatrix} \begin{bmatrix}
1 & 13 & 8 & 16 & 5 \\
9 & 40 & 21 & 26 & 22 \\
11 & 24 & 14 & 39 & 28 \\
32 & 19 & 37 & 3 & 10 \\
30 & 17 & 36 & 7 & 34 \\
\end{bmatrix} \begin{bmatrix}
34 & 21 & 40 & 22 & 35 & 41 \\
18 & 33 & 31 & 30 & 12 & 43 \\
19 & 11 & 39 & 24 & 28 & 23 \\
44 & 1 & 36 & 5 & 38 & 45 \\
14 & 17 & 9 & 16 & 13 & 26 \\
8 & 3 & 47 & 6 & 25 & 4 \\
\end{bmatrix} \begin{bmatrix}
20 & 36 & 17 & 1 & 15 & 50 & 18 \\
72 & 67 & 34 & 10 & 32 & 3 & 55 \\
42 & 43 & 9 & 6 & 30 & 61 & 39 \\
28 & 41 & 54 & 27 & 23 & 5 & 70 \\
48 & 13 & 25 & 12 & 46 & 58 & 63 \\
52 & 37 & 8 & 45 & 33 & 14 & 68 \\
59 & 65 & 56 & 73 & 60 & 64 & 22 \\
\end{bmatrix} \begin{bmatrix}
85 & 56 & 52 & 75 & 89 & 44 & 41 & 68 \\
27 & 15 & 87 & 91 & 32 & 37 & 39 & 73 \\
6 & 7 & 64 & 19 & 99 & 78 & 46 & 16 \\
42 & 21 & 63 & 100 & 4 & 1 & 72 & 13 \\
11 & 97 & 30 & 93 & 28 & 40 & 3 & 36 \\
50 & 70 & 25 & 80 & 58 & 9 & 60 & 84 \\
54 & 96 & 17 & 29 & 43 & 34 & 23 & 35 \\
77 & 61 & 82 & 48 & 2 & 94 & 38 & 66 \\
\end{bmatrix} \begin{bmatrix}
56 & 79 & 90 & 61 & 71 & 122 & 110 & 31 & 55 \\
11 & 44 & 28 & 4 & 85 & 1 & 30 & 6 & 18 \\
84 & 43 & 38 & 66 & 113 & 24 & 96 & 20 & 102 \\
75 & 68 & 5 & 88 & 80 & 98 & 35 & 100 & 77 \\
13 & 21 & 64 & 108 & 10 & 60 & 114 & 40 & 23 \\
47 & 2 & 73 & 106 & 82 & 32 & 120 & 26 & 36 \\
53 & 93 & 69 & 104 & 54 & 19 & 111 & 117 & 62 \\
17 & 27 & 8 & 87 & 33 & 49 & 15 & 58 & 116 \\
95 & 112 & 57 & 118 & 91 & 51 & 42 & 65 & 45 \\
\end{bmatrix}
Plaintext Test Cases:
```
[[8, 5, 6], [11, 10, 1], [3, 15, 13]]
[[21, 10, 12, 16], [17, 6, 22, 14], [8, 5, 19, 26], [13, 24, 3, 1]]
[[1, 13, 8, 16, 5], [9, 40, 21, 26, 22], [11, 24, 14, 39, 28], [32, 19, 37, 3, 10], [30, 17, 36, 7, 34]]
[[34, 21, 40, 22, 35, 41], [18, 33, 31, 30, 12, 43], [19, 11, 39, 24, 28, 23], [44, 1, 36, 5, 38, 45], [14, 17, 9, 16, 13, 26], [8, 3, 47, 6, 25, 4]]
[[20, 36, 17, 1, 15, 50, 18], [72, 67, 34, 10, 32, 3, 55], [42, 43, 9, 6, 30, 61, 39], [28, 41, 54, 27, 23, 5, 70], [48, 13, 25, 12, 46, 58, 63], [52, 37, 8, 45, 33, 14, 68], [59, 65, 56, 73, 60, 64, 22]]
[[85, 56, 52, 75, 89, 44, 41, 68], [27, 15, 87, 91, 32, 37, 39, 73], [6, 7, 64, 19, 99, 78, 46, 16], [42, 21, 63, 100, 4, 1, 72, 13], [11, 97, 30, 93, 28, 40, 3, 36], [50, 70, 25, 80, 58, 9, 60, 84], [54, 96, 17, 29, 43, 34, 23, 35], [77, 61, 82, 48, 2, 94, 38, 66]]
[[56, 79, 90, 61, 71, 122, 110, 31, 55], [11, 44, 28, 4, 85, 1, 30, 6, 18], [84, 43, 38, 66, 113, 24, 96, 20, 102], [75, 68, 5, 88, 80, 98, 35, 100, 77], [13, 21, 64, 108, 10, 60, 114, 40, 23], [47, 2, 73, 106, 82, 32, 120, 26, 36], [53, 93, 69, 104, 54, 19, 111, 117, 62], [17, 27, 8, 87, 33, 49, 15, 58, 116], [95, 112, 57, 118, 91, 51, 42, 65, 45]]
```
Please ask for more if you solve them all. :-) And many thanks to the people who helped me refine this challenge while [in the sandbox](https://codegolf.meta.stackexchange.com/a/16882/70347).
---
1 A reasonable amount of time: any amount of time that doesn't undermine our patience while testing your solution. Note that TIO only runs code for 60 seconds, any amount of time over that limit will make us test the code in our machines. Example: my rather inefficient algorithm takes a few milliseconds to solve matrices of order 3x3 and 4x4, but I have just tested it with a 5x5 matrix and it took 317 seconds to solve it (in over 5 million movements, very funny if we consider that the matrix to solve was scrambled *only* 10K times). I tried to reduce the number of movements to less than 10K but I surrendered after 30 minutes executing the code.
[Answer]
# [Nim](http://nim-lang.org/)
```
import algorithm, math, sequtils, strutils
let l = split(stdin.readLine())
var m = map(l, parseInt)
let n = int(sqrt(float(len(m))))
let o = sorted(m, system.cmp[int])
proc rotations(P, Q: int): tuple[D, L, R, U: string, P, Q: int]=
result = (D: "D", L: "L", R: "R", U: "U", P: P, Q: Q)
if P > n - P:
result.D = "U"
result.U = "D"
result.P = n - P
if Q > n - Q:
result.L = "R"
result.R = "L"
result.Q = n - Q
proc triangle(r: int): string=
let p = r div n
let q = r mod n
let i = find(m, o[r])
let s = i div n
let t = i mod n
var u = s
var v = q
if s == p and t == q:
return ""
var patt = 0
if p == s:
u = s + 1
patt = 4
elif q == t:
if q == n - 1:
v = t - 1
patt = 8
else:
u = p
v = t + 1
patt = 3
elif t > q:
patt = 2
else:
patt = 7
var Q = abs(max([q, t, v]) - min([q, t, v]))
var P = abs(max([p, s, u]) - min([p, s, u]))
let x = p*n + q
let y = s*n + t
let z = u*n + v
let w = m[x]
m[x] = m[y]
m[y] = m[z]
m[z] = w
let R = rotations(P, Q)
result = case patt:
of 2:
repeat("$#$#," % [$v, R.D], R.P) &
repeat("$#$#," % [$u, R.L], R.Q) &
repeat("$#$#," % [$v, R.U], R.P) &
repeat("$#$#," % [$u, R.R], R.Q)
of 3:
repeat("$#$#," % [$q, R.U], R.P) &
repeat("$#$#," % [$p, R.L], R.Q) &
repeat("$#$#," % [$q, R.D], R.P) &
repeat("$#$#," % [$p, R.R], R.Q)
of 4:
repeat("$#$#," % [$p, R.L], R.Q) &
repeat("$#$#," % [$q, R.U], R.P) &
repeat("$#$#," % [$p, R.R], R.Q) &
repeat("$#$#," % [$q, R.D], R.P)
of 7:
repeat("$#$#," % [$v, R.D], R.P) &
repeat("$#$#," % [$u, R.R], R.Q) &
repeat("$#$#," % [$v, R.U], R.P) &
repeat("$#$#," % [$u, R.L], R.Q)
of 8:
repeat("$#$#," % [$s, R.R], R.Q) &
repeat("$#$#," % [$t, R.D], R.P) &
repeat("$#$#," % [$s, R.L], R.Q) &
repeat("$#$#," % [$t, R.U], R.P)
else: ""
proc Tw(p, t, P, Q: int): string =
let S = P + Q
result = "$#D,$#$#U,$#$#D,$#$#U," % [
$t, if P > n - P: repeat("$#L," % $p, n - P) else: repeat("$#R," % $p, P),
$t, if S > n - S: repeat("$#R," % $p, n - S) else: repeat("$#L," % $p, S),
$t, if Q > n - Q: repeat("$#L," % $p, n - Q) else: repeat("$#R," % $p, Q),
$t]
proc line(r: int): string=
let p = n - 1
let q = r mod n
let i = find(m, o[r])
var t = i mod n
if t == q:
return ""
let j = t == n - 1
var P = t - q
let x = p*n + q
let y = x + P
let z = y + (if j: -1 else: 1)
let w = m[x]
m[x] = m[y]
m[y] = m[z]
m[z] = w
if j:
let R = rotations(1, P)
result = "$#D,$#$#U,$#$#R,$#D,$#L,$#U," % [
$t, repeat("$#$#," % [$p, R.R], R.Q),
$t, repeat("$#$#," % [$p, R.L], R.Q),
$p, $t, $p, $t]
else:
result = Tw(p, t, P, 1)
proc swap: string=
result = ""
if m[^1] != o[^1]:
m = o
for i in 0..(n div 2-1):
result &= Tw(n - 1, n - 2*i - 1, 1, 1)
result &= "$#R," % $(n - 1)
var moves = ""
for r in 0..(n^2 - n - 1):
moves &= triangle(r)
if n == 2 and m[^1] != o[^1]:
m = o
moves &= "1R"
else:
for r in (n^2 - n)..(n^2 - 3):
moves &= line(r)
if n mod 2 == 0:
moves &= swap()
if len(moves) > 0:
moves = moves[0..^2]
echo moves
```
[Try it online!](https://tio.run/##5Vddb5tYEH33r5i1uxW0NOLTBkvZJ7@s5Afb2TxZrsQmpKXCgAE7Sf989szciw1J101Wu09bVYY7nJk5Z@ZehuTp9ukp3ZZF1VCcfSmqtPm6tWgbN18tqpPdvkmzGndNJXeDQZY0lNEl1WWWNkbd3Kb5RZXEt/M0TwzTHBziirZ4vo1LI7OojKs6@T1vTHHM8SDN4barGuMuK@LGyJLc2Jr4J4CCI4NLcmuARf1YN8n24mZbruG1MQeDsipuqCqauEmLvDYWFi2nHNGcUrMvs2Q9s2hu0cqi6ymTTvMvFh1Rm8sBUZXU@6xBHmM2peFsCAdc57iucF0NxXV4jetiql2XJvzSO1rQb5DwCQ@wbiNdzBAL@K7pmk2znmkBk/iqUEsdatkLNWe/Vc9vxaZ5z7TUoZa6HpAZ51@yxKjaWijlrJaLWgJf0W16oFxbdmLZFrdHSwrLXZpL2Yt1tTG1veaO9XwbsbS@3O49N03fH3C/UxLheonccX7LPjC3Upt9ldNwqD3KuOGQtnIqGVlPSaASmD6SIysN9LFIMkB3DG1U0HbJZXGUiYRLwwa91gFCWSZZnbRAzlP2nD4@d/LarA0ap5XoR@6gG00bJ1od9yr@sza28YOx3lnUWHTYmCC1TfOOwdTwRRde4gRYtD/Bj4a2Ow9M/EMOujtteeSSiaXRlu@w7MVy0JZ7Pp7rhw2WfJHVo1o9qtV3tfrOq3vtxRuxf/JwHjvH6SauE1Gv6lDckdvWt0rKBEd9@G70bmQN6VdavzvguF3MNvy7MOk9aeQPsXtGzQW7BPYcVMJevyHsSodtOXtnOO/eELx8PefdG0pR/oizf4bzMx70UyInfa/m8Zqwrb6W8@Tf3Bur/2ZvzJ/VOTzDuX5DQZq@vnPQ@g3ta7r6Tu84ftOqOfHHvVHKC6c7NtWooHZWXOEkL/CuWHaPNrLMLM50Lb/tvaSVRJy7Nx87/OaC4x0jj0zN6gRYHQEL0@qGu9Lhrn6Mlkcvw53yXZkWdeOdZu7f0lueo7c8xdvokmb81XNm7OZ6/Lx@6PIU6I9YGToyP@nFAOUo32RiXZ6StYOEZ9/u7KR4wHrRmROPWBvI921KnxxdCcf8x2NDIgnnlwPE4XZ3vmpebrOVpdZzq7/ZVD9/9lKy6BXg@QswzOygrpveZD/y7J4jxyT2Vbuhvo/L7i44KRuqamzXn50N/XKJbuNGheWP5ULu7ooKbU9zsi8ujFw@utxPjnl660i090JAeq32rPshVQv@3yvpe6mp3sDKhZ@rb/TikNSKGuetjnk/u8ApLGdWOEQ6fWWaA0jJece58nX3UlWr6eg8dPBV25bymK9NZh7zelrt0VEdMP39ncuZcDmz/QzHpTc0TP6k4AcmDnwPeKmuawj97HJ3B8nN10IZn0YuOeTjS28UUkBjchxybJg8cgJyYHaVATA8nADh4tYnRjsRuTB65PqMH4wcXoSMDCgi3yY4u8rDYRD8PPiE5Lns7E3YzSbP5sjemPDjD0aez37s7ZIXkI@o8PDIcwTpku@xN0JyMJ/juR75PrPmzF5IfsC5EDQS2h6zQAzyRQBiQpfNaEAcVhrYnGTi0pg5CCkkpwBQyRfBD8nHjhYAUgEyTzhzQBOb/FDSBMIPLEIa44nLGoUO@IPRGGVDKOSDWI/GiIgoLoovJuAnAYURi0EGoJEB7EIIcYTRhPOzJ2oFV5QhwjrklBAKrqjcmIsKRlAGQWCFSkUTph95wh3ipFI2Ewfl0Ga@EdMJfdYVSWHciJVzNzzuw2TC8kOXpboU@Vzn8XgwYimgIcWZoJjSbZu7heohtS8dwo4JSBo45kojD8fmCMDIDkJS9MSxpQZcKApDphaFnJ0VgQFDHVFuh9wlUHZQV94s0l2Xi@PYY@bJmwwR0XoW67H6MfaDLRJlA4Etb2lX1HKjUGg0yo9kSyABahqxCJcC5AZvtCFwuM7ooR88/Y@1/wU "Nim – Try It Online")
A quick attempt to implement the Torus puzzle solution algorithm from an article published in [Algorithms 2012, 5, 18-29](https://www.researchgate.net/publication/220654877_How_to_Solve_the_Torus_Puzzle) that I mentioned in comments.
Accepts the input matrix in flattened form, as a line of space-delimited numbers.
Here also is a validator in [Python 2](https://tio.run/##lVVNb@M2EL37Vwx8WRvQLkSKX14gNx11UqHTdlGoXQcxYMuq5G2bX58OSWlEUkqKBi@2RM7ne0O6f3283Dv@9na59ffhAd3PW/@62w3t3/AE@Pnbpet/Pg7HL2N/veD3rsV1Z/SlHYb29XBr@8Ole2TW@HjcdbiNrwdvMv45PA7Xc3dwm6HzcB5f2v58aDM4dBl0uHm7/3UeN7N@yj4dd/2AcWH/yx9De/v9ev4Bt/YxXP75tdtn0O6e7wPYAJjcfY9fdwCXqRi78O3rZ/b9iIs/cNEt4Lu1ecYVdNo35d762L/x5fL8QDPmd5@eYF/u4Xwdz/CZTTZLK4@h7cb@PmIzx3nz2@X70ur9ej3YlcwHPv5XBJvog1LqVSkfZyPmUN@Etrc3qUCf4JSDYqAZMM6BsRwKBlLiEwgB3IAAg29QoBkwA0aAKKAwoPCVFcAFnBTwHFjOQUtQBiQYtMvhZKBA1zwHrcGaMlAC3w3@g0IPhrFy4AUIDehc4LoCw6HAQjAiV1AokAWcClAn3BQg0R@fsDjGNCi0Q08NmE5DgXFwT4LEBEzByTbBQWJurPuEXWFLHJQEIXd5mbEqQt5krI7RRMjRrIyQ1xl3cbjzLcoZ@NzMqDIR5BJBFlluQNcTZLMBXU1Q5QJRW6hmgagsdDkl0s2U3ZQLvNcaplng46yB7CWgwgjIZwJqjZDwyVZxEgnYKkgiImmRgJeBOg6qslhkclC1BerFqwmoF68nkEYhXSRNyE8iTYhEoxCol0@EevnsoV4ylkZW/1uCj/n3hIRUezaQOkRYJzKMCJsiurijlBjj7lCIGdLx6SHrjclfT7tyVKhyosWDO648rC51wFK1UJSX70xvsz35ySiaKkIyh6aO4FlCWMaaCXbAgpHznIfz5mUSZYQwKdHlEWaceKtjeOqqCOFdEaof3hjR5JQRfDoi32OqcKbdj8oapIWfrjX86EYrblbDIJsisvdFJP7trM66iDrSwsRCmEAF4oFoX@7kcsV2yHNwtMMbwNNI7XgCqV8ikIiiE51MIB3kZPbCmzO8JKl3E8ykcTPpKynmMugMLtM1n0HKrjZV3lJWO1p0GR3MpOblKkt6XDW@bjk5nsl55POQ83mqJ8Wd8SS3sxTOUjiz5Jd3@Z31oIHcOhTRWai3sNUp9UttTt257MzVE5ZNNYeXA6VQLrVyWfQ7Zeh3ajBeJndz8tmXB8Y0QjKOLFcBvQGuq9hSrSyp4KTadZHeQAcxVfNRnDAC@dJDvP4v). It takes two lines as input: the original scrambled matrix in the same form as the main code, and the proposed sequence of moves. The output of the validator is the matrix resulting from applying these moves.
## Explanation
In the first part of the algorithm, we order all rows except the last one.
We do this by performing series of "triangle rotations" (`proc triangle`) - the sequences of moves that result in only three cells swapping places, and all the rest staying unchanged. We take each consecutive "working" cell with coordinates \$[p, q]\$, then find the cell \$[s, t]\$ that currently contains the number that should go to \$[p, q]\$, and complete the right triangle by selecting a third point \$[u, v]\$ according to some pattern, as shown in Fig. 4 of the linked article.
In Fig. 2, the authors present 8 possible patterns and the corresponding sequences of moves, but in my code all cases have actually been covered by only 5 patterns, so that no. 1, 5, and 6 are not used.
In the second part, the last row except the two last elements is ordered by performing "three elements rotations" on a line (`proc line`), which consist of two triangle rotations each (see Fig. 3 of the article).
We select our current working cell \$[p, q]\$ as the left point, cell containing the target value \$[s, t]\$ as the central point, and \$[s, t+1]\$ as the right point. This westbound movement is named \$T\_W\$ in the article, and so is my string forming proc for this. If \$t\$ is already the last column, so that \$t+1\$ does not exist, we take \$[s, t-1]\$ as the third point, and modify the action accordingly: two triangle rotations are performed by patterns 7 and 8 (instead of 7 and 1 in the original \$T\_W\$ sequence).
Finally, if \$n\$ is odd, the remaining two elements must be already in place, as we are guaranteed that a solution exists.
If \$n\$ is even, and the two remaining elements are not in place, then according to Lemma 1 (page 22), they can be swapped by a series of \$T\_W\$ moves, followed by one shift east (\$=R\$). Since the provided example swaps the first two entries, and we need to swap the last two, our `proc swap` performs \$T\_W\$ moves in reverse order.
In the edge case of \$n = 2\$ we don't need all these complex procedures at all - if the last row elements are not in place after part 1, a single \$1R\$ move is sufficient to make the matrix fully ordered.
**Update:** Added new `proc rotations` that reverses the direction of moves if that would result in less steps.
[Answer]
# [Python 2](https://docs.python.org/2/), size 100 in <30 seconds on TIO
```
import random
def f(a):
d = len(a)
r = []
def V(j, b = -1):
b %= d
if d - b < b:
for k in range(d - b):
if r and r[-1] == "U%d" % j:r.pop()
else:r.append("D%d" % j)
b = a[-1][j]
for i in range(len(a) - 1):
a[-1 - i][j] = a[-2 - i][j]
a[0][j] = b
else:
for k in range(b):
if r and r[-1] == "D%d" % j:r.pop()
else:r.append("U%d" % j)
b = a[0][j]
for i in range(len(a) - 1):
a[i][j] = a[i + 1][j]
a[-1][j] = b
def H(i, b = -1):
b %= d
if d - b < b:
for k in range(d - b):
if r and r[-1] == "L%d" % i:r.pop()
else:r.append("R%d" % i)
a[i] = a[i][-1:] + a[i][:-1]
else:
for k in range(b):
if r and r[-1] == "R%d" % i:r.pop()
else:r.append("L%d" % i)
a[i] = a[i][1:] + a[i][:1]
b = sorted(sum(a, []))
for i in range(d - 1):
for j in range(d):
c = b.pop(0)
e = sum(a, []).index(c)
if e / d == i:
if j == 0:H(i, e - j)
elif j < e % d:
if i:
V(e % d, 1)
H(i, j - e)
V(e % d)
H(i, e - j)
else:
V(e)
H(1, e - j)
V(j, 1)
else:
if j == e % d:
H(e / d)
e += 1
if e % d == 0:e -= d
if i:
V(j, i - e / d)
H(e / d, e - j)
V(j, e / d - i)
c = [b.index(e) for e in a[-1]]
c = [sum(c[(i + j) % d] < c[(i + k) % d] for j in range(d) for k in range(j)) % 2 and d * d or sum(abs(c[(i + j) % d] - j) for j in range(d)) for i in range(d)]
e = min(~c[::-1].index(min(c)), c.index(min(c)), key = abs)
H(d - 1, e)
for j in range(d - 2):
e = a[-1].index(b[j])
if e > j:
c = b.index(a[-1][j])
if c == e:
if e - j == 1:c = j + 2
else:c = j + 1
V(e)
H(d - 1, j - e)
V(e, 1)
H(d - 1, c - j)
V(e)
H(d - 1, e - c)
V(e, 1)
return r
```
[Try it online!](https://tio.run/##tVbLbtpAFN37K0aRkGYak@JH0gSFrlhkwQop3VhegD00doJBNpGaTX@dnntnbGNDKa3USMie@zxnzh1Pth@7l03h7/fZerspd6JcFOlm7aR6JVZyocaOSMVEvOkCC0eUeI9i2OD@JnNXLGEYehSG18FEpHjJVsgZYv0oluQQq00pXkVWUPHvWrKTUzi2FGgpymjoxWIyEVfPg/RKDEQ@Lm@2m61UHKffKg3DYrvVRSqvpjbGOAnEgvKjPGYDNczahgY9unq2K0djnVGGSfbrpWP8I@taOrb5CSJnSEwvIPF8gsTobzi08DNxLbwD9GYvDHzS6klm/0WrmaGQnaM5tzHKqVEbyDGqjGMA5/cxSv7bVs8vwDD7LYZDCISANqnCQdCprN7XcuFi3hXSenKkjRLkyA8cBmhCe894RtxTU9mm3k1WpPqHTNgFSlp8pmM2AYmaZU7L0ZiF02iW17zY9wjbQKR2EmCyiQKnkj0u0FkLl8hRQqtuTCfgoEcrgolt47xunPkEmEZtTg3@EOGTZIp1fXE9EV6DnQMNXVQ3c9khxW0yYtAWsRU7gDjO7OWQtSYVoqXdba1YK01a8QmJbQDpkkSSzlCuCEuM/bWGV2s4Urk/oLmiSJ9nMxWf8IOfFV9W/eoE@LiiOpoxBYQ0OOuskD@TaExnxJIhU6KUK5K@4VV/0GwvK/B/MnPqsvT9hvD4PKy6/nzaUkt8OpRjpfmKb1g70Cag/r7U45uw3I36rAiZvDFl5WDut4eyNrH@9XQ1QNs5hauercabNFofJVLTpJtY6t17Cbr7BansRPeuuHXFXew6kYcMb4QfLQI84fACTMS2zIqdWNgn3YCNyVbx61QfP1PsC6q6widDSAbTyHuAzQSggx@6ghpd1CNAMPUJR6ZsgHIhY/VQO0CdAN7AoggD9qAd0QoeTDMfkT57QqzIccewAtjDW84gO7BT4h3xr/HeM9TQ0qLe51HTDVPKioaJCZgBq3AK8GHhB/Sujua7UvY/iSlOj7mVOvf4H27A83d45wanJs@dJqNLe5y@Y49v2LnMOOX8/UaRsxOR/VuoB8sb4Y@TzL9nN8nLJku0jKbuszt3Z7GS1kGPenfbI2AGq6Q6qickMSYxG/v@Fw "Python 2 – Try It Online") Link includes three small test cases with full move output, plus a silent test of 100x100 to show that the code works (the move output would exceed TIO's limits). Explanation: The code attempts to perform an insertion sort on the array, building it up in ascending order as it goes. For all the rows except the last row, there are a number of cases:
* The element is in the correct row, but belongs in column 0. In this case, it is simply rotated until it reaches column 0.
* The element is in the correct place. In this case, nothing happens. (This is also true if the element belongs in column 0, it's just that 0 rotations happen in that case.)
* The element is in the top row but in the wrong column. In that case, it is rotated down, then horizontally until the element is in the correct column, then rotated up again.
* The element is in the correct row but in the wrong column. In that case, it is rotated up, then the row is rotated to its column, then it is rotated down, then the row is rotated back. (Effectively this is a rotation of the next case.)
* The element is in the correct column but in the wrong row. In that case, the row is rotated right, to reduce it to the last case.
* The element is in the wrong row and the wrong column. In this case, the correct column is rotated to the wrong row (skipped for the top row), that row is then rotated to the correct column, and the column is then rotated back.
The above rotations are performed in whichever direction minimises the number of steps; a size 2 square is always solved using left and up moves, regardless of the description above.
Before the bottom row is completed, it is rotated to minimise the total distance out of place, but also to ensure that the parity of the bottom row is even, as it can't be changed by the final part of the algorithm. If there is more than one rotation with the same minimal distance, the rotation with the smallest number of moves is chosen.
The algorithm for the bottom row relies on a 7-operation sequence which exchanges the elements in three columns. The sequence is applied to each of the remaining numbers of the bottom row in order in turn to bring them to their desired location; if possible the element in that location is moved to its desired location, but if a straight swap is needed the element is simply moved to the nearest available column, hopefully allowing it to be fixed up next time.
] |
[Question]
[
## Block shuffle sort
The *block shuffle sort* is a (rather artificial) method of sorting a list.
It works as follows, illustrated by an example.
```
[6, 1, 0, 3, 2, 4, -2, -1]
Break list into contiguous blocks
[6][1, 0][3, 2, 4][-2, -1]
Sort each block
[6][0, 1][2, 3, 4][-2, -1]
Sort blocks lexicographically
[-2, -1][0, 1][2, 3, 4][6]
Concatenate
[-2, -1, 0, 1, 2, 3, 4, 6]
```
The partition into contiguous blocks can be chosen arbitrarily.
However, not all choices of blocks will yield a sorted list at the end:
```
[6, 1, 0, 3, 2, 4, -2, -1]
[6, 1, 0][3, 2, 4][-2, -1]
[0, 1, 6][2, 3, 4][-2, -1]
[-2, -1][0, 1, 6][2, 3, 4]
[-2, -1, 0, 1, 6, 2, 3, 4]
```
If all blocks have length 1, or if there is only one block, then the result will of course be sorted.
But these are rather extreme cases.
In this challenge, your task is to find a balance between the number of blocks and the maximum length of a block.
## The task
Your input is a nonempty list of integers **L**, taken in any reasonable format.
Your output shall be the smallest integer **N** such that **L** can be block shuffle sorted so that the number of blocks and the length of each block are at most **N**.
The lowest byte count in each language wins.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test cases
```
[5] -> 1
[1,2] -> 2
[0,2,1,-1] -> 3
[-1,0,2,1] -> 2
[9,3,8,2,7] -> 4
[9,2,8,3,7] -> 3
[5,9,3,7,2,4,8] -> 7
[-1,-2,1,2,-1,-2,7] -> 4
[6,1,0,3,2,4,-2,-1] -> 4
[12,5,6,-6,-1,0,2,3] -> 3
[1,0,1,0,1,0,1,0,1,0] -> 6
[1,2,1,3,1,2,3,2,4,3] -> 5
[7,7,7,7,8,9,7,7,7,7] -> 4
```
[Answer]
## [Brachylog](https://github.com/JCumin/Brachylog), ~~23~~ ~~22~~ ~~20~~ 19 bytes
*Thanks to Zgarb, H.PWiz and Fatalize for saving some amount of bytes.*
```
~cᶠ{oᵐoc≤₁&≡ᵃlᵐ⌉}ˢ⌋
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3wvy754bYF1flAZn7yo84lj5oa1R51Lny4tTkHKPSop7P29KJHPd3//0crRJvG6ihEG@oYgSgDHSMdQ514QxA73lAHzAWxLXWMdSyAHHMIxwjIMQZyFGIB "Brachylog – Try It Online")
I'm sure there's more to golf here...
### Explanation
```
~cᶠ Find all lists that concatenate into the input, i.e. all partitions
of the input.
{ Discard all partitions for which this predicate fails, and replace
the rest with the output of this predicate.
oᵐ Sort each sublist of the partition.
o Sort the entire list.
c≤₁ And require concatenation of the result to be sorted.
& Then:
≡ᵃ Append the partition to itself.
lᵐ Map "length" over this list, i.e. we get the length of each block, as
well as the length of the partition itself.
⌉ Take the maximum.
}ˢ
⌋ Take the minimum of all those maxima.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Ṣ€ṢF
ŒṖÇÐṂ+Z$€L€Ṃ
```
[Try it online!](https://tio.run/##XU67EUIhEMxfHWYuMw@Qjw0Y2YAyhCbOa8CU5KWOgQUY2wAxYyHYCB6fyGHgdu@Wvb1eluVWSo6vb3jTe5g@jxyfaU33HMP2vKH2sY1CSSuBUynOKT/BcYhaZghwMF4x42i04j0kLBHTiSAiO1GoM0OtHez4xqqJQEdNpVHNZFMxMRZwAQUNpjFWyZ5kxt8dAQnKZtx9mtqgH0sxBvaT/wE "Jelly – Try It Online")
### Alternate version, 15 bytes, postdates challenge
In the latest version, `Ɗ` combines three links into a monadic chain. This allows the following golf.
```
ŒṖṢ€ṢFƊÐṂ+ZLƊ€Ṃ
```
[Try it online!](https://tio.run/##XY49DgIhEIX7vYqPZAH58QJWXkAJpY3ZC9jSmGxlLDyAtReg3rj3wIvg8FMZAnxveLyZy3marjl/Hik@U3x9w5vO/Tov9xTD5nRY51oKebkRHHN2TvkBjkOUa4QAB@OFGUeVhXeQsCRME4KEbEKhvBkqbWH7N1ZCBBpVl0YJk9XFRG/ABRQ0mEZvJdskI/52H5BQ1uCWU90GbVkao7Mf/A8 "Jelly – Try It Online")
### How it works
```
Ṣ€ṢF Helper link. Argument: P (partitioned array)
Ṣ€ Sort each chunk.
Ṣ Sort the sorted chunks.
F Flatten.
ŒṖÇÐṂ+Z$€L€Ṃ Main link. Argument: A (array)
ŒṖ Generate all partitions of A.
ÇÐṂ Keep those for which the helper link returns the minimal array, i.e.,
those that return sorted(A).
+Z$€ Add each partition to its transpose.
Due to how Jelly vectorizes, the length of the sum is the maximum of
the length of the operands, and the length of the transpose is the
length of the array's largest column.
L€ Take the length of each sum.
Ṃ Take the minimum.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~28~~ ~~26~~ ~~25~~ ~~24~~ 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437
```
é%(>ù│ê²☻û◙T╠►╜◘íaæAtI╥
```
[Run and debug online!](https://staxlang.xyz/#p=8225283e97b388fd02960a54cc10bd08a16191417449d2&i=%5B5%5D%0A%5B1,2%5D%0A%5B0,2,1,-1%5D%0A%5B-1,0,2,1%5D%0A%5B9,3,8,2,7%5D%0A%5B9,2,8,3,7%5D%0A%5B5,9,3,7,2,4,8%5D%0A%5B-1,-2,1,2,-1,-2,7%5D%0A%5B6,1,0,3,2,4,-2,-1%5D%0A%5B12,5,6,-6,-1,0,2,3%5D%0A%5B1,0,1,0,1,0,1,0,1,0%5D%0A%5B1,2,1,3,1,2,3,2,4,3%5D%0A%5B7,7,7,7,8,9,7,7,7,7%5D&a=1&m=2)
*Credits to @recursive for saving 3 bytes.*
Stax is a bit verbose here. It takes two bytes to sort an array by default, two bytes to get the maximum/minimum of an array and two bytes to flatten an array. Anyway I am still posting the solution ~~and hope there can be helpful suggestions on how to improve it~~ there is.
## Explanation
Uses the unpacked version to explain.
```
%cFxs|!F{{omo:f:^!C_Mch\%|m
%cFxs|!F Do for all partitions, grouped by number of sub-arrays
Grouping by number of sub-arrays in this problem does not help but it's the default
{{om{o Sort inside block then sort blocks lexicographically
:f:^ The result when flattened is sorted
!C Skip the rest of the loop if the last line is false
_|< Take the current partition, pad to the longest
h Take the first element, whose length is now the maximum of all sub-arrays in the original partition
\ Zip with the current partition, the shorter one is repeated
% Number of elements
Which is the maximum of all sub-array sizes and the number of sub-arrays in the current partition
|m Take the minimum among all choices of partitions
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
```
~c₎{oᵐoc≤₁&lᵐ⌉≤}ᵈ
```
[Try it online!](https://tio.run/##XY5NCsIwEIWv4srVWzQTm9SrWELQLnRRCLgTUbALsSDiITyAmx6ouUic/KwkhLxv8ubN7I7b7nDq3Z6Cv3/9cJund7h2fnidHUvX@fHD1WXP4J8j02WeHiG0bW2waAUoPhUIAlZEbQUSRr2GRMOgMxCDzFAj/mkurdCUNhtDCFkll0IMk8llqQwQhBoKVqGMknmTCn@3LMhSpuCck9wa@TS8RtHGhM0P "Brachylog – Try It Online")
## Explanation
This is a self-answer; I designed this challenge with Brachylog in mind and found `~c₎{…}ᵈ` an interesting construct.
The built-in `c` concatenates a list of lists.
If it is given a subscript `N`, it requires the number of lists to be `N`.
The symbol `₎` modifies a built-in to take a pair as input and use its right element as the subscript.
Thus `c₎` takes a pair `[L,N]`, requires that the number of lists in `L` is `N`, and returns the concatenation of `L`.
When run in reverse, `~c₎` takes a list `L` and returns a pair `[P,N]`, where `P` is a partition of `L` into `N` blocks.
They are enumerated in increasing order of `N`.
The metapredicate `ᵈ` transforms an ordinary predicate into one that checks a relation between the two elements of a pair.
More explicitly, `{…}ᵈ` takes a pair `[A,B]`, checks that `A{…}B` holds, and outputs `B`.
I use it to verify that `P` can be block-sorted and only contains lists of length at most `N`.
```
~c₎{oᵐoc≤₁&lᵐ⌉≤}ᵈ Input is a list, say L = [9,2,8,3,7].
~c₎ Guess the pair [P,N]: [[[9],[2],[8,3,7]],3]
{ }ᵈ Verify this predicate on P and N and return N:
oᵐ Sort each list in P: [[9],[2],[3,7,8]]
o Sort lexicographically: [[2],[3,7,8],[9]]
c Concatenate: [2,3,7,8,9]
≤₁ This list is nondecreasing: true.
&lᵐ Length of each list in P: [1,1,3]
⌉ Maximum: 3
≤ This is at most N: true.
```
Note that `P` may contain empty lists.
This ensures correctness also in those cases where the maximal length of a block is greater than the number of blocks.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~186~~ 146 bytes
```
lambda l:min(max(map(len,z+[z]))for z in p(l)if sum(s(z),[])==s(l))
p=lambda l:[q+[s(l[i:])]for i in range(len(l))for q in p(l[:i])]or[l]
s=sorted
```
[Try it online!](https://tio.run/##bZDdboMwDIXv/RS@K1HNVML6MyT2IlkumMq2qPyV0Gmj6rMzJ6nWqkIo6GCOT@yv@x2@2kZOh/xtqor6fV9gldWmierih08XVWVD41KNWoiPtscRTYNcFeYD7amObDQKUlrkueWigC7/T1HHpeKiMpkW2vUa19sXzWfpUp3dVY/XRJUZ9rW9qjTY3Lb9UO6nobSDxRyVWmtSCUl@r0hSQnHCMk7If7F8oZR2rLdeS9ap12tyf7ZceaZdaIldv6SgnGdDLif1nliG6ETSmjYUb@h6SeoHWNHDCWOxSn1oCHHeLYVnxwNctdYAbuXvojqVbm2/XgaIXW@aARfnC8aveL4snthWF0PknYSHIISYmAN4DnDjADcOcMcB7jjAAweY4QAzHGCOA8xygFkOMMvhDw "Python 2 – Try It Online")
The second function is taken from [this tip](https://codegolf.stackexchange.com/a/53046/64121) by [feersum](https://codegolf.stackexchange.com/users/30688/feersum).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 158 bytes
```
f=->l,i=[],s=l.size,m=s{k=*l;i.sum==s&&i.map{|z|k.shift(z).sort}.sort.flatten==l.sort&&[m,[i.size,*i].max].min||i.sum<s&&(1..s).map{|z|f[l,i+[z],s,m]}.min||m}
```
[Try it online!](https://tio.run/##fVB/b4IwEP3fT9FoQtQdjRQBl637Ik2zOAezCGpsSRw/Pjs7Wpxmf4yG9u69u3evvVQf332fcf@tAMWFBM0LqlWdQsl1c@DL4kVRXZWca89TtNyem7ZuD1TvVWbm9YLq08V0dqdZsTUmPfJBAXPPEyUI5dSWSmLzFTd1bFsr@YqK84BSvbjJZgJNPIkaXUApO1dbdv25MppM1RFP8s/3dTIkvZ7TnUk/pxMxIUSISAIJJNg4AIYZG7MVMAjAR5KEI@QHYNGHqmcIYYNYgtj6F2OIhRa7tUYwVCbIrGGDeHKX9Ic5DFz0qBPDMC@0PT5zVm5cwCCCGPwYRlPhw7AB@fMjG9@viUhohzrxoTca2QTc2qDhMbZjJ5Km292eNK2CvCXuyWeNoub0rmmRV9qQcNXhM8@aTCjporybdv0P "Ruby – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~24 23~~ 20 bytes
```
hSmeSlMs]Bd.msSSMb./
```
**[Test suite.](https://pyth.herokuapp.com/?code=hSmeSlMs%5DBd.msSSMb.%2F&test_suite=1&test_suite_input=%5B5%5D%0A%5B1%2C2%5D%0A%5B0%2C2%2C1%2C-1%5D%0A%5B-1%2C0%2C2%2C1%5D%0A%5B9%2C3%2C8%2C2%2C7%5D%0A%5B9%2C2%2C8%2C3%2C7%5D%0A%5B5%2C9%2C3%2C7%2C2%2C4%2C8%5D%0A%5B-1%2C-2%2C1%2C2%2C-1%2C-2%2C7%5D%0A%5B6%2C1%2C0%2C3%2C2%2C4%2C-2%2C-1%5D%0A%5B12%2C5%2C6%2C-6%2C-1%2C0%2C2%2C3%5D%0A%5B1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%5D%0A%5B1%2C2%2C1%2C3%2C1%2C2%2C3%2C2%2C4%2C3%5D%0A%5B7%2C7%2C7%2C7%2C8%2C9%2C7%2C7%2C7%2C7%5D&debug=0)**
### How it works
```
hSmeSlMs]Bd.msSSMb./ – Full program. Hereby, Q represents the input.
./ – All possible partitions of Q.
.m – Take the partitions which yield a minimal (i.e. sorted) list over:
sSSMb – Sorting function. Uses the variable b.
SMb – Sort each list in each partition b.
S – Sort the partition b.
s – And flatten (by 1 level).
meSlMs]Bd – Map. Uses a function whose variable is d.
]Bd – Pair d with its wrapping in a singleton list. Returns [d, [d]].
s – Flatten (by 1 level). Returns [*d, d], where "*" is splatting.
lM – Take the length of each element.
eS – Retrieve the maximal length.
hS – Return the minimum element of the list of maximal lengths.
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~71~~ 67 bytes
```
{⌊/(⌈/≢,≢¨)¨T/⍨{S[⍋S]≡∊⍵[⍋↑⍵]}¨T←{⍵[⍋⍵]}¨¨⊂∘S¨(-≢S)↑¨2⊥⍣¯1¨⍳2*≢S←⍵}
```
`⎕IO` must be `0`
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud9UT/9HbRMMuNyAZPWjni59jUc9HfqPOhfpAPGhFZqHVoToP@pdUR0c/ai3Ozj2UefCRx1dj3q3griP2iYCWbG1QDVg3VBRiNChFY@6mh51zAg@tEJDF2hWsCZQ@aEVRo@6lj7qXXxovSFQQe9mIy2QFFA3UFctF9A5QKabgrkOBFroWEJZ5v//AwA "APL (Dyalog Classic) – Try It Online")
## How?
* `⌊/` - **Find the minimum of ...**
* `(⌈/≢,≢¨)` - **... the maximum of the length and number of elements ...**
* `¨` - **... of each element of ...**
* `T/⍨` - **... the elements that ...**
* `{S[⍋S]≡∊⍵[⍋↑⍵]}¨` - **... are sorted when flattened, of ...**
* `T←{⍵[⍋⍵]}¨¨` - **... the sorted elements of the elements of ...**
* `⊂∘S¨(-≢S)↑¨2⊥⍣¯1¨⍳2*≢S←⍵` - **... the partitions of the argument (along with some junk)**
] |
[Question]
[
Given a directed graph, output the longest cycle.
## Rules
* Any reasonable input format is allowed (e.g. list of edges, connectivity matrix).
* The labels are not important, so you may impose any restrictions on the labels that you need and/or desire, so long as they do not contain additional information not given in the input (e.g. you can't require that the nodes in cycles are labeled with integers, and other nodes are labeled with alphabetic strings).
* A cycle is a sequence of nodes that are all connected, and no node is repeated, other than the node that is the start and end of the cycle (`[1, 2, 3, 1]` is a cycle, but `[1, 2, 3, 2, 1]` is not).
* If the graph is acyclic, the longest cycle has length 0, and thus should yield an empty output (e.g. empty list, no output at all).
* Repeating the first node at the end of the list of nodes in the cycle is optional (`[1, 2, 3, 1]` and `[1, 2, 3]` denote the same cycle).
* If there are multiple cycles of the same length, any one or all of them may be output.
* Builtins are allowed, but if your solution uses one, you are encouraged to include an alternate solution that does not use trivializing builtins (e.g. a builtin that outputs all cycles). However, the alternate solution will not count towards your score at all, so it is entirely optional.
## Test Cases
In these test cases, input is given as a list of edges (where the first element is the source node and the second element is the destination node), and the output is a list of nodes without repetition of the first/last node.
```
[(0, 0), (0, 1)] -> [0]
[(0, 1), (1, 2)] -> []
[(0, 1), (1, 0)] -> [0, 1]
[(0, 1), (1, 2), (1, 3), (2, 4), (4, 5), (5, 1)] -> [1, 2, 4, 5]
[(0, 1), (0, 2), (1, 3), (2, 4), (3, 0), (4, 6), (6, 8), (8, 0)] -> [0, 2, 4, 6, 8]
[(0, 0), (0, 8), (0, 2), (0, 3), (0, 9), (1, 0), (1, 1), (1, 6), (1, 7), (1, 8), (1, 9), (2, 1), (2, 3), (2, 4), (2, 5), (3, 8), (3, 1), (3, 6), (3, 7), (4, 1), (4, 3), (4, 4), (4, 5), (4, 6), (4, 8), (5, 0), (5, 8), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 9), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 8), (7, 9), (8, 0), (8, 1), (8, 2), (8, 5), (8, 9), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6)] -> [0, 9, 6, 7, 8, 2, 5, 4, 3, 1]
[(0, 0), (0, 2), (0, 4), (0, 5), (0, 7), (0, 9), (0, 11), (1, 2), (1, 4), (1, 5), (1, 8), (1, 9), (1, 10), (2, 0), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 0), (3, 1), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 11), (4, 1), (4, 3), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (5, 0), (5, 4), (5, 6), (5, 7), (5, 8), (5, 11), (6, 0), (6, 8), (6, 10), (6, 3), (6, 9), (7, 8), (7, 9), (7, 2), (7, 4), (7, 5), (8, 8), (8, 9), (8, 2), (8, 4), (8, 7), (9, 0), (9, 1), (9, 2), (9, 3), (9, 6), (9, 10), (9, 11), (10, 8), (10, 3), (10, 5), (10, 6), (11, 2), (11, 4), (11, 5), (11, 9), (11, 10), (11, 11)] -> [0, 11, 10, 6, 9, 3, 8, 7, 5, 4, 1, 2]
```
[Answer]
## Mathematica, 80 58 bytes
*Saved a whopping 22 bytes thanks to JungHwan Min*
```
(FindCycle[#,∞,All]/.{}->{Cases[#,v_v_]})[[-1,;;,1]]&
```
`` is the three byte private use character `U+F3D5` representing `\[DirectedEdge]`. Pure function with first argument `#` expected to be a list of directed edges. Finds `All` cycles of length at most `Infinity` in `Graph@#`, then replaces the empty list with the list of self-loops. Cycles are represented as lists of edges and sorted by length, so we take the last such cycle, then from all of its edges we take the first argument so that we get a list of vertices in the specified output format.
If only Mathematica treated loops as a cycle of length `1` (`AcyclicGraphQ @ CycleGraph[1, DirectedEdges -> True]` gives `True`, seriously), then we could save another `26` bytes:
```
FindCycle[#,∞,All][[-1,;;,1]]&
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~157 154~~ 150 bytes
```
import Data.List
g#l=nub[last$(e:d):[d|p==last q||e`elem`init d]|d@(p:q)<-l,[e,f]<-g,p==f]
h g=snd$maximum$((,)=<<length)<$>[]:until((==)=<<(g#))(g#)g
```
[Try it online!](https://tio.run/nexus/haskell#Hc6xasMwEAbg3U9xEA0SXEqSJouQQocshWwdhSAqUmSBpDjxmXbwu7tyl@@O@//hllSGx4vg4si9XdNIXdxkXadvk91IjAfphTR@HrReD/Cc53ALOZRbqonA29l/8EE@hdpmNAHvVm0jtvbddj1EPVbPivtNZSqMcxRaqRxqpF4odjZWTpVS5lzrNeFxI8RKXCJICcZ8VrK2i6DbvsO9RbPHw7/vzQMem0c8NU8ttV1xqbbyMNEXva4VGIz946eN9svyBw "Haskell – TIO Nexus")
Thanks @Laikoni and @Zgrab for saving a bunch of bytes!
This is a very inefficient program:
The first function `#` takes a list of paths `l` (a list of lists of numbers) and tries to extend the elements of `l` by prepending every possible edge (a list of length 2) of `g` to each element of `l`. This happens only if the element of `l` isn't already a cycle *and* if the new node that would be prepended is not already contained in the element of `l`. If it is already a cycle, we do not prepend anything but add it again to the new list of paths, if we can extend it, we add the extended path to the new list, otherwise we don't add it to the new list.
Now the function `h` repeatedly tries to extend those paths (starting with the list of edges itself) until we reach a fixed point, i.e. we cannot extend any path any further. At this point we only have cycles in our list. Then it is just a matter of picking the longest cycle. Obviously the cycles appear multiple times in this list since every possible cyclic rotation of a cycle is again a cycle.
[Answer]
# Pyth, 20 bytes
```
eMefqhMT.>{eMT1s.pMy
```
[Test suite](https://pyth.herokuapp.com/?code=eMefqhMT.%3E%7BeMT1s.pMy&test_suite=1&test_suite_input=%5B%280%2C+0%29%2C+%280%2C+1%29%5D%0A%5B%280%2C+1%29%2C+%281%2C+2%29%5D%0A%5B%280%2C+1%29%2C+%281%2C+0%29%5D%0A%5B%280%2C+1%29%2C+%281%2C+2%29%2C+%281%2C+3%29%2C+%282%2C+4%29%2C+%284%2C+5%29%2C+%285%2C+1%29%5D%0A%5B%280%2C+1%29%2C+%280%2C+2%29%2C+%281%2C+3%29%2C+%282%2C+4%29%2C+%283%2C+0%29%2C+%284%2C+6%29%2C+%286%2C+8%29%2C+%288%2C+0%29%5D&debug=0)
Takes a list of edges, like in the examples.
Explanation:
```
eMefqhMT.>{eMT1s.pMy
eMefqhMT.>{eMT1s.pMyQ Variable introduction
yQ Take all subsets of the input, ordered by length
.pM Reorder the subsets in all possible ways
s Flatten
(This should be a built in, I'm going to make it one.)
f Filter on (This tests that we've found a cycle)
qhMT The list of first elements of edges equals
eMT The last elements
.> 1 Rotated right by 1
{ Deduplicated (ensures no repeats, which would not be a
simple cycle)
e Take the last element, which will be the longest one.
eM Take the last element of each edge, output.
```
[Answer]
# Bash + bsdutils, 129 bytes
```
sed 's/^\(.*\) \1$/x \1 \1 x/'|sort|(tsort -l>&-)|&tr c\\n '
'|sed 's/x //g'|awk 'm<NF{m=NF;gsub(/[^0-9 ] ?/,"");print}'|tail -1
```
[tsort](https://www.freebsd.org/cgi/man.cgi?query=tsort) does all the heavy lifting, but its output format is rather unique and it doesn't detect cycles of length 1. Note that this doesn't work with GNU tsort.
### Verification
```
--- t1 ---
0
--- t2 ---
--- t3 ---
0 1
--- t4 ---
1 2 4 5
--- t5 ---
0 2 4 6 8
--- t6 ---
0 2 1 6 3 7 4 8 9 5
--- t7 ---
0 11 10 3 1 2 4 7 5 8 9 6
```
[Answer]
# JavaScript (ES6), ~~173~~ ~~163~~ ~~156~~ ~~145~~ 139 bytes
*Saved 5 bytes thanks to @Neil*
```
f=(a,m,b=[])=>a.map(z=>!([x,y]=z,m&&x-m.slice(-1))&&b.length in(c=(n=m||[x],q=n.indexOf(y))?~q?b:f(a.filter(q=>q!=z),[...n,y]):n)?b=c:0)&&b
```
### Test snippet
```
f=(a,m,b=[])=>a.map(z=>!([x,y]=z,m&&x-m.slice(-1))&&b.length in(c=(n=m||[x],q=n.indexOf(y))?~q?b:f(a.filter(q=>q!=z),[...n,y]):n)?b=c:0)&&b
g=a=>console.log("Input:",JSON.stringify(a),"Output:",JSON.stringify(f(a)))
g([[0,0]])
g([[0,1],[1,2]])
g([[0,1],[1,0]])
g([[0,1],[1,2],[2,0]])
g([[0,1],[1,2],[1,3],[2,4],[4,5],[5,1]])
g([[0,1],[0,2],[1,3],[2,4],[3,0],[4,6],[6,8],[8,0]])
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~109~~ 108 bytes
```
import Data.List
f g=last$[]:[b|n<-[1..length g],e:c<-mapM(\_->g)[1..n],b<-[snd<$>e:c],b==nub(fst<$>c++[e])]
```
A brute force solution: generate all lists of edges of increasing lengths until the length of the input, keep those that are cycles, return the last one.
Takes the graph in the format `[(1,2),(2,3),(2,4),(4,1)]`.
[Try it online!](https://tio.run/nexus/haskell#HY7NCoMwEITvPsUePERcpf5dgvHUS6F9gjSUaDUNaComvfXd7dbDfDA7M7C7Xdb3FuCsg86v1odoAiNm7UMsFZf917WZLPJ8Hp0JLzAKRz602aLXG7s/ss4k/9Qp7Knn3bONOyqQFcJ9ejb5QJchTeWoErUb4Bwku7iApERFBgT5ExYJsgLLgxWxxJpYY0NsjrQiqmjR1tFk3awLEAP9uv8A "Haskell – TIO Nexus")
## Explanation
```
f g= -- Define function f on input g as
last$ -- the last element of the following list
[]: -- (or [], if the list is empty):
[b| -- lists of vertices b where
n<-[1..length g], -- n is between 1 and length of input,
e:c<- -- list of edges with head e and tail c is drawn from
mapM(\_->g)[1..n], -- all possible ways of choosing n edges from g,
b<-[snd<$>e:c], -- b is the list of second elements in e:c,
b== -- and b equals
nub(fst<$>c++[e])] -- the de-duplicated list of first elements
-- in the cyclic shift of e:c.
```
[Answer]
# MATLAB, ~~291~~ 260 bytes
Takes an adjecency matrix `A` where an edge `(i,j)` is denoted by a `1` in `A(i,j)`, and `A` is zero in all other entries. The output is a list of a longest cycle. The list is empty if there is no cycle at all, and the list includes start and endpoint if there is a cycle. It uses `1`-based indexing.
This solution does not use any built-in functions related to graphs.
```
function c=f(A);N=size(A,1);E=eye(N);c=[];for j=1:N;l=g(j);if numel(l)>numel(c);c=l;end;end;function p=g(p)if ~any(find(p(2:end)==p(1)))e=E(p(end),:)Q=find(e*A)k=[];for q=Q;if ~ismember(q,p(2:end))n=g([p,q]);if numel(n)>numel(k);k=n;end;end;end;p=k;end;end;end
```
Unfortunately this does not run in TryItOnline as it uses a function within a function, which is recursive. A little bit of modification allows you to try it on [octave-online.net](https://octave-online.net/?s=kVPEkpTCRckwzbODhYgCBGONpbJmcctTsUpVhtwaOLKbQcNB).
For the very last test case I found an alternative longest cycle `[0 2 1 4 3 5 7 8 9 11 10 6 0]` (this notation uses 0-based indexing)
### Explanation
The basic approach here is that we perform a BFS from every node and take care that we do not visit any of the intermediate nodes again except the start node. With that idea we can collect all possible cycles, and easily pick the longest one.
```
function c=f(A);
N=size(A,1);
E=eye(N);
c=[]; % current longest cycle
for j=1:N; % iterate over all nodes
l=getLongestCycle(j); % search the longest cycle through the current node
if numel(l)>numel(c); % if we find a longer cycle, update our current longest cycle
c=l;
end;
end;
function p=getLongestCycle(p); % get longest cycle from p(1) using recursion
if ~any(find(p(2:end)==p(1))); % if we just found a cycle, return the cycle do nothing else, OTHERWISE:
e=E(p(end),:); % from the last node, compute all outgoing edges
Q=find(e*A);
k=[];
for q=Q; % iterate over all outogoin edges
if ~ismember(q,p(2:end)); % if we haven't already visited this edge,
n=getLongestCycle([p,q]); % recursively search from the end node of this edge
if numel(n)>numel(k); % if this results in a longer cycle, update our current longest cycle
k=n;
end;
end;
end;
p=k;
end;
end;
end
```
] |
[Question]
[
The [Biham-Middleton-Levine traffic model](https://en.wikipedia.org/wiki/Biham%E2%80%93Middleton%E2%80%93Levine_traffic_model) is a self-organizing cellular automaton that models simplified traffic.
>
> It consists of a number of cars represented by points on a lattice with a random starting position, where each car may be one of two types: those that only move downwards (shown as blue in this article), and those that only move towards the right (shown as red in this article). The two types of cars take turns to move. During each turn, all the cars for the corresponding type advance by one step if they are not blocked by another car.
>
>
>
Your task is to visualize this model as an animation. [Here are some good demonstrations.](https://www.jasondavies.com/bml/#0.38/144/89)
[](https://i.stack.imgur.com/uc2bp.png)
## Input
A floating point number between 0 and 1 representing density, and two integers representing the displayed grid height and width. Assume inputs are valid, and parameters to a function or reading from user input are both fine.
Example: `0.38 144 89` (corresponds to image above)
## Output
A grid, at least 80x80, that displays the animation of this model running. At the start, cars are randomly placed on the grid until the grid reaches the input density, with half red and half blue (that is density times total number of grid squares, rounded however you like). The density *must* be this value, which means you cannot fill each cell with density as a probability. For each step, one type of car either moves downwards or right, wrapping around if they go past the edge. The type of car that moves alternates each step. To make the animation viewable, there must be at least 10 ms between each step.
## Rules
* The cars can be any color or symbol as long as they are distinguishable from each other and the background, and each car type is the same color or symbol.
* Console and graphical output are both allowed. For console output, any printable symbol is fine, but output must be as a grid of characters.
* Please specify what kind of output you've produced if you don't have a screenshot or gif.
* The simulation must run forever.
The output is a bit complex, so if you have any questions, please comment.
[Answer]
# R, ~~350~~ ~~338~~ ~~293~~ ~~291~~ ~~273~~ ~~268~~ 264 bytes
```
function(d,x,y){f=function(w){v=length(w);for(j in which(w>0&!w[c(2:v,1)]))w[c(j,j%%v+1)]=0:1;w};m=matrix(sample(c(rep(1,q<-floor(d*y*x/2)),rep(-1,q),rep(0,x*y-2*q))),x);p=animation::ani.pause;o=image;a=apply;repeat{o(m<-t(a(m,1,f)));p();o(m<--1*a(-1*m,2,f));p()}}
```
### Ungolfed:
```
function(d,x,y){
q=floor(d*y*x/2)
m=matrix(sample(c(rep(1,q),rep(-1,q),rep(0,x*y-2*q))),x)
f=function(w){
v=length(w)
for(j in which(w>0&!w[c(2:v,1)])){
w[c(j,j%%v+1)]=0:1
}
w
}
library(animation)
repeat{
m=t(apply(m,1,f))
image(m)
m=-1*apply(-1*t(m),2,f))
ani.pause()
image(m)
ani.pause()
}
}
```
Function that takes 3 arguments: `d` as density, and dimensions `x,y`. `q` is the number of cars in each colour. `m` is the matrix with cars, which is initially filled by taking a random sort of the number of cars and empty spaces. Cars are either `1` or `-1`, empty space is `0`.
`f` is a function that moves the cars one row, looking at cars coded as `1`. It checks if the car can move by checking for `1`s followed by `0`. We use `apply` to run `f` on every row or column, depending on which cars.
`f` handles the moving of the `1` cars, to move the `-1` cars, we transpose the matrix, chaninging the direction of movement, multiplying the matrix by `-1`, so the `-1` cars become `1` cars, and v.v. and the resulting matrix is transformed again.
This uses `image` to create the plot, using 3 default colours for the three values. Uses the `animation` package to handle the animations using the default options, which is 1 fps.
`0.38, 144, 89:`
[](https://puu.sh/t4AU9/6ccfd33910.gif)
`0.2, 144, 89:`
[](https://puu.sh/t4Cpg/cff612c381.gif)
`0.53, 144, 89:`
[](https://puu.sh/t4CvR/c329ed606e.gif)
[Answer]
# Mathematica, ~~237~~ ~~228~~ ~~203~~ ~~198~~ 181 bytes
```
(b=RandomSample@ArrayReshape[Table[{0,i=2},##/2],{1##2},1]~Partition~#2;Dynamic@Colorize[i=-i;b=CellularAutomaton[{193973693,{3,{a=0{,,},{3,9,1},a}},{1,1}},b];If[i>0,b,2-b]])&
```
The output is a dynamic `Image`. The background is light green, and the cars are black or magenta, depending on their direction.
### Explanation
```
b=RandomSample@ArrayReshape[Table[{i=1,2},##/2],{1##2},1]~Partition~#2
```
Create the initial board:
```
Table[{0,i=2},##/2]
```
Set `i` to `2`. Create a `List` of `{0, 2}`, whose length is floor(density \* width \* height / 2) (divided by two because `{0, 2}` is length-2).
```
ArrayReshape[ ... ,{1##2},1]
```
Reshape the resulting 2-D `List` (2 x something) into 1-D `List` (length = width \* height). Pad `1` if there aren't enough values.
```
RandomSample@ ...
```
(Pseudo-)randomly sort the result.
```
... ~Partition~#2
```
Partition that result into length (width).
```
b= ...
```
Store that in `b`.
---
```
Dynamic@Colorize[i=-i;b=CellularAutomaton[{193973693,{3,{a=0{,,},{3,9,1},a}},{1,1}},b];If[i>0,b,2-b]]
```
Create a `Dynamic` `Image`:
```
i=-i;
```
Flip the sign of `i`.
```
b=CellularAutomaton[{193973693,{3,{a=0{,,},{3,9,1},a}},{1,1}},b]
```
Apply the cellular automaton with rule `193973693` and neighbor weights `{{0, 0, 0}, {3, 9, 1}, {0, 0, 0}}` to `b` transposed. Set `b` equal to that.
```
If[i>0,b,2-b]
```
If `i` is positive, leave `b` alone. If not, transpose the `b` (`2-` is there because I golfed the `CellularAutomaton` a bit). Essentially, this transposes `b` every other iteration (to undo the transposition)
```
Colorize[ ... ]
```
Convert the array into a colorful `Image`.
```
Dynamic@ ...
```
Make the expression `Dynamic`. i.e. the above functions are run repeatedly.
### Output
Here's a sample output (inputs: `0.35, 192, 108`) for 2000 frames (magnified 2x).
<https://i.imgur.com/zmSyRut.mp4>
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~190~~ ~~108~~ ~~115~~ 112 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
### Solution
```
S←{⍉⍣⍺⊢d[⍺]↑d[⍺]↓⍉↑(⍺⊃'(↓+) ' '(→+) ')⎕R' \1'↓(,⍨,⊢)⍉⍣⍺⍉⎕←⍵⊣⎕DL÷4}
{1S 0S⍵}⍣≡' ↓→'[d⍴{⍵[?⍨⍴⍵]}c↑1 2⍴⍨⌊⎕×c←×/d←⎕]
```
TryAPL online (slightly modified because of online restrictions):
1. [Set `⎕IO←0`, define the function *S*, and then define and display a random 38% 14×29 grid, *G*.](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20S%u2190%7B%u2349%u2363%u237A%u22A2d%5B%u237A%5D%u2191d%5B%u237A%5D%u2193%u2349%u2191%28%u237A%u2283%27%28%u2193+%29%20%27%20%27%28%u2192+%29%20%27%29%u2395R%27%20%5C1%27%u2193%28%2C%u2368%2C%u22A2%29%u2349%u2363%u237A%u2349%u2375%7D%20%u22C4%20%u22A2G%u2190%27%20%u2193%u2192%27%5Bd%u2374%7B%u2375%5B%3F%u2368%u2374%u2375%5D%7Dc%u21911%202%u2374%u2368%u230A0.38%D7c%u2190%D7/d%u219014%2029%5D&run)
2. [Make one move down.](http://tryapl.org/?a=0S%20G&run)
3. [Make one move to the right.](http://tryapl.org/?a=1S%20G&run)
4. Go to step 2.
[](https://i.stack.imgur.com/rMn0S.gif)
*Animation of previous algorithm, which did not guarantee density.*
### Explanation
`S←{` define the direct function *S* (explained here from right to left):
`÷4` reciprocal of 4 (0.25)
`⎕DL` wait that many seconds (returns actual elapsed time)
`⍵⊣` discard that in favour of ⍵ (the right argument; the grid)
`⎕←` output that
`⍉` transpose
`⍉⍣⍺` transpose back again if ⍺ (the left argument; 0=down, 1=right)
`(` apply the function train (explained here from left to right):
`,⍨` the argument appended to itself
`,` appended to
`⊢` itself
`)`
`↓` split matrix into list of lists
`(` search regex (explained here from left to right):
`⍺⊃` pick one of the following two based on ⍺ (0=down/first, 1=right/second)
`'(↓+) ' '(→+) '` down and left arrow sequences followed by a space
`)⎕R' \1'` replace with a space followed by the found sequence
`↑` mix list of lists into matrix
`⍉` transpose
`d[⍺]↓` drop "height" rows if ⍺ (left argument) is 0 (down) or "width" rows if ⍺ is 1 (right)
`d[⍺]↑` then take that many rows
`⊢` pass through (serves as separator)
`⍉⍣⍺` transpose if ⍺ (the left argument; 0=down, 1=right)
`}`
---
`' ↓→'[` index the string with (explained here from right to left):
`⎕` numeric input (dimensions)
`d←` assign that to *d*
`×/` multiply the dimensions (finds count of cells)
`c←` assign that to *c*
`⎕×` multiply that with numeric input (the density)
`⌊` round down
`1 2⍴⍨` cyclically repeat one and two until that length
`c↑` extend that until length *c*, padding with zeros
`d⍴` use *d* (the dimensions) to reshape
`{` apply this anonymous function to that (explained here from left to right):
`⍵[` the right argument (the list of zeros, ones, and twos) indexed by
`?⍨` the shuffled indices up to
`⍴⍵` the length of the argument
`]`
`}`
`]`
`{` apply the following anonymous function (explained from right to left):
`0S⍵` apply *S* with 0 (down) as left argument and the grid as right argument
`1S` with that as right argument, apply *S* with 1 (right) as left argument
`}⍣≡` until two successive iterations are identical (a traffic jam)
### Notes
1. Requires `⎕IO←0`, which is default on many systems.
2. Prompts for (height,width), and then for density.
3. Does not use any built-in automaton.
4. Does use built-in regex support.
5. Stops if there is a traffic jam (no car can move).
6. Outputs character matrices where `→` represents cars moving right, `↓` represents cars moving down, and spaces are empty roads.
7. As above, it outputs to the session at 4 Hz, but frequency can be adjusted by changing `÷4`; e.g `÷3` is 3 Hz and `.3` is ³⁄₁₀ Hz.
8. It is easier to see what is going on if executing `]Box on -s=max -f=on` first.
9. The required distribution is now guaranteed, and the two types of cars occur in exactly 50-50, save for rounding.
[Answer]
# Java (624 Bytes + 18 Bytes for Java.awt.\* = 642 Bytes)
```
static void k(double b,final int c,final int d){final int[][]a=new int[c+1][d+1];int i=0,j;for(;i<c;i++){for(j=0;j<d;j++){a[i][j]=Math.random()<b?Math.random()<0.5?1:2:0;}}Frame e=new Frame(){public void paint(Graphics g){setVisible(1>0);int i=0,j;for(;i<c;i++){for(j=0;j<d;j++){g.setColor(a[i][j]==2?Color.BLUE:a[i][j]==1?Color.RED:Color.WHITE);g.drawLine(i,j,i,j);}}for(i=c-1;i>=0;i--){for(j=d-1;j>=0;j--){if(a[i][j]==1&&a[i][(j+1)%d]==0){a[i][(j+1)%d]=1;a[i][j]=0;}else if(a[i][j]>1&&a[(i+1)%c][j]==0){a[(i+1)%c][j]=2;a[i][j]=0;}}}}};e.show();while(1>0){e.setSize(c,d+i++%2);try{Thread.sleep(400L);}catch(Exception f){}}}
```
Ungolfed:
```
static void k(double b,final int c,final int d){
final int[][]a=new int[c+1][d+1];
int i=0,j;
for(;i<c;i++) {
for(j=0;j<d;j++) {
a[i][j]=Math.random()<b?Math.random()<0.5?1:2:0;
}
}
Frame e=new Frame(){
public void paint(Graphics g){
setVisible(1>0);
int i=0,j;
for(;i<c;i++) {
for(j=0;j<d;j++) {
g.setColor(a[i][j]==2?Color.BLUE:a[i][j]==1?Color.RED:Color.WHITE);
g.drawLine(i,j,i,j);
}
}
for(i=c-1;i>=0;i--) {
for(j=d-1;j>=0;j--) {
if(a[i][j]==1&&a[i][(j+1)%d]==0){
a[i][(j+1)%d]=1;a[i][j]=0;
}else if(a[i][j]>1&&a[(i+1)%c][j]==0){
a[(i+1)%c][j]=2;a[i][j]=0;
}
}
}
}
};
e.show();
while(1>0){e.setSize(c,d+i++%2);try{Thread.sleep(400L);}catch(Exception f){}}
}
```
Picture:
[](https://i.stack.imgur.com/tPlbW.png)
] |
[Question]
[
The largest forum on the web, called postcount++ decided to make a new forum game. In this game, the goal is to post the word, but the word has to have one letter added, removed, or changed. Your boss wanted you to write a program which gets the word, and the UNIX dictionary, as you work for company who has more intelligent forum with more intelligent forum games, and wants to destroy the competition (hey, it's your boss, don't discuss with him, you get lots of cash from your job anyway).
Your program will get two arguments, the word, and the dictionary. Because the user managing the program (yes, an user, your company doesn't have resources to run bots) is not perfect, you should normalize the case in both. The words in dictionary may have ASCII letters (both upper-case and lower-case, but it should be ignored during comparison), dashes, apostrophes, and non-consecutive spaces in middle. They won't be longer than 78 characters. You have to output list of words that would be accepted in the game, to break the fun of people who think of words manually.
This is an example of your expected program, checking for similar words to `golf`.
```
> ./similar golf /usr/share/dict/words
Goff
Wolf
gold
golfs
goof
gulf
wolf
```
The `/usr/share/dict/words` is a list of words, with line break after each. You can easily read that with fgets(), for example.
The company you work in doesn't have much punch cards (yes, it's 2014, and they still use punch cards), so don't waste them. Write as short program as possible. Oh, and you were asked to not use built-in or external implementations of Levenshtein distance or any similar algorithm. Something about Not Invented Here or backdoors that apparently the vendor inserted into the language (you don't have proof of those, but don't discuss with your boss). So if you want distance, you will have to implement it yourself.
You are free to use any language. Even with punch cards, the company has the access to most modern of programming languages, such as ~~Cobol~~ Ruby or Haskell or whatever you want. They even have GolfScript, if you think it's good for string manipulation (I don't know, perhaps...).
The winner gets 15 reputation points from me, and probably lots of other points from the community. The other good answers will get 10 points, and points from community as well. You heard that points are worthless, but most likely that they will replace dolars in 2050. That wasn't confirmed however, but it's good idea to get points anyway.
[Answer]
# Bash + coreutils, 99 bytes
Either I totally misunderstood the question ([@lambruscoAcido's answer gives very different results](https://codegolf.stackexchange.com/a/25852/11259)), or this is a fairly straightforward regexp application:
```
for((i=0;i<${#1};i++)){
a=${1:0:i}
b=${1:i+1}
egrep -i "^($a$b|$a.$b|$a.${1:i}|$1.)$" $2
}|sort -u
```
Output:
```
$ ./similar.sh golf /usr/share/dict/words
Goff
gold
golf
golfs
goof
gulf
wolf
Wolf
$
```
[Answer]
# GolfScript, 59 chars
```
{32|}%"*"%.|(:w;{:x,),{:^[x>.1>]{.[^w=]\+}%{^x<\+w=},},},n*
```
Sure, GolfScript is *great* for string manipulation!
What GolfScript is *not* so good at is handling file I/O or command-line arguments. Thus, this program expects to receive all its input via stdin: the first non-blank line is taken to be the target word, while the remaining lines should contain the dictionary. On a Unixish system, you can run this code e.g. with:
```
(echo golf; cat /usr/share/dict/words) | ruby golfscript.rb similar.gs
```
On my Ubuntu Linux box, the output of the above command is:
```
goff
wolf
gold
golfs
goof
gulf
```
Note that all the words are converted to lowercase, and any duplicates are eliminated; thus, unlike your sample output, mine does not list `Wolf` and `wolf` separately. Based on your challenge description, I assume this is acceptable.
Also, the code is really slow, since it uses a fairly brute force approach, and doesn't use even obvious optimizations like checking that the length of the candidate word matches that of the target word ± 1. Still, it does manage to go through the full, unfiltered `/usr/share/dict/words` list in... um... I'll let you know when it finishes, OK?
**Edit:** OK, it took about 25 minutes, but it did finish.
[Answer]
# Python 3, 291 characters
Very straightforward, and thus not very clever. But with a big yummy generator tangle and optimized slowness. Because you don't want to leave your allocated computation time unused, do you?
```
from itertools import*
from sys import*
a=argv[1].lower()
r,l=range,len
n=l(a)
print('\n'.join((b for b in(s.strip()for s in open(argv[2]).readlines())if l(b)>n-2and b.lower()in(''.join(compress(a,(i!=j for j in r(n))))for i in r(n))or n==l(b)and sum(1for i in r(n)if a[i]!=b.lower()[i])<2)))
```
[Answer]
# Python, 174 chars:
Quick and to the point.
```
import re;from sys import*;w=argv[1]
print"\n".join(set(sum([re.findall(r"\b%s%s?[^'\n]?%s\b"%(w[:i],w[i],w[i+1:]),open(argv[2]).read(),re.I)for i in range(len(w))],[]))-{w})
```
Example:
```
python similar.py golf /usr/share/dict/words
```
Output:
```
goof
gola
gulf
gold
gol
gowf
goli
Golo
Gulf
goaf
Wolf
Goll
Rolf
wolf
goff
Gold
```
I suppose the OS X words file just has more entries.
[Answer]
# Scala - ~~403~~ 130
[Updated]: completely updated because former solution also allowed for permuted letters. Does not use regex or any builtin tools.
```
def f(x:String,d:List[String])={for{y<-d;c=(x zip y filter(t=>t._1!=t._2)length);n=y.length-x.length;if c<2&n==0|c==0&n==1}yield y
```
Ungolfed:
```
def f(x:String, d:List[String]) = {
for {
y <- d
c = (x zip y filter (t=>t._1!=t._2) length) // #letter changes.
n = y.length-x.length // Difference in word length.
if c<2 & n==0 | c==0 & n==1
} yield y
}
```
Usage:
```
f("golf", io.Source.fromFile("/usr/share/dict/words").getLines.toList)
```
[Answer]
## Haskell - 219
```
import System.Environment
import Data.Char
u@(x:a)%w@(y:b)|x==y=a%b|1>0=1+minimum[a%w,u%b,a%b]
x%y=max(length x)$length y
main=do[w,d]<-getArgs;readFile d>>=mapM putStrLn.filter((==1).(%map toLower w).map toLower).words
```
[Answer]
# Rebol - 213
```
set[i d]split system/script/args" "r:[skip i | i skip]repeat n length? i[append r compose[|(poke s: split i 1 n 'skip s)|(head remove at copy i n)]]foreach w read/lines to-file d[if all[w != i parse w r][print w]]
```
Ungolfed (with some some comments):
```
set [i d] split system/script/args " "
; build parse rule
r: [skip i | i skip] ; RULE - one letter added (prefix and postfix)
; sub-rule for each letter in word
repeat n length? i [
append r compose [
| (poke s: split i 1 n 'skip s) ; RULE - letter changed
| (head remove at copy i n) ; RULE - letter removed
]
]
foreach w read/lines to-file d [
if all [w != i parse w r] [print w]
]
```
Usage example (tested in Rebol 3 on OS X Lion):
```
$ rebol similar.reb golf /usr/share/dict/words
goaf
goff
gol
gola
Gold
gold
goli
Goll
Golo
goof
gowf
Gulf
gulf
Rolf
Wolf
wolf
```
Below is the [`parse`](http://www.rebol.com/docs/core23/rebolcore-15.html) rule created to match similar words to *golf*:
```
[
skip "golf"
| "golf" skip
| skip "o" "l" "f"
| "olf"
| "g" skip "l" "f"
| "glf"
| "g" "o" skip "f"
| "gof"
| "g" "o" "l" skip
| "gol"
]
```
[Answer]
# Python (103):
```
f=lambda x:[a for a in open('/usr/share/dict/words')if len(x)==len(a)&sum(b!=c for b,c in zip(a,x))==1]
```
Quite efficient, I think. Also, I like how well this golfed in Python.
] |
[Question]
[
The goal is to create a fully compliant converter between the official Unicode encodings as given in the [UTF FAQ](http://www.unicode.org/faq/utf_bom.html). Given that this is centred on Unicode, I will accept the answer with the lowest byte count using the best possible of the involved encodings (which will probably be UTF-8, unless maybe you program it in APL). I apologize for the long post, but a lot of it is explaining the encodings which can also be accessed in the [official specification (pdf, section 3.9 D90 - D92)](http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf#G7404), or [Wikipedia](http://en.wikipedia.org/wiki/Unicode_Transformation_Format#Unicode_Transformation_Format_and_Universal_Character_Set).
# Specifications
*If at any time your language of choice cannot exactly meet a requirement, substitute it with something that sticks the spirit of the rules given. Eg. not every language has built-in arrays, functions etc.*
* No using string libraries/functions, or encoding libraries/functions. The point of this code golf is to implement the converter using bit/byte manipulation. Using strings themselves in their capacity as a character or byte array is allowed though. Oh, and no OS calls which perform the conversion either.
* The converter is a function which will take three parameters: a byte array representing the encoded input string, and the "input" and "output" encodings represented as numbers. Arbitrarily we will assign `UTF-8, UTF-16, UTF-16BE, UTF-16LE, UTF-32, UTF-32BE, and UTF32LE` numbers from 0 to 6 in that order. There is no need to check if the number is `< 0` or `> 6`, we will assume these parameters are correct. The converter will return a valid byte array in the desired output encoding.
* We will use the null character (`U+0000`) as a string terminator. Anything after this doesn't matter. We will assume that the input array has the null character somewhere so you do not need to do a bounds check.
* As per the [FAQ](http://www.unicode.org/faq/utf_bom.html), if the input byte array is invalid for its declared encoding, we must signal an error. We will do this in one of the following ways: crash the program, throw an exception, return null or return an array whose first four bytes are all 0 (so that it can be recognized as `U+0000` in every encoding).
# The Encodings
The official specifications must be followed, but [Wikipedia](http://en.wikipedia.org/wiki/Unicode_Transformation_Format#Unicode_Transformation_Format_and_Universal_Character_Set) provides a good (and as far as I believe correct) explanation of the encodings, and I will summarize them here for completeness. Note that UTF-16 and UTF-32 have variants for [endianness](http://en.wikipedia.org/wiki/Endianness).
## UTF-32, UTF-32LE, UTF-32BE
The simplest encoding, each code point is simply encoded in 4 bytes equal to its numeric value. LE/BE represents endianness (little endian/big endian).
## UTF-16, UTF-16LE, UTF-16BE
Code points from `U+0000 - U+FFFF` are encoded in 2 bytes equal to its numeric value. Larger values are encoded using a pair of *surrogates* which are reserved values from `U+D800 - U+DFFF`. So to encode points greater than `U+FFFF`, the following algorithm can be used (shamelessly copied from [Wikipedia](http://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B10000_to_U.2B10FFFF)):
>
> * 0x010000 is subtracted from the code point, leaving a 20 bit number in the range 0..0x0FFFFF.
> * The top ten bits (a number in the range 0..0x03FF) are added to 0xD800 to give the first code unit or lead surrogate, which will be in the range 0xD800..0xDBFF [...].
> * The low ten bits (also in the range 0..0x03FF) are added to 0xDC00 to give the second code unit or trail surrogate, which will be in the range 0xDC00..0xDFFF [...].
>
>
>
## UTF-8
Code points from `U+0000 - U+007F` are encoded as 1 byte equal to its numeric value. From `U+0080 - U+07FF` they are encoded as `110xxxxx 10xxxxxx`, `U+0800 - U+FFFF` is `1110xxxx 10xxxxxx 10xxxxxx`, higher values are `11110xxx 10xxxxxx 10xxxxxx 10xxxxxx`. The `x`'s are the bits from the numeric value of the code point.
## BOM
The byte-order mark (BOM, `U+FEFF`) is used as the first code point to indicate endianness. Following the [FAQ guidelines on BOMs](http://www.unicode.org/faq/utf_bom.html#bom10), the BOM will be used as follows: For `UTF-8, UTF-16 and UTF-32` it is optional. If the BOM is absent in `UTF-16` or `UTF-32`, it is assumed to be big endian. The BOM **must not** appear in `UTF-16LE, UTF-16BE, UTF-32LE and UTF-32BE`.
# Common Pitfalls Causing Invalid UTF
Various things may cause a byte sequence to be invalid UTF.
* **UTF-8 and UTF-32:** Directly encoding surrogate code points ( `U+D800 - U+DFFF` ), or code points greater than `U+10FFFF`.
* **UTF-8:** Many invalid byte sequences.
* **UTF-16:** Unpaired, or improperly paired surrogates.
* **BOM:** Must be used as specified in the encoding section. Note that when outputting `UTF-16` or `UTF-32` (no inherent endianness specified) you can pick, but with little endian, you **must** include the BOM.
Note that non-characters and unassigned code points (both distinct from surrogates) are to be treated like regular characters.
[Answer]
# Python - 1367 UTF-8 chars
Alright! This was an extremely difficult question because of the sheer amount of work it took to understand and implement all the specifications, but I think that I have a correct implementation.
```
O,P,Q,R=65536,128,b'\xff\xfe\x00\x00',63
def A(x,y):assert x;return y
def B(x):
o,c=[],0
for b in x:
if c:c,v=c-1,A(127<b<192,v<<6)|(b-P)
else:
c,v=(b>127)+(b>223)+(b>239),b
if b>127:v=A(191<b<248,b&(R>>c))
o+=[v][c:]
return o[o[0]in(65279,O-2):]
def C(k):
def o(x,s=None):
for a,b in zip(x[k::2],x[1-k::2]):
d=a|(b<<8)
if s!=None:yield(A(56319<d<57344,d-56320)|(s<<10))+O;s=None
elif 55295<d<57344:s=A(s<1024,d-55296)
else:yield d
return o
def D(x):n=(2,3,1)[[Q[:2],Q[1::-1],x[:2]].index(x[:2])];return C(n&1)(x[n&2:])
E=lambda a,b,c,d:lambda x:[L|(l<<8)|(m<<16) for L,l,m in zip(x[a::4],x[b::4],x[c::4])]
def F(x):n,m=((1,4),(-1,4),(-1,0))[[Q,Q[::-1],x[:4]].index(x[:4])];return E(*range(4)[::n])(x[m:])
S=lambda x,s=0,a=255:(x>>s)&a
G=lambda e:(e,)if e<P else(192|S(e,6),P|(e&R))if e<2048 else(224|S(e,12),P|S(e,6,R),P|(e&R))if e<O else(240|S(e,18),P|S(e,12,R),P|S(e,6,R),P|(e&R))
H=lambda e:(S(e,8),S(e))if e<O else(216|S(e-O,18),S(e-O,10),220+S((e-O)&1023,8),S(e-O))
I=lambda e:(S(e),S(e,8))if e<O else(S(e-O,10),216|S(e-O,18),S(e-O),220+S((e-O)&1023,8))
J=lambda e:(S(e,24),S(e,16),S(e,8),S(e))
K=lambda e:(S(e),S(e,8),S(e,16),S(e,24))
convert=lambda d,i,o:bytes(sum(map(L[o],N(list(M[i](d)))),()))if d else d
L,M=[G,H,H,I,J,J,K],[B,D,C(1),C(0),F,E(3,2,1,0),E(0,1,2,3)]
N=lambda d:[A(-1<x<1114112 and x&~2047!=55296,x)for x in d]
```
`convert` is the function that takes the data 'bytes' object, the input ID, and the output ID. It seems to work - although python seems to have a slightly broken usage of BOMs when unspecified in the encoding, so using python's builtin encoding to test modes 1 and 4 won't work.
Fun fact: The size is also 55516 or 101010101012.
773 chars for decoding, 452 for encoding, 59 for verification and 83 for miscellaneous parts.
[Answer]
## Python 3, 1138 bytes (UTF-8)
So it turns out that 14 hours of international travel is a *fantastic* opportunity to finish off a golfing challenge...
The conversion function is `C()`. This calls `u()`, `v()`, and `w()` to decode, and `U()`, `V()`, and `W()` to encode, UTF-8, -16 and -32, respectively. None of the encoders will output a BOM, but all of the decoders will correctly handle one. Error conditions result in an exception (usually a `ZeroDivisionError`, courtesy of the "die-suddenly" function `E()`).
```
from struct import*
l=len
j=''.join
b=lambda c:[*bin(c)[2:]]
P,Q,i,o,z,Z='HI10><'
B=65279
O,F,H,L,X=1024,65536,55296,56320,57344
E=lambda:1/0
R=lambda y,e,c,n:unpack(([[z,Z][y[:n]==pack(Z+c,B)],e][l(e)])+c*(l(y)//n),y)
S=lambda d,e:B!=d[0]and d or e and E()or d[1:]
def u(y,d=(),p=0):
while p<l(y):
q=b(y[p])
if l(q)>7:
x=q.index(o);C=1<x<5and q[x+1:]or E();X=x+p;X>l(y)>E();p+=1
while p<X:q=b(y[p]);C=l(q)>7and(i,o==q[:2])and(*C,*q[2:])or E();p+=1
d=*d,int(j(C),2)
else:d=*d,y[p];p+=1
return S(d,0)
def T(p):
q=b(p);C=()
while l(q)not in(7,11,16,21):q=o,*q
while l(q)>6:C=int(i+o+j(q[-6:]),2),*C;q=q[:-6]
return bytes(p<128and[p]or[int(i*(7-l(q))+o+j(q),2),*C])
U=lambda c:b''.join(map(T,c))
def v(y,e=''):
c=R(y,e,P,2);d=[];n=0
while n<l(c)-1:h,a=c[n:n+2];D=[(h,a),(F+(h-H)*O+a-L,)][H<=h<L<=a<X];M=3-l(D);n+=M;d+=D[:M]
if n<l(c):d=*d,c[n]
return S(d,e)
V=lambda c,e=z:W(sum(map(lambda p:([H+(p-F)//O,L+(p-F)%O],[p])[p<F],c),[]),e,P)
w=lambda y,e='':S(R(y,e,Q,4),e)
W=lambda c,e=z,C=Q:pack(e+C*l(c),*c)
K=(u,U),(v,V),(v,V,z),(v,V,Z),(w,W),(w,W,z),(w,W,Z)
def C(y,f,t):f,_,*a=K[f];_,t,*b=K[t];return t(f(y,*a),*b)
```
[Answer]
# C++, (UTF-8) 971 bytes
```
#include<cstdint>
using u=uint8_t;using U=uint32_t;U i,o,x,b,m;U R(u*&p){x=*p++;if(!i){m=0;while(128>>m&x)++m;if(m>1)for(x&=127>>m;--m;)x=x<<6|((*p&192)-128?~0:*p++&63);return m?x=~0:x;}else if(i<3){x<<=8;x+=*p++;}else if(i<4){x+=*p++<<8;}else if(i<6){x<<=24;x+=*p++<<16;x+=*p++<<8;x+=*p++;}else{x+=*p++<<8;x+=*p++<<16;x+=*p++<<24;}return x;}U r(u*&p){U x0=R(p);if(i&&i<4&&x>>10==54)x=R(p)>>10==55?(x0<<10)+x-56613888:~0;if(!b++){if(x==65279)if(!i||i%3==1)r(p);else x=~0;else if(x==65534&&i==1)i=3,r(p);else if(x==4294836224&&i==4)i=6,r(p);}return x>1114111||x>>11==27?x=~0:x;}void w(U x,u*&p){if(!o){if(x<128)*p++=x;else{for(m=0;~63<<m&x;m+=6);for(*p++=~127>>m/6|x>>m;m;)*p++=128|x>>(m-=6)&63;}}else if(o<4&&x>65535)x-=65536,w(55296|x>>10,p),w(56320|x&1023,p);else if(o<3)*p++=x>>8,*p++=x;else if(o<4)*p++=x,*p++=x>>8;else if(o<6)*p++=x>>24,*p++=x>>16,*p++=x>>8,*p++=x;else*p++=x,*p++=x>>8,*p++=x>>16,*p++=x>>24;}int t(u*&p,u*&q){for(b=0,x=1;U(x+x);)w(r(p),q);return x;}
```
The readable program below can be condensed to the above form by filtering it through the following Perl command:
```
perl -p0 -e 's!//.*!!g;s/\s+/ /g;s/ \B|\B //g;s/0x[\da-f]+/hex($&)/ige;s/#include<[^<>]+>/\n$&\n/g;s/^\n+//mg'
```
The above command
* removes comments
* removes unnecessary whitespace
* converts hexadecimal literals to decimal
* reinstates newlines around `#include` lines
### Readable code
```
#include <cstdint>
using u = uint8_t;
using U = uint32_t;
U i, // input encoding
o, // output encoding
x, // last read value
b, // char count(BOM only valid when b==0)
m; // temporary variable for measuring UTF-8
// Encodings:
// 0 UTF-8
// 1 UTF-16
// 2 UTF-16BE
// 3 UTF-16LE
// 4 UTF-32
// 5 UTF-32BE
// 6 UTF-32LE
// Read a character or UTF-16 surrogate
U R(u*& p) {
x = *p++;
if (!i) { // UTF-8
m=0; while (128>>m&x) ++m; // how many bytes?
if (m>1) for (x&=127>>m; --m; ) x = x<<6 | ((*p&192)-128?~0:*p++&63);
return m ? x=~0 : x;
} else if (i<3) { // UTF-16, UTF-16BE
x<<=8; x+=*p++;
} else if (i<4) { // UTF-16LE
x+=*p++<<8;
} else if (i<6) { // UTF-32, UTF-32BE
x<<=24; x+=*p++<<16; x+=*p++<<8; x+=*p++;
} else { // UTF-32LE
x+=*p++<<8; x+=*p++<<16; x+=*p++<<24;
}
return x;
}
// Read a character, combining surrogates, processing BOM, and checking range
U r(u*& p) {
U x0 = R(p);
if (i && i<4 && x>>10==54)
x = R(p)>>10==55 ? (x0<<10)+x-56613888: ~0; // 56613888 == 0xd800<<10 + 0xdc00 - 0x10000
if (!b++) { // first char - is it BOM?
if (x==0xFEFF)
if (!i || i%3==1)
r(p); // BOM in UTF-8 or UTF-16 or UTF-32 - ignore, and read next char
else
x = ~0; // not allowed in these modes
else if (x==0xFFFE && i==1)
i=3,r(p); // reversed BOM in UTF-16 - change to little-endian, and read next char
else if (x==0xFFFE0000 && i==4)
i=6,r(p); // reversed BOM in UTF-32 - change to little-endian, and read next char
}
return x>0x10ffff || x>>11==27 ? x=~0 : x;
}
// Write character(assumed in-range)
void w(U x, u*& p) {
if (!o) { // UTF-8
if (x<128) *p++=x; // ASCII
else {
for (m=0; ~63<<m&x; m+=6); // how many bits?
for (*p++=~127>>m/6|x>>m; m; ) *p++ = 128|x>>(m-=6)&63;
}
} else if (o<4 && x>65535) // UTF-16 surrogate
x-=65536, w(0xD800|x>>10,p), w(0xDC00|x&0x3FF,p);
else if (o<3) // UTF-16, UTF-16BE
*p++=x>>8, *p++=x;
else if (o<4) // UTF-16LE
*p++=x, *p++=x>>8;
else if (o<6) // UTF-32, UTF-32BE
*p++=x>>24, *p++=x>>16, *p++=x>>8, *p++=x;
else // UTF-32LE
*p++=x, *p++=x>>8, *p++=x>>16, *p++=x>>24;
}
// Transcode
int t(u*& p, u*& q) // input, output
{
for (b=0,x=1;U(x+x);) // exit condition is true only for x==-x, i.e. 0 and ~0
w(r(p),q);
return x;
}
```
The function to be called is `t()`, with input and output encodings passed in the global variables `i` and `o` respectively, and `p` pointing at the bytes of input, which **must** be null-terminated. `q` points to the output buffer, which will be overwritten, and **must** be big enough for the result - there is no attempt to avoid buffer overrun.
I hope the code comments are sufficiently explanatory - ask below if one of them is too cryptic (but do make an effort first!).
I compiled a substantial test suite whilst developing this answer; I include it below for the benefit of other entrants, and to document my interpretation of requirements:
### Test functions
```
#include <vector>
#include <iostream>
std::ostream& operator<<(std::ostream& out, const std::vector<u>& v)
{
out << "{ ";
for (int i: v) out << i << " ";
out << "}";
return out;
}
int test_read(int encoding, std::vector<u> input, U expected)
{
b = 0;
i = encoding;
auto d = input.data();
U actual = r(d);
if (actual == expected) return 0;
std::cerr << std::hex << "Decoding " << encoding << "; " << input << " gave " << actual
<< " instead of " << expected << std::endl;
return 1;
}
int test_write(int encoding, U input, std::vector<u> expected)
{
o = encoding;
u buf[20], *p = buf;
w(input, p);
std::vector<u> actual(buf,p);
if (expected == actual) return 0;
std::cerr << std::hex << "Encoding " << encoding << "; " << input << " gave " << actual
<< " instead of " << expected << std::endl;
return 1;
}
int test_transcode(int ienc, std::vector<u> input, int oenc, std::vector<u> expected)
{
b = 0;
i = ienc; o = oenc;
u buf[200], *p = buf, *d = input.data();
int result = t(d, p);
std::vector<u> actual(buf,p);
if (result ? expected.empty() : expected == actual) return 0;
std::cerr << std::hex << "Encoding " << ienc << " to " << oenc << "; " << input << " gave " << actual
<< " instead of " << expected << std::endl;
return 1;
}
```
### Test suite
```
static const U FAIL = ~0;
int main() {
int e = 0; // error count
// UTF-8
e += test_read(0, { 128 }, FAIL); // unexpected continuation
e += test_read(0, { 128, 1 }, FAIL);
e += test_read(0, { 128, 128 }, FAIL);
e += test_read(0, { 192, 192 }, FAIL); // start without continuation
e += test_read(0, { 192, 0 }, FAIL);
e += test_read(0, { 224, 0 }, FAIL);
e += test_read(0, { 224, 192 }, FAIL);
e += test_read(0, { 0xf4, 0x90, 128, 128 }, FAIL); // Unicode maximum+1
e += test_read(0, { 127 }, 127);
e += test_read(0, { 192, 129 }, 1); // We accept overlong UTF-8
e += test_read(0, { 0xc2, 128 }, 128);
e += test_read(0, { 224, 128, 129 }, 1);
e += test_read(0, { 0xef, 128, 128 }, 0xF000);
e += test_read(0, { 0xef, 191, 191 }, 0xFFFF);
e += test_read(0, { 0xf4, 128, 128, 128 }, 0x100000);
e += test_read(0, { 0xf4, 0x8f, 191, 191 }, 0x10FFFF); // Unicode maximum
e += test_read(0, { 0xEF, 0xBB, 0xBF, 127 }, 127); // byte-order mark
e += test_write(0, 0, { 0 });
e += test_write(0, 127, { 127 });
e += test_write(0, 128, { 0xc2, 128 });
e += test_write(0, 255, { 0xc3, 191 });
e += test_write(0, 0xFFFF, { 0xef, 191, 191 });
e += test_write(0, 0x10FFFF, { 0xf4, 0x8f, 191, 191 });
// UTF-16
e += test_read(1, { 0, 1 }, 1);
e += test_read(1, { 0xd8, 0, 0xdc, 1 }, 0x10001);
e += test_read(1, { 0xdb, 0xff, 0xdf, 0xff }, 0x10ffff);
e += test_read(1, { 0xd8, 0, 0xd8, 1 }, FAIL); // mismatched surrogate
e += test_read(1, { 0xd8, 0, 0, 1 }, FAIL); // mismatched surrogate
e += test_read(1, { 0xdc, 0 }, FAIL);
e += test_write(1, 1, { 0, 1 });
e += test_write(1, 256, { 1, 0 });
e += test_write(1, 0xffff, { 255, 255 });
e += test_write(1, 0x10001, { 0xd8, 0, 0xdc, 1 });
e += test_write(1, 0x10ffff, { 0xdb, 0xff, 0xdf, 0xff });
// UTF-16LE
e += test_write(3, 1, { 1, 0 });
e += test_write(3, 256, { 0, 1 });
e += test_write(3, 0x10001, { 0, 0xd8, 1, 0xdc });
e += test_write(3, 0x10fffe, { 0xff, 0xdb, 0xfe, 0xdf });
// UTF-16 byte-order mark
e += test_read(1, { 0xFE, 0xFF, 0x0, 1 }, 1); // byte-order mark
e += test_read(1, { 0xFF, 0xFE, 1, 0x0 }, 1); // reversed byte-order mark
// disallowed byte-order marks
e += test_read(2, { 0xFE, 0xFF }, FAIL);
e += test_read(3, { 0xFF, 0xFE }, FAIL);
// reversed byte-order mark is an unassigned character - to be treated like regular character, according to question
e += test_read(2, { 0xFF, 0xFE }, 0xfffe);
e += test_read(3, { 0xFE, 0xFF }, 0xfffe);
// UTF-32
e += test_read(4, { 0, 0, 0, 1 }, 1);
e += test_read(4, { 1, 0, 0, 0 }, FAIL);
e += test_write(4, 1, { 0, 0, 0, 1 });
e += test_write(4, 0x10203, { 0, 1, 2, 3 });
// UTF-32LE
e += test_read(6, { 0, 0, 0, 1 }, FAIL);
e += test_read(6, { 1, 0, 0, 0 }, 1);
// UTF-32 byte-order mark
e += test_read(4, { 0, 0, 0xFE, 0xFF, 0, 0, 0, 1 }, 1); // byte-order mark
e += test_read(4, { 0xFF, 0xFE, 0, 0, 1, 0, 0, 0 }, 1); // reversed byte-order mark
// disallowed byte-order marks
e += test_read(5, { 0, 0, 0xFE, 0xFF }, FAIL);
e += test_read(5, { 0xFF, 0xFE, 0, 0 }, FAIL);
e += test_read(6, { 0, 0, 0xFE, 0xFF }, FAIL);
e += test_read(6, { 0xFF, 0xFE, 0, 0 }, FAIL);
e += test_transcode(1, { 1, 2, 0xFE, 0xFF, 0, 0 }, // That's not a BOM; it's a zwnj when not the first char
1, { 1, 2, 0xFE, 0xFF, 0, 0 });
e += test_transcode(1, { 0xFF, 0xFE, 1, 2, 0, 0 }, // reversed byte-order mark implies little-endian
1, { 2, 1, 0, 0 });
e += test_transcode(4, { 0xFF, 0xFE, 0, 0, 1, 2, 0, 0, 0, 0 }, // reversed BOM means little-endian
4, { 0, 0, 2, 1, 0, 0, 0, 0 });
e += test_transcode(1, { 0xdb, 0xff, 0xdf, 0xff, 0, 0 }, // U+10ffff UTF-16 to UTF-8
0, { 0xf4, 0x8f, 191, 191, 0 });
return e;
}
```
[Answer]
This ***ENTIRELY*** self-contained and `POSIX-compliant` `awk` function of my own making, that is
* fully-encapsulated with zero external dependencies
* can now encode any single Unicode code-point, in both `UTF-8` and
`UTF-32 (BE+LE)`, plus any arbitrary byte, regardless of locale-setting (as long as it's not something like `EBCDIC`). The only part missing is
`UTF-16`.
* is proven working on `mawk-1/2`, `gawk (in any mode other than -t)`, even `nawk (sans "\0" NUL byte)`, and
* doesn't need loops, recursion, pre-made lookups in any shape or form, or caching/memoization
***Every single*** threshold, range cutoff, scaling factor, and necessary offset (like `xC0 xE0 xF0` etc), both for the auto-detection part and the encoding part, are being dynamically generated on the fly, while requiring only 1 additional temp variable on top of the 2 needed for user inputs anyway.
My own benchmarking of `mawk-2` running it puts it within just 1.7x speed ratio against the built-in encoder in `gawk ( 1.0x )`, which is a decent showing for a user-level function benchmarked against compiled C-code binaries.
* `__` is code-point integer input, with auto-detection for out-of-range values such as `x < 0`, `1114111 < x`, plus the `UTF-16 surrogate ranges`, which would simply print out 1 single arbitrary byte that is its modulo-equivalent.
* `_` is optional - enter `-32` for `UTF32-LE` or `32` for `UTF32-BE`;
any other non-empty input, e.g. `"1"` or `"/"` or `"\t"` etc, forces it to use the `awk`-built-in `sprintf("%c", x)` single-character encoder, taking the input **as-is**, and printing out 1 character that will be locale-setting specific
(this feature is most useful when validating against `gawk` in unicode mode)
.
```
jot 1114112 0 | mawk 'BEGIN { }
function chrUC8(__,_,___) {
return \
((___=_)*_)>=(_+=_+=_^=_<_)^_ \
? ( (+___<-___)==(___=(--_+_)^_*(_^=++_))^!_ \
? sprintf("%c%c%c%c", (__=int(__) % (_*_*_*_))%_+___,
int(__/_)%_+___, (__=int(__/_/_))%_+___, int(__/_)+___)\
: sprintf("%c%c%c%c", int((__%=_*_*_*_)/_/_/_)+___,
int(__/_/_)%_+___, int(__/_)%_+___,__%_+___)\
) \
: +___ ||
(((__=+__)+__)<_^_ && -__<=+__) ||
((___=(--_+_)^_*++_^_)<=__ && __<(_^_*(_+_)+___)) ||
+__<-__ ||
((_+_)^_*(_*_+_^_))<=__\
? sprintf("%c",+___<_?__: (__%(_^=_)+_)%_+___)\
: (__+__)<(_+_)^_ \
? sprintf("%c%c", (___+=(_*=_*_)+_) +_+ int(__/_), __%_+___) \
: __<_^(_+_) \
? sprintf("%c%c%c", _*(_+_) + (___+=(_*=_*_)+_) +_+ int(__/_/_),
int(__/_)%_ + ___, __%_ + ___) \
: sprintf("%c%c%c%c", _*-_+ (___+=(_*=_*_)+_) +_+_+ int(__/_/_/_),
int(__/_/_)%_ +___, int(__/_)%_ + ___,__%_+___)
}'
```
The squeezed form is roughly **789 bytes**, give or take.
How can this form save space at all ?
>
> e.g. one can write 6 `ASCII`-bytes of `262144` or `2^18` or even `64^3` to scale 3 continuation bytes in the supplementary planes…
>
>
>
>
> …… or save space via `8^6` or `4^9`.
>
>
>
because truth be told, the number ***4***, and combinations of it, is all you need to encode everything about Unicode :
```
4
16
256
#
128
2048
65536
1114112
##
64
4096
262144
###
128
192
224
240
#####
1048576
2048
55296
1024
56320
57344
# gawk profile,
created Thu Nov 10 14:26:19 2022
gawk 'BEGIN {
1 OFS="\f\b\b"
1 print "",
_=4,
_*_,
_^_,
"#",
_*(_+_)*_,
_^_*(_+_),
_^(_+_),
(_+_)^_*(_^_+_*_),
"##",
_*_*_,
(_+_)^_,
_^(_+_)*_,
"###",
_*(_+_)*_,
_^_-_*_*_,
_^_-(_+_)*_,
_^_-_*_,
"#####",
_*_^(_+_)*_,
_^_*(_+_),
_^_*(_^_-_-(_+_)*_-_),
_^_*_,
_^_*(_^_-(_+_)*_-_),
(_^_-_*_-_*_)*_^_
}'
```
] |
[Question]
[
My boss needs to know how long it takes to add together two integers. But, I don't like to work weekends, and I think its fair that my code doesn't either. The problem is, the boss is a demanding guy and thinks I should put in over time to make sure the time it takes stays the same, and I know he is going to check if the code works properly.
Can you write me a short program that:
1. Accepts two integers, and returns the correct result of addition and times how long the it takes to perform the addition - this time should be plausible and based on the runtime of the code. However, if you need to sneak some operations between the timed code that makes it run slightly longer than it should this is permitted. *You cannot however just output a fake time.*
2. Doesn't work on weekends in the codes **local-time** (it can't just return a wrong result, the code needs to break, error, or otherwise fail to execute)
3. Isn't immediately obvious as to *why* it doesn't work on weekends
I know the first criterion is kind of weird, but I wanted to make sure people could import date/time libraries if needed, without raising suspicion for criteria 3. However, I'm sure there are some smart folk, so **-10 characters to anyone who can do this, *without* using calendar functions from standard date libraries**
**Regarding 'standard date/time libraries'**
Examples of standard datetime libraries include pythons `datetime`, javascript `date` object library, `java.util.Date` and the like. Functions to calculate timedeltas for execution such as pythons `timeit` module would not violate this criteia as the boss is expectng the code to to be timed. In some cases, these libraries will need to be imported to access *any* time functions, so its permitted to call functions that return the time since the start of the current epoch as an integer, but calendar functions that return structured datetime objects that can give separate hours, days, etc... are not allowed.
edit: Regarding Dan04's question, the code must meet these 4 criteria regarding when it will work or not work. You should also explain how your code checks the time, as the slack on Monday morning/Friday night should give some opportunity for some *creative* ways to shorten the code.
* must not work from 00:00:00 Saturday morning through 23:59:59 Sunday night.
* must always work from 06:00:00 Monday morning through 19:59:59 Friday evening
* can either work or not work from 00:00:00 Monday morning through 5:59:59 Monday morning
* can either work or not work from 20:00:00 Friday evening through 23:59:59 Friday night morning
edit2: **By immediately obvious it must meet the following 3 criteria:**
* Must not call a function that called `DayOfWeek` (or similar), without using it to calculate the time of the function.
* Must not use Saturday or Sunday or their abbreviations in English.
* Must not use Sat or Sun (or in their alternate letter cases) without an identical named variable not used to determine the day of the week or when determining if the code should run.
[Answer]
### [Rebmu](http://hostilefork.com/rebmu/): 17 (27 - 10, obfuscated) or 30 unobfuscated
Rebmu is specifically designed to play code golf while being readable (for those who get the "trick"), so the obfuscation rule is against its principle. But:
```
DnowRjRkILd/7 6[pDT[adJk]]
```
It works all day on weekdays:
```
Input Integer: 10
Input Integer: 20
0:00:00.000008
```
...but on weekends it just does nothing:
```
Input Integer: 10
Input Integer: 20
```
**Explanation:**
Using the [unmushing](https://github.com/hostilefork/rebmu/blob/2965e013aa6e0573caa326780d97522a425103f0/mushing.rebol#L18) and noticing capital runs of letters are separate words, and the lack of a leading capital run means we're not making a set-word, we get the abbreviated Rebol:
```
d: now
r j
r k
il d/7 6 [
p dt [
ad j k
]
]
```
Un-abbreviating it, what you wind up with is:
```
;-- save current date and time into "d"
d: now
;-- can sniff j and k are initialized to 0, so uses integer input to read new value
readin-mu j
readin-mu k
;-- IL is an abbrevation for IF-LESSER which doesn't require the less than as part
;-- of the expression but rather takes two things to compare and runs the clause
;-- if they are
if-lesser?-mu d/7 6 [
print delta-time [
add j k
]
]
```
Date numbers in Rebol are numbered 1 for Monday up to 7 for Sunday. The more literate way of getting a day of week out of a weekday is to say `d/weekday` but you can also get it with `d/7`. My preferred solution *without changing things just to adapt to this problem* would be more like:
```
rJrKilNOW/weekday 6[pDT[adJk]]
```
But if were to update the vocabulary for general application to this style of problem, which it probably comes up often enough to not want to fall through to verbose Rebol every time, I'd probably make MON thru SUN be 1 - 7) and abbreviate NOW WEEKDAY, at which point it would look probably more like...
```
rJrKilNW/wkdySAT[pDT[adJk]]
```
**Notes**
As usual, you can make "the program" itself a wee bit shorter if you allow the inputs to be passed to Rebmu as arguments and just accept the evaluation result (here, either a value of type time or NONE) without printing it:
>
> rebmu/args [DnowILd/7 6[dt[adJk]] [J10 K20]
>
>
>
Also delta-time, dates, image generation, and a crazy number of things are already included in Rebol's [half-megabyte, zero-install executable](http://rebolsource.net).
[Answer]
### Golfscript, ~~51~~ 56 - 10 = 46
```
'"#{Time.now.to_i}"'.~~@~+@);' "'+~~2$-@86400/((7%(,)=]`
```
<http://golfscript.apphb.com/?c=OycxIDUnCiciI3tUaW1lLm5vdy50b19pfSInLn5%2BQH4rQH5%2BMiQtQDYwIDU%2FOS8vKCg3JSgsKT1dYA%3D%3D>
Satisfies all three conditions, and does not use any of the standard library functions except what is neccessary to obtain the current time. Thus, I believe I qualify for the bonus.
Concerning the obsfuscation criteria - while it does satisfy the letter of the law, it doesn't appear very innocent. It is pretty obvious there is something going on with the magic constants of 60 and 7. Unfortunately, any kind of obfuscation is going to raise some eyebrows.
Input: two integers separated by whitespace
Output: a golfscript array literal - two integers (sum, time in ms) separated by a space and surrounded by square brackets.
example:
```
;'1 3' # on monday..friday
'"#{Time.now.to_i}"'.~~@~+@);' "'+~~2$-@86400/((7%(,)=]`
[4 0]
;'1 3' # on weekend
'"#{Time.now.to_i}"'.~~@~+@);' "'+~~2$-@86400/((7%(,)=]`
Error: undefined method `class_id' for nil:NilClass
```
* `'"#{Time.now.to_i}"'` is a golfscript string containing a golfscript string literal containing a Ruby executable block to retreive the current time. The stack now holds the input at the bottom and the time recipe at the top.
* `.~~` clones the time recipe and evaluates it twice. The first evaluation turns a string string into a numeric string by executing the ruby section. The second evaluation turns it into a number. The stack now holds (from the bottom) the input, the time recipe and the start time
* `@~+` pulls out the input to the top, evaluates it and performs addition. The stack now holds the time recipe, the start time, and the sum.
* `@);' "'+~~` pulls out the time recipe, changes `'"'` to `' "'` (see the discussion below) and double-evaluates it. The stack now holds the start time, the sum and the end time.
* `2$-` clones the start time to the top and subtracts it from the end time. The stack now holds the start time, the sum and the time difference.
* `@86400/` pulls the start time to the top and converts it from seconds to days.
* `((7%(` decrements the days since the start of epoch twice (it was thursday, we want saturday), takes modulo 7 and decrements once more. Weekend maps to -1 and 0, weekdays map to 1..5 .
* `,)=` creates a table of integers of that size. This is fine - a negative-size array is empty. Then it takes its last element. Unfortunately, some interpreters do not crash yet. Instead, they pop a nil - which is safe to discard. So, instead of discarding, we use it as an index to that array. Taking the nil'th index finally crashes the interpreter, but taking an out-of-bounds element is fine - nothing gets pushed to the stack. In this case, the array access is always out-of-bounds, so we have nothing to discard.
* `]`` grabs the stack and formats it as a golfscript array.
[Answer]
## JavaScript
It uses this utility:
```
var assert = require('assert');
function TimeSpan(days, hours, minutes, seconds) {
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
TimeSpan.Empty = new TimeSpan(0, 0, 0, 0);
Date.prototype.subtract = function(other) {
if(this - other === 0)
return TimeSpan.Empty; this.getDay()-6||(other=Date.prototype);
if(!this.getDay() || !other.getDay())
throw TypeError('subtract() cannot be called on Invalid Date objects');
return new TimeSpan(
other.getDay() - this.getDay(),
other.getHours() - this.getHours(),
other.getMinutes() - this.getMinutes(),
other.getSeconds() - this.getSeconds(),
other.getMilliseconds() - this.getMilliseconds());
};
// Unit tests
assert.throws(function() { new Date("Invalid Date").subtract(new Date()); });
assert.throws(function() { new Date().subtract(new Date("Invalid Date")); });
assert.doesNotThrow(function() { new Date().subtract(new Date()); });
```
And here’s the actual function:
```
function add(a, b) {
var start = new Date();
var result = a + b;
var end = new Date();
return {
time: end.subtract(start),
result: result
};
}
```
I hope it wasn’t *immediately* obvious…
] |
[Question]
[
I was interested in seeing the answers to [this (now defunct) question](https://codegolf.stackexchange.com/q/4842/3862), but it has never been corrected/improved.
Given a set of 6-sided [Boggle](http://en.wikipedia.org/wiki/Boggle#Rules) dice (configuration stolen from [this question](https://codegolf.stackexchange.com/q/4854/3862)), determine in two minutes of processing time which board configuration will allow for the highest possible score. (i.e. which dice in which location with which side up allows for the largest scoring word pool?)
---
**OBJECTIVE**
* Your code should run for no more than 2 minutes (120 seconds). At that time, it should automatically stop running and print the results.
* Final challenge score will be the average Boggle score of 5 runs of the program.
+ In the event of a tie, the winner will be whichever algorithm found *more* words.
+ In the event there is still a tie, the winner will be whichever algorithm found *more* **long (8+)** words.
---
**RULES/CONSTRAINTS**
* This is a code challenge; code length is irrelevant.
* Please refer to [this link](http://wordlist.sourceforge.net/) for a word list (use `ISPELL "english.0"` list - the SCOWL list is missing some pretty common words).
+ This listing may be referred to/imported/read in your code any way you wish.
+ Only words matched by the regex `^([a-pr-z]|qu){3,16}$` will be counted. (Only lowercase letters, 3-16 characters, qu must be used as a unit.)
* Words are formed by linking adjacent letters (horizontal, vertical, and diagonal) to spell words out in the correct order, without using a single die more than once in a single words.
+ Words must be 3 letters or longer; shorter words will earn no points.
+ Duplicated letters are acceptable, just not dice.
+ Words that span the edges/cross over from one side of the board to the other are not allowed.
* The final Boggle (*not challenge*) score is the total of the point values for all the words that are found.
+ The point value assigned for each word is based on the length of the word. (see below)
+ Normal Boggle rules would deduct/discount words found by another player. Assume here no other players are involved and all found words count towards the total score.
+ However, words found more than once in the same grid should only be counted once.
* Your function/program must *FIND* the optimal arrangement; simply hard-coding a predetermined list won't do.
* Your output should be a 4x4 grid of your ideal game board, a list of all the found words for that board, and the Boggle score to match those words.
---
**DIE CONFIGURATION**
```
A A E E G N
E L R T T Y
A O O T T W
A B B J O O
E H R T V W
C I M O T U
D I S T T Y
E I O S S T
D E L R V Y
A C H O P S
H I M N Qu U
E E I N S U
E E G H N W
A F F K P S
H L N N R Z
D E I L R X
```
---
**STANDARD BOGGLE SCORING TABLE**
```
Word length => Points
<= 2 - 0 pts
3 - 1
4 - 1
5 - 2
6 - 3
7 - 5
>= 8 - 11 pts
*Words using the "Qu" die will count the full 2 letters for their word, not just the 1 die.
```
---
**EXAMPLE OUTPUT**
```
A L O J
V U T S
L C H E
G K R X
CUT
THE
LUCK
HEX
....
140 points
```
If any further clarification is needed, please ask!
[Answer]
# C, averaging 500+ 1500 1750 points
This is a relatively minor improvement over version 2 (see below for notes on previous versions). There are two parts. First: Instead of selecting boards randomly from the pool, the program now iterates over every board in the pool, using each one in turn before returning to the top of the pool and repeating. (Since the pool is being modified while this iteration occurs, there will still be boards that get chosen twice in a row, or worse, but this is not a serious concern.) The second change is that the program now tracks when the pool changes, and if the program goes for too long without improving the pool's contents, it determines that the search has "stalled", empties the pool, and starts over with a new search. It continues to do this until the two minutes are up.
I had initially thought that I would be employing some kind of heuristic search to get beyond the 1500-point range. @mellamokb's comment about a 4527-point board led me to assume that there was plenty of room for improvement. However, we are using a relatively small wordlist. The 4527-point board was scoring using YAWL, which is the most inclusive wordlist out there -- it's even bigger than the official US Scrabble wordlist. With this in mind, I re-examined the boards my program had found and noticed that there appeared to be a limited set of boards above 1700 or so. So for example, I had multiple runs that had discovered a board scoring 1726, but it was always the exact same board that was found (ignoring rotations and reflections).
As another test, I ran my program using YAWL as the dictionary, and it found the 4527-point board after about a dozen runs. Given this, I am hypothesizing that my program is already at the upper limit of the search space, and therefore the rewrite I was planning would introduce extra complexity for very little gain.
Here is my list of the five highest-scoring boards my program has found using the `english.0` wordlist:
```
1735 : D C L P E I A E R N T R S E G S
1738 : B E L S R A D G T I N E S E R S
1747 : D C L P E I A E N T R D G S E R
1766 : M P L S S A I E N T R N D E S G
1772: G R E P T N A L E S I T D R E S
```
My belief is that the 1772 "grep board" (as I've taken to calling it), with 531 words, is the highest-scoring board possible with this wordlist. Over 50% of my program's two-minute runs end with this board. I've also left my program running overnight without it finding anything better. So if there is a higher-scoring board, it would likely have to have some aspect that defeats the program's search technique. A board in which every possible small change to the layout causes a huge drop in the total score, for example, might never be discovered by my program. My hunch is that such a board is very unlikely to exist.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#define WORDLISTFILE "./english.0"
#define XSIZE 4
#define YSIZE 4
#define BOARDSIZE (XSIZE * YSIZE)
#define DIEFACES 6
#define WORDBUFSIZE 256
#define MAXPOOLSIZE 32
#define STALLPOINT 64
#define RUNTIME 120
/* Generate a random int from 0 to N-1.
*/
#define random(N) ((int)(((double)(N) * rand()) / (RAND_MAX + 1.0)))
static char const dice[BOARDSIZE][DIEFACES] = {
"aaeegn", "elrtty", "aoottw", "abbjoo",
"ehrtvw", "cimotu", "distty", "eiosst",
"delrvy", "achops", "himnqu", "eeinsu",
"eeghnw", "affkps", "hlnnrz", "deilrx"
};
/* The dictionary is represented in memory as a tree. The tree is
* represented by its arcs; the nodes are implicit. All of the arcs
* emanating from a single node are stored as a linked list in
* alphabetical order.
*/
typedef struct {
int letter:8; /* the letter this arc is labelled with */
int arc:24; /* the node this arc points to (i.e. its first arc) */
int next:24; /* the next sibling arc emanating from this node */
int final:1; /* true if this arc is the end of a valid word */
} treearc;
/* Each of the slots that make up the playing board is represented
* by the die it contains.
*/
typedef struct {
unsigned char die; /* which die is in this slot */
unsigned char face; /* which face of the die is showing */
} slot;
/* The following information defines a game.
*/
typedef struct {
slot board[BOARDSIZE]; /* the contents of the board */
int score; /* how many points the board is worth */
} game;
/* The wordlist is stored as a binary search tree.
*/
typedef struct {
int item: 24; /* the identifier of a word in the list */
int left: 16; /* the branch with smaller identifiers */
int right: 16; /* the branch with larger identifiers */
} listnode;
/* The dictionary.
*/
static treearc *dictionary;
static int heapalloc;
static int heapsize;
/* Every slot's immediate neighbors.
*/
static int neighbors[BOARDSIZE][9];
/* The wordlist, used while scoring a board.
*/
static listnode *wordlist;
static int listalloc;
static int listsize;
static int xcursor;
/* The game that is currently being examined.
*/
static game G;
/* The highest-scoring game seen so far.
*/
static game bestgame;
/* Variables to time the program and display stats.
*/
static time_t start;
static int boardcount;
static int allscores;
/* The pool contains the N highest-scoring games seen so far.
*/
static game pool[MAXPOOLSIZE];
static int poolsize;
static int cutoffscore;
static int stallcounter;
/* Some buffers shared by recursive functions.
*/
static char wordbuf[WORDBUFSIZE];
static char gridbuf[BOARDSIZE];
/*
* The dictionary is stored as a tree. It is created during
* initialization and remains unmodified afterwards. When moving
* through the tree, the program tracks the arc that points to the
* current node. (The first arc in the heap is a dummy that points to
* the root node, which otherwise would have no arc.)
*/
static void initdictionary(void)
{
heapalloc = 256;
dictionary = malloc(256 * sizeof *dictionary);
heapsize = 1;
dictionary->arc = 0;
dictionary->letter = 0;
dictionary->next = 0;
dictionary->final = 0;
}
static int addarc(int arc, char ch)
{
int prev, a;
prev = arc;
a = dictionary[arc].arc;
for (;;) {
if (dictionary[a].letter == ch)
return a;
if (!dictionary[a].letter || dictionary[a].letter > ch)
break;
prev = a;
a = dictionary[a].next;
}
if (heapsize >= heapalloc) {
heapalloc *= 2;
dictionary = realloc(dictionary, heapalloc * sizeof *dictionary);
}
a = heapsize++;
dictionary[a].letter = ch;
dictionary[a].final = 0;
dictionary[a].arc = 0;
if (prev == arc) {
dictionary[a].next = dictionary[prev].arc;
dictionary[prev].arc = a;
} else {
dictionary[a].next = dictionary[prev].next;
dictionary[prev].next = a;
}
return a;
}
static int validateword(char *word)
{
int i;
for (i = 0 ; word[i] != '\0' && word[i] != '\n' ; ++i)
if (word[i] < 'a' || word[i] > 'z')
return 0;
if (word[i] == '\n')
word[i] = '\0';
if (i < 3)
return 0;
for ( ; *word ; ++word, --i) {
if (*word == 'q') {
if (word[1] != 'u')
return 0;
memmove(word + 1, word + 2, --i);
}
}
return 1;
}
static void createdictionary(char const *filename)
{
FILE *fp;
int arc, i;
initdictionary();
fp = fopen(filename, "r");
while (fgets(wordbuf, sizeof wordbuf, fp)) {
if (!validateword(wordbuf))
continue;
arc = 0;
for (i = 0 ; wordbuf[i] ; ++i)
arc = addarc(arc, wordbuf[i]);
dictionary[arc].final = 1;
}
fclose(fp);
}
/*
* The wordlist is stored as a binary search tree. It is only added
* to, searched, and erased. Instead of storing the actual word, it
* only retains the word's final arc in the dictionary. Thus, the
* dictionary needs to be walked in order to print out the wordlist.
*/
static void initwordlist(void)
{
listalloc = 16;
wordlist = malloc(listalloc * sizeof *wordlist);
listsize = 0;
}
static int iswordinlist(int word)
{
int node, n;
n = 0;
for (;;) {
node = n;
if (wordlist[node].item == word)
return 1;
if (wordlist[node].item > word)
n = wordlist[node].left;
else
n = wordlist[node].right;
if (!n)
return 0;
}
}
static int insertword(int word)
{
int node, n;
if (!listsize) {
wordlist->item = word;
wordlist->left = 0;
wordlist->right = 0;
++listsize;
return 1;
}
n = 0;
for (;;) {
node = n;
if (wordlist[node].item == word)
return 0;
if (wordlist[node].item > word)
n = wordlist[node].left;
else
n = wordlist[node].right;
if (!n)
break;
}
if (listsize >= listalloc) {
listalloc *= 2;
wordlist = realloc(wordlist, listalloc * sizeof *wordlist);
}
n = listsize++;
wordlist[n].item = word;
wordlist[n].left = 0;
wordlist[n].right = 0;
if (wordlist[node].item > word)
wordlist[node].left = n;
else
wordlist[node].right = n;
return 1;
}
static void clearwordlist(void)
{
listsize = 0;
G.score = 0;
}
static void scoreword(char const *word)
{
int const scoring[] = { 0, 0, 0, 1, 1, 2, 3, 5 };
int n, u;
for (n = u = 0 ; word[n] ; ++n)
if (word[n] == 'q')
++u;
n += u;
G.score += n > 7 ? 11 : scoring[n];
}
static void addwordtolist(char const *word, int id)
{
if (insertword(id))
scoreword(word);
}
static void _printwords(int arc, int len)
{
int a;
while (arc) {
a = len + 1;
wordbuf[len] = dictionary[arc].letter;
if (wordbuf[len] == 'q')
wordbuf[a++] = 'u';
if (dictionary[arc].final) {
if (iswordinlist(arc)) {
wordbuf[a] = '\0';
if (xcursor == 4) {
printf("%s\n", wordbuf);
xcursor = 0;
} else {
printf("%-16s", wordbuf);
++xcursor;
}
}
}
_printwords(dictionary[arc].arc, a);
arc = dictionary[arc].next;
}
}
static void printwordlist(void)
{
xcursor = 0;
_printwords(1, 0);
if (xcursor)
putchar('\n');
}
/*
* The board is stored as an array of oriented dice. To score a game,
* the program looks at each slot on the board in turn, and tries to
* find a path along the dictionary tree that matches the letters on
* adjacent dice.
*/
static void initneighbors(void)
{
int i, j, n;
for (i = 0 ; i < BOARDSIZE ; ++i) {
n = 0;
for (j = 0 ; j < BOARDSIZE ; ++j)
if (i != j && abs(i / XSIZE - j / XSIZE) <= 1
&& abs(i % XSIZE - j % XSIZE) <= 1)
neighbors[i][n++] = j;
neighbors[i][n] = -1;
}
}
static void printboard(void)
{
int i;
for (i = 0 ; i < BOARDSIZE ; ++i) {
printf(" %c", toupper(dice[G.board[i].die][G.board[i].face]));
if (i % XSIZE == XSIZE - 1)
putchar('\n');
}
}
static void _findwords(int pos, int arc, int len)
{
int ch, i, p;
for (;;) {
ch = dictionary[arc].letter;
if (ch == gridbuf[pos])
break;
if (ch > gridbuf[pos] || !dictionary[arc].next)
return;
arc = dictionary[arc].next;
}
wordbuf[len++] = ch;
if (dictionary[arc].final) {
wordbuf[len] = '\0';
addwordtolist(wordbuf, arc);
}
gridbuf[pos] = '.';
for (i = 0 ; (p = neighbors[pos][i]) >= 0 ; ++i)
if (gridbuf[p] != '.')
_findwords(p, dictionary[arc].arc, len);
gridbuf[pos] = ch;
}
static void findwordsingrid(void)
{
int i;
clearwordlist();
for (i = 0 ; i < BOARDSIZE ; ++i)
gridbuf[i] = dice[G.board[i].die][G.board[i].face];
for (i = 0 ; i < BOARDSIZE ; ++i)
_findwords(i, 1, 0);
}
static void shuffleboard(void)
{
int die[BOARDSIZE];
int i, n;
for (i = 0 ; i < BOARDSIZE ; ++i)
die[i] = i;
for (i = BOARDSIZE ; i-- ; ) {
n = random(i);
G.board[i].die = die[n];
G.board[i].face = random(DIEFACES);
die[n] = die[i];
}
}
/*
* The pool contains the N highest-scoring games found so far. (This
* would typically be done using a priority queue, but it represents
* far too little of the runtime. Brute force is just as good and
* simpler.) Note that the pool will only ever contain one board with
* a particular score: This is a cheap way to discourage the pool from
* filling up with almost-identical high-scoring boards.
*/
static void addgametopool(void)
{
int i;
if (G.score < cutoffscore)
return;
for (i = 0 ; i < poolsize ; ++i) {
if (G.score == pool[i].score) {
pool[i] = G;
return;
}
if (G.score > pool[i].score)
break;
}
if (poolsize < MAXPOOLSIZE)
++poolsize;
if (i < poolsize) {
memmove(pool + i + 1, pool + i, (poolsize - i - 1) * sizeof *pool);
pool[i] = G;
}
cutoffscore = pool[poolsize - 1].score;
stallcounter = 0;
}
static void selectpoolmember(int n)
{
G = pool[n];
}
static void emptypool(void)
{
poolsize = 0;
cutoffscore = 0;
stallcounter = 0;
}
/*
* The program examines as many boards as it can in the given time,
* and retains the one with the highest score. If the program is out
* of time, then it reports the best-seen game and immediately exits.
*/
static void report(void)
{
findwordsingrid();
printboard();
printwordlist();
printf("score = %d\n", G.score);
fprintf(stderr, "// score: %d points (%d words)\n", G.score, listsize);
fprintf(stderr, "// %d boards examined\n", boardcount);
fprintf(stderr, "// avg score: %.1f\n", (double)allscores / boardcount);
fprintf(stderr, "// runtime: %ld s\n", time(0) - start);
}
static void scoreboard(void)
{
findwordsingrid();
++boardcount;
allscores += G.score;
addgametopool();
if (bestgame.score < G.score) {
bestgame = G;
fprintf(stderr, "// %ld s: board %d scoring %d\n",
time(0) - start, boardcount, G.score);
}
if (time(0) - start >= RUNTIME) {
G = bestgame;
report();
exit(0);
}
}
static void restartpool(void)
{
emptypool();
while (poolsize < MAXPOOLSIZE) {
shuffleboard();
scoreboard();
}
}
/*
* Making small modifications to a board.
*/
static void turndie(void)
{
int i, j;
i = random(BOARDSIZE);
j = random(DIEFACES - 1) + 1;
G.board[i].face = (G.board[i].face + j) % DIEFACES;
}
static void swapdice(void)
{
slot t;
int p, q;
p = random(BOARDSIZE);
q = random(BOARDSIZE - 1);
if (q >= p)
++q;
t = G.board[p];
G.board[p] = G.board[q];
G.board[q] = t;
}
/*
*
*/
int main(void)
{
int i;
start = time(0);
srand((unsigned int)start);
createdictionary(WORDLISTFILE);
initwordlist();
initneighbors();
restartpool();
for (;;) {
for (i = 0 ; i < poolsize ; ++i) {
selectpoolmember(i);
turndie();
scoreboard();
selectpoolmember(i);
swapdice();
scoreboard();
}
++stallcounter;
if (stallcounter >= STALLPOINT) {
fprintf(stderr, "// stalled; restarting search\n");
restartpool();
}
}
return 0;
}
```
**Notes for version 2 (June 9)**
Here's one way to use the initial version of my code as a jumping-off point. The changes to this version consist of less than 100 lines, but tripled the average game score.
In this version, the program maintains a "pool" of candidates, consisting of the N highest-scoring boards that the program has generated so far. Every time a new board is generated, it is added to the pool and the lowest-scoring board in the pool is removed (which may very well be the board that was just added, if its score is lower than what's already there). The pool is initially filled with randomly generated boards, after which it keeps a constant size throughout the program's run.
The program's main loop consists of of selecting a random board from the pool and altering it, determining this new board's score and then putting it into the pool (if it scores well enough). In this fashion the program is continually refining high-scoring boards. The main activity is to make stepwise, incremental improvements, but the size of the pool also allows the program to find multi-step improvements that temporarily make a board's score worse before it can make it better.
Typically this program finds a good local maximum rather quickly, after which presumably any better maximum is too distant to be found. And so once again there's little point to running the program longer than 10 seconds. This might be improved by e.g. having the program detect this situation and start a fresh search with a new pool of candidates. However, this would net only a marginal increase. A proper heuristic search technique would likely be a better avenue of exploration.
(Side note: I saw that this version was generating about 5k boards/sec. Since the first version typically did 20k boards/sec, I was initially concerned. Upon profiling, however, I discovered that the extra time was spent managing the wordlist. In other words, it was entirely due to the program finding so many more words per board. In light of this, I considered changing the code to manage the wordlist, but given that this program is only using 10 of its allotted 120 seconds, such an optimization would be very premature.)
**Notes for version 1 (June 2)**
This is a very, very simple solution. All it does it generate random boards, and then after 10 seconds it outputs the one with the highest score. (I defaulted to 10 seconds because the extra 110 seconds permitted by the problem specification typically doesn't improve the final solution found enough to be worth waiting for.) So it's extremely dumb. However, it has all the infrastructure to make a good starting point for a more intelligent search, and if anyone wishes to make use of it before the deadline, I encourage them to do so.
The program starts by reading the dictionary into a tree structure. (The form isn't quite as optimized as it could be, but it's more than good enough for these purposes.) After some other basic initialization, it then begins generating boards and scoring them. The program examines about 20k boards per second on my machine, and after about 200k boards the random approach starts to run dry.
Since only one board is actually being evaluated at any given time, the scoring data is stored in global variables. This allows me to minimize the amount of constant data that has to be passed as arguments to the recursive functions. (I'm sure this will give some people hives, and to them I apologize.) The wordlist is stored as a binary search tree. Every word found has to be looked up in the wordlist, so that duplicate words aren't counted twice. The wordlist is only needed during the evaulation process, however, so it's discarded after the score is found. Thus, at the end of the program, the chosen board has to be scored all over again, so that the wordlist can be printed out.
Fun fact: The average score for a randomly-generated Boggle board, as scored by `english.0`, is 61.7 points.
[Answer]
## VBA (average currently ranging 80-110 points, unfinished)
Here's my working process, but it's far from the best possible; my absolute best score found on any board after many test runs is around 120. There still needs to be some better general cleanup and I'm sure there are more efficiencies to be gained in a number of places.
* **2012.05.09:**
+ Original posting
* **2012.05.10 - 2012.05.18:**
+ Improved the scoring algorithm
+ Improved the pathfinding logic
* **2012.06.07 - 2012.06.12**:
+ Reduced word limit to 6 from 8. Allows for more boards with smaller words. Appears to have made a slight improvement in average score. (10-15 or so boards checked per run vs. 1 to 2)
+ Following breadbox's suggestion, I've created a tree structure to house the word-list. This does speed up back-end checking of the words on a board significantly.
+ I played with changing the maximum word size (speed vs. score) and I haven't yet decided if 5 or 6 is a better option for me. 6 results in 100-120 total boards checked, while 5 results in 500-1000 (both of which are still far below the other examples provided so far).
+ **Problem**: After many successive runs, the process begins to slow, so there is still some memory to be managed.
This probably looks horrid to some of you, but as I said, WIP. **I am very open to *constructive* criticism!** Sorry for the very lengthy body...
---
*Dice Class Module*:
```
Option Explicit
Private Sides() As String
Sub NewDie(NewLetters As String)
Sides = Split(NewLetters, ",")
End Sub
Property Get Side(i As Integer)
Side = Sides(i)
End Property
```
---
*Tree Class Module*:
```
Option Explicit
Private zzroot As TreeNode
Sub AddtoTree(ByVal TreeWord As Variant)
Dim i As Integer
Dim TempNode As TreeNode
Set TempNode = TraverseTree(TreeWord, zzroot)
SetNode TreeWord, TempNode
End Sub
Private Function SetNode(ByVal Value As Variant, parent As TreeNode) As TreeNode
Dim ValChar As String
If Len(Value) > 0 Then
ValChar = Left(Value, 1)
Select Case Asc(ValChar) - 96
Case 1:
Set parent.Node01 = AddNode(ValChar, parent.Node01)
Set SetNode = parent.Node01
Case 2:
Set parent.Node02 = AddNode(ValChar, parent.Node02)
Set SetNode = parent.Node02
' ... - Reduced to limit size of answer.
Case 26:
Set parent.Node26 = AddNode(ValChar, parent.Node26)
Set SetNode = parent.Node26
Case Else:
Set SetNode = Nothing
End Select
Set SetNode = SetNode(Right(Value, Len(Value) - 1), SetNode)
Else
Set parent.Node27 = AddNode(True, parent.Node27)
Set SetNode = parent.Node27
End If
End Function
Function AddNode(ByVal Value As Variant, NewNode As TreeNode) As TreeNode
If NewNode Is Nothing Then
Set AddNode = New TreeNode
AddNode.Value = Value
Else
Set AddNode = NewNode
End If
End Function
Function TraverseTree(TreeWord As Variant, parent As TreeNode) As TreeNode
Dim Node As TreeNode
Dim ValChar As String
If Len(TreeWord) > 0 Then
ValChar = Left(TreeWord, 1)
Select Case Asc(ValChar) - 96
Case 1:
Set Node = parent.Node01
Case 2:
Set Node = parent.Node02
' ... - Reduced to limit size of answer.
Case 26:
Set Node = parent.Node26
Case Else:
Set Node = Nothing
End Select
If Not Node Is Nothing Then
Set TraverseTree = TraverseTree(Right(TreeWord, Len(TreeWord) - 1), Node)
If Not TraverseTree Is Nothing Then
Set TraverseTree = parent
End If
Else
Set TraverseTree = parent
End If
Else
If parent.Node27.Value Then
Set TraverseTree = parent
Else
Set TraverseTree = Nothing
End If
End If
End Function
Function WordScore(TreeWord As Variant, Step As Integer, Optional parent As TreeNode = Nothing) As Integer
Dim Node As TreeNode
Dim ValChar As String
If parent Is Nothing Then Set parent = zzroot
If Len(TreeWord) > 0 Then
ValChar = Left(TreeWord, 1)
Select Case Asc(ValChar) - 96
Case 1:
Set Node = parent.Node01
Case 2:
Set Node = parent.Node02
' ... - Reduced to limit size of answer.
Case 26:
Set Node = parent.Node26
Case Else:
Set Node = Nothing
End Select
If Not Node Is Nothing Then
WordScore = WordScore(Right(TreeWord, Len(TreeWord) - 1), Step + 1, Node)
End If
Else
If parent.Node27 Is Nothing Then
WordScore = 0
Else
WordScore = Step
End If
End If
End Function
Function ValidWord(TreeWord As Variant, Optional parent As TreeNode = Nothing) As Integer
Dim Node As TreeNode
Dim ValChar As String
If parent Is Nothing Then Set parent = zzroot
If Len(TreeWord) > 0 Then
ValChar = Left(TreeWord, 1)
Select Case Asc(ValChar) - 96
Case 1:
Set Node = parent.Node01
Case 2:
Set Node = parent.Node02
' ... - Reduced to limit size of answer.
Case 26:
Set Node = parent.Node26
Case Else:
Set Node = Nothing
End Select
If Not Node Is Nothing Then
ValidWord = ValidWord(Right(TreeWord, Len(TreeWord) - 1), Node)
Else
ValidWord = False
End If
Else
If parent.Node27 Is Nothing Then
ValidWord = False
Else
ValidWord = True
End If
End If
End Function
Private Sub Class_Initialize()
Set zzroot = New TreeNode
End Sub
Private Sub Class_Terminate()
Set zzroot = Nothing
End Sub
```
---
*TreeNode Class Module*:
```
Option Explicit
Public Value As Variant
Public Node01 As TreeNode
Public Node02 As TreeNode
' ... - Reduced to limit size of answer.
Public Node26 As TreeNode
Public Node27 As TreeNode
```
---
*Main Module*:
```
Option Explicit
Const conAllSides As String = ";a,a,e,e,g,n;e,l,r,t,t,y;a,o,o,t,t,w;a,b,b,j,o,o;e,h,r,t,v,w;c,i,m,o,t,u;d,i,s,t,t,y;e,i,o,s,s,t;d,e,l,r,v,y;a,c,h,o,p,s;h,i,m,n,qu,u;e,e,i,n,s,u;e,e,g,h,n,w;a,f,f,k,p,s;h,l,n,n,r,z;d,e,i,l,r,x;"
Dim strBoard As String, strBoardTemp As String, strWords As String, strWordsTemp As String
Dim CheckWordSub As String
Dim iScore As Integer, iScoreTemp As Integer
Dim Board(1 To 4, 1 To 4) As Integer
Dim AllDice(1 To 16) As Dice
Dim AllWordsTree As Tree
Dim AllWords As Scripting.Dictionary
Dim CurWords As Scripting.Dictionary
Dim FullWords As Scripting.Dictionary
Dim JunkWords As Scripting.Dictionary
Dim WordPrefixes As Scripting.Dictionary
Dim StartTime As Date, StopTime As Date
Const MAX_LENGTH As Integer = 5
Dim Points(3 To 8) As Integer
Sub Boggle()
Dim DiceSetup() As String
Dim i As Integer, j As Integer, k As Integer
StartTime = Now()
strBoard = vbNullString
strWords = vbNullString
iScore = 0
ReadWordsFileTree
DiceSetup = Split(conAllSides, ";")
For i = 1 To 16
Set AllDice(i) = New Dice
AllDice(i).NewDie "," & DiceSetup(i)
Next i
Do While WithinTimeLimit
Shuffle
strBoardTemp = vbNullString
strWordsTemp = vbNullString
iScoreTemp = 0
FindWords
If iScoreTemp > iScore Or iScore = 0 Then
iScore = iScoreTemp
k = 1
For i = 1 To 4
For j = 1 To 4
strBoardTemp = strBoardTemp & AllDice(k).Side(Board(j, i)) & " "
k = k + 1
Next j
strBoardTemp = strBoardTemp & vbNewLine
Next i
strBoard = strBoardTemp
strWords = strWordsTemp
End If
Loop
Debug.Print strBoard
Debug.Print strWords
Debug.Print iScore & " points"
Set AllWordsTree = Nothing
Set AllWords = Nothing
Set CurWords = Nothing
Set FullWords = Nothing
Set JunkWords = Nothing
Set WordPrefixes = Nothing
End Sub
Sub ShuffleBoard()
Dim i As Integer
For i = 1 To 16
If Not WithinTimeLimit Then Exit Sub
Board(Int((i - 1) / 4) + 1, 4 - (i Mod 4)) = Int(6 * Rnd() + 1)
Next i
End Sub
Sub Shuffle()
Dim n As Long
Dim Temp As Variant
Dim j As Long
Randomize
ShuffleBoard
For n = 1 To 16
If Not WithinTimeLimit Then Exit Sub
j = CLng(((16 - n) * Rnd) + n)
If n <> j Then
Set Temp = AllDice(n)
Set AllDice(n) = AllDice(j)
Set AllDice(j) = Temp
End If
Next n
Set FullWords = New Scripting.Dictionary
Set CurWords = New Scripting.Dictionary
Set JunkWords = New Scripting.Dictionary
End Sub
Sub ReadWordsFileTree()
Dim FSO As New FileSystemObject
Dim FS
Dim strTemp As Variant
Dim iLength As Integer
Dim StartTime As Date
StartTime = Now()
Set AllWordsTree = New Tree
Set FS = FSO.OpenTextFile("P:\Personal\english.txt")
Points(3) = 1
Points(4) = 1
Points(5) = 2
Points(6) = 3
Points(7) = 5
Points(8) = 11
Do Until FS.AtEndOfStream
strTemp = FS.ReadLine
If strTemp = LCase(strTemp) Then
iLength = Len(strTemp)
iLength = IIf(iLength > 8, 8, iLength)
If InStr(strTemp, "'") < 1 And iLength > 2 Then
AllWordsTree.AddtoTree strTemp
End If
End If
Loop
FS.Close
End Sub
Function GetScoreTree() As Integer
Dim TempScore As Integer
If Not WithinTimeLimit Then Exit Function
GetScoreTree = 0
TempScore = AllWordsTree.WordScore(CheckWordSub, 0)
Select Case TempScore
Case Is < 3:
GetScoreTree = 0
Case Is > 8:
GetScoreTree = 11
Case Else:
GetScoreTree = Points(TempScore)
End Select
End Function
Sub SubWords(CheckWord As String)
Dim CheckWordScore As Integer
Dim k As Integer, l As Integer
For l = 0 To Len(CheckWord) - 3
For k = 1 To Len(CheckWord) - l
If Not WithinTimeLimit Then Exit Sub
CheckWordSub = Mid(CheckWord, k, Len(CheckWord) - ((k + l) - 1))
If Len(CheckWordSub) >= 3 And Not CurWords.Exists(CheckWordSub) Then
CheckWordScore = GetScoreTree
If CheckWordScore > 0 Then
CurWords.Add CheckWordSub, CheckWordSub
iScoreTemp = iScoreTemp + CheckWordScore
strWordsTemp = strWordsTemp & CheckWordSub & vbNewLine
End If
If Left(CheckWordSub, 1) = "q" Then
k = k + 1
End If
End If
Next k
Next l
End Sub
Sub FindWords()
Dim CheckWord As String
Dim strBoardLine(1 To 16) As String
Dim Used(1 To 16) As Boolean
Dim i As Integer, j As Integer, k As Integer, l As Integer, m As Integer, n As Integer
Dim StartSquare As Integer
Dim FullCheck As Variant
n = 1
For l = 1 To 4
For m = 1 To 4
If Not WithinTimeLimit Then Exit Sub
strBoardLine(n) = AllDice(n).Side(Board(m, l))
n = n + 1
Next m
Next l
For i = 1 To 16
For k = 1 To 16
If Not WithinTimeLimit Then Exit Sub
If k Mod 2 = 0 Then
For j = 1 To 16
Used(j) = False
Next j
Used(i) = True
MakeWords strBoardLine, Used, i, k / 2, strBoardLine(i)
End If
Next k
Next i
For Each FullCheck In FullWords.Items
SubWords CStr(FullCheck)
Next FullCheck
End Sub
Function MakeWords(BoardLine() As String, Used() As Boolean, _
Start As Integer, _
Direction As Integer, CurString As String) As String
Dim i As Integer, j As Integer, k As Integer, l As Integer
j = 0
Select Case Direction
Case 1:
k = Start - 5
Case 2:
k = Start - 4
Case 3:
k = Start - 3
Case 4:
k = Start - 1
Case 5:
k = Start + 1
Case 6:
k = Start + 3
Case 7:
k = Start + 4
Case 8:
k = Start + 5
End Select
If k >= 1 And k <= 16 Then
If Not WithinTimeLimit Then Exit Function
If Not Used(k) Then
If ValidSquare(Start, k) Then
If Not (JunkWords.Exists(CurString & BoardLine(k))) And Not FullWords.Exists(CurString & BoardLine(k)) Then
Used(k) = True
For l = 1 To MAX_LENGTH
If Not WithinTimeLimit Then Exit Function
MakeWords = CurString & BoardLine(k)
If Not (JunkWords.Exists(MakeWords)) Then
JunkWords.Add MakeWords, MakeWords
End If
If Len(MakeWords) = MAX_LENGTH And Not FullWords.Exists(MakeWords) Then
FullWords.Add MakeWords, MakeWords
ElseIf Len(MakeWords) < MAX_LENGTH Then
MakeWords BoardLine, Used, k, l, MakeWords
End If
Next l
Used(k) = False
End If
End If
End If
End If
If Len(MakeWords) = MAX_LENGTH And Not FullWords.Exists(MakeWords) Then
FullWords.Add MakeWords, MakeWords
Debug.Print "FULL - " & MakeWords
End If
End Function
Function ValidSquare(StartSquare As Integer, EndSquare As Integer) As Boolean
Dim sx As Integer, sy As Integer, ex As Integer, ey As Integer
If Not WithinTimeLimit Then Exit Function
sx = (StartSquare - 1) Mod 4 + 1
ex = (EndSquare - 1) Mod 4 + 1
sy = Int((StartSquare - 1) / 4 + 1)
ey = Int((EndSquare - 1) / 4 + 1)
ValidSquare = (sx - 1 <= ex And sx + 1 >= ex) And (sy - 1 <= ey And sy + 1 >= ey) And StartSquare <> EndSquare
End Function
Function WithinTimeLimit() As Boolean
StopTime = Now()
WithinTimeLimit = (Round(CDbl(((StopTime - StartTime) - Int(StopTime - StartTime)) * 86400), 0) < 120)
End Function
```
[Answer]
Quick look at size of the search space.
```
16! => 20922789888000 Dice Permutations
(6^16) => 2821109907456 Face Permutations
59025489844657012604928000 Boggle Grids
```
Reducing to exclude the repetition on each die.
```
16! => 20922789888000 Dice Permutations
(4^4)*(5^6)*(6^5) => 31104000000 Unique Face Permutations
650782456676352000000000 Boggle Grids
```
@breadbox store the dictionary as an Hash Table O(1) checking.
**EDIT**
Best Board (I've witnessed so far)
```
L E A N
S E T M
T S B D
I E G O
Score: 830
Words: 229
SLEETIEST MANTELETS
MANTEELS MANTELET MATELESS
MANTEEL MANTELS TESTEES BETISES OBTESTS OBESEST
SLEETS SLEEST TESTIS TESTES TSETSE MANTES MANTEL TESTAE TESTEE
STEELS STELES BETELS BESETS BESITS BETISE BODGES BESEES EISELS
GESTES GEISTS OBTEST
LEANT LEATS LEETS LEESE LESES LESTS LESBO ANTES NATES SLEET SETAE
SEATS STIES STEEL STETS STEAN STEAM STELE SELES TAELS TEELS TESTS
TESTE TELES TETES MATES TESTA TEATS SEELS SITES BEETS BETEL BETES
BESET BESTS BESIT BEATS BODGE BESEE DOGES EISEL GESTS GESTE GESSE
GEITS GEIST OBESE
LEAN LEAT LEAM LEET LEES LETS LEST LESS EATS EELS ELSE ETNA ESES
ESTS ESSE ANTE ANTS ATES AMBO NATS SLEE SEEL SETA SETS SESE SEAN
SEAT SEAM SELE STIE STET SEES TAEL TAES TEEL TEES TEST TEAM TELE
TELS TETS TETE MATE MATS MAES TIES TEAT TEGS SELS SEGO SITS SITE
BEET BEES BETA BETE BETS BEST BEAN BEAT BEAM BELS BOGS BEGO BEGS
DOGE DOGS DOBS GOBS GEST GEIT GETS OBES
LEA LEE LET LES EAN EAT EEL ELS ETA EST ESS ANT ATE NAT NAE NAM
SEE SET SEA SEL TAN TAE TAM TEE TES TEA TEL TET MNA MAN MAT MAE
TIE TIS TEG SEG SEI SIT BEE BET BEL BOD BOG BEG DOG DOB ITS EGO
GOD GOB GET OBS OBE
EA EE EL ET ES AN AT AE AM NA ST TA TE MA
TI SI BE BO DO IT IS GO OD OB
```
[Answer]
My entry is over [here](http://www.dreamincode.net/forums/topic/283066-boggle-the-dawg/ "Boggle The DAWG") on Dream.In.Code ~30ms per a board search (on a 2 core machine, should be quicker with more cores)
] |
[Question]
[
There is a well-known bijection between the permutations of \$n\$ elements and the numbers \$0\$ to \$n!-1\$ such that the lexicographic ordering of the permutations and the corresponding numbers is the same. For example, with \$n=3\$:
```
0 <-> (0, 1, 2)
1 <-> (0, 2, 1)
2 <-> (1, 0, 2)
3 <-> (1, 2, 0)
4 <-> (2, 0, 1)
5 <-> (2, 1, 0)
```
It is also well-known that the permutations of \$n\$ elements form a group (the symmetric group of order \$n!\$) - so, in particular, that one permutation of \$n\$ elements applied to a second permutation of \$n\$ elements yields a permutation of \$n\$ elements.
For example, \$(1, 0, 2)\$ applied to \$(a, b, c)\$ yields \$(b, a, c)\$, so \$(1, 0, 2)\$ applied to \$(2, 1, 0)\$ yields \$(1, 2, 0)\$.
Write a program which takes three integer arguments: \$n\$, \$p\_1\$, and \$p\_2\$; interprets \$p\_1\$ and \$p\_2\$ as permutations of \$n\$ elements via the bijection described above; applies the first to the second; and outputs the corresponding integer, reapplying the above bijection. For example:
```
$ ./perm.sh 3 2 5
3
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
[Answer]
## J, 30
I like the elegance of this:
```
[:A.[:{/]A.~/~i.@[
```
or this:
```
13 :'A.{/(i.x)(A.)~/y'
```
but they work like this:
```
3 f 2 5
3
12 f 8 9
17
```
So this is the valid entry:
```
([:A.[:{/i.@{.A.~/}.)".}.>ARGV
```
Some explanations:
* `3 A. 0 1 2`: gives the 3rd permutation of `0 1 2` (= `1 2 0`)
* `0 1 2 (A.)~ 3`: is the same but with arguments reversed
* `0 1 2 (A.)~/ 3 4 5 ...` "applies" `(A.)~` to `3 4 5 ...`, so it gives the 3rd, 4th, 5th, ... permutation of `0 1 2`.
* `A. 1 2 0`: gives the order of the permutation of `1 2 0` (= 3)
* `i. n`: gives the sequence `0 1 2 ... n-1`
* `1 2 0 { 0 2 1` arranges `0 2 1` by `1 2 0` (= `2 1 0`)
[Answer]
# Ruby - 77 chars
```
n,a,b=$*.map &:to_i
l=[*[*0...n].permutation]
p l.index(l[b].values_at *l[a])
```
[Answer]
## Python 2.6, 144 chars
```
import sys
from itertools import*
n,p,q=map(int,sys.argv[1:])
R=range(n)
P=list(permutations(R))
print P.index(tuple(P[q][P[p][i]] for i in R))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
œ?Ụị¥/Œ¿
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//xZM/4buk4buLwqUvxZLCv////zMsIDb/NA "Jelly – Try It Online")
Uses 1-indexing, Jelly's default (i.e. just increment every number in the challenge body). [+2 bytes](https://tio.run/##ASYA2f9qZWxsef//4oCYxZM/4buk4buLwqUvxZLCv@KAmf///zIsIDX/Mw) to use zero indexing. Takes \$[p\_1, p\_2]\$ on the left and \$n\$ on the right.
The text of the question is kinda confusing. "Applying" one permutation to another is essentially sorting the elements of the second by the values of the first, which is exactly what "grade up, then index into" does.
## How it works
```
œ?Ụị¥/Œ¿ - Main link. Takes [p1, p2] on the left and n on the right
œ? - Generate the permutations of [1, 2, ..., n], then yield the p1'th and p2'th values
¥/ - Reduce those permutations by the following, with perm(p1) on the left and perm(p2) on the right:
Ụ - Grade up perm(p1); This sorts the indices of perm(p1) by their corresponding values
ị - Index into perm(p2) with these sorted indices
Œ¿ - Sort the corresponding list, get all permutations and find it's index in them
```
] |
[Question]
[
Given two positive numbers \$x\$ and \$n\$ with \$x<2^n\$, write the shortest possible function to compute \$x^{-1} \mod 2^n\$. In other words, find \$y\$ such that \$xy=1 \mod 2^n\$.
Your function must complete in a reasonable time for at least \$n=64\$, so exhaustive search will not work.
If the inverse does not exist, you must indicate that to the caller somehow (throw an exception, return a sentinel value, etc).
If you're wondering where to start, try the [Extended Euclidean Algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm).
[Answer]
# Python, 29 bytes
```
lambda x,n:pow(x,2**n-1,2**n)
```
This returns 0 for even *x*. It uses Euler’s theorem, with the observation that 2^*n* − 1 is divisible by 2^(*n* − 1) − 1, via Python’s builtin fast modular exponentiation. This is plenty fast enough for *n* up to 7000 or so, where it starts taking more than about a second.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 25 bytes
```
lambda a,b:pow(a,-1,2**b)
```
[Try it online!](https://tio.run/##XY3PCsIwDMbvfYqwUzfq2CaiDDz6Cp68tK7DQteWNP7Z09duigc/SAhffl8SZrp5tz0ETCMc4ZKsnNQgQQrVB//kUmxa0VWVKpOZgkeCOEfGRo9gjdNg3GLUkQbjegZZhPNnWCQFqHx2koEbR2LN1DFYQ7wsf1TAvOQjX@ivrV9XHQjO0t71CdFj/0cXzlP@/tBIRlldlKltYMf2a3UN2ze5vwE "Python 3.8 (pre-release) – Try It Online")
[Answer]
## Mathematica - 22
```
f=PowerMod[#,-1,2^#2]&
```
`f[x,n]` returns `y` with `x*y=1 mod 2^n`, otherwise `x is not invertible modulo 2^n`
[Answer]
## GolfScript (23 chars)
```
{:^((1${\.**2^?%}+*}:f;
```
The sentinel result for a non-existent inverse is `0`.
This is a simple application of [Euler's theorem](http://en.wikipedia.org/wiki/Euler's_theorem). \$x^{\varphi(2^n)} \equiv 1 \pmod {2^n}\$, so \$x^{-1} \equiv x^{2^{n-1}-1} \pmod {2^n}\$
Unfortunately that's rather too big an exponential to compute directly, so we have to use a loop and do modular reduction inside the loop. The iterative step is \$x^{2^k-1} = \left(x^{2^{k-1}-1}\right)^2 \times x\$ and we have a choice of base case: either `k=1` with
```
{1\:^(@{\.**2^?%}+*}:f;
```
or `k=2` with
```
{:^((1${\.**2^?%}+*}:f;
```
---
I'm working on another approach, but the sentinel is more difficult.
The key observation is that we can build the inverse up bit by bit: if \$xy \equiv 1 \pmod{2^{k-1}}\$ then \$xy \in \{ 1, 1 + 2^{k-1} \} \pmod{2^k}\$, and if \$x\$ is odd we have \$x(y + xy-1) \equiv 1 \pmod{2^k}\$. (If you're not convinced, check the two cases separately). So we can start at any suitable base case and apply the transformation \$y' = (x+1)y - 1\$ a suitable number of times.
Since \$0x \equiv 1 \pmod {2^0}\$ we get, by induction
\$x\left(\frac{1 - (x+1)^n}{x}\right) \equiv 1 \pmod {2^n}\$
where the inverse is the sum of a geometric sequence. I've shown the derivation to avoid the rabbit-out-of-a-hat effect: given this expression, it's easy to see that (given that the bracketed value is an integer, which follows from its derivation as a sum of an integer sequence) the product on the left must be in the right equivalence class if \$x+1\$ is even.
That gives the 19-char function
```
{1$)1$?@/~)2@?%}:f;
```
which gives correct answers for inputs which have an inverse. However, it's not so simple when \$x\$ is even. One potentially interesting option I've found is to add `x&1` rather than `1`.
```
{1$.1&+1$?@/~)2@?%}:f;
```
This seems to give sentinel values of either \$0\$ or \$2^{n-1}\$, but I haven't yet proved that.
Taking that one step further, we can ensure a sentinel of \$0\$ for even numbers by changing the expression \$1 - (x+1)^n\$ into \$1 - 1^n\$:
```
{1$.1&*)1$?@/~)2@?%}:f;
```
That ties with the direct application of Euler's theorem for code length, but is going to have worse performance for large \$n\$. If we take the arguments the other way round, as `n x f`, we can save one character and get to **22 chars**:
```
{..1&*)2$?\/~)2@?%}:f;
```
[Answer]
## Python 95 89
`c` is your function. Returns 0 if there is no inverse (i.e. when x is even).
```
p=lambda x,y,m:y and p(x,y/2,m)**2*x**(y&1)%m or 1
c=lambda x,n:[0,p(x,2**n-1,2**n)][x%2]
```
[Answer]
## Ruby - 88 characters
Use the function `f`.
```
def e a,b;a%b==0?[0,1]:(x,y=e(b,a%b);[y,x-(y*(a/b))])end
def f x,n;e(x,2**n)[0]*(x%2)end
```
Simply the recursive function from the linked wiki page, returns 0 on error.
[Answer]
# Haskell, 42 bytes
```
_!1=1
x!n|r<-x!div(n+1)2=(2-r*x)*r`mod`2^n
```
Using an [algorithm based on Hensel’s lemma](http://arxiv.org/abs/1209.6626) that doubles the number of digits in every iteration, this runs in under a second for *n* up to about 30 *million*!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
.^Et^2Q^2
```
[Try it here!](https://pyth.herokuapp.com/?code=.%5EEt%5E2Q%5E2&input=9%0A5&debug=0)
Takes input in reverse order. Or, 9 bytes too: `.^EtK^2QK`.
# Explanation
```
.^Et^2Q^2 - Full program.
.^ - Pow function. The same in Python (pow).
E - The second input.
^2Q - And 2 ^ first input.
t - Decremented.
^2 - And 2 ^ first input again.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
2*æi@
```
[Try it online!](https://tio.run/##y0rNyan8/99I6/CyTIf/1kqHlzvoP2pa4/7/f7ShgY6CaayOQrQ5gjYyADMMwCwA "Jelly – Try It Online")
Takes input with \$n\$ first and \$x\$ second, returns \$0\$ if no such inverse exists. The Footer in the TIO link reverses the input for you and formats the test cases.
## How it works
```
2*æi@ - Main link. Takes n on the left and x on the right
2* - Yield 2*n
æi@ - Modular inverse of x, modulo 2*n, or if none exists, 0.
```
[Answer]
# GAP, 39 bytes
```
f:=function(x,n)return 1/x mod 2^n;end;
```
`f(x,n)` returns the inverse of `x` modulo `2^n` and gives an error message
```
Error, ModRat: for <r>/<s> mod <n>, <s>/gcd(<r>,<s>) and <n> must be coprime
```
if no inverse exists.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 10 9 bytes
```
2\?:q(?q%
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPlvrGDy3yjG3qpQw75Q9f9/AA "GolfScript – Try It Online")
A port of Mr. XCoder's solution, to GS. Stack manipulation is a little messy, could probably be done with a little tomfoolery. Takes in input as X N.
V 1.1 : Improved stack manip, it sucks a lot less now.
```
2\?:q(?q% #Multiplicative Inverse
2\ #Move "2" to the second pos on the stack. X 2 N
? #Exponentiate. X 2^N
:q #Remember, q is 2^N.
( #Decrement. X 2^N-1
? #Exponentiate. X^(2^N-1)
q? #Mod by 2^N.
# X^([2^N] -1) % 2^N is the multiplicative inverse, since
# X^([2^N] -1)*X = X^(2^N)
# which is 1 mod 2^N if X and 2^N are coprime.
```
If there is no M.I., it will return 0.
[Answer]
# [Python 3](https://docs.python.org/3.8/), ~~77~~ 57 bytes
```
f=lambda x,n,b=1,i=1:n and f(x,n-1,b-(b&i)*~-x,i+i)or b%i
```
Outgolfed all you snek users (except for the `pow(x, -1, 2**n)` cheapshots) with nothing but pure algorithm.
[Try it online!](https://tio.run/##XU7tboMgFP3vU9y4rMWONgo2oIkPAxPbu1gkwrb2z17dgWbJUpL7weFwznGPcJ0sl25elqEb1U33Cu7UUt1VFLuqtaBsDwOJ2LGi@kj0DovDz/FO8Q2LaQb9igve3DQH8A@fvYBbJYGfJKCHj08fYIi8cDWQm7sz78HnWUJGtAbQpm8nH3q0bQbxKAoaOrgpR9AGutJO3o0YSFGsDDfHB/In1kJOQe2qNaibvomiMSk7HHSKl9spRJMvMwfUo8mpsX23p3CZQgv7TS9Eu4Ek3@2OQ4I6KLdA/yyfxDa6Gb15ZoZiqUo4Z2ItVmaiTL3hsmaiil3WggvBZFrPMg4m2VnUgjWsKXkt05S8qaUAyfgv "Python 3.8 (pre-release) – Try It Online") (Only uses Python 3.8 for comparison against `pow(a,-1,2**n)`)
Ungolfed version:
```
def func(value, shift, acc = 1, mask = 1):
if value != 0:
return func(value, shift - 1, acc - (acc & mask) * (value - 1), mask << 1)
else:
return acc & (mask - 1)
```
Or, as a loop with size hacks removed:
```
def func(value, exponent):
value -= 1
acc = 1
for i in range(exponent):
if acc & (1 << i):
acc -= value << i
return acc & ((1 << i) - 1)
```
## Explanation
The function is a lambda called `f`. It takes two positive integers, and returns either the multiplicative modular inverse or zero.
You may be wondering what the heck is going on. This uses a different, faster, and smaller algorithm for modular inverse for powers of 2 instead of the Euclidian approach.
I'm not going to go too far into the details of *why* it works, as it is really complex and explained better by others. Translation: even I don't fully understand it.
This set of algorithms is explained [here on algassert](https://algassert.com/post/1709) with a related algorithm explained [here on Crypto SE](https://crypto.stackexchange.com/questions/47493/how-to-determine-the-multiplicative-inverse-modulo-64-or-other-power-of-two) with some interesting papers linked.
This algorithm actually uses no true multiplication (just shifts), the multiplication is just a shortcut for size.
This naturally returns `0` for even numbers, as the *odd* subtraction (we start with `x - 1`) causes a chain reaction of trailing with `0b0`, which, when masked off, turns the result to zero. No need for a manual sentinel.
```
0000 0001 - 0000 1101 -> 1111 0010
1111 0010 - 0001 1010 -> 1110 0000
```
] |
[Question]
[
The [TAK function](https://mathworld.wolfram.com/TAKFunction.html) is defined as follows for integers \$x\$, \$y\$, \$z\$:
$$
t(x, y, z) = \begin{cases}
y, & \text{if $x \le y$} \\
t(t(x-1,y,z), t(y-1,z,x), t(z-1,x,y)), & \text{otherwise}
\end{cases}
$$
Since it can be proved that it always terminates and evaluates to the simple function below,
$$
t(x, y, z) = \begin{cases}
y, & \text{if $x \le y$} \\
z, & \text{if $x > y$ and $y \le z$} \\
x, & \text{otherwise}
\end{cases}
$$
your job is not to just implement the function, but **count the number of calls to \$t\$** when initially called with the given values of \$x\$, \$y\$, and \$z\$. (As per the standard rules, you don't need to implement \$t\$ if there is a formula for this value.)
You may assume that the three input values are nonnegative integers.
Note that the task is slightly different from the definition of the function \$T\$ (the number of "otherwise" branches taken) on the Mathworld page.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
(x, y, z) -> output
(0, 0, 1) -> 1
(1, 0, 2) -> 5
(2, 0, 3) -> 17
(3, 0, 4) -> 57
(4, 0, 5) -> 213
(5, 0, 6) -> 893
(1, 0, 0) -> 5
(2, 0, 0) -> 9
(2, 1, 0) -> 9
(3, 0, 0) -> 13
(3, 1, 0) -> 29
(3, 2, 0) -> 17
(4, 0, 0) -> 17
(4, 1, 0) -> 89
(4, 2, 0) -> 53
(4, 3, 0) -> 57
(5, 0, 0) -> 21
(5, 1, 0) -> 305
(5, 2, 0) -> 149
(5, 3, 0) -> 209
(5, 4, 0) -> 213
```
[Python implementation](https://ato.pxeger.com/run?1=jVExDsIwDNz7ittohCvBghCi_CVAA5UqF4VUavoVFhZ4DOID_Ia0CW0FC57sy53Pdi73kzXHkq_XW2VUsnw995mCimuCJTRiFcHFThbFGSlmXdUyzBejDS65KB3V03vYi6cp5j2UK9RYp7Ar6MxUmmH7twCY2Fkkc7LUCHKVdXlDdZc3Lq_JCtGJhlGikb5zDTs9VKnByBla8iGLF2HooHOLMWFG4Kkf8aRzNnHfljBJNhMaXUVEkee4pO0tf3u38HaA5ehOg60kbClc9T9jv9Hnt94) was used to generate the test cases.
[Answer]
# JavaScript (ES6), 73 bytes
**Using a single recursive function**
Expects `(x, y, z)`.
```
f=(x,y,z,w)=>x>(r=y)?f(x-1,y,z)+f(y-1,z,x,w=r)+f(z-1,x,y,z=r)-~f(w,z,r):1
```
[Try it online!](https://tio.run/##bZJNboMwEIX3nGLUDbZiIoyhDYlMVj0FYoFS6I9QqCBtgKo9QaVuumzv0fPkAj0CHWzSOGmlkeX5PO/N2PJd@pjWq@r2fuOsy6us73NJGtayjm2pjJqIVLKly5w0Dh8oneSkxW3HGraV1ZB2mCoFps5LTrZ4WNE57xexBRCDy4bgGACQMMW4Yh6D4MA8xQTWXfwyoZiPdQfmKxagnIs9CxQ7ZzALxXEP958eGOER46dM7OuwhcHGsUOTaUt@Ot8fprWz0GRaGwiT6dbGfYO9n8dNpv2EGxhsnMUPDab9PNdk/uiHb2Ul1jQvq8t0dUNIDA2DlkHHoHzYQEJBRvAERbaBKqtBAv4DXUAXsCrXdVlk06K8JvGIE5jAGTgRLhMlGdJhT5ReKtsl2N9fb7uPd1xtmIO9@3y1KTo@0/4H "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
x, y, z, // (x, y, z) = input integers
w // w = local variable
) => //
x > (r = y) ? // save y in the global r; if x is greater than y:
f(x - 1, y, z) + // process the 1st recursive call
f(y - 1, z, x, w = r) + // save r in w and process the 2nd recursive call
f(z - 1, x, y, z = r) - // save r in z and process the 3rd recursive call
~f(w, z, r) // last recursive call, using the previous results
// add all returned values together, and add 1
: // else:
1 // stop and return 1
```
---
# JavaScript (ES6), 76 bytes
**Using a wrapper function**
Expects `[x, y, z]`.
Simply does exactly what is said on the tin.
```
a=>(r=0,(t=(x,y,z)=>++r&&x>y?t(t(x-1,y,z),t(y-1,z,x),t(z-1,x,y)):y)(...a),r)
```
[Try it online!](https://tio.run/##bdBdToNAEAfw955i4kPZDVvCsqClzdInT0F4IC31I00xsBrAeAMTX3zUe3ieXsAj4LCA3VaTDRl@mfnPwn36lJbr4u5Bzfb5Jmu3sk1lRArpMqIkqVjNGioj2y6m0yqqV4ooUs24ZqZIjWXDqq5ssMR2Shc1JY7jpJQVtF3GE4AYXNYdjgcAEqaNa/MYBEfztAnsu/o1oc3HvqP52gIc52K0QNslg3koTne4/@zAE54YPzcx9uEKw4Zrh6b1kfz8fn@sn52HpvWzgTCtX218bzDmedy0Pk@4gWHDXfzQsD7Pc03zhzz8V5Nk4mzz4jpd3xISQ8WgZtAwyB8VJBRkBM@wyxQUWQkStiQeOhK6hHW@L/Nd5uzym6ODDRcwi/Bh66HutauJTpA6eAXW99fb4eMdnxYswDp8vloUE19o@wM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), (22?) 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṙJ_JỊ$ṙ-Ñ€Ñ
‘ɼṛṖṪÇ}ṢƑ?
Çṛ®
```
A full program that accepts a list of three non-negative integers, `[x, y, z]`, and prints the call count. (Or 22 bytes as a monadic Link that accepts the same and accumulates in the register (?) - remove the last line.)
**[Try it online!](https://tio.run/##AUgAt/9qZWxsef//4bmZSl9K4buKJOG5mS3DkeKCrMORCuKAmMm84bmb4bmW4bmqw4d94bmixpE/CsOH4bmbwq7///9bNSwgMywgMF0 "Jelly – Try It Online")** or see the [test suite](https://tio.run/##y0rNyan8///hzple8V4Pd3epAFm6hyc@alpzeCLXo4YZJ/c83Dn74c5pD3euOtxe@3DnomMT7bkOtwMFD60D6mo7tPLE@sPtOg5HJz3cOSPrUcMcBVs7hUcNczUj//@PjjbQUQAiw1gdhWhDMNMIxDQCM41BTGMw0wTENAEzTUFMUzDTDKHNAKENxjSEMo0RosYookZQpglCgQlCgQmKAmMo0xSh1hSh1hSh1hRFLcjo2FgA "Jelly – Try It Online").
### How?
There's probably a clever way to produce the count, but this implements the description from the question.
```
ṙJ_JỊ$ṙ-Ñ€Ñ - Link 1: [x, y, z]
J - indices {[x, y, z]} -> [1, 2, 3]
ṙ - {[x, y, z]} rotate left by -> [[y, z, x], [z, x, y], [x, y, z]]
$ - last two links as a monad - f([x, y, z]):
J - indices {[x, y, z]} -> [1, 2, 3]
Ị - insignificant? -> [1, 0, 0]
_ - subtract -> [[y-1, z, x], [z-1, x, y], [x-1, y, z]]
ṙ- - rotate right -> [[x-1, y, z], [y-1, z, x], [z-1, x, y]]
Ñ€ - call Link 2 for each
Ñ - call link 2
-
‘ɼṛṖṪÇ}ṢƑ? - Link 2, t: [x, y, z]
ɼ - apply to the register and yield:
‘ - increment
Ṗ - pop {[x, y, z]} -> [x, y]
ṛ - right argument -> [x,y]
? - if...
Ƒ - ...condition: is {[x, y]} invariant under?:
Ṣ - sort
Ṫ - ...then: tail -> y
Ç} - ...else: call Link 1 as a monad - f(x, y, z)
Çṛ® - Main Link: [x, y, z]
Ç - call Link 2 as a monad - t(x, y, z)
® - recall from the register -> count
ṛ - right argument -> count
```
[Answer]
# [Perl 5](https://www.perl.org/) `-Mfeature+signatures -ap`, 83 bytes
```
sub f($x,$y,$z){++$;;$y<$x?f(f($x-1,$y,$z),f($y-1,$z,$x),f($z-1,$x,$y)):$y}f@F;$_=$
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhTUOlQkelUkelSrNaW1vF2lql0kalwj5NAyShawiV0gHyKkG8Kh2VCjCvCsQD6dTUtFKprE1zcLNWibdV@f/fSMFAwfhffkFJZn5e8X9d37TUxJLSolTt4sz0PDALKFiQCAA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 103 bytes
```
def t(x,y,z):t.c+=1;return t(t(x-1,y,z),t(y-1,z,x),t(z-1,x,y))if x>y else y
t.c=0
t(*input())
print t.c
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dY9BTsQwDEX3OYXVzSSMi6YsECrq3CVt06HS4FbBlZpehU03o5G4EUtugttUIARk46__Yz_79doHfurobn6rutpBAUmSXAZu0of3U-0aYD1iwMnkfFvti-zROx48iS1Bmq0Rsg4iJxwXOYmUFmPaBsZjAHd-cRCUtBcHxfqmpX5gbYzqfUsM4m-4DyEr1XQeCFoCb-nk9L3JFchbu2S7s30ua5uDJoQDAu0zs-Zx2DYbYZced7gGbnQVLKepCIwE-5uw2OW3bTf7T7hFKIVvvn78i_-xQjx0nmP9BA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 116 bytes
```
≔⦃⦄θ⊞υE³NFυ«≔I⪫()⪫ι,ηF¬§θη¿‹§ι¹§ι⁰«≔EιEι⁻§ι⁺μξ¬ξζ⊞ζEζ§λ∨¬‹§λ¹§λ⁰⊗¬‹§λ²§λ¹≔Eζ§θI⪫()⪫λ,ε¿⬤ελ§≔θη⊕ΣεF⊞Oζι⊞υλ»§≔θη¹»I§θη
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVJNT8JAEE280V8x6Wk3WRKKFxNORC8YBYxH46GURTaZbmE_DIHwS7xw0Ohv8te40y1KDb10tjNv3tv3-vZVLHNTVDkeDh_eLbpX3xcPQ2vVi2a7vYA1HyRTb5fMC7jPV-xSwEivvBv7ciYN4zz0F5UB5jnskk6DvM6tY7eV0ixlPBVQl0pAKtKAELAMqE4NG1eODd1Iz-WGranBOagFsDtp7W8jILOAOjn2aC7wHQlJmooK6aW0b6GnGM6lgA2RE2UoqNySjk59v21Eb_9oUMDE1AJbYrAtBqMYATeVn6GcnwX024CMN8-gfYMT8uDFWRPxaCJRynoB2TVEZFIABlfivlNPKbLCyFJqF_Q9-pLJhluilVDnQB5MVtLkrjKkQ4VNx9yRZvdJnD63PgsD-2RqlHYx-n-JDt7trLDN__X5lHZfMX3-yKAH_fjtBw) Link is to verbose version of code. Explanation: Charcoal isn't really suited for this.
```
≔⦃⦄θ
```
Start with an empty dictionary which will hold `T(x, y, z)` for each required tuple.
```
⊞υE³N
```
Start with the input tuple.
```
Fυ«
```
Loop over the required tuples as they are found.
```
≔I⪫()⪫ι,η
```
Convert the tuples from a list to a Python tuple so that they can be used as a dictionary key.
```
F¬§θη
```
Test to see whether this tuple's `T` value is already known.
```
¿‹§ι¹§ι⁰«
```
Test to see whether this is a trivial tuple.
```
≔EιEι⁻§ι⁺μξ¬ξζ
```
Generate the dependent tuples, `(x-1, y, z)`, `(y-1, z, x)` and `(z-1, x, y)`.
```
⊞ζEζ§λ∨¬‹§λ¹§λ⁰⊗¬‹§λ²§λ¹
```
Also generate the fourth tuple by calculating `t` for each of these tuples nonrecursively.
```
≔Eζ§θI⪫()⪫λ,ε
```
Get any `T` values we have for these tuples already.
```
¿⬤ελ
```
If all of these tuples already have `T` values, then...
```
§≔θη⊕Σε
```
... take the sum and set this as the `T` value for the required tuple.
```
F⊞Oζι⊞υλ
```
Otherwise push all of the tuples to the list for reprocessing because it's simpler that way.
```
»§≔θη¹
```
If this is a trivial tuple then just set its `T` value to `1`.
```
»I§θη
```
Output the `T` value of the input tuple.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"¼Â¦`@iÅsë2Ý._εć<š®.V}®.V"©.V¾
```
Input as a triplet \$[x,y,z]\$.
[Try it online](https://tio.run/##yy9OTMpM/f9f6dCew02HliU4ZB5uLT682ujwXL34c1uPtNscXXhonV5YLYhQOrRSL@zQvv//ow11DHSMYv/r6ubl6@YkVlUCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/pUN7DjcdWpbgkHm4tfjwaqPDc/Xiz2090m5zdOGhdXphtSBC6dBKvbBD@/7r6B3a@j862kDHQMcwVifaEEgbAWkjIG0MpI2BtAmQNgHSpkDaFEibQdUZQNVBaEMwbQzlG8P5RmDaBCpuAhU3gYsbg2lTqLwpVN4UKm8KlweaEBv7X1c3L183J7GqEgA).
**Explanation:**
```
"..." # Push the recursive string explained below
© # Store it in variable `®` (without popping)
.V # Pop and evaluate it as 05AB1E code
¾ # Push counter variable `¾`
# (which is output implicitly as result)
¼ # Increase the counter variable `¾` by 1 (starts at 0 by default)
 # Bifurcate the current triplet; short for Duplicate & Reverse copy
# (which will use the implicit input-triplet in the first iteration)
¦ # Remove the first item of the reversed triplet (the z)
` # Pop and push y and x separated to the stack
@i # Pop both, and if x>=y:
Ås # Pop the triplet, and push its middle: y
ë # Else:
2Ý # Push list [0,1,2]
._ # Rotate the triplet that many times towards the left: [[x,y,z],[y,z,x],[z,x,y]]
ε # Map over each rotated triplet:
ć # Extract its head; push remainder-pair and first item separately
< # Decrease this first item by 1
š # Prepend it back to the pair
®.V # Do a recursive call by evaluating string `®`
}®.V # After the map: do a recursive call on the resulting triplet as well
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/), 82 bytes
```
func t(x,y,z){$0=++c;return x>y?t(t(x-1,y,z),t(y-1,z,x),t(z-1,x,y)):y}t($1,$2,$3)1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JY5BCoMwEEX3OUUWWSQYIRNtKS22d-gNitRNwYVEaiyepBtBeihv05_J5vEy_8-Q7_Z4v9b1N4auPO33buxbGfRko53NR7mmKNrL8Azj0MvpGm9BIyyJYxt0hM52SjpDsWbMOS5BK7LKW1UZype3tnHZ1n1x0kkSBHrhwUpUYC1q8CAO4JFTx2kiXtxJzI6E-4nEzBO0-EIiMT0zz7GRf_EH)
] |
[Question]
[
## Background
[Tetris Grand Master 3](https://harddrop.com/wiki/TGM3) has a hidden grading system based on the shape of the stack at the end of the game, which is called [**Secret ">" Stacking Challenge**](https://harddrop.com/wiki/Tetromino_art#Greater_than). It consists of entirely filling the lowest rows except for the zigzag pattern which starts at the left bottom cell and spans the entire width:
```
#
.#########
#.########
##.#######
###.######
####.#####
#####.####
######.###
#######.##
########.#
#########.
########.#
#######.##
######.###
#####.####
####.#####
###.######
##.#######
#.########
.#########
```
The board is graded by how many lines follow this exact pattern from the bottom line. Note that the topmost hole in the pattern must be blocked by an extra piece of block. If you consider the `#`s and `.`s as the mandatory pattern (blanks can be anything), you can get the score of 19 only if the exact pattern above is matched from the bottom line. Analogously, if the board matches this pattern
```
#
###.######
##.#######
#.########
.#########
```
but not
```
#
####.#####
###.######
##.#######
#.########
.#########
```
then the score is 4.
For this challenge, consider a board of arbitrary size (other than 20 cells high and 10 cells wide). We can grade the board for the same pattern: for example, if the board has width 4, this is the pattern for score 3:
```
#
##.#
#.##
.###
```
and this is the pattern for score 10:
```
#
###.
##.#
#.##
.###
#.##
##.#
###.
##.#
#.##
.###
```
## Challenge
Given the final state of the Tetris board of arbitrary size, grade the board using the system above.
You can take the board using any sensible format for a rectangular matrix, where every cell contains one of two distinct values (for empty and filled respectively). You can assume the grid is a valid Tetris board (no row is entirely filled). Also, the width of the grid is at least 2.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
In order to prevent possible confusion, the test cases here use `O` for the blocks and `.` for empty spaces.
```
Input:
..O.O
OOOO.
OOO..
OO.OO
O.OOO
.OOOO
Output: 3
Input:
..
O.
.O
.O
O.
.O
O.
.O
Output: 4
Input:
.OOO
O.OO
OO.O
OO.O
OO.O
O.OO
.OOO
Output: 2 (any lines above the first non-conforming line are ignored;
doesn't get 3 because 3rd line's hole is not capped)
Input:
OOO.
.OOO
O.OO
OO.O
OOO.
OO.O
O.OO
Output: 0 (Wrong starting hole)
Input:
.OOO
O.OO
OO.O
OOO.
Output: 0 (Wrong starting hole)
Input:
.OOO
.OOO
Output: 0 (Hole is not covered)
Input:
OOO...O..O
.OOOOOOOOO
O.OOOOOOOO
OO.OOOOOOO
OOO.OOOOOO
OOOO.OOOOO
OOOOO.OOOO
OOOOOO.OOO
OOOOOOO.OO
OOOOOOOO.O
OOOOOOOOO.
OOOOOOOO.O
OOOOOOO.OO
OOOOOO.OOO
OOOOO.OOOO
OOOO.OOOOO
OOO.OOOOOO
OO.OOOOOOO
O.OOOOOOOO
.OOOOOOOOO
Output: 19
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
Lδ↑€…¢ŀT¹↑εΨ↑-↔m¥0
```
[Try it online!](https://tio.run/##yygtzv7/3@fclkdtEx81rXnUsOzQoqMNIYd2Avnntp5bAaR0H7VNyT201OD////R0QY6hiAYqxMNpnUMoCwDPGIGUB0wvbEA "Husk – Try It Online")
Takes a 0-1 matrix.
## Explanation
There are three occurrences of `↑` in this program, and they all work differently thanks to the modifier functions `δ` and `Ψ`.
By default, `↑α` expects `α` to be a unary function, takes a list and returns the longest prefix of elements for which `α` returns a truthy value.
`Ψ↑α` expects `α` to be binary, and returns the longest prefix of elements `x` for which `α x y` is truthy, where `y` is the next element.
`δ↑α` expects `α` to be binary and takes two lists instead of one.
It returns the longest prefix of the second list whose elements `y` satisfy `α x y`, where `x` is the corresponding element of the first list.
```
Input is a list of lists of integers.
Example: [[0,1,1],[1,0,1],[1,1,0],[1,0,1],[1,1,0],[0,0,1],[0,1,1]]
m Map
¥0 indices where 0 occurs:
[[1],[1,2],[3],[2],[3],[2],[1]]
↔ Reverse:
[[1],[2],[3],[2],[3],[1,2],[1]]
↑ Take while
Ψ this element and the next
- have nonempty set difference:
[[1],[2],[3],[2],[3],[1,2]]
↑ Take while
ε this element is a singleton:
[[1],[2],[3],[2],[3]]
Call this list X.
ŀT¹ Indices of input transposed:
[1,2,3]
¢ Cycle infinitely:
[1,2,3,1,2,3,..]
… Rangify:
[1,2,3,2,1,2,3,2,1,..]
↑ Take from X while
δ the corresponding integer in this list
€ is an element of it:
[[1],[2],[3],[2]]
L Length: 4
```
[Answer]
# [J](http://jsoftware.com/), 57 42 bytes
Takes in 0 for blocked, 1 for empty.
```
[:#.~(|.@$2^|@}:@i:@<:)/@$=2#.[*[+_1|.!.2]
```
[Try it online!](https://tio.run/##jVDLCsIwELznK1YrtvExao@pQkDwJCx4DepN0W@o/nrNy1o0iiEZhmR2djPXpo/8RCtFOU1oTsqeKWi9224aozLcixp6UB5qfVP6ovRSyZkerMoMZmTGx0WNHsp9I5uz86CiIqPoRDkjH14ghTiTqXAsqfDeUgAMFmwXHMIh2N5YYOGAhUxUWYF9dTuQgAklRzPv2wVE/0SRn@ajktGp/KOT1X9R/Wjr8kD8uF8hiUhb7rUvGrmngQcaUuSWP@kzc26Df7tFwgGJbkhM9pq38wspHg "J – Try It Online")
### How it works
```
[*[+_1|.!.2]
```
Shift the board down by one (2 gets pushed in at the top to make sure the top spots don't count.) Then it adds to the original board and multiplies with itself. This basically boils down to: a valid open spot stays 1, while invalid ones become 2.
```
(|.@$2^|@}:@i:@<:)/@$
```
Given the dimensions, get the exclusive range `-x … x - 1` for the width, for e.g. 4: `_3 _2 _1 0 1 2`, and get their absolute values `3 2 1 0 1 2`. Resize that list to the height of the board, rotate it so the starting 3 aligns to the last row, and `2^x` the list: `8 4 2 1 2 4 8 4 2…`
```
=2#.
```
Interpret the rows as a base 2 number and compare it to the zig-zag list.
```
[:#.~
```
And by [reflexive base conversion](https://codegolf.stackexchange.com/a/98765/95594) we can count the leading 1's, so the leading rows that are valid.
[Answer]
# JavaScript (ES6), 84 bytes
Expects a list of strings, with `1` for empty spaces and `0` for blocks.
```
f=(a,i=j=1<<a[k=0].length)=>(v='0b'+a.pop()+0)^i?v&i/k&&-1:1+f(a,i*=k=i&j?.5:i&2||k)
```
[Try it online!](https://tio.run/##bVDBUoMwFLznK3IiibSv1BkvbdOe9JpDj1ZnIg00gICAnXGs344JoeBYMpnN8t5m2ZdEnmUdVrps5nlxVG0bcSpnmid8udnI55QHL5CpPG5OjG/pmZPgjfgSyqKkzA/Yq96dPb1IPW@@XC39yN694ynXXrKDh5X27i@XlLWV@vjUlaIkqgmDSsnjk87U/isPacCgKfZNpfOYMqjLTDeUHPJDboRRUT3K8ERrzLf4G2EsMcf1KDKSd1m6dm1sy0yGii5gEc9waIs@NQfHBAhjbG0MwiKvi0xBVsRUQlLo3PncNMl8iwn2sZmImaMTrdEPawEECCTMAotgEYSpGBDIgkDIVsF82O2Iw66PnN7ZDAD9bdS53goF/BFOttGQwHnYpNBH6pbL2NOBd9qR9ryjjjvq5hMDv9Lra4jhSf5VYcIBJv4GE8nGvOMUvw "JavaScript (Node.js) – Try It Online")
### How?
Each string in the input array is padded with an extra `0` and interpreted as a binary number. The variable `j` is initialized to `2**W`, where `W` is the width of the board. We use a bit mask `i` initialized to `j` to keep track of the expected position of the hole in the pattern.
After each iteration, `i` is multiplied by `k`. We update the value of `k` whenever `(i & j) != 0` (bouncing on the leftmost side) or `(i & 2) != 0` (bouncing on the rightmost side).
Example for `W = 5`:
```
j = 0b100000
i = 0b100000 // -> set k to 1/2
i = 0b010000 // \
i = 0b001000 // }-> leave k unchanged
i = 0b000100 // /
i = 0b000010 // -> set k to 2
i = 0b000100 // \
i = 0b001000 // }-> leave k unchanged
i = 0b010000 // /
i = 0b100000 // -> set k to 1/2
...
```
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input array
i = j = // i = hole bit mask, initialized to ...
1 << a[k = 0] // ... j = 2 ** W, where W is the width of the board
.length // k = bit mask multiplier, initialized to 0
) => //
( v = // pop the last value from a[], append a '0' and interpret
'0b' + a.pop() + 0 // it as a binary number saved in v
) ^ i ? // if v is not equal to i:
v & i / k // use the previous bit mask i / k to test whether there's
&& -1 // a hole in v above the last hole of the pattern, in
// which case we subtract 1 from the final result
: // else:
1 + // add 1 to the final result
f( // do a recursive call:
a, // pass a[] unchanged
i *= // multiply i by:
k = // the new value of k:
i & j ? // if we've reached the leftmost side:
.5 // set k to 1/2
: // else:
i & 2 // set k to 2 if we've reached the rightmost side,
|| k // or leave k unchanged otherwise
) // end of recursive call
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
WS⊞υι≔⮌υυP⪫υ¶W∧⁼.O⪫KD²↓ω⁼¹№§υⅉ.M✳⁻⁷⊗÷﹪ⅉ⊗⊖Lθ⊖Lθ≔ⅉθ⎚Iθ
```
[Try it online!](https://tio.run/##dZBPa4QwEMXvforgaQJpoL0UuifRHrZUlPZU6MXqoKFpsuaP9tvbibvgqRCGl7w3vyTTT53rbae3bZ2URgZnc4nhPThlRuCctdFPEAVT/JQV3qvRwBsu6DxC5IJFOq6jDupCDQFerDIpnX@anJN1YxZmgOc5dtpDLptcsD3XIn5XymEflDXwINhTZVdD0JVTueXvBSttJHQRzmbA30T/gBTIJV1BL6ztgnBwamWih0fBKhu/NA70oVCpRQ0ItR2itkDth1th7/AHTSD9imYME8wJS4l/HM6PUeyomfalxs4BiXafQ9n5kNKnbZMya2Qmm7Su4lq3u0X/AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of strings of `.` and `O` characters. Explanation:
```
WS⊞υι
```
Input the list.
```
≔⮌υυ
```
Reverse the list.
```
P⪫υ¶
```
Print the list without moving the cursor.
```
W∧
```
Repeat while both...
```
⁼.O⪫KD²↓ω
```
... the character under the cursor is a `.` and the character below (because the list was reversed) is an `O`, and...
```
⁼¹№§υⅉ.
```
... the current list line contains exactly one `.`:
```
M✳⁻⁷⊗÷﹪ⅉ⊗⊖Lθ⊖Lθ
```
Move the cursor diagonally down and either right or left depending on the row.
```
≔ⅉθ⎚Iθ
```
Capture the first invalid row index (0-indexed, so equal to the number of valid rows), clear the canvas, and print it as a string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ZJŒḄṖṁLW€⁻"ⱮṚT€,Ḋ$ƊZḄCTḢ’
```
A monadic Link accepting a list of lines where each line is a list of `1`s (empty) and `0`s (filled) which yields a non-negative integer (the score).
**[Try it online!](https://tio.run/##y0rNyan8/z/K6@ikhztaHu6c9nBno1f4o6Y1jxp3Kz3auO7hzlkhQJ7Owx1dKse6ooBqnEMe7lj0qGHm/4e7t9g@apird7j9/389PX89fy5/INADkXogUs8fKAIk/LlAhD8A "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##bZCxCsIwEIb3PIY4yr2Bk1uXWwpCdxfxBdxaEYSODoKii64iCA4NHUXf4/Ii8ZJLU9GE5ufL5e/lT@azxWJpbZG9ttSsSe9IV9nUrK6magfmfiN9yHk1oqYevuuCPZOcmrMp95baB@mLKY@mPI15wnPDTmsBEFAhD3AKTgG5woLKCSrlqsAL9wmI@n0lfmkTBcLfynf9NyJ8GZPbKiaQHi4phEh@SMaAkb23x8AehQXlfhi5w@41MD7JTxUSHSBxGiSS9Xn7W3wA "Jelly – Try It Online").
### How?
Builds a list of the expected empty indices for each line from the bottom and compares it to each of two lists, (a) the actual empty indices and (b) the actual empty indices dequeued. The results of this comparison are then processed to find the score.
```
ZJŒḄṖṁLW€⁻"ⱮṚT€,Ḋ$ƊZḄCTḢ’ - Link: list of lines, A
Z - transpose
J - range of length -> [1,2,...,w=#Columns]
ŒḄ - bounce -> [1,2,...,w-1,w,w-1,...,2,1]
Ṗ - pop -> [1,2,...,w-1,w,w-1,...,2]
L - length (A) -> h=#Lines
ṁ - mould like (repeat Ṗ result such that it is length h)
W€ - wrap each of these integers in a list (call this x)
Ɗ - last three links as a monad - i.e. f(A):
Ṛ - reverse (A)
T€ - for each (line) get the list of truthy ("empty") indices
$ - last two links as a monad - i.e. f(z=that):
Ḋ - dequeue (drop the leftmost)
, - (z) pair (that)
Ɱ - map across (the two results of f(A)) applying:
" - (x) zip with (result) applying:
⁻ - not equal?
Z - transpose - now we have leading [0,1]'s for valid rows
from the bottom up
Ḅ - convert from binary - now leading 1s for valid rows
C - complement (subtract (each) from one)
T - truthy indices
Ḣ - head
’ - decrement
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
R©εDgݨû¨NèDU._ƶO®N>èX.__н*Θ}γнO
```
Input as a matrix of 1s and 0s, where the 1s are empty spaces and 0s are filled cells.
[Try it online.](https://tio.run/##yy9OTMpM/f8/6NDKc1td0g/PPbTi8O5DK/wOr3AJ1Ys/ts3/0Do/u8MrIvTi4y/s1To3o/bc5gt7/f//j4421DHUMQDhWJ1oAx0INISzDeFskCqIGkOIKiAbygKyYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU@l1aLcOl5J/aQlM4H/QoZXntrqkH557aMXh3YdW@B1e4RKqF39sm/@hdX52h1dE6MXHX9irdW5G7bnNF/b6/9c5tM3@f3R0tKGOoY4BCMfqRBvoQKAhnG0IZ4NUQdQYQlQB2VAWkA3kRMPUGkJk4CSyCIIN0WGAairCLpwsQ1S7weYgXE3YRANkHyGpI849IN2oKrG4QwcWpoaooYSAyOGIJoohjhQX2ERRxJFEkcRRRJHjD9V@Q6yi6GkDSZxItYZEusGQSL8ZEhlm2MIXW1zAYg6eLmC6YeqR@NjlY2MB).
**Explanation:**
```
R # Reverse the rows of the (implicit) input-matrix
© # Store it in variable `®` (without popping)
ε # Map over each row:
Dg # Get the width of the matrix
Ý # Push a list in the range [0,width]
¨ # Remove the last element to change the range to [0,width-1]
û # Palindromize it: [0,1,2,...,w-2,w-1,w-2,...,2,1,0]
¨ # Remove the last value: [0,1,2,...,w-2,w-1,w-2,...,2,1]
Nè # Index the map-index into this list
DU # Store a copy in variable `X`
._ # Rotate the current row that many times to the left
ƶ # Multiply each value by its 1-based index
O # And sum this list
® # Push the reversed input-matrix again from variable `®`
N>è # Index the map-index + 1 into this to get the next row
X._ # Also rotate it `X` amount of times towards the left
_ # Invert all booleans (1s becomes 0s, and vice-versa)
н # And only leave the first value
* # Multiply both together
Θ # And check that it's equal to 1 (1 if 1; 0 otherwise)
}γ # After the map: split the list into groups of adjacent equivalent values
н # Only leave the first group
O # And take the sum of that
# (after which it is output implicitly as result)
```
] |
[Question]
[
The previous neural net golfing challenges ([this](https://codegolf.stackexchange.com/questions/183036/can-a-neural-network-recognize-primes) and [that](https://codegolf.stackexchange.com/questions/187562/machine-learning-golf-multiplication)) inspired me to pose a new challenge:
## The challenge
Find the smallest feedforward neural network such that, given any 4-dimensional input vector \$(a,b,c,d)\$ with integer entries in \$[-10,10]\$, the network outputs \$\textrm{sort}(a,b,c,d)\$ with a coordinate-wise error strictly smaller than \$0.5\$.
## Admissibility
For this challenge, a [feedforward neural network](https://en.wikipedia.org/wiki/Feedforward_neural_network) is defined as a composition of **layers**. A layer is a function \$L\colon\mathbf{R}^n\to\mathbf{R}^m\$ that is specified by a matrix \$A\in\mathbf{R}^{m\times n}\$ of **weights**, a vector \$b\in\mathbf{R}^m\$ of **biases**, and an **activation function** \$f\colon\mathbf{R}\to\mathbf{R}\$ that is applied coordinate-wise:
$$ L(x) := f(Ax+b), \qquad x\in\mathbf{R}^n. $$
Since activation functions can be tuned for any given task, we need to restrict the class of activation functions to keep this challenge interesting. The following activation functions are permitted:
* **Identity.** \$f(t)=t\$
* **ReLU.** \$f(t)=\operatorname{max}(t,0)\$
* **Softplus.** \$f(t)=\ln(e^t+1)\$
* **Hyperbolic tangent.** \$f(t)=\tanh(t)\$
* **Sigmoid.** \$f(t)=\frac{e^t}{e^t+1}\$
Overall, an admissible neural net takes the form \$L\_k\circ L\_{k-1}\circ\cdots \circ L\_2\circ L\_1\$ for some \$k\$, where each layer \$L\_i\$ is specified by weights \$A\_i\$, biases \$b\_i\$, and an activation function \$f\_i\$ from the above list. For example, the following neural net is admissible (while it doesn't satisfy the performance goal of this challenge, it may be a useful gadget):
$$\left[\begin{array}{c}\min(a,b)\\\max(a,b)\end{array}\right]=\left[\begin{array}{rrrr}1&-1&-\frac{1}{2}&-\frac{1}{2}\\1&-1&\frac{1}{2}&\frac{1}{2}\end{array}\right]\mathrm{ReLU}\left[\begin{array}{rr}\frac{1}{2}&\frac{1}{2}\\-\frac{1}{2}&-\frac{1}{2}\\1&-1\\-1&1\end{array}\right]\left[\begin{array}{c}a\\b\end{array}\right]$$
This example exhibits two layers. Both layers have zero bias. The first layer uses ReLU activation, while the second uses identity activation.
## Scoring
Your score is the total number of *nonzero* weights and biases.
(E.g., the above example has a score of 16 since the bias vectors are zero.)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~96 88 87 84 76 54~~ 50 weights & biases
This 6-layer neural net is essentially a 3-step [sorting network](https://en.wikipedia.org/wiki/Sorting_network) built from a very simple `min`/`max` network as a component. It is basically the example network from wikipedia as shown below, with a small modification: The first two comparisons are done in parallel. To bypass negative numbers though the ReLU, we just add 100 first, and then subtract 100 again at the end.

So this should just be considered as a baseline as it is a naive implementation. It does however sort all possible numbers that do not have a too large magnitude perfectly. (We can adjust the range by replacing 100 with another number.)
[Try it online!](https://tio.run/##hVLLboMwELzzFXsrTiGyoT2tWpX@RpUDCVRCipwqJS3Jz9N92ASqPmTJHs@OZ8fgw66vP9pxfD35Xd8dPHzCA/i2TweTVI7wi13fgwWZMdeNLugYOqYZMQg6njHKZEGpkxr1CLgNJs/i75gQadDLwLDCsoyyFd1v2lAk/6qY8qsYF22Cl@Z3VyPVC772jfZKO81f/JH//6BL85/yl@o/nY1uaOcNMR7Ub@umPpyxVg9rszgIb24o/Nw8NPh@FVxGml1AzbfikUf3PFgf2/2JCk/0hgZYryAdHq3B5Ewc/fIVcD2tGA1EX5guJprRmWh@h5Qx0owucAt1aWjelpi0vhmb7v0t5dd6rH3TpYXN7jJnKIcx4xc "Octave – Try It Online")
### max/min-component
There is a (~~considerably less elegant~~ way more elegant now, thanks @xnor!) way to find the minimum and maximum of two numbers using less parameters:
$$\begin{align} \min &= a - ReLU(a-b) \\ \max &= b + ReLU(a-b) \end{align}$$
This means we have to use a lot less weights and biases.
Thanks @Joel for pointing out that it is sufficient to make all numbers positive in the first step and reversing it in the last one, which makes -8 weights. Thanks @xnor for pointing out an even shorter max/min method which makes -22 weights! Thanks @DustinG.Mixon for the tip of combining certain matrices which result in another -4 weights!
```
function z = net(u)
a1 = [100;100;0;100;100;0];
A1 = [1 0 0 0;0 0 1 0;1 0 -1 0;0 1 0 0;0 0 0 1;0 1 0 -1];
B1 = [1 0 -1 0 0 0;0 0 0 1 0 -1;0 1 1 0 0 0;0 0 0 0 1 1];
A2 = [1 0 0 0;0 1 0 0;1 -1 0 0;0 0 1 0;0 0 0 1;0 0 1 -1];
A3 = [1 0 -1 0 0 0;0 1 1 0 0 0;0 0 0 1 0 -1;0 1 1 -1 0 1;0 0 0 0 1 1];
B3 = [1 0 0 0 0;0 1 0 -1 0;0 0 1 1 0;0 0 0 0 1];
b3 = -[100;100;100;100];
relu = @(x)x .* (x>0);
id = @(x)x;
v = relu(A1 * u + a1);
w = id(B1 * v) ;
x = relu(A2 * w);
y = relu(A3 * x);
z = id(B3 * y + b3);
% disp(nnz(a1)+nnz(A1)+nnz(B1)+nnz(A2)+nnz(A3)+nnz(B3)+nnz(b3)); %uncomment to count the total number of weights
end
```
[Try it online!](https://tio.run/##bVLBbsIwDL3nK3xBSoBOTbtbtGn0NxCHloZRCZKppLT05zs7DRmgqUpsP7@X50axe1de9TQdOrN3jTUwwgcY7XgnWCkx38o0VbTm3Wc7xTZzD1L6FO2YK6oT6QEZG5iHOpGoLKIyeZTfGZ763PAIeWbPnrOFDOfEIf48qfaem/wfz1ebJ3/Pky8DFPnDAHGEREZz@TgzCioSJPEKw8JGq08dtr74IAZ4WwIfPlOhWFPfQcWumBKN41UvoYMVlBIpPcJNzQsCrwIUGyIvQ6hHyi0iOSIDImMQUX3Dk6ocwQXUzeWHGzNyPHlFcRNica@zEPOAh4h6oWCBb8aez9o4cBb2tqPkqLFw5QlMd650C/YAvW6@j@7CtKkn@uu2NHXDs3T9vpYikalifpDtxbb07tbh/e3E9As "Octave – Try It Online")
] |
[Question]
[
*Inspired by [We do tower hopping](https://codegolf.stackexchange.com/questions/156497/we-do-tower-hopping) and related to [2D Maze Minus 1D](https://codegolf.stackexchange.com/questions/105621/2d-maze-minus-1d)*
# Introduction
Your task is to find the shortest path to get out of an array maze following specified rules.
# Challenge
A 1D array *a* with *n* elements can be regarded as a maze composed of *n* points, where point with index *k* is connected to the points with *k*+*a*[*k*] and *k*-*a*[*k*] in a one-way manner. In other words, you can jump forward or backward exactly *a*[*k*] steps from the point with index *k*. Points with an index outside the bounds of the array are considered outside the maze.
To illustrate this, consider the following array,
```
[0,8,5,9,4,1,1,1,2,1,2]
```
If we are at the 5th element right now, since the element is 4, we can hop 4 steps forward to the 9th element, or 4 steps backward to the 1st element. If we do the latter, we end up with the element 0, which indicates no further moves are possible. If we do the former, since the 9th element is 2, we can choose to hop to the 11th element, which is again a 2, and then we can hop again to the "13th element", which is out of the bounds of the array and considered an exit to the maze.
So if we start from the element in the middle, one way to get out of the maze is hopping 1 step back, 4 steps forward, 2 steps forward and again 2 steps forward, which can be expressed as the array `[-1,4,2,2]`. Alternatively you can express it with the array `[4,8,10,12]` which records the zero-based index of all intermediate and final points (1-based index is also fine), or just the signs, `[-1,1,1,1]`.
Escaping the maze from the low-index end is also OK.
Using the first notation and starting from the same element, `[1,1,1,2,2]` is also a solution but it is not optimal since there are 5 steps instead of 4.
The task is to find out the shortest path to get out of the array maze and output the path. If there are more than one optimal paths, you can output any or all of them. If there are no solution, you should output a falsy value chosen by you that is discernible from a valid path (producing no output at all is also OK).
For simplicity, the number of elements in the array is always an odd number and we always start from the element in the middle.
# Test cases
The test cases illustrates various forms of output, but you are not limited to these.
```
Input
Output
[0,8,5,9,4,1,1,1,2,1,2]
[-1,4,2,2]
[2,3,7,1,2,0,2,8,9]
[2,9] (or [2,-5] or [[2,9],[2,-5]])
[0,1,2,2,3,4,4,4,3,2,2,3,0]
[1,-1,1,1]
[0,1,2,2,4,4,6,6,6,6,6,4,2,1,2,2,0]
[]
```
# Specs
* You may write a function or a full program.
* The array only contains nonnegative integers.
* You can take input and output through [any standard form](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), but please specify in your answer which form you are using.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest number of bytes wins.
* As usual, [default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 bytes
```
ḟȯ¬€ŀ¹FS+o*!¹⌈½L¹ṁπṡ1ŀ
```
Returns a list of signs, or an empty list if a solution does not exist.
[Try it online!](https://tio.run/##yygtzv7//@GO@SfWH1rzqGnN0YZDO92CtfO1FA/tfNTTcWivz6GdD3c2nm94uHOh4dGG////RxvoGOgYA6GBjpGOiQ6IZ6hjEAsA "Husk – Try It Online")
## Explanation
This is a brute-force solution that checks lists over `-1,0,1` of increasing length, and returns the first one that results in a jump out of the array.
Since it is of minimal length, it will not contain 0s.
```
ḟȯ¬€ŀ¹FS+o*!¹⌈½L¹ṁπṡ1ŀ Implicit input, say A = [0,1,1]
ŀ Indices of A: [1,2,3]
ṁ Map over them and concatenate:
π Cartesian power
ṡ1 of the symmetric range [-1,0,1].
Result is B = [[-1],[0],[1],[-1,-1],...,[1,1,1]]
ḟ Find the first element of B that satisfies this:
Argument is a list, say C = [1,-1].
F Reduce C from the left
⌈½L¹ using ceil(length(A)/2) as the initial value
S+o*!¹ with this function:
Arguments are an index of A, say I = 2, and a sign, say S = 1.
!¹ The element of A at I: 1
o* Multiply by S: 1
S+ Add to I: 2
At the end of the reduction, we have a number I, here 2.
€ŀ¹ Is it an element of the indices of A: Yes.
ȯ¬ Negate: No.
The result is the shortest list C for which I is outside of A.
```
[Answer]
# JavaScript (ES6), 117 bytes
Returns an array of 0-indexed intermediate and final points, or an empty array if no solution exists.
```
a=>(g=(x,p,d=a[x])=>1/d?[d,-d].map(d=>p.includes(X=x+d)||g(X,[...p,X])):o=o==''|o[p.length]?p:o)(a.length>>1,o=[])&&o
```
[Try it online!](https://tio.run/##fY3NDoIwEITvPoi2camA@JtsfQ2SpoeGAmKQbUQNB94dAYkHY8xkDpP5dudinqZOboW7exXZtMuwMyhZjqwBBxaNajRHGazsSVnwrBZX45hF6URRJeXDpjWLsVla3rY5i0EJIRzEmvMjISEuFi0pJ8q0yu9nfXJH4sxMUcoACJXm8zl1CVU1lakoKWcZUz7sYQMHiCAYFQ7uv86@uBDWsBt7v/ceDj8Yf@wHMhq1npL/hx247UfRe39Y6W@6Fw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // given the maze a[]
(g = ( // g = recursive function taking:
x, // x = current position
p, // p[] = list of visited cells
d = a[x] // d = value of current cell
) => //
1 / d ? // if d is defined:
[d, -d].map(d => // for d and -d:
p.includes(X = x + d) // if the cell at X=x+d was not yet visited,
|| g(X, [...p, X]) // do a recursive call to g at this position
) // end of map()
: // else:
o = // update o:
o == '' | // if o was empty
o[p.length] ? // or p is shorter than o:
p // set o to p
: // else:
o // let o unchanged
)(a.length >> 1, o = []) // initial call to g(), starting in the middle
&& o // return o
```
[Answer]
# [Python 3](https://docs.python.org/3/), 195 188 179 bytes
```
def f(a):
v=len(a);x,*s={v//2},[v//2]
while all(v>b>-1for*c,b in s)*s:s=[x.add(u)or c+[b,u]for*c,b in s for u in[b+a[b],b-a[b]]if{u}-x]
return[b[1:]for b in s if not-1<b[-1]<v]
```
[Try it online!](https://tio.run/##bY3RboMwDEXf@Qo/JtRZCbCtpaU/EuWBFKJGQqECQpmqfjtLWFVt0nRl2dY9175@jZfOZstSNxo0qWgRwVS2jfXjYcZ4KO/Tdps@UIQmI7hdTNtA1bZkOqkT47rr4zMqMBYGGg/FUIr5rapr4mjXw3kjFDr5GwK/gPOjUJtKKImKhSaNvrsHm/2Lvhld723Bi5CEZ85osN3I@FEJxuVxksu1N3YkmogEd/iOe8yRr0pDSUqjF5Fihp@rk/ja4f6Pm6xOYPJV2XNL/qUC8fFS/vMtXPb08g0 "Python 3 – Try It Online")
**Edit:**
* Saved 9 bytes by `all(..)and s => all(..)*s`, `if u not in x => if{u}-x`
The former exploits `boolean * list == int * list`, the latter uses set difference (empty set is also falsy).
Output format: Nested array of all optimal answers, given as zero-based indices of intermediate and final points.
For example: `f([0,8,5,9,4,1,1,1,2,1,2]) == [[4, 8, 10, 12]]`.
The algorithm is simple BFS. `s` records all possible `i`-length paths on `i`th iteration, excluding the indices already visited. Note that the extended star notation is (ab)used because repeated array access is expensive. I found that such a notation can also reduce some whitespace if used correctly.
I also made a recursive (but longer) version out of the above solution. Both `s and` and `or s` are needed, otherwise it doesn't work.
# [Python 3](https://docs.python.org/3/), 210 bytes
```
lambda a:[b[1:]for b in g(a,[[len(a)//2]],{len(a)//2})if not-1<b[-1]<len(a)]
g=lambda a,s,x:s and all(-1<b<len(a)for*c,b in s)and g(a,[x.add(u)or c+[b,u]for*c,b in s for u in[b+a[b],b-a[b]]if u not in x],x)or s
```
[Try it online!](https://tio.run/##bY7dbsIwDIXveYpcJsMd/YNBBU/i@cKhK1TqUkRbqdO0Z@/iwCqQJstKrPPZ51y@@nPrsqk6vE8Nf9qSFRdoMSmoaq/Kqtqpk2ZAbD6cZrNapUTwPQ8/pq6Ua/so2VuMEtrfFFqcDn/noIOx6BS7UnHTaCHvlHd4OULw6IzowWl85bLUg/H2xyVaGOiRUxJr8F@0S0ZLYCN5yMcYJIhAI8Eo6910udau15XGGLawhh3kkIRKpcmYxUykkMFbUGLfW9g9qXFQhMlDZfcp/pcSYjNXfnOTy56efgE "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~207~~ 202 bytes
5 bytes saved thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo).
```
l=length
x!p|i<-h p,d<-x!!i=[p++[x]|x<-[(-d,i-d),(d,i+d)],x`notElem`p]
x?p|i<-h p=i<0||i>=l x
h=snd.last
x#[]=[]
x#p|l(x%p)<1=x#(p>>=(x!))|1>0=x%p
(%)=filter.(?)
f x=(tail.map fst)<$>x#[[(0,l x`div`2)]]
```
[Try it online!](https://tio.run/##ZY5da4MwFIbv8yuObQcJjUWtW1swFga72lgvtrsQUFBnWGpDTUcG/ncX3bqPLieH5Hw87zl13r6WSvW9YqpsXkyNrKc7mfg1aFokvvU8ybiez7kVnU18jv2CSr8gFLt3XhBBbdYczJ0q95kWyG7PNJNJ0HUyZQosqlnbFAuVtwbZKReMu86p7hS2V5okIbNTrNOUYesR0oVpwFwe4SvCKqlMeVzgLUEVWIZNLtVin2uoWkOSWerUOA6om5EV8i2LiBC9haytDydV3JYZvAMDfTJP5vjQwAykUwHGXNrUZQOT3f0EStWWMHncPYOLENrnsnFQcUDgTgU8oGt6TTc0puFo0eDi9xDO/dCVI5cWZyqiS7oauwPna7q5JCIK/kpQGH@rHzAYoQGPR1t@RcGFQOx4Ry7d/Q8P4M23xZ87D7v8FRH9Bw "Haskell – Try It Online")
This is a function that takes a list of `Int` as a parameter and returns a list of paths where each path is a list of relative jumps taken to get out of the array.
The ungolfed version:
```
move :: [Int] -> [(Int, Int)] -> [Path]
move xs path = map(\x->path++[x]) $ filter (\s -> s`notElem`path) $ [(-delta, i-delta), (delta, i+delta)]
where (_,i) = last path
delta = xs!!i :: Int
outside :: [Int] -> Path -> Bool
outside xs paths = i < 0 || i >= length xs
where (_,i) = last paths
shortest' :: [Path] -> [Int] -> [Path]
shortest' paths xs | null paths = []
| not (null ready) = ready
| otherwise = shortest' paths' xs
where ready = filter (outside xs) paths
paths' = concatMap (move xs) paths
shortest xs = map tail $ map (map fst) $ shortest' [[(0,length xs`div`2)]] xs
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 269 bytes
```
#define A n){for(printf("%d,",n);i^l[i];i=l[i])printf("%d,",x[i]);break;}if(!u[n]){u[n]=x[m]=n;l[m++]=i;
#define M calloc(r,sizeof(s))
*x,*u,*l,s,m=1,i,j,n,w;main(r,v)char**v;{s=r-1;x=M;u=M;l=M;for(*x=1+s/2;i<m;i++){j=x[i];if(w=atoi(v[j])){n=j+w;if(s<A}n=j-w;if(1>A}}}}
```
[Try it online!](https://tio.run/##VU7tSsQwEPx/T1FPhHwV7aGg7EXoA9wTlAo11@jWNJXk2gZLnz02B/5wl9llZhZ2VP6hVIy351ajbbMys3TRgyPfDu1Fk/3dWeyFpYBvpsIaUKZF/7khKfDu2uYLVtTkZqxsTZc0Zaj6WlowVc95LRF2f49OmWqMGRRxwuNPO2jiKd2xINgomBFe9LIQKDphxQx9g3Y7nKj6bBxjEyxeuryAIE8wbjAbUmgWZMH9/QHw2ANyTpdOhmtsTWbZXAYkU9XVlC5WdnxOsj@W60byKyley3WrGONDfI5P8SU@xuLah4Rf "C (gcc) – Try It Online")
Initially tried a recursive backtracking search, because using `main` for recursion is always fun. In the end though a straightforward non-recursive breadth-first search was able to be made smaller, which is what this version is. This program takes the input array as command-line arguments, with no braces, e.g.
`0 8 5 9 4 1 1 1 2 1 2` for the first provided example. The program outputs on stdout a list of *1-indexed*, comma-delimited array indices in reverse order, starting from the final, out-of-bounds/'escaped' index and working back through the intermediate indices reached (it does not output the center, starting index). The program does not output braces around the array and leaves a trailing comma because separate `printf` statements take a lot of characters. The output corresponding to the first test example above is `13,11,9,5,`, for example.
If there is no escape route from the array maze, the program does not output anything.
Degolfed and explained it is below (heavily degolfed with some changes for readability):
```
int *x, *u, *l, s, m = 1, i, j, n, w; //Declare all the state we'll need
int main(r, v) char** v;{
s = r - 1; //s is our actual array size, since v[0] is the program name.
x = calloc(r, sizeof(int)); //x is an array that will form our BFS queue. Since it is a BFS we've no need to visit any elements more than once (first visit will have been on a shortest route to it), so the amount of space we have here should suffice.
u = calloc(r, sizeof(int)); //u is an array that will be used to flag when an array index has been visited; only reason it's int* is for ease of declaration
l = calloc(r, sizeof(int)); //l is an array that will be used parallel to x and stores backpointers in the form of indexes into x, which will be used to construct the actual path once it is found.
x[0] = 1 + (s/2); //Init the first element in the queue to our center index of the array, adding one because of the program name in v/argv.
for(; i < m; i++) { //m is the number of elements in our BFS queue. It starts at 1 and grows during iteration; if this loop terminates before finding a path there is none.
j = x[i]; //Current index in the array we are examining
if (w = atoi(v[j])) { //Set w to be the actual array value at the current index (and check that it's nonzero since if it isn't we can't get anywhere from here)
n = j + w; //Try a move in the positive direction
if (n > s) { //If the move escapes the array
for(printf("%d,", n); i ^ l[i]; i = l[i]) { //Print the location escaped to and then loop back through the backpointers to reconstruct the path. The only backpointer that will point to its own queue index is the starting one, so terminate there.
printf("%d,", x[i]); //Print each intermediate array index
}
break; //Then break the outer for loop and exit.
}
if(!u[n]) { //If the jump didn't take us out of the array and we haven't visited where it goes to, add it to the queue.
u[n] = x[m] = n; //m is the current tail of the queue, so put this new location there. Since we're 1-indexed and if n was zero we'd have escaped, we know it isn't so can use it to mark this index as visited also.
l[m++] = i; //Also set the backpointer for this new queue element to point back to the current index, then increment the tail of the queue.
}
n = j - w; //Now the backwards move
if (n < 1) { //Repeat analogous to the forward case.
for(printf("%d,", n); i ^ l[i]; i = l[i]) {
printf("%d,", x[i]);
}
break;
}
if (!u[n]) {
u[n] = x[m] = n;
l[m++] = i;
}
}
}
}
```
As usual for golfed C code, compilation output will of course include a friendly wall of warnings and notes.
[Answer]
# [Perl 5](https://www.perl.org/), -a: 73 bytes
(old style counting: 75 bytes, `+1` for `a` and `+1` for replacing `-//` by `-/$/` and using `$`` for `$'`)
```
#!/usr/bin/perl -a
use 5.10.0;
@;=$#F/2;$v{$^H=$_}//=push@;,map$'+$_*($F[$^H]//1/!say$').$".$',-//,1for@
```
Give the input array as one line on STDIN e.g. `0 8 5 9 4 1 1 1 2 1 2`
prints the visited positions in reverse order including the starting point, then crashes
Prints nothing if there is no solution
[Try it online!](https://tio.run/##K0gtyjH9/9/B2lZF2U3fyFqlrFolzsNWJb5WX9@2oLQ4w8FaJzexQEVdWyVeS0PFLRooG6uvb6ivWJxYqaKuqaeipKeirqOrr69jmJZf5PD/v4GChYKpgqWCiYIhGBqB8L/8gpLM/Lzi/7qJ/3V9TfUMDfQMAA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 102 bytes
```
->a{b=[[a.size>>1]];b.map{|x|(v=a[w=x[0]])&&w>=0?[w-v,w+v].map{|j|x.index(j)?0:b<<[j]+x}:(break p x)}}
```
[Try it online!](https://tio.run/##VYzdCoJAEIXvewqvQnGU9adSc/VBlrnYJQWNQozcLfXZzV0jiMO5mO8bTv8Ur6Wmi1fwUVDGuP9o3lVRBIhn4d94N05qsgfKmaSKEURnv5cFJSWT3gDSHXB7aiflN/dLpezWKUkm8py16Ko5s0Vf8avVWcqZ56VmjEACB0ghhsAk1EXcrSqECE4GkbUJpBsmBmkZm0Tfi/xrrY6/xNuw3kJcPg "Ruby – Try It Online")
Takes input maze as an array, outputs by printing the escape path in reverse, from the exit to the starting point (inclusive). Prints nothing if there is no escape.
This approach misuses the map method to iterate through a temporary array storing the history of paths, which is constantly extended on the fly whenever there is another possible step to take.
In principle, I could save another byte by using `return x` instead of `break p x`, but that would mean claiming that my falsy value is equal to all the monstrous rubbish stored in `b`. Probably, this would be too much, even considering the allowed flexibility of the output...
## Walkthrough
```
->a{
b=[[a.size>>1]] #Initialize an array of paths with our starting point index
b.map{|x| #Iterate through this array
(v=a[w=x[0]]) #w is the current point in the path, v is its array value
&&w>=0 #Ruby's support for negative indexing costs us 6 bytes :(
? #If we are still within the bounds of the maze
[w-v,w+v].map{|j| #Try moving in both directions
x.index(j)? #If we have been there before, or stuck on zero
0 #This is a dead-end, just assign a throwaway value
:b<<[j]+x #Otherwise push the elongated path on top of our iterator
}
:(break p x) #Escaped! Exit the loop and report the path
}
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 133 bytes
```
def f(k,*s):*p,x=len(k)//2,*s;return{x}-{*p}and min([a for a in(f(k,*s,x-k[x]),f(k,*s,x+k[x]))if a]or[()],key=len)if~0<x<len(k)else s
```
[Try it online!](https://tio.run/##TY1BT4NAEIXv/RVz3MVpioDaYj3WqxdvhMNqh5QsLpth0SVN/eu4gJrOyyT7vZd9Ywd3ak06jkeqoBIao07mkUX/1JARWm42SbAemVzP5uwv63NkL8oc4aM2olBQtQwKwnv5i36tC19K/MObGWVdgSpbLoQsUdMwlQfvO977/XKHmo6gG79OdUPwyj3lKwDHQw6Wa@NCPX2qRtTG9k7IMCEm/07WweHl@cDccg5vTEqPRYxbvMMdZng7K5m2XBUJpvgwcxx2i7vgxTNPSTYr/aX4Kpv8@39lS9/UUv4A "Python 3 – Try It Online")
Outputs the shortest list of all visited indices.
Port of my answer to [Find the shortest route on an ASCII road](https://codegolf.stackexchange.com/a/195042/87681).
] |
[Question]
[
Multiplication between 2 integers can be reduced into a series of addition like so
```
3 * 5 = 3 + 3 + 3 + 3 + 3 = 5 + 5 + 5
```
Exponentiation (raising **a** to the power **b**) can also be reduced into a series of multiplications:
```
5 ^ 3 = 5 * 5 * 5
```
Therefore, exponentiation can be reduced into a series of additions, by creating a multiplication expression, then into a series of additions. For example, `5 ^ 3` (5 cubed) can be rewritten as
```
5 ^ 3 = 5 * 5 * 5
= (5 + 5 + 5 + 5 + 5) * 5
= (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5)
= 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5
```
Your task is, given expressions added together consisting of exponentiation, multiplication and addition, reduce it to the shortest series of additions. The "shortest" expression is defined as the expression with the fewest number of `+` symbols, still using only one of the two numbers in the original expression. For example, the shortest expression of `10 * 2` is `10 + 10`.
The numbers involved in the input will all be positive integers, and the expression will consist of only `+` (addition), `*` (multiplication) and `^` (exponentiation), along with integers and brackets (`()`) to indicate precedence.
The output should consist of positive integers and `+` symbols only. You shouldn't output the individual steps of the reductions, just the final output. The output may not consist of any numbers that don't appear in the input. However, you may use any 3 distinct symbols instead of `+*^`, but please say what symbols they are
The spaces separating inputs and outputs may or may not be used in your programs, i.e. `3 * 5` can be outputted as either `5 + 5 + 5` or `5+5+5`.
Note that in most cases, addition is not actually performed. The only case where addition is to be performed is when you have something like `5 ^ (1 + 2)`, in which case, addition is necessary to continue `-> 5 ^ 3 -> 5 * 5 * 5 -> ...`. See test case #4.
Your code does not need to handle inputs that arrive at an ambiguous expression. For example, `(2 + 2) * (4 + 1)`. Because of the rules set forth so far, the goal is not to calculate the answer, the goal is to simplify to additions. So the result could be different depending on the order that expressions are resolved or commuted (which additions to simplify, which to leave?). Another invalid example: `((3 + 2) ^ 2) ^ 3 -> ((3 + 2) * (3 + 2)) ^ 3 -> ???`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins
## Test cases
```
Input => output
5 ^ 3 + 4 * 1 ^ 5 => 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 4
2 ^ 1 * 2 + 3 + 9 => 2 + 2 + 3 + 9
2 ^ 1 * (2 + 3) + 9 => 2 + 3 + 2 + 3 + 9
2 ^ (1 * (2 + 3)) + 9 => 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 9
10 + 3 * 2 + 33 ^ 2 => 10 + 3 + 3 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33
100 * 3 => 100 + 100 + 100
2 ^ 1 + 2 ^ 1 + 2 ^ 2 + 8 ^ 1 => 2 + 2 + 2 + 2 + 8
(1 + 2 + 5 * 8 + 2 ^ 4) * 2 => 1 + 2 + 8 + 8 + 8 + 8 + 8 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 1 + 2 + 8 + 8 + 8 + 8 + 8 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 302 bytes
I'm sure this can be golfed, but at this point, I'm just glad it works. The exponentiation and multiplication sections are both very similar, but since order of operations is important, I don't know how to combine them.
`y` - Exponentiation
`x` - Multiplication
`p` - Addition
```
\d+
$*
{1`(\(\w+\)|1+)y(\(\w+\)|1+)
>$0<
(?<=>(\(\w+\)|1+)y1*)1
$1x
>(\(\w+\)|1+)y
(
x<
)
\((1+(x1+)*)\)(?!y)
$1
(?<!1)(1+)x(\(\w+\)|1+\1)(?!1)
$2x$1
1`(\(\w+\)|1+)x1+
>$0<
(?<=>(\(\w+\)|1+)x1*)1
$1p
>(\(\w+\)|1+)x
(
p<
)
(?<!x|y)\((1+(p1+)*)\)(?!x|y)
$1
y\((1+)p([1p]*\))
y($1$2
}`y\((1+)\)
y$1
1+
$.0
```
[**Try it online**](https://tio.run/##dZBBasNADEX3ukVgCpINxZqJIQEnWfYQnYIL7aKbIkKhEknP7kqOofGii4Gvrz/SQ@f3r4/P1@np4TLCVN9aSA1ceMSK9butdOWW7L6AY@oGwNNwOK4y3BBDYoW1DQg6AEFF5BbVrYYq4Wlj5OmYs2HyFundt8qRYE9k9dCaxmf8w6ALg6wZ1BkkGGKZXo1uLPLHEmbQ2NwhwWeWl6YSgWHilOFnXFrVrSDyMz1209Rbka2y9ZCNNUuR/azQJc0alyIq7qREqFh23WmJrNxelp35OVxKrzs3tqT5Fw "Retina – Try It Online") - all test cases
[Test case converter](https://tio.run/##K0otycxL/P9fgYsrJCFOK6GygismIUabq@D/fw1DBW0FIyA2VdBSsACz4xRMNIEcIwA)
### Explanation
```
\d+ Convert to unary
$*
{1`(\(\w+\)|1+)y(\(\w+\)|1+) Begin loop: Delimit current exponentiation group
>$0<
(?<=>(\(\w+\)|1+)y1*)1 Replace exponentiation with multiplication
$1x
>(\(\w+\)|1+)y Replace garbage with parentheses
(
x<
)
\((1+(x1+)*)\)(?!y) Remove unnecessary parentheses around multiplication
$1
(?<!1)(1+)x(\(\w+\)|1+\1)(?!1) Maybe swap order of multiplicands
$2x$1
1`(\(\w+\)|1+)x1+ Delimit current multiplication group
>$0<
(?<=>(\(\w+\)|1+)x1*)1 Replace multiplication with addition
$1p
>(\(\w+\)|1+)x Replace garbage with parentheses
(
p<
)
(?<!x|y)\((1+(p1+)*)\)(?!x|y) Remove unnecessary parentheses around addition
$1
y\((1+)p([1p]*\)) Handle the 4th test case by adding if necessary
y($1$2
}`y\((1+)\) End of loop
y$1
1+ Convert unary back to decimal
$.0
```
You may also notice that the most commonly used group is `(\(\w+\)|1+)`. This matches an inner expression with parentheses, or an integer. I chose to use the symbols I did so that I could use `\w` rather than a character class. I'm not sure if it would be better to use non-word symbols and replace some lookarounds with word borders (`\b`).
[Answer]
# Mathematica, ~~250~~ ~~218~~ ~~183~~ 170 bytes
```
f~(s=SetAttributes)~HoldAll;{a,t}~s~Flat;f@n_:=Infix[Hold@n//.{a_~Power~b_:>t@@Hold@a~Table~b,Times->t,Plus->a,Hold->Dot}/.t->(a@@Table[#,1##2]&@@Reverse@Sort@{##}&),"+"]
```
It works! Finally!
Defines the function in `f`.
The input is a plain math expression. (i.e. `1 + 2` not `"1 + 2"`).
[Try it Online!](https://tio.run/##HY1Bq4JAFEb3/gppIJTGJJdFcoN4vMVbSLUTk2vdoYFRYeb23kKcv@7TNt9ZnANfi/yiFlk/cJqUj9zxSnxitrp5M7nYf/fmeTLmMKDk0Tv/ZZAPCrp6f7xopQyVP9oxQLSE0KXpdsDaF/0fWd/U@3xWH4P@ho0h38ibbsklOcvCvGeiXHySn3se0y0neYQAn7YUcidEVq0BLvRL1hFce8swCDGu41iuwk24qqbC6m5@UWUQZOE9jJbJ4iCopn8)
Note that the TIO link has a slightly different code, as TIO (which, I presume, uses Mathematica kernel) doesn't like `Infix`. I used `Riffle` instead to get the same appearance as Mathematica REPL.
## Ungolfed
```
f~(s = SetAttributes)~HoldAll; (* make f not evaluate its inputs *)
{a, t}~s~Flat; (* make a and t flat, so that a[a[1,a[3]]] == a[1,3] *)
f@n_ := (* define f, input n *)
Infix[
Hold@n (* hold the evaluation of n for replacement *)
//. { (* expand exponents *)
(* change a^b to t[a,a,...,a] (with b a's) *)
a_~Power~b_ :> t @@ Hold@a~Table~b,
(* Replace Times and Plus with t and a, respectively *)
Times -> t,
Plus -> a,
(* Replace the Hold function with the identity, since we don't need
to hold anymore (Times and Plus are replaced) *)
Hold -> Dot
} /. (* Replace; expand all t (= `Times`) to a (= `Plus`) *)
(* Take an expression wrapped in t. *)
(* First, sort the arguments in reverse. This puts the term
wrapped in `a` (if none, the largest number) in the front *)
(* Next, repeat the term found above by <product of rest
of the arguments> times *)
(* Finally, wrap the entire thing in `a` *)
(* This will throw errors when there are multiple elements wrapped
in `a` (i.e. multiplying two parenthesized elements) *)
t -> (a @@ Table[#, 1 ##2] & @@
Reverse@Sort@{##} &),
"+"] (* place "+" between each term *)
```
[Answer]
# Mathematica, ~~405~~ 406 bytes
```
f~SetAttributes~HoldAll;p=(v=Inactive)@Plus;t=v@Times;w=v@Power;f@x_:=First@MinimalBy[Inactivate@{x}//.{w[a___,b_List,c___]:>(w[a,#,c]&/@b),t[a___,b_List,c___]:>(t[a,#,c]&/@b),p[a___,b_List,c___]:>(p[a,#,c]&/@b),p[a_]:>a,w[a_,b_]:>t@@Table[a,{Activate@b}],t[a___,t[b__],c___]:>t[a,b,c],p[a___,p[b__],c___]:>p[a,b,c],{a___,{b__},c___}:>{a,b,c},t[a__]:>Table[p@@Table[i,{Activate[t@a/i]}],{i,{a}}]},Length];f
```
## Ungolfed and explained
```
SetAttributes[f, HoldAll]
p = Inactive[Plus]; t = Inactive[Times]; w = Inactive[Power];
f[x_] := First@MinimalBy[
Inactivate[{x}] //. {
w[a___, b_List, c___] :> (w[a, #, c] & /@ b),
t[a___, b_List, c___] :> (t[a, #, c] & /@ b),
p[a___, b_List, c___] :> (p[a, #, c] & /@ b),
(* distribute lists of potential expansions over all operations *)
p[a_] :> a,
(* addition of a single term is just that term *)
w[a_, b_] :> t @@ Table[a, {Activate@b}],
(* a^b simplifies to a*a*...*a b times no matter what b is *)
t[a___, t[b__], c___] :> t[a, b, c],
p[a___, p[b__], c___] :> p[a, b, c],
{a___, {b__}, c___} :> {a, b, c},
(* operations are associative *)
t[a__] :> Table[p @@ Table[i, {Activate[t@a/i]}], {i, {a}}]
(* for a product, generate a list of potential expansions *)}
, Length]
f
```
I went to a great deal of trouble to get the following effect: this function takes as input a standard Mathematica expression, with the usual `+`, `*`, and `^` operations (and parentheses) in it, and outputs what looks like a standard Mathematica expression (but with "deactivated" plus signs) as the answer.
The function above begins by deactivating all operations in the input. Then, it applies expansion rules repeatedly until nothing can be simplified anymore. Whenever it encounters a product such as `2 * 3 * 4`, which can be expanded in multiple ways, it makes a list of possible expansions, and keeps going. At the end, we get a list of possible final answers, and the shortest is picked.
] |
[Question]
[
## Balanced bases:
Balanced bases are essentially the same as normal bases, except that digits can be positive or negative, while in normal bases digits can only be positive.
From here on, balanced bases of base `b` may be represented as `balb` - so balanced base 4 = `bal4`.
In this challenge's definition, the range of digits in a balanced base of base `b` is from `-(k - 1)` to `b - k`, where
```
k = ceil(b/2)
```
Examples of the range of digits in various balanced bases:
```
bal10:
k = ceil(10/2) = 5
range = -(5 - 1) to 10 - 5 = -4 to 5
= -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
bal5:
k = ceil(5/2) = 3
range = -(3 - 1) to 5 - 3 = -2 to 2
= -2, -1, 0, 1, 2
```
Representations of numbers in balanced bases is basically the same as normal bases. For example, the representation of the number `27` (base 10) to `bal4` (balanced base 4) is `2 -1 -1`, because
```
2 -1 -1 (bal4)
= 2 * 4^2 + -1 * 4 + -1 * 1
= 32 + (-4) + (-1)
= 27 (base 10)
```
## Task:
Your task is, given three inputs:
* the number to be converted (`n`)
+ this input can be flexible, see "I/O Flexibility"
* the base which `n` is currently in (`b`)
* the base which `n` is to be converted to (`c`)
Where `2 < b, c < 1,000`.
Return the number in balanced base `c` representation of `n`. The output can also be flexible.
The program/function must determine the length of `n` from the input itself.
### I/O Flexibility:
Your input `n` and output can be represented in these ways:
* your language's definition of an array
* a string, with any character as a separator (e.g. spaces, commas)
## Examples:
*Note that these use a Python array as `n` and the output. You may use whatever fits your language, as long as it fits within "I/O Flexibility"'s definition.*
```
[2, -1, -1] 4 7 = [1, -3, -1]
[1, 2, 3, 4] 9 5 = [1, 2, 2, -1, 2]
[10, -9, 10] 20 5 = [1, 1, 1, -2, 1, 0]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# Mathematica, 85 bytes
```
#~FromDigits~#2~IntegerDigits~#3//.{p___,a_:0,b_,q___}/;b>⌊#3/2⌋:>{p,a+1,b-#3,q}&
```
**Explanation**
```
#~FromDigits~#2
```
Convert `#1` (1 is implied--input 1, a list of digits) into an integer base `#2` (input 2).
```
... ~IntegerDigits~#3
```
Convert the resulting integer into base `#3` (input 3), creating a list of digits.
```
... //.{p___,a_:0,b_,q___}/;b>⌊#3/2⌋:>{p,a+1,b-#3,q}
```
Repeatedly replace the list of digits; if a digit is greater than floor(`#3`/2), then subtract `#3` from it and add `1` to the digit to the left. If there is nothing on the left, insert a `0` and add `1`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 47 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410)
```
{z↓⍨⊥⍨0=⌽z←m+u⊤v-⍺⊥m←⌈.5×1-u←⍺⍴⍨1+⌈⍺⍟1⌈|v←⍺⍺⊥⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v7rqUdvkR70rHnUtBZIGto969gJFJuRqlz7qWlKm@6h3F1AmFyjyqKdDz/TwdEPdUhAHKNy7BajBUBsoDubNNwSyaspgkrvABm6t/Z8GFul71DfV0/9RV/Oh9caP2iYCecFBzkAyxMMz@L@5holCmqaRwqH1hmCs8Kh3rgKIaQzicplqWAKlDRWMFIwVTGCSRgoQ9UZAaSMDkLwBkG@pAKSgKgzBRhgBSQMuMw1DI6CaQ@tNgUImQFNMIapgNoKwsQLYOgA "APL (Dyalog Unicode) – Try It Online")
A dop that takes `n`, `b`, `c` as three separate values. Call it like `c (b f) n` where `f` is the submission.
Dyalog APL has a [dfns library function `bt`](http://dfns.dyalog.com/n_bt.htm) that does various arithmetic in balanced ternary. Part of it is encode/decode, i.e. conversion between balanced ternary and plain integer:
```
encode←{ ⍝ balanced ternary from integer.
digs←1+⌈3⍟1⌈|⍵ ⍝ number of ternary digits.
tlz ¯1+(digs⍴3)⊤⍵+3⊥digs⍴1 ⍝ vector of bt digits.
} ⍝ :: ∇ num → bt
decode←{3⊥⍵} ⍝ integer from balanced ternary.
```
(the hidden function `tlz` trims leading zeros.)
This submission is just a generalization of the above code.
### Ungolfed with comments
```
{ ⍝ Input: ⍵←n, ⍺⍺←b, ⍺←c
v←⍺⍺⊥⍵ ⍝ v← plain integer from base b
u←⍺⍴⍨1+⌈⍺⍟1⌈|v ⍝ u← copies of c with the size enough to fit the answer
1⌈|v ⍝ max(1,abs(v)) so that it works well with log(⍟)
⌈⍺⍟ ⍝ number of digits enough to fit v in plain base c
1+ ⍝ ...enough to fit v in balanced base c
⍺⍴⍨ ⍝ that many copies of c
m←⌈.5×1-u ⍝ m← the minimum value in balanced base c with that many digits
z←m+u⊤v-⍺⊥m ⍝ z← n in balanced base c, possibly with leading zeros
⍺⊥m ⍝ m as plain integer
v- ⍝ subtract from v (or, since m<0, add abs(m) to v)
u⊤ ⍝ encode that value to plain base c, with that many digits
m+ ⍝ revert the offset
z↓⍨⊥⍨0=⌽z ⍝ remove leading zeros from z and return it
⊥⍨0=⌽z ⍝ count trailing zeros (⊥⍨) on reversed z
z↓⍨ ⍝ drop that many items from z
}
```
[Answer]
# [Perl 6](http://perl6.org/), 121 bytes
```
->\n,\b,\c{sub f{sum [R,](@^n)Z*($^b X**0..*)}
first {f(b,n)==f c,$_},map {[$_-($_>floor c/2)*c for .base(c).comb]},0..*}
```
Slow brute-force solution.
How it works:
* `map {[ .base(c).comb]}, 0..*` -- Generate the lazy infinite sequence of natural numbers in base `c`, with each number represented as an array of digits.
* `$_ - ($_ > floor c/2) * c` -- Transform it by subtracting `c` from each digit that is greater than floor(c / 2).
* `first { f(b, n) == f(c, $_) }, ...` -- Get the first array of that sequence which when interpreted as a base `c` number, equals the input array `n` interpreted as a base `b` number.
* `sub f { sum [R,](@^n) Z* ($^b X** 0..*) }` -- Helper function that turns an array `@^n` into a number in base `$^b`, by taking the sum of the products yielded by zipping the reversed array with the sequence of powers of the base.
[Answer]
# [SageMath](https://www.sagemath.org/), 53 bytes
```
f=lambda a,b,c:ZZ(a[::-1],b).balanced_digits(c)[::-1]
```
I’d be (pleasantly) surprised if there is a more concise way to write this in Sage than the obvious one. The only complication here is that Sage represents numbers as lists of digits with the least-significant digit first, whereas this challenge assumes most-significant first. So the digit lists need to be reversed.
[Answer]
## JavaScript (ES6), 89 bytes
```
(n,b,c,g=(n,d=n%c,e=d+d<c)=>[...(n=n/c+!e|0)?g(n):[],e?d:d-c])=>g(n.reduce((r,d)=>r*b+d))
```
100 bytes works for negative values of `n`.
```
(n,b,c,g=(n,d=(n%c+c)%c)=>[...(n-=d,n/=c,d+d<c||(d-=c,++n),n?g(n):[]),d])=>g(n.reduce((r,d)=>r*b+d))
```
[Answer]
## Mathematica, 118 114 bytes
```
IntegerDigits[#3~FromDigits~#2,k=⌊#/2⌋;#]//.{{a_,x___}/;a>k:>{1,a-#,x},{x___,a_,b_,y___}/;b>k:>{x,a+1,b-#,y}}&
```
`⌊` and `⌋` are the 3-byte characters [`U+230A`](https://reference.wolfram.com/language/ref/character/LeftFloor.html) and [`U+230B`](https://reference.wolfram.com/language/ref/character/RightFloor.html), respectively. Converts `#3` to base `10` from base `#2`, then converts to base `#` (so the argument order is reversed from the examples). If any digit is greater than the maximum allowed digit `k=⌊#/2⌋`, decrement that digit by `#` and increment the next digit up (may need to prepend `1`). Keep doing this until all the digits are less than `k`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~55~~ ~~51~~ 49 bytes
*Saved 4 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)*
```
{2↓((⊃(⊢,⍨⍵÷⍨-)x-⍨(⍵|(x←⌊⍵÷2)+⊃)),1∘↓)⍣(=⍥⊃)⍺⊥⍺⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT//v/KhtQrXGo96tQKTwqHeXJogAIgWE2FbN2v/VRo/aJmtoPOpqBuJFOo96VwDFD28H0rqaFbpACqS8RqMCaNqjni6wnJGmNlC5pqaO4aOOGUDdmo96F2vYOoPEQFZ0LYVYVPs/DaSptw8ocWi98aO2iY/6pgYHOQPJEA/P4P8mChpGCofWG4JxmqaCOZelgoahgpGCsYIJiG/KZWQAFDAAylsqACmQEAA "APL (Dyalog Unicode) – Try It Online") (The `⍥` has been replaced by a `C` in the link because TIO has an older version of APL).
## Without a train, ~~55~~ ~~54~~ 52 bytes (SBCS)
*Saved a byte here too thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)*
```
{c←⍵⋄2↓{m←x-⍨c|⊃⍵+x←⌊c÷2⋄(c÷⍨⊃⍵-m),m,1↓⍵}⍣(=⍥⊃)⍺⊥⍺⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT//v/KhtQrXGo96tQKTwqHeXJogAIgWE2FbN2v/VyUB1IJHuFqNHbZOrc4HcCt1HvSuSax51NQMltCtACnq6kg9vNwIq0gDSQFmInG6upk6ujiFQH5BT@6h3sYatM1BGE2RT11KIfbX/08A29AElDq03ftQ28VHf1OAgZyAZ4uEZ/N9EQcNI4dB6QzBO01Qw57JU0DBUMFIwVjAB8U25jAyAAgZAeUsFIAUSAgA "APL (Dyalog Unicode) – Try It Online")
There's already a better APL answer here, but here's mine anyway.
Can be invoked with `b (n f) c`.
`⍺⊥⍺⍺` converts `n` from base `b` to base 10.
`(...)⍣(=⍥⊃)` repeatedly takes a vector whose first element is the rest of the number to be converted and whose other elements are the digits of the result. It repeats until the first digit of the created vector is 0 (given by `(=⍥⊃)`).
The `2↓` at the beginning is because the function is applied one extra time, so there's 2 zeroes at the start of the vector.
In the top snippet, `m` represents the new leading digit. It's just \$(r + x (\mod c)) - x\$ where \$x\$ is \$\lfloor \frac{c}{2} \rfloor\$ and \$r\$ is the head of the vector, the leftover part from last time.
To get the new leftover part, it's \$\frac{(r - m)}{c}\$ (this is guaranteed to be an integer since \$r-m\$ is divisible by \$c\$). Then we join this leftover part with `m` and `1↓⍵` (to drop last time's leftovers).
[Answer]
# [R](https://www.r-project.org/), ~~105~~ ~~102~~ ~~101~~ 96 bytes
*Edit: -5 bytes thanks to Giuseppe*
```
function(a,b,c){x=a%*%b^(sum(a|1):1-1)
e={}
while(x){e=c(r<-x%%c-c*(x%%c>c/2),e);x=(x-r)%/%c}
e}
```
[Try it online!](https://tio.run/##ZY3LCsIwEEX3/YqCBGZkhjZpRXzERRd@hpCGiIU@oCoGar@9pogLlXu5Z3Pg9tOtO/ZdU5i6MFenp/O9tbeqa8FQSRYHr41YivIE13sD5ilxK1li5PQwRo9LVTvwODhtod@zF8KyXcLMg00UksOd1@C5R5EIO0Zu/P4DC4pYhiLltMZ4EcuYs5hl9OtJUpRRjrSh1dtTIRzwr6bEG5Ipkko/8hxWYdLpBQ "R – Try It Online")
```
toFromBalBase=
function(a,b,c){
x=sum(a*b^(sum(a|1):1-1)) # get value x after conversion from balanced base b
e=NULL # initialze empty output vector of values
while(x){ # repeat while x is not yet zero:
e=c(...,e) # prepend output vector with
r<-(r=x%%c) # define r as x mod c (base to convert to)
-(r>c/2)*c # adjusted to be balanced
x=(x-r)%/%c} # and update x to result of division,
# after accounting for possibly-negative remainder.
e} # finally, output e = output vector with all positive and negative
# remainders prepended
```
] |
[Question]
[
A bit of background:
When I first learned about Brainf\*ck, one of the first things I did was to write a Java application that would take in a string and create a, somewhat, optimized program to print said string.
Recently, I've been playing around with [Piet](http://www.dangermouse.net/esoteric/piet.html), and I have been playing with doing the same thing. I have realized that Piet is a rather interesting language that adds a bit to this challenge.
So, I wanted to put the challenge out to my friends at SE. Let's see what you can do with this language.
## The Challenge
Write a program or function that takes in some non-empty string of ASCII characters. Process the string so that you generate a Piet program that will print the string and terminate.
Output is a piet source image in whatever format is best for you. PNG is preferred, but not mandatory.
Piet functionality can be tested [here](http://www.bertnase.de/npiet/npiet-execute.php).
The Piet code **must** generate the output string itself. No input from users is allowed.
Only Piet-Approved colors may be used, as seen below:

As this is a popularity contest, winners will be chosen by votes. Ties will be broken by source code size.
Bonus points will be awarded at my discretion based on the creativity of the output images. These are pictures, after all.
[Answer]
## C, (78 + 26 \* strlen) codels
This was surprisingly tricky to optimize, mostly because of the possibility of color collisions in neighbouring lines.
The characters are converted to base 12, so each character is a 2-digit number. Every standard line contains the following: pointer (now right for odd lines, left for even lines), duplicate (the number 12, which is first on the stack), push (1st digit), multiply, push (2nd digit), add, outc, push (1 for odd lines, 3 for even lines), duplicate, whitespace, pointer (now down at the end of the line).
To avoid color collisions in neighbouring lines the state after whitespace filling is remembered, and the generation is rolled back to it if a collision happens. The next try starts there with the next color.
Output for "Hello Piet!":

**asciipiet2.c**
```
#include "img.h"
#define WIDTH 26
#define OP(op, h, d) int op() { hue += h; dark += d; hue %= 6; dark %= 3; return setp(); }
#define CCMP(c1, c2) (((c1).r == (c2).r) && ((c1).g == (c2).g) && ((c1).b == (c2).b))
#define OPCNT(op) if(op) continue
Color piet[6][2] =
{
{{0xff, 0xc0, 0xc0}, {0xff, 0x00, 0x00}, {0xc0, 0x00, 0x00}},
{{0xff, 0xff, 0xc0}, {0xff, 0xff, 0x00}, {0xc0, 0xc0, 0x00}},
{{0xc0, 0xff, 0xc0}, {0x00, 0xff, 0x00}, {0x00, 0xc0, 0x00}},
{{0xc0, 0xff, 0xff}, {0x00, 0xff, 0xff}, {0x00, 0xc0, 0xc0}},
{{0xc0, 0xc0, 0xff}, {0x00, 0x00, 0xff}, {0x00, 0x00, 0xc0}},
{{0xff, 0xc0, 0xff}, {0xff, 0x00, 0xff}, {0xc0, 0x00, 0xc0}}
};
Color white = {0xff, 0xff, 0xff};
Image img;
int hue, dark, x, y, dx = 1;
void nextline()
{
x -= dx;
dx = -dx;
y += 1;
}
int setp()
{
if(y > 0 && CCMP(piet[hue][dark], imgGetP(img, x, y - 1)))
{
return 1;
}
imgSetP(img, x, y, piet[hue][dark]);
x += dx;
return 0;
}
void whiteto(int to)
{
if(dx == 1)
{
while(x < to) imgSetP(img, x++, y, white);
}
else
{
while(x >= WIDTH - to) imgSetP(img, x--, y, white);
}
}
OP(fill, 0, 0)
OP(pushraw, 0, 1)
OP(pop, 0, 2)
OP(add, 1, 0)
OP(sub, 1, 1)
OP(mul, 1, 2)
OP(divi, 2, 0)
OP(mod, 2, 1)
OP(not, 2, 2)
OP(gt, 3, 0)
OP(pnt, 3, 1)
OP(sw, 3, 2)
OP(dup, 4, 0)
OP(roll, 4, 1)
OP(in, 4, 2)
OP(inc, 5, 0)
OP(out, 5, 1)
OP(outc, 5, 2)
int push(int num);
int pushn(int num) { int i; for(i = 0; i < num - 1; ++i) { if(fill()) return 1; } return pushraw(); }
int push0() { return (push(1) || not()); }
int push8() { return (push(2) || dup() || dup() || mul() || mul()); }
int push9() { return (push(3) || dup() || mul()); }
int push10() { return (push(9) || push(1) || add()); }
int push11() { return (push(9) || push(2) || add()); }
int push(int num)
{
switch(num)
{
case 0: return push0();
case 8: return push8();
case 9: return push9();
case 10: return push10();
case 11: return push11();
default: return pushn(num);
}
}
int main(int argc, char* argv[])
{
char* str;
int len, i;
if(argc != 2)
{
printf("Usage: %s \"string to print\"\n", argv[0]);
return -1;
}
str = argv[1];
len = strlen(str);
imgCreate(img, WIDTH, len + 3);
fill(); push(4); push(3); mul(); push(1); dup(); whiteto(WIDTH - 2);
for(i = 0; i < len; ++i)
{
int var, sx = x, sy = y, sdx = dx, fin = 0, off = rand();
for(var = 0; var < 18 && !fin; var++)
{
x = sx; y = sy; dx = sdx;
hue = ((var + off) % 18) / 3; dark = ((var + off) % 18) % 3;
OPCNT(fill()); OPCNT(pnt());
nextline(); pnt(); dup();
OPCNT(push(str[i] / 12)); OPCNT(mul()); OPCNT(push(str[i] % 12)); OPCNT(add()); OPCNT(outc()); OPCNT(push(2 - dx)); if(i != len - 1) { OPCNT(dup()); }
whiteto(WIDTH - 2);
fin = 1;
}
if (!fin)
{
printf("collision unavoidable\n");
return -1;
}
}
x -= dx;
{
int var, sx = x, sy = y, sdx = dx, fin = 0;
for(var = 0; var < 18 && !fin; var++)
{
x = sx; y = sy; dx = sdx;
hue = var / 3; dark = var % 3;
OPCNT(fill()); OPCNT(pnt()); OPCNT(fill());
fin = 1;
}
if (!fin)
{
printf("collision unavoidable\n");
return -1;
}
}
x -= 2 * dx;
y += 1;
imgSetP(img, x, y, white);
x -= dx;
y += 1;
hue = 0; dark = 1;
fill(); fill(); fill();
imgSave(img, "piet.pnm");
return 0;
}
```
**img.h**
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct
{
unsigned char r;
unsigned char g;
unsigned char b;
} Color;
typedef struct
{
Color* data;
int width;
int height;
} Image;
#define imgCreate(img, w, h) {\
int length;\
(img).width = (w);\
(img).height = (h);\
length = (img).width * (img).height * sizeof(Color);\
(img).data = malloc(length);\
memset((img).data, 0, length);\
}
#define imgDestroy(img) {\
free((img).data);\
(img).width = 0;\
(img).height = 0;\
}
#define imgGetP(img, x, y) ((img).data[(int)(x) + (int)(y) * (img).width])
#define imgSetP(img, x, y, c) {\
(img).data[(int)(x) + (int)(y) * (img).width] = c;\
}
#define imgLine(img, x, y, xx, yy, c) {\
int x0 = (x), y0 = (y), x1 = (xx), y1 = (yy);\
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;\
int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;\
int err = dx + dy, e2;\
\
for(;;)\
{\
imgSetP((img), x0, y0, c);\
if (x0 == x1 && y0 == y1) break;\
e2 = 2 * err;\
if (e2 >= dy) {err += dy; x0 += sx;}\
if (e2 <= dx) {err += dx; y0 += sy;}\
}\
}
#define imgSave(img, fname) {\
FILE* f = fopen((fname), "wb");\
fprintf(f, "P6\n%d %d\n255\n", (img).width, (img).height);\
fwrite((img).data, sizeof(Color), (img).width * (img).height, f);\
fclose(f);\
}
#define imgLoad(img, fname) {\
FILE* f = fopen((fname), "rb");\
char buffer[16];\
int index = 0;\
int field = 0;\
int isP5 = 0;\
unsigned char c = ' ';\
while(field < 4)\
{\
do\
{\
if(c == '#') while(c = fgetc(f), c != '\n');\
} while(c = fgetc(f), isspace(c) || c == '#');\
index = 0;\
do\
{\
buffer[index++] = c;\
} while(c = fgetc(f), !isspace(c) && c != '#' && index < 16);\
buffer[index] = 0;\
switch(field)\
{\
case 0:\
if (strcmp(buffer, "P5") == 0) isP5 = 1;\
else if (strcmp(buffer, "P6") == 0) isP5 = 0;\
else fprintf(stderr, "image format \"%s\" unsupported (not P5 or P6)\n", buffer), exit(1);\
break;\
case 1:\
(img).width = atoi(buffer);\
break;\
case 2:\
(img).height = atoi(buffer);\
break;\
case 3:\
index = atoi(buffer);\
if (index != 255) fprintf(stderr, "image format unsupported (not 255 values per channel)\n"), exit(1);\
break;\
}\
field++;\
}\
imgCreate((img), (img).width, (img).height);\
if (isP5)\
{\
int length = (img).width * (img).height;\
for(index = 0; index < length; ++index)\
{\
(img).data[index].r = (img).data[index].g = (img).data[index].b = fgetc(f);\
}\
}\
else\
{\
fread((img).data, sizeof(Color), (img).width * (img).height, f);\
}\
fclose(f);\
}
```
[Answer]
## C, (384 + 256 \* strlen) codels, no optimization
No clever hacking in this solution. Every character is represented by a single line with height in pixels = ascii value. Op sequence is then push, outc, push, outc, ...
Output for "Hello Piet!" (and zoom of top part):

**asciipiet.c**
```
#include "img.h"
Color piet[6][3] = {
{{0xff,0xc0,0xc0},{0xff,0x00,0x00},{0xc0,0x00,0x00}},
{{0xff,0xff,0xc0},{0xff,0xff,0x00},{0xc0,0xc0,0x00}},
{{0xc0,0xff,0xc0},{0x00,0xff,0x00},{0x00,0xc0,0x00}},
{{0xc0,0xff,0xff},{0x00,0xff,0xff},{0x00,0xc0,0xc0}},
{{0xc0,0xc0,0xff},{0x00,0x00,0xff},{0x00,0x00,0xc0}},
{{0xff,0xc0,0xff},{0xff,0x00,0xff},{0xc0,0x00,0xc0}}
};
Color white = {0xff,0xff,0xff};
int main(int argc, char* argv[])
{
char* str;
int len, i, hue, dark;
Image out;
if(argc != 2)
{
printf("Usage: %s \"string to print\"\n", argv[0]);
return -1;
}
str = argv[1];
len = strlen(str);
imgCreate(out, len * 2 + 3, 128);
hue = 0;
dark = 1;
for(i = 0; i < len; i++)
{
imgLine(out, i * 2, 0, i * 2, str[i] - 1, piet[hue][dark]);
dark = (dark + 1) % 3;
imgSetP(out, i * 2 + 1, 0, piet[hue][dark]);
dark = (dark + 2) % 3;
hue = (hue + 5) % 6;
}
imgSetP(out, len * 2, 0, piet[hue][dark]);
imgSetP(out, len * 2 + 1, 0, white);
imgSetP(out, len * 2 + 2, 0, white);
imgSetP(out, len * 2 + 2, 1, white);
imgSetP(out, len * 2 + 2, 2, white);
imgSetP(out, len * 2 + 2, 3, white);
imgSetP(out, len * 2 + 1, 3, white);
imgSetP(out, len * 2, 2, piet[0][4]);
imgSetP(out, len * 2, 3, piet[0][5]);
imgSetP(out, len * 2, 4, piet[0][6]);
imgSave(out, "piet.pnm");
return 0;
}
```
**img.h**
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct
{
unsigned char r;
unsigned char g;
unsigned char b;
} Color;
typedef struct
{
Color* data;
int width;
int height;
} Image;
#define imgCreate(img, w, h) {\
int length;\
(img).width = (w);\
(img).height = (h);\
length = (img).width * (img).height * sizeof(Color);\
(img).data = malloc(length);\
memset((img).data, 0, length);\
}
#define imgDestroy(img) {\
free((img).data);\
(img).width = 0;\
(img).height = 0;\
}
#define imgGetP(img, x, y) ((img).data[(int)(x) + (int)(y) * (img).width])
#define imgSetP(img, x, y, c) {\
(img).data[(int)(x) + (int)(y) * (img).width] = c;\
}
#define imgLine(img, x, y, xx, yy, c) {\
int x0 = (x), y0 = (y), x1 = (xx), y1 = (yy);\
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;\
int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;\
int err = dx + dy, e2;\
\
for(;;)\
{\
imgSetP((img), x0, y0, c);\
if (x0 == x1 && y0 == y1) break;\
e2 = 2 * err;\
if (e2 >= dy) {err += dy; x0 += sx;}\
if (e2 <= dx) {err += dx; y0 += sy;}\
}\
}
#define imgSave(img, fname) {\
FILE* f = fopen((fname), "wb");\
fprintf(f, "P6\n%d %d\n255\n", (img).width, (img).height);\
fwrite((img).data, sizeof(Color), (img).width * (img).height, f);\
fclose(f);\
}
#define imgLoad(img, fname) {\
FILE* f = fopen((fname), "rb");\
char buffer[16];\
int index = 0;\
int field = 0;\
int isP5 = 0;\
unsigned char c = ' ';\
while(field < 4)\
{\
do\
{\
if(c == '#') while(c = fgetc(f), c != '\n');\
} while(c = fgetc(f), isspace(c) || c == '#');\
index = 0;\
do\
{\
buffer[index++] = c;\
} while(c = fgetc(f), !isspace(c) && c != '#' && index < 16);\
buffer[index] = 0;\
switch(field)\
{\
case 0:\
if (strcmp(buffer, "P5") == 0) isP5 = 1;\
else if (strcmp(buffer, "P6") == 0) isP5 = 0;\
else fprintf(stderr, "image format \"%s\" unsupported (not P5 or P6)\n", buffer), exit(1);\
break;\
case 1:\
(img).width = atoi(buffer);\
break;\
case 2:\
(img).height = atoi(buffer);\
break;\
case 3:\
index = atoi(buffer);\
if (index != 255) fprintf(stderr, "image format unsupported (not 255 values per channel)\n"), exit(1);\
break;\
}\
field++;\
}\
imgCreate((img), (img).width, (img).height);\
if (isP5)\
{\
int length = (img).width * (img).height;\
for(index = 0; index < length; ++index)\
{\
(img).data[index].r = (img).data[index].g = (img).data[index].b = fgetc(f);\
}\
}\
else\
{\
fread((img).data, sizeof(Color), (img).width * (img).height, f);\
}\
fclose(f);\
}
```
] |
[Question]
[
You are a project manager. One day, one of your programmers went insane (*not your fault*) and took all the expressions in the codebase and added random brackets to them, before quitting on the spot, ranting about your incompetence (*also not your fault*). This would be an easy fix, however, for some reason you aren't using revision control (*totally not your fault*). And for some reason, none of the other programmers want to go through every expression to fix up the mismatched brackets (*by the way, that is not your fault*). Programmers these days, you think to yourself. You will have to do it yourself. The horror! Such tasks were supposed to be beneath you...
The input will be a single line, which will contain a number of left brackets (`( [ {`) and right brackets (`) ] }`). It also may, but not always, contain comments (`/* */`) and string literals (`" "` or `' '`) and various numbers, letters, or symbols.
There will be at least one bracket (outside of a comment or string literal) that does not have a corrosponding opposite (outside of a comment or string literal). For example, an errant `}` without a `{` prior. Another example: a `(` which does not have a `)` afterwards. Your program will replace with a space the minimum number of brackets required to make the brackets match up.
Examples:
`(4 + (2 + 3))]` ==> `(4 + (2 + 3))` (the square bracket at the end)
`][][[]]` ==> `[][[]]` (the square bracket at the start)
`("Hel(o!"))` ==> `("Hel(o!")` (the parenthesis at the end)
`( /* )]*/` ==> `/* )]*/` (the parenthesis at the start)
`{()]` ==> `()` (the curly bracket and the square bracket)
* Input can be taken from whichever way is most convenient (STDIN, command line argument, reading from a file, etc.)
* If there is more than one way to resolve the mismatch with the same number of removals, either is acceptable.
* There will be only mismatches in brackets. String literals and comments will always be correctly formed.
* The title comes from [this SO thread](https://stackoverflow.com/a/766363/3677860)
* There will never be any quotes in comments, quotes in quotes, comments in comments, or comments in quotes.
This is code golf, so minimum number of bytes wins. Ask questions in comments if the specification is not clear.
[Answer]
# Ruby, 223 characters
This one turned out a bit long.
```
u,b,i=[],[[],[],[]],-1
s=gets.gsub(/(\/\*|"|').*?(\*\/|"|')|~/){|m|u+=[m];?~}
s.chars{|c|i+=1
(t='{[('.index(c))?b[t].push(i):((t='}])'.index(c))&&(b[t].pop||s[i]=' '))}
b.flatten.map{|l|s[l]=' '}
puts s.gsub(/~/){u.shift}
```
What it does is take out the strings and comments first, so they don't get counted (and puts them back in later).
Then, it goes through the string character by character. When it finds an opening brace, it stores its position. When it finds a closing brace, it pops from its respective open brace storage array.
If `pop` returns `nil` (i.e. there weren't enough opening braces), it removes the closing brace. After this entire thing is done, it removes the remaining extra opening braces (i.e. there weren't enough closing braces).
At the end of the program, it puts all the strings and comments back and outputs them.
Ungolfed:
```
in_str = gets
# grab strings and comments before doing the replacements
i, unparsed = 0, []
in_str.gsub!(/(\/\*|"|').*?(\*\/|"|')|\d/){|match| unparsed.push match; i += 1 }
# replaces with spaces the braces in cases where braces in places cause stasis
brace_locations = [[], [], []]
in_str.each_char.with_index do |chr, idx|
if brace_type = '{[('.index(chr)
brace_locations[brace_type].push idx
elsif brace_type = '}])'.index(chr)
if brace_locations[brace_type].length == 0
in_str[idx] = ' '
else
brace_locations[brace_type].pop
end
end
end
brace_locations.flatten.each{|brace_location| in_str[brace_location] = ' ' }
# put the strings and comments back and print
in_str.gsub!(/\d+/){|num| unparsed[num.to_i - 1] }
puts in_str
```
[Answer]
# Python 3, ~~410~~ ~~322~~ 317
```
import re;a='([{';z=')]}';q=[re.findall('".*?"|/\*.*?\*/|.',input())]
while q:
t=q.pop(0);s=[];i=0
for x in t:
if x in a:s+=[x]
try:x in z and 1/(a[z.find(x)]==s.pop())
except:s=0;break
if[]==s:print(''.join(t));break
while 1:
try:
while t[i]not in a+z:i+=1
except:break
u=t[:];u[i]=' ';q+=[u];i+=1
```
Tries every possible set of deletions, starting with smaller ones, until it finds one where the braces are balanced. (By which I mean fully correctly balanced: `{{(})` produces `( )`, not `{(})`.)
The first version used a recursive generator function, which was really cool but also really long. This version performs a simple breadth-first search using a queue. (Yes, it's a factorial time algorithm. What's the problem? :^D)
[Answer]
## C - 406
An Attempt in C without using regular expressions.
```
#define A if((d==125||d==93||d==41)
char*s;t[256];f(i,m,n,p){while(s[i]!=0){int c=s[i],k=s[i+1],v=1,d;if((c==42&&k==47)||(c==m&&i>n))return i;if(!p||p==2){if((c==39||c==34)||(c==47&&k==42)){i=f(i,c*(c!=47),i,p+1);
c=c==47?42:c;}d=c+1+1*(c>50);A){v=f(i+1,d,i,2);if(!p&&v)t[d]++;if(p==2&&v)i=v;}}d=c;A&&!p){v=!!t[c];t[c]-=v;}if(p<2)putchar(c*!!v+32*!v);i++;}return 0;}main(int c,char*v[]){s=v[1];f(0,0,0,0);}
```
To compile and run (on a linux machine):
gcc -o brackets brackets.c
./brackets "[(])"
In undefined cases like [ ( ] ) it returns the last valid bracket pair ( )
[Answer]
# Python 3, 320
```
import re
O=dict(zip('([{',')]}'))
def o(s,r,m=0,t=[]):m+=re.match(r'([^][)({}/"]|/(?!\*)|/\*.*?\*/|".*?")*',s[m:]).end();return r and o(s[:m]+' '+s[m+1:],r-1,m+1,t)or(o(s,r,m+1,t+[O[s[m]]])if s[m]in O else[s[m]]==t[-1:]and o(s,r,m+1,t[:-1]))if s[m:]else not t and s
s=input();i=0;a=0
while not a:a=o(s,i);i+=1
print(a)
```
Like DLosc's solution, this investigates every possible deletion, but it uses a recursive explore and fallback strategy which is a lot faster. I know that speed is not a criterion in code golf, and exhaustive search is in any case exponential, but this one can handle inputs like `({({({({({({({({(}}}}}}}}` in a couple of seconds.
] |
[Question]
[
The zombie apocalypse has come, and the world is coming to an end. Suddenly, someone discovers a formula that takes the current hour, minute, and day, and spits out the perfect note to play on a piano that instantly kills every zombie that hears it. Unfortunately, there is only one piano player left in the world, and he has forgotten how to read notes, but he still knows how to read sheet music. Of course, this is a very time-sensitive thing, so it seems natural to have a computer do it.1
Your challenge is to take a note, such as `G`, and output the note placed on a staff (in treble clef), like this:
```
-----
-----
|
---|-
|
--O--
-----
```
Specification:
* You must output a staff of alternating lines of `-----` (5 dashes) and a blank line. There will be 5 `-----`s total. The note must be superimposed on top of this staff.
* The input will specify where the note is located. The input will be:
+ an optional `H` or `L`, specifying "high" or "low"
+ a letter from `A` to `G`, specifying the pitch
+ an optional `#` or `b`, specifying sharp or flat.
* The "note" is defined as:
+ One `O` (capital O) aligned to the middle of the staff, which is in the place of the note. (The top line is `HF` (high F), and the bottom line is `E` (a normal E).)
+ Three `|`s (vertical bars), the stem, which will be:
- one space to the left of the note and going downwards (starting one space below the note) if the note is on the middle line (`B`) or above, or
- one space to the right of the note and going upwards (starting one space above the note) if the note is below the middle line.
+ A `#` or `b` one space directly to the left of the note if specified in the input.
* Ledger lines must be added if the note is too high or low. These lines will be `---` (only 3 dashes in width, as opposed to 5) and will only appear if the note is on or above/below (for top/bottom ledger lines respectively) the ledger lines.
* Extraneous spaces may be placed anywhere you want; for example, you could make the blank lines have spaces or have a space after the ledger lines if it helps you save any characters.
Here is a visualization, to understand the specification more easily, with all the note names next to the lines:
```
HB
--- HA
HG
----- HF
HE
----- HD
HC
----- B
A
----- G
F
----- E
D
--- C
LB
--- LA
LG
--- LF
... (bottom cut off for brevity, you get the idea anyway)
```
Here are some more examples that you can use to test your program:
Input: `HG#`
```
#O
-|---
|
-|---
-----
-----
-----
```
Input: `LAb`
```
-----
-----
-----
-----
-----
|
--|
|
bO-
```
Input: `HB`
```
O
|--
|
-|---
-----
-----
-----
-----
```
Input: `C`
```
-----
-----
-----
-----
|
---|-
|
-O-
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win!
1: most realistic exposition evar! :-P
[Answer]
## Ruby – ~~271~~ ~~267~~ ~~252~~ ~~249~~ ~~234~~ ~~229~~ ~~220~~ 214 characters
I literally just learned Ruby for this. So there is certainly room for improvement in golfing it down. Or doing anything really. But I needed a language with mutable strings. :)
```
def f(n)s=[0]*20
s.fill{|i|i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s[[3,l].min..[11,l].max]end
```
Somewhat ungolfed:
```
def f(note)
staff=[]
0.step(20) {|i| staff[i] = " "*5}
1.step(19,2) {|i| staff[i] = " ---"}
3.step(11,2) {|i| staff[i] = "-"*5}
level = 7
if !(pos="HL".index note[i=0]).nil?
level = 14*pos
i += 1
end
level += (73-note[i].ord)%7
staff[level][2] = "O"
mark = note[-1]
if !"#b".index(mark).nil?
staff[level][1] = mark
end
offset = (level > 7) ? 3 : 1
staff[level-2*offset+3,3].map {|line| line[offset] = "|"}
first = [3,level].min
last = [11,level].max
puts s[first..last]
end
```
I can cut it by another 2 characters down to **212 characters** if leading blank lines are allowed. This solution doesn't fill the lines that aren't printed anyway:
```
def f(n)s=[]
[3,l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)].min.step(l>11?l:11){|i|s[i]=i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s
end
```
Are lambda's fair game? Then I can get **210 characters** with the first approach
```
f=->n{s=[0]*20
s.fill{|i|i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s[[3,l].min..[11,l].max]}
```
Or **207 characters** with additional blank lines:
```
f=->n{s=[]
[3,l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)].min.step(l>11?l:11){|i|s[i]=i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s}
```
Of course, now you'd need to do `f.call("HGb")`.
[Answer]
# Python, ~~329~~ ~~309~~ ~~295~~ ~~286~~ ~~280~~ 277 characters
Golfed a bit more now. Still can be improved, but not sure if I can beat out the ruby or golfscript solutions with this approach.
```
R=range
N='J'+raw_input()+' '
X=N[1]>'G'
a,b,c=N[X:3+X]
z=266-ord(a)/2*7+(ord(b)-4)%7
Z=[list((' '*5,(' ---','-'*5)[8<r<18])[r%2])for r in R(21)]
Z[z][2]='o'
if' '<c:Z[z][1]=c
Q=(z<13)*2
for i in(1,2,3):Z[z+i*Q-i][Q+1]='|'
for r in R(max(17,z),min(z-1,8),-1):print''.join(Z[r])
```
Initially I was printing out line-by-line, but it turned out to take too much, so I generate a string grid and then fill in what needs be filled in. Input is from command line, e.g.:
```
>echo HG# | python note2_golf.py
#o
-|---
|
-|---
-----
-----
-----
```
[Answer]
# GolfScript - ~~243~~ ~~232~~ ~~228~~ 227 characters
I translated my CoffeeScript answer into GolfScript, which is much more suited to the string manipulations.
**EDIT:** Saved six characters by properly using the increment operator, three by making good use of the stack, six more by irresponsibly redefining operators I'm not using, and one more by not printing the trailing space after grace lines.
Entirely golfed:
```
..0="HL"?2+3%:o)2%.@="CDEFGAB"?7o*+:`2%45 32if:r;
).2$,<{=}{;;r}if:&;
[" "5*:|" ---":g]4*[|"-"5*]5*+[|g|]+.
[`<~]\[`>([0=:^&79r^]''+\~]
+17`<`)18if<9`>`9if:j>:t 13`>.2*):x;
4,1>{`j-\2${+}{-}if}%\;
{.@<\t>(:v[x<'|'+x)v>+]\++:t}
/-1%n*
```
With comments:
```
# extract octave
..0="HL"?2+3%:o
# extract note
2%1\-.@="CDEFGAB"?7o*+:k
# line spacer
2%45 32if:r;
# extract accidental
1+.2$,<{=}{;;r}if:a;
# staff
[" "5*:|" --- ":g]4*[|"-"5*]5*+[|g|]+.
# lines below
[k<~]\
# note line and above
[k>([0=:w a 79r w]''+\~]+
# cut off just what we need
17k<1k+18if<
9k>k 9if:j>:t;
# and the note stem
13k>.2*1+:x;4,1>{k j-\2${+}{-}if}%\;
{
.t<\
t>(:v[x<'|'+1x+v>+]\++:t;
}/
# now output the note
t-1%n*
```
[Answer]
# Golfscript, ~~211~~ ~~210~~ ~~209~~ ~~197~~ ~~195~~ 192 characters
Coming in for the (as of this post) win, a GolfScript version of my [latest Python version](https://codegolf.stackexchange.com/a/24848/4800):
```
"J"\+[0]+.1=71>>3<{}/@7*2/246-@3+7%-:z;:c;21,{..3z<3z
if<\11z>11z
if>|{;}{...2>\12<&\2%.{'-'' 'if}:Q~:9;&Q\.z={c!9{[c]''+}if}{..z>\4z+<&8z>&'|'9if}if\.z='o'9if\..z
4-\<\z<&7z<&'|'9if\;3$n}if}/
```
Test it out [here](http://golfscript.apphb.com/?c=OyJCYiIKCiJKIlwrWzBdKy4xPTcxPj4zPHt9L0A3KjIvMjQ2LUAzKzclLTp6OzpjOzIxLHsuLjN6PDN6CmlmPFwxMXo%2BMTF6CmlmPnx7O317Li4uMj5cMTI8JlwyJS57Jy0nJyAnaWZ9OlF%2BOjk7JlFcLno9e2MhOXtbY10nJyt9aWZ9ey4uej5cNHorPCY4ej4mJ3wnOWlmfWlmXC56PSdvJzlpZlwuLnoKNC1cPFx6PCY3ejwmJ3wnOWlmXDszJG59aWZ9Lw%3D%3D) (first 2 lines are user-input, normally it comes from stdin).
'Readable' version:
```
;"HCb"
"J"\+[0]+ #process input
.1=71>>3< #first char is HJL, second is letter, third is #b or space
{}/ #spill chars onto stack, now we working with ints
@7*2/246-@3+7%- #convert HC/JD/LE etc to a number from 0 to 20
:z;:c;
21,{ #for r in range(21):
..3z<3z if< #either out-of-bounds or process the line
\11z>11z if>|
{;}{
...2>\12<&\2%.{'-'' 'if}:Q~:9;&Q\ #1st char
.z={c!9{[c]''+}if} #2nd char accidental
{..z>\4z+<&8z>&'|'9if}if\ #2nd char stem or row
.z='o'9if\ #3rd char
..z 4-\<\z<&7z<&'|'9if\ #4th char stem or row
;3$ #5th char=1st char
n
}if
}/
```
[Answer]
# Python, ~~250~~ ~~245~~ ~~242~~ 235 characters
A very different approach which ended up beating out my other one! Input processing code is similar but that's about it.
```
M=' -'
N=raw_input()+M
a,b,c=('J'+N)[N>'G':][:3]
z=ord(a)*7/2-246-(ord(b)+3)%7
for r in range(21):
L=M[r%2];F=M[2<r<12and r%2]
if min(3,z)<=r<=max(11,z):print F+((L,'|')[8>z<r<z+4],(L,c)[M<c])[r==z]+(L,'o')[r==z]+(L,'|')[z-4<r<z>7]+F
```
I mapped out each character's value based on the row and column and then golfed the printing:
```
#given row r, with note on row n, how to print each char?
#rows are:
# HB : 0
# --- HA : 1
# HG : 2
# ----- HF : 3
# HE : 4
# ----- HD : 5
# HC : 6
# ----- B : 7
# A : 8
# ----- G : 9
# F : 10
# ----- E : 11
# D : 12
# --- C : 13
# LB : 14
# --- LA : 15
# LG : 16
# --- LF : 17
# LE : 18
# --- LD : 19
# LC : 20
#chars are:
# 0 | 1 | 2 | 3 | 4
#
# 0,4:
# if r%2:
# if 2<r<12: '-'
# else ' '
# else: ' '
# 1: ' -b#|'
# if r==n:
# if A: c
# else: ' -'[r%2]
# elif n<8 and n<r<n+4: '|'
# else: ' -'[r%2]
# 2: ' -o'
# if r==n: 'o'
# else: ' -'[r%2]
# 3: ' -|'
# if n>7 and n-4<r<n: '|'
# else: ' -'[r%2]
```
[Answer]
# Java - ~~921~~ ~~907~~ 863 characters
I build up each string seperately, storing each string in an array.
Then loop through the array and print out each line.
```
public class D{public static void main(String[]a){char[]z=a[0].toCharArray();char[]y=new char[3];y[0]=('H'==z[0]||'L'==z[0])?z[0]:'N';int o=(y[0]=='N')?0:1;y[1]=z[o++];y[2]=z.length>o?z[o]:'!';int n=y[1]<'C'?((int)(y[1]-'A'))+6:((int)(y[1]-'C'))+1;n=(y[0]=='N')?n+7:(y[0]=='H'?n+14:n);String s=" ";String b=" --- ";String[]u=new String[22];for(int i=1;i<=21;i+=2){u[i]=s;}for(int i=10;i<=18;i+=2){u[i]="-----";}u[20]=n>19?b:s;u[2]=n<3?b:s;u[4]=n<5?b:s;u[6]=n<7?b:s;u[8]=n<9?b:s;char c=u[n].charAt(0);char e=u[n].charAt(1);char[]h=new char[]{c,y[2]=='!'?e:y[2],'O',e,c};u[n]=new String(h);for(int i=0;i<22;i++){if(n<14&&i-n<4&&i>n)u[i]=u[i]!=null?u[i].substring(0,3)+"|"+u[i].charAt(4):s;else if(n>13&&n-i<4&&n>i)u[i]=u[i]!=null?u[i].substring(0,3)+"|"+u[i].charAt(4):s;}for(int i=21;i>=0;i--)if(!(i>n&&i>18||i<n&&i<10))System.u.println((u[i]==null)?s:u[i]);}}
```
Oh please don't hate me, it's my first time. I coulnd't find any faq/introduction so I hope my posting format is ok.
Not sure how serious people got about character counts....
normal version of the code - extra is linebreak/spaces (1313 characters):
```
public class DisplayNote
{
public static void main(String[] args)
{
char[] z=args[0].toCharArray();
char[] y=new char[3];
y[0]=('H'==z[0]||'L'==z[0])?z[0]:'N';
int o=(y[0]=='N')?0:1;
y[1]=z[o++];
y[2]=z.length>o?z[o]:'!';
int noteValue=y[1]<'C'?((int) (y[1] - 'A')) + 6:((int) (y[1] - 'C')) + 1;
noteValue=(y[0]=='N')?noteValue+7:(y[0]=='H'?noteValue+14:noteValue);
String s=" ";
String b=" --- ";
String[] out=new String[22];
for (int i=1;i<=21;i+=2){out[i]=s;}
for (int i=10;i<=18;i+=2){out[i]="-----";}
out[20]=noteValue>19?b:s;
out[2]=noteValue<3?b:s;
out[4]=noteValue<5?b:s;
out[6]=noteValue<7?b:s;
out[8]=noteValue<9?b:s;
char c=out[noteValue].charAt(0);
char e=out[noteValue].charAt(1);
char[] h=new char[]{c,y[2]=='!'?e:y[2],'O',e,c};
out[noteValue]=new String(h);
for (int i=0;i<22;i++)
{
if (noteValue<14&&i-noteValue<4&&i>noteValue)
out[i]=out[i]!=null?out[i].substring(0,3)+"|"+out[i].charAt(4):s;
else if (noteValue>13&¬eValue-i<4&¬eValue>i)
out[i]=out[i]!=null?out[i].substring(0,3)+"|"+out[i].charAt(4):s;
}
for (int i=21;i>=0;i--)
if (!(i>noteValue&&i>18||i<noteValue&&i<10))
System.out.println((out[i]==null)?s:out[i]);
}
}
```
[Answer]
# Haskell 377C
```
import Data.Char
(<.)=elem
n(c:r)|elem c"HL"=let(s,a)=n r in(s+case c of 'H'->7;_-> -7,a)|1<2=(mod(ord c-67)7-2,case r of[]->' ';[x]->x)
r(s,a)y x=c where d|s>4= -1|1<2=1;c|x<.[0,4]&&(y<0||y>8)=' '|x==2&&y==s='o'|y==s&&x==1&&' '/=a=a|x==2+d&&y<.[s+k*d|k<-[1..3]]='|'|1<2="- "!!mod y 2
g p@(s,a)=unlines$[map(r p y)[0..4]|y<-reverse[min 0 s..max 8 s]]
main=getLine>>=putStr.g.n
```
Ungolfed version:
```
import Data.Char
fromName ('H':s) = let (step, alter) = fromName s in ((step + 7), alter)
fromName ('L':s) = let (step, alter) = fromName s in ((step - 7), alter)
fromName (x:s) = (mod (ord x - 67) 7 - 2, if null s then ' ' else head s)
renderChar :: (Int, Char) -> Int -> Int -> Char
renderChar (step, alter) y x = let
dir = if step > 4 then -1 else 1
normal = "- "!!mod y 2
stemYs = [step + k * dir | k <- [1..3]]
c | elem x [0,4] && not(elem y [0,2,4,6,8]) = ' '
| x == 2 && y == step = 'o'
| y == step && x == 1 && alter /= ' ' = alter
| elem y stemYs && x == 2 + dir = '|'
| otherwise = normal
in c
render :: (Int, Char)-> String
render (step, alter) = unlines [map (renderChar (step, alter) y) [0..4] | y <- ys]
where
ys = reverse [min 0 step .. max 8 step]
main = getLine >>= (putStr.render.fromName)
```
[Answer]
# Literate CoffeeScript - ~~497~~ 527 characters
I'm sure there's a better way to build the grid but I can't figure it out.
One golf helper.
```
_=(q)->->q.split ""
```
A C major scale and staff.
```
s=_("CDEFGAB")()
l=_ "-----"
e=_ " "
g=_ " --- "
t=->
o=[e(),l(),e(),l(),e(),l(),e(),l(),e(),l(),e(),g(),e()]
o.unshift e(),g() for [0..3]
o
```
Our notation function will take the string representation of a note.
```
f=(i)->
o=1
m=t()
```
First we'll determine the octave.
```
if /L|H/.test i[0]
if i[0]=="L" then o=0 else o=2
i=i[1..]
```
Then the note and accidental. Gotta love deconstructing assignment.
```
[n,a]=i
```
Let's convert the note and octave to an index and plot the note.
```
x=7*o+s.indexOf n
m[x][1]=a if a
m[x][2]='O'
```
Now we'll cut out only as much staff as we need.
```
j=9
k=17
if x>17
k=x
else if x<9
j=x
u=x-j
m=m[j..k]
```
And the note stem.
```
if x<13
m[x][3]='|' for x in [u+3...u]
else
m[x][1]='|' for x in [u-3...u]
```
Now let's output the results.
```
m.map((p)->p.join '').reverse().join '\n'
```
Finally, we'll export the function for console testing. These
characters don't count towards the total.
```
module.exports = f
```
[Answer]
# C, ~~325~~ 304
Now 21 bytes shorter thanks to [@ace](/users/12205)!
```
i;j;c;n;main(t){char
x[133];for(i;i<132;i++){x[i]="-----\n \n"[i%12];if((i<18||i>77)&&!((i%12)&11))x[i]=32;}for(;!n;){c=getchar();if(c>71)t=c^72?2:0;else
n=7*t+7-(c-4)%7;}x[i=n*6+2]=79;if((c=getchar())>32)x[i-1]=c;for(t=0,j=n<9?i+5:i-17;t<3;t++,j+=6)x[j]='|';x[n<13?77:n*6+5]=0;puts(x+(n>4?24:n*6));}
```
### Output:
```
./a.out
HBb
bO
|--
|
-|---
-----
-----
-----
-----
./a.out
LG#
-----
-----
-----
-----
-----
--|
|
--|
#O
```
[Answer]
# JavaScript 390 388
A bit of a challenge, I'll have to admit... I'm sure there's ways of reducing this further... I'm open to suggestions...
First Iteration
```
C=(a,x,o,c)=>{a[x]=a[x].substr(0,o)+c+a[x].substr(o+1)};l=7;s=[];for(i=21;i--;)s[i]=" ";for(j=1;19>j;j+=2)s[j]=" ---";for(k=3;12>k;k+=2)s[k]="-----";~(p="HL".indexOf((n=prompt())[i=0]))&&(l=14*p,i++);l+=(73-n.charCodeAt(i))%7;C(s,l,2,"O");m=n[n.length-1];"#"!=m& "b"!=m||C(s,l,1,m);o=7<l?3:1;for(z=0;3>z;C(s,t=l-2*o+3+z++,o,"|"));S=s.splice(3<=l?3:l,11>=l?11:l);console.log(S.join("\n"))
```
Second Iteration (using `n.slice(-1)` instead of `n[n.length-1]`), shaves 2 bytes
```
C=(a,x,o,c)=>{a[x]=a[x].substr(0,o)+c+a[x].substr(o+1)};l=7;s=[];for(i=21;i--;)s[i]=" ";for(j=1;19>j;j+=2)s[j]=" ---";for(k=3;12>k;k+=2)s[k]="-----";~(p="HL".indexOf((n=prompt())[i=0]))&&(l=14*p,i++);l+=(73-n.charCodeAt(i))%7;C(s,l,2,"O");m=n.slice(-1);"#"!=m& "b"!=m||C(s,l,1,m);o=7<l?3:1;for(z=0;3>z;C(s,t=l-2*o+3+z++,o,"|"));S=s.splice(3<=l?3:l,11>=l?11:l);console.log(S.join("\n"))
```
Ungolfed version:
```
function C(a,x,o,c){
a[x]=a[x].substr(0,o)+c+a[x].substr(o+1);
}
l=7;s=[];
for(i=21;i--;){
s[i]=" ";
}
for(j=1;19>j;j+=2){
s[j]=" ---";
}
for(k=3;12>k;k+=2){
s[k]="-----";
}
i=0;n=prompt();
p="HL".indexOf(n[i]);
if(p>=0){
l=14*p;i++;
}
l+=(73-n.charCodeAt(i))%7;
C(s,l,2,"O");
m=n.slice(-1);
if((m=="#")||m=="b"){
C(s,l,1,m);
}
o=7<l?3:1;
for(z=0;3>z;z++){
C(s,t=l-2*o+3+z,o,"|");
}
F=Math.min(3,l);
L=Math.max(11,l);
S=s.splice(F,L);
console.log(S.join("\n"));
```
] |
[Question]
[
Your task is to check the volume of water in a pool. Your have to create a program that takes in a input that is represented by an `10 by 10` grid of integers, with heights ranging from `A=1` to `Z=26` from the latin alphabet. Find the volume of water each pool can hold.
You have to output the volume of water that the pool can hold. Outside the pool the height is 0, so no water is held on the cells at the edge of the pool. The water does not leak diagonally.
# Test cases
```
ZZZZZZZZZZ
ZAAAAAAAAZ
ZAAAAAAAAZ
ZAAAAAAAAZ
ZAAAAAAAAZ
ZAAAAAAAAZ
ZAAAAAAAAZ
ZAAAAAAAAZ
ZAAAAAAAAZ
ZZZZZZZZZZ
OR
[[26, 26, 26, 26, 26, 26, 26, 26, 26, 26], [26, 1, 1, 1, 1, 1, 1, 1, 1, 26], [26, 1, 1, 1, 1, 1, 1, 1, 1, 26], [26, 1, 1, 1, 1, 1, 1, 1, 1, 26], [26, 1, 1, 1, 1, 1, 1, 1, 1, 26], [26, 1, 1, 1, 1, 1, 1, 1, 1, 26], [26, 1, 1, 1, 1, 1, 1, 1, 1, 26], [26, 1, 1, 1, 1, 1, 1, 1, 1, 26], [26, 1, 1, 1, 1, 1, 1, 1, 1, 26], [26, 26, 26, 26, 26, 26, 26, 26, 26, 26]]
->
1600
ZZZZZZZZZZ
ZRRRRRRRRZ
ZRRRRRRRRZ
ZRRRRRRRRZ
ZFFFFFFFFZ
ZDDDDDDDDZ
ZDDDDDDDDZ
ZDDDDDDDDZ
ZDDDDDDDDZ
ZZZZZZZZZZ
OR
[[26, 26, 26, 26, 26, 26, 26, 26, 26, 26], [26, 18, 18, 18, 18, 18, 18, 18, 18, 26], [26, 18, 18, 18, 18, 18, 18, 18, 18, 26], [26, 18, 18, 18, 18, 18, 18, 18, 18, 26], [26, 6, 6, 6, 6, 6, 6, 6, 6, 26], [26, 4, 4, 4, 4, 4, 4, 4, 4, 26], [26, 4, 4, 4, 4, 4, 4, 4, 4, 26], [26, 4, 4, 4, 4, 4, 4, 4, 4, 26], [26, 4, 4, 4, 4, 4, 4, 4, 4, 26], [26, 26, 26, 26, 26, 26, 26, 26, 26, 26]]
->
1056
XXXXXXXXXX
XSSSSRAAAX
XSSSSRAAAX
XSSSSRAAAX
XXXXXCXXXX
XSSSSCBBBX
XSSSSCBBBX
RSSSSCBBBX
XSSSSCBBBX
XXXXXXXXXX
OR
[[24, 24, 24, 24, 24, 24, 24, 24, 24, 24], [24, 19, 19, 19, 19, 18, 1, 1, 1, 24], [24, 19, 19, 19, 19, 18, 1, 1, 1, 24], [24, 19, 19, 19, 19, 18, 1, 1, 1, 24], [24, 24, 24, 24, 24, 3, 24, 24, 24, 24], [24, 19, 19, 19, 19, 3, 2, 2, 2, 24], [24, 19, 19, 19, 19, 3, 2, 2, 2, 24], [18, 19, 19, 19, 19, 3, 2, 2, 2, 24], [24, 19, 19, 19, 19, 3, 2, 2, 2, 24], [24, 24, 24, 24, 24, 24, 24, 24, 24, 24]]
->
449
ZZZZZZZZZZ
RAAAAZEEEZ
RAAAAZEEEZ
RAAAAZEEEZ
RAAAAZEEEZ
RAAAAAEEEZ
RAAAAZEEEZ
RAAAAZEEEZ
QAAAAZEEEZ
ZZZZZZZZZZ
OR
[[26, 26, 26, 26, 26, 26, 26, 26, 26, 26], [18, 1, 1, 1, 1, 26, 5, 5, 5, 26], [18, 1, 1, 1, 1, 26, 5, 5, 5, 26], [18, 1, 1, 1, 1, 26, 5, 5, 5, 26], [18, 1, 1, 1, 1, 26, 5, 5, 5, 26], [18, 1, 1, 1, 1, 1, 5, 5, 5, 26], [18, 1, 1, 1, 1, 26, 5, 5, 5, 26], [18, 1, 1, 1, 1, 26, 5, 5, 5, 26], [17, 1, 1, 1, 1, 26, 5, 5, 5, 26], [26, 26, 26, 26, 26, 26, 26, 26, 26, 26]]
->
816
```
>
> The input is in the form of a 2D list of integers. The one with letters is just a reference (You can input it as letters if you want to)
>
>
>
## Worked Example:
For the 1st test case:
There is only 1 box and that is 10 lines of `26` or `A`'s, and since this a pool, the `A`, represents the bottom of the pool, and the `Z` is the top, so `26-1=25` is the depth of the entire pool. Take `25*8*8=1600`, as the `Z` is the wall so only a `8*8` area is occupied.
Test Case 3 has a `R` in the outer row of `X`, so do take note the water level cannot go past this
Test Case 4:
The lowest wall is `Q`, so we take `17-1=16` as the highest water level for maximum height of `A=1`. We take `16*4*8=512`, next there is a `Z` wall, BUT there is an `A` breaking through the wall, which is connecting all the `E` to the wall of height `16`, so the max height of the water level of `E` is `17-5=12`, and take `12*3*8=288`. Finally, we take `512+12+288=816`(12 comes from the extra `A` inside the `Z` wall)
## Tips:
Think of this challenge as water held in many different boxes inside a large box
## Others:
* You may assume that all inputs are from the alphabet and that they are all uppercase
* You may assume that the outer row of alphabets do not always have the highest height, and can all have different heights
* The outer row MUST have a higher level than the 2nd outermost row due to the rule of no overflowing
* Water level cannot be higher than the highest "wall"
## Scoring
This is code-golf, so shortest code wins!
Credits to the codingame community for this puzzle! [Puzzle link](https://www.codingame.com/ide/puzzle/retaining-water)
[Answer]
# [Python 3](https://docs.python.org), 230 bytes
*-1 from 12944qwerty*
```
R=range;S=(1,0,-1,0)
def m(A,r=0):
for l in R(2,27):
K={(i,j)for i in R(10)for j in R(10)if A[i][j]<l};B={s for s in K if set(s)&{0,9}}
for _ in R(64):B|=K&{(i+S[k],j+S[k-1])for(i,j)in B for k in R(4)}
r+=len(K-B)
return r
```
[Try it online!](https://tio.run/##5ZPBboMwDIbvfQqfqkQNEqGUQrscypVbe0RomjTYoJSiwA4T49lZErRurcSg1dgOk2wg@LP/yE7y1/L5mM3tnDfNlvGH7Clc7xiiRCeaeODJYxjBAW0IZzpeTSA6ckghzmCLDGIs5S/wWIVikmAZi9sY1dUqOa3iCDZ@HPhJcJfWa5dVhSpVSMADES3CEhV4WunEqWtRVEbv23TLxCv3jXlTITPb@fuAJPKl0UCKKGnBuSpl36aYWNbgM5aGGfI0F0@Ah@ULz4A3OY@zEh2Q7xsWgX4PCCiSdth/JQZ0LsDAGFBLFwfp5rbb3/u4ZJd9EmaH/TYxfBz6wjobhyzT60pGfFHnwu2vh2Mk7NLnQ3cnwZNdQal9/FCtgf1th2Oazm1X5axztI0sPuyPETqWzrIXuepm2NTCzTs) Input is a list of lists of numbers from 1 to 26 inclusive.
For each possible water level from B (2) to Z (26) this function first fills the pool to that height, then drains off any water touching the edge. `K` is the set of tentatively filled cells and `B` that of "**b**urned" cells (since it implements a flood fill).
[Answer]
# Python3, 259 bytes
```
import numpy as np
r=range
l=np.array([[ord(j)-65for j in input()]for i in r(10)])
p=l.copy()
p[1:-1,1:-1]=25
for _ in r(11):
for i in r(1,9):
for j in r(1,9):p[i][j]=max(min([p[i+a][j+b]for a,b in[(-1,0),(0,1),(0,-1),(1,0)]]),l[i][j])
print(sum(sum(p-l)))
```
[Try it online!](https://tio.run/##jY7BagMhEIbvPoXHGeKGtSWFBjzksA/QHCNSTNKmLqsOZheyT7/VTUhyKh3GmZ@PX39p7H9ieJ0m5ymmnofB08jtmQdiSSUbTl@sU4GWNiU7gtYxHaHF6m31HRNvuQu5aegBTQGugASyRoOMVLc8RBohSy3XlRRlGPWyYsX7efNKXDP@fFm8F8LvATdE2hndGuXtBbwLoDNY2IwW@znbin12a8g5NQqohZxnVVZBxqDorm/kDyUXejgPfj5UdYg4Tbt7se0m165pmv/KzR@Gj4d8RPwC)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~144~~ 143 bytes
need extra stack
```
f=(x,t=[...f+f].map((_,i)=>~i%16&&26),z=0)=>t.some((v,i)=>[1,-1,16,-16].some(d=>v>~~t[i+d],p=(x[i>>4]||0)[i%16]|0,z+=v-p)&v>p&&t[i]--)?f(x,t):z
```
[Try it online!](https://tio.run/##5ZJda8MgFIbv9yt6s6BEJXYldBu6HyIyQhKLW1tliowQ8tOXmYx9UMiafXQ3k/OKeB5eD@d4V4TClQ/aerw3Vd33ioFH5JkghKhUSbIrLAC3SEPGO31O8yRZ5hA1LIsXnjizqwEIY1pQhCmiedxz@ZKpGA@867zQaSWRjdZCc76SbZtBMbjJNkNNygK2MAncJklEJcbwRg1VwKumvz4rzd6ZbU22ZgMUEGKZo8VxSbQYSToR/5WY0TkJ4U@bvv5cpyWn4p1YTcRfE98dxmByVOMj8UQvD7T@@DFOhB3qYm51A/gWX6DGOn7Ja2Z/42j6J2O9juPpMXa@KO@x003NaPa6ngE "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 150 bytes
```
f=(x,t=[...f+f].map((_,i)=>~i%16&&26),u,z=0,r=t.map((v,i)=>[1,-1,16,-16].some(d=>v>~~t[i+d],p=(x[i>>4]||0)[i%16]|0,z+=v-p)&v>p?u=[v-1]:v))=>u?f(x,r):z
```
[Try it online!](https://tio.run/##5ZJda8MgFIbv9yt6s6DkRGJXpOvQ/hCREZqkONoq@ZARQv56ZjLYRiFr9tHdDN5XhPPwejjHp8Ql5a7QtopOJs36PufoGSouCSF5mCtyTCxCj6AxF52@pSwIlgxDDQ2PoeDVa92NdUkhokCZP5kipTlmKOXCia6rpA5TBdZnSy3ESrVtjOUQp9oYmpC7yOLACbutuXQRVRuHfWC9zX0zBd40/cPNzpxKc8jIwexRjqRcMlhctoLFSNIJ/VdixuQUxj8d@vpzX5ec0juxmtBfE99dxhBy0eMj/kbvz7z@@DGuhJ37bm53A/imL1BjH7@UNXO@fjX9Cw "JavaScript (Node.js) – Try It Online")
`t[16*y+x]` stores water level
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 108 bytes
```
⊞υE⁺Aθ⁰WS⊞υE⁺Aι⌕ακ≔EυEιφθ≔⟦E³¦⁰⟧ηFη«≔⊟ιδ≔⊟ιε≔⌈⟦⊟ι§§υδε⟧ζ¿‹ζ§§θδε«§≔§θδεζF²F²⊞ηE⟦ζεδ⟧⁺μ∧⁼κ⊖ν⊖⊗λ»»I⁻ΣEθΣιΣEυΣι
```
[Try it online!](https://tio.run/##dVHBbsIwDD2vXxFxsqVMmrbjTgU2CWlIFVyQEIeMBhqRptA0G2Li2zu7a4Ft4ENtPb/n57jLTJXLQtm6ToLPIEgxVltIbPDQi3tS7FCKB8Tn6DMzVgsYuW2oplVp3BoQxXWRIdGrcSkoKTbI6th7s3bAtJZtpFghssGpO2f8if0WUmSEr4pSQIbiK7prKUlBSlKl1P2L6QtsrPYmDznMu2ZcjVyq99DlwDNYs6DvgZVmJeBNew@H/@xdx8ZmmdblFqsdeNes/4iiy82xsp/nzw8NMaWXNnfLyZQO9rILynrYSDHUy1Ln2lU6BceHugSGRXi3lC02QWbH6Bgl9FcqGChfwdg4GjqlC7AZLcalQZ7TgeEM8oi6np0imk0pJnEc3yw5BmfuoN/v/yonV9ELi/r@w34D "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υE⁺Aθ⁰WS⊞υE⁺Aι⌕ακ
```
Read in the pool, but add a border of zero depth.
```
≔EυEιφθ
```
Try to fill the pool to a height of `1000`.
```
≔⟦E³¦⁰⟧ηFη«
```
Begin a breadth-first search of the pool starting at the top left corner.
```
≔⊟ιδ≔⊟ιε
```
Get the next co-ordinates to check.
```
≔⌈⟦⊟ι§§υδε⟧ζ
```
Get the height of the neighbouring water level that triggered this search, but limit it to the height of the cell.
```
¿‹ζ§§θδε«
```
If this is less than the current height of the water, then:
```
§≔§θδεζ
```
Update the water height.
```
F²F²
```
Loop over the neighbouring cells.
```
⊞ηE⟦ζεδ⟧⁺μ∧⁼κ⊖ν⊖⊗λ
```
Add them to the search list of cells to check.
```
»»I⁻ΣEθΣιΣEυΣι
```
Subtract the heights of cells from the heights of the water and output the total.
[Answer]
# [MATLAB](https://www.gnu.org/software/octave/), 267 bytes
```
function d=p(A)
d=0;I=true(10);I(2:9,2:9)=0;for i=2:26
B=int8(A>=i);while any(~B(~I))
[j,k]=find(B==0,1);f(j,k);end
if any(B(I)==2)break
end
d=d+sum(sum(B==2));end
function f(x,y)
if (x<11&y<11&x>0&y>0)&~B(x,y)
B(x,y)=2;f(x-1,y);f(x+1,y);f(x,y+1);f(x,y-1);end
end
end
```
tried using the flood-fill algorithm to determine what squares on each layer should be filled. If the flood-fill ever reaches the outer edge, that's where the summation stops. I had a much shorter version, but it failed on test case 3 because the lowest outer wall is technically blocked off entirely, raising the effective maximum water level.
[Try it online!](https://tio.run/##bVA9b4MwEN35FUxwJ4yEGao29JDsTKzpUinKQGKjuEkhItDCkr9O7Xx2yJOe/fTune/kZtOVP3qaqr7edKapfUUHEOgpSrKCurbXwBPMCkhnb8wSrV81rW8onaUvniRTd68gcjKY/W7NXvtlPcJJwqlA9JZfbLeiytQKJFHCOGYVWA8zXSvPVOewhAKJUly3utx5rqBIRcf@GxylK13y9x0rGNiIrh@Gd86D0R1DngRjnmBgh5/Ll4tSO3KIuZVORDfBxohfRcwv7185Ta0@bsuDBtX0672G8POBD4uFEOK5cpjfc3Mp5T@1eOI9EGJ8GydCtGsuV8z9/B8 "Octave – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~224~~ ~~214~~ ~~213~~ 212 bytes
-10 bytes by using ternaries (thanks @ceilingcat) and simplifying parameter declaration
-1 bytes by using `for` instead of `do while` (thanks @ceilingcat)
-1 bytes by initialising `L` and `m` together (thanks @ceilingcat)
```
#define F for(m=0,j=10;j--;)for(i=10;i--;)
#define L l[j+1][i+1]
#define C(y,x)m=L>h[j][i]&L>l[y+j][x+i]?--L:m;
f(int**h){int m,j,i,l[12][12]={};F L=m=26;for(;m;)F{C(,1)C(1,)C(1,2)C(2,1)}F m+=L-h[j][i];return m;}
```
[Try it online!](https://tio.run/##rVBdb5swFH2Of4XXaosJJsJRh7a6zpSw8IQ0LXupwnjgsxgBqQhorSJ@e3aNWMKkdurDjuTrc4@POJcbGQ9RdDpdx0kqqwQ7ON3XpBQmzQUzeW4YXFOKVJ1UHfpjdXHh5TrzPQnlrNrkmT5ppXCXmZfDm//BXRbesw78SZf@F8Nwb0uOUiKrZjbLtCPcuKQ5lbTw2MJXRxw77mBXlGJhcZXOS645R5tQptmE0b4soC5A6Bxc6sI1hjheJ01bV7jk3elaVlHRxsndoYnlfp4tUR8WyIpoRzRRjYTkzGOmrw6dBeriaBJlQY1Dj1mqifdgnqg5cgEruVN70XX1BVAfkuZAQsosqkIqjfdqvzFYmPJK8CpxMkwoQijGdDXVWW8OQBbqTXUdnMcaJkvJ1fv4Z3VFUxJo/Vdfiup@ZbJIyCx8J6bzKSjdaXcG2q0G/G96iRjz3XbAq9QZAPTrgLfQUdz9Gej@B2ALA71KFeyL116v13/R7YvqKGIcve3/fbPZvJWu/mH4fqGjiDlC39rmsW3wIdu3RYzD5BYhZpkmYuZHC93cfEafmPUb "C (gcc) – Try It Online")
Reduce the water level of each box that has water and its level is above one of its neighbours. Repeat until there are no changes to the water level.
] |
[Question]
[
Let us define a sequence. We will say that \$a(n)\$ is the smallest number, \$x\$, that has the following properties:
* \$x\$ and \$n\$ are co-prime (they share no factor)
* \$x\$ does not appear earlier in the sequence
* \$|n - x| > 1\$
Unlike most sequences the domain and range of our sequence are the integers *greater than* 1.
---
Let us calculate the first couple of terms.
\$a(2)\$, must be at least **4**, but **4** and **2** share a factor of **2** so \$a(2)\$ must be **5**.
\$a(3)\$, must be at least **5** but **5** is taken by \$a(2)\$, so it is at least **6**, but **6** shares a factor with **3** so it must be at least **7**, **7** fulfills all three requirements thus \$a(3)=7\$.
\$a(4)\$
* **2** Shares a factor
* **3** Too close
* **4** Too close
* **5** Too close
* **6** Shares a factor
* **7** Taken by **a(3)**
* **8** Shares a factor
* **9** is good
\$a(5)\$
* **2** is good
---
## Task
In this challenge you are to write a program that takes a number greater than 1 and returns \$a(n)\$.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with fewer bytes being better.
## Test Cases
Here are the first couple terms of the sequence (They are of course 2 indexed):
```
5,7,9,2,11,3,13,4,17,6,19,8,23,22,21,10,25,12,27,16,15,14
```
## ~~Bonus~~ Fun fact
As proven by Robert Israel on Math.se ([link](https://math.stackexchange.com/a/2366358/276060)) this sequence is its own inverse, that means that \$a(a(n)) = n\$ for all n.
## OEIS
After asking this question I submitted this sequence to the OEIS and after a few days it was added.
[OEIS A290151](https://oeis.org/A290151)
[Answer]
# [Haskell](https://www.haskell.org/), 61 bytes
```
f n=[i|i<-[2..],gcd i n<2,all((/=i).f)[2..n-1],abs(n-i)>1]!!0
```
[Try it online!](https://tio.run/##FcpBDoMgEAXQq3wTF5AALboVL2JYTGupE3Ek6rJ3p3H93kLn@sm51gQJE/94sFPnXDTf9wyGDJ2hnJV6BNYu6dvE@mjodSqxrEcfm@ZZN2JBwLyjHCwXWmxUkHB/38f6Bw "Haskell – Try It Online")
I'm fairly new to Haskell, so any golfing tips are appeciated.
Thanks to Wheat Wizard for 2 bytes and nimi for 4 bytes
Explanation:
```
f n=[i|i<-[2..],gcd i n<2,all((/=i).f)[2..n-1],abs(n-i)>1]!!0
f n= -- define a function f :: Int -> Int
[i|i<-[2..], -- out of positive integers greater than two
gcd i n<2, -- gcd of i and n is 1
all((/=i).f)[2..n-1], -- i isn't already in the sequence
abs(n-i)>1] -- and |n-i| > 1
!!0 -- take the first element
```
[Answer]
# [Alice](https://github.com/m-ender/alice), 42 bytes
```
/oi
\1@/2-&whq&[]w].q-H.t*n$K.qG?*h$KW.!kq
```
[Try it online!](https://tio.run/##S8zJTE79/18/P5MrxtBB30hXrTyjUC06tjxWr1DXQ69EK0/FW6/Q3V4rQ8U7XE8xu/D/f0MDAA "Alice – Try It Online")
### Explanation
```
/oi
\1@/.........
```
This is a standard template for programs that take a number as input, and output a number, modified to place a 1 on the stack below the input number.
The main part of the program places each number `k` in slot `a(k)` on the tape. The inner loop computes a(k), and the outer loop iterates over k until a(n) is computed.
```
1 push 1
i take input
2-&w repeat n-1 times (push return address n-2 times)
h increment current value of k
q&[ return tape to position 0
] move right to position 1
w push return address to start inner loop
] move to next tape position
.q- subtract tape position from k
H absolute value
.t* multiply by this amount minus 1
n$K if zero (i.e., |k-x| = 0 or 1), return to start of inner loop
.qG GCD(k, x)
? current value of tape at position: -1 if x is available, or something positive otherwise
* multiply
h$K if not -1, return to start of inner loop
W pop return address without jumping (end inner loop)
.! store k at position a(k)
k end outer loop
q get tape position, which is a(n)
o output
@ terminate
```
[Answer]
# VB.NET (.NET 4.5), 222 bytes
```
Function A(n)
Dim s=New List(Of Long)
For i=2To n
Dim c=2
While Math.Abs(i-c)<2Or g(c,i)>1Or s.Contains(c)
c+=1
End While
s.Add(c)
Next
Return s.Last
End Function
Function g(a, b)
Return If(b=0,a,g(b,a Mod b))
End Function
```
I had to roll your own GCD. I also couldn't figure out how to get it to not be an entire function.
GCD is always >= 1, so only need to ignore 1
Took out short-circuiting in the golf because it's shorter
Un-golfed
```
Function Answer(n As Integer) As Integer
Dim seqeunce As New List(Of Integer)
For i As Integer = 2 To n
Dim counter As Integer = 2
' took out short-circuiting in the golf because it's shorter
' GCD is always >= 1, so only need to ignore 1
While Math.Abs(i - counter) < 2 OrElse GCD(counter, i) > 1 OrElse seqeunce.Contains(counter)
counter += 1
End While
seqeunce.Add(counter)
Next
Return seqeunce.Last
End Function
' roll your own GCD
Function GCD(a, b)
Return If(b = 0, a, GCD(b, a Mod b))
End Function
```
[Answer]
# Mathematica, 111 bytes
```
(s={};Table[m=2;While[m<3#,If[CoprimeQ[i,m]&&FreeQ[s,m]&&Abs[i-m]>1,s~AppendTo~m;m=3#];m++],{i,2,#}];s[[#-1]])&
```
[Try it online!](https://tio.run/##HcbNCoJAEADgh1mQwglxPW4bShB0qxA6DHPQWnOgUXG9ib769vOdPqmmlh8@NDZsvJ0XU1b126FYbe4t/7bPFJwbPPbDyOKuyCAURafRfe//L2qPvBM6pODXYhhc9yz7VYzYTJGROCaYGTSohYxHVLuUaBuFy8jdlORNkt@q7uVQg84ofAA "Mathics – Try It Online") 2..23 (range mode)
[Try it online!](https://tio.run/##HcZNC4IwGADgHzMYhROa0mlNlCDoViB0GO9Ba8MXenVs3kT/@vp4Tg9184DPmJxOu6iXVbVd/7aGdKEeA/52Kpm4OnOefECyd4OCgPNLsN/H/5s@GswJKini1nhvx1c7baRIlwwUZRmIBUUh2AoqGsNyCbDn6RZwnGtXy@MhfQA "Mathics – Try It Online") or 150 (distinct values)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 33 bytes (non-competing?)†
```
ò2 rÈc_aY >1«XøZ «Yk øZk}a+2}[] o
```
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=8jIgcshjX2FZID4xq1j4WiCrWWsg+FprfWErMn1bXSBv&inputs=Mg==,Mw==,NA==,NQ==,Ng==,Nw==,OA==,OQ==,MTA=)
† I [fixed a bug in the Japt Interpreter](https://github.com/ETHproductions/japt/commit/223f6dbc196b309312750eabaab31018409a7113) while working on this solution. [This meta post](https://codegolf.meta.stackexchange.com/a/7833/69583)
from a year ago deems this answer non-competing, but [this newer meta post](https://codegolf.meta.stackexchange.com/q/12877/69583) is pushing for more freedom in this. Regardless, I spent too much time on this to scrap it.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2IŸεDU°2Ÿ¯KʒX¿}ʒXα1›}θDˆ}θ
```
[Try it online](https://tio.run/##yy9OTMpM/f/fyPPojnNbXUJDtIyO7ji03vvUpIhD@2uB5LmNho8adtWe2@Fyug1IAlWaAgA) or [output the first \$n\$ terms as list](https://tio.run/##yy9OTMpM/f/fyPPojnNbXUJDtIyO7ji03vvUpIhD@2uB5LmNho8adtWe2@Fyuq0WqM4UAA). (NOTE: `°` is obviously extremely slow, so replaced with `T*` in the TIO links (\$10\*n\$ instead of \$10^n\$).)
**Explanation:**
```
2IŸ # Create a list in the range [2, input]
ε # Map each value `y` to:
DU # Store a copy of `y` in variable `X`
°2Ÿ # Create a list in the range [10**`y`,2]
¯K # Remove all values already in the global_array
ʒX¿} # Only keep values with a greatest common divider of 1 with `X`
ʒXα1›} # Only keep values with an absolute difference larger than 1 with `X`
θ # After these filters: keep the last (the smallest) element
Dˆ # And add a copy of it to the global_array
}θ # After the map: only leave the last value
# (and output the result implicitly)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 bytes
```
!¡λḟ§&oε⌋o>1≠→L¹`-N);1
```
[Try it online!](https://tio.run/##AToAxf9odXNr/21vd1Ms4oKB4oCmMiAyM/8hwqHOu@G4n8KnJm/OteKMi28@MeKJoOKGkkzCuWAtTik7Mf// "Husk – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
It pains me to have to invoke a function without a shortcut - can't remember the last time I had to, if ever - but it worked out shorter than any other method I could come up with.
```
@W{WjY «ZøW ©ÓWaY}a}g
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFd7V2pZIKta%2bFcgqdNXYVl9YX1n&input=Mg)
] |
[Question]
[
*Inpsired by a [youtube video](https://www.youtube.com/watch?v=-Wxui-9b8cw) from a fellow PPCG user...*
You challenge is to use ASCII-art draw a Minecraft castle wall of Andesite and Diorite. The *shape* of the wall is the [Cantor Set](https://en.wikipedia.org/wiki/Cantor_set). For reference, the Cantor Set is made by repeating the following **N** times:
* Triple the current step
* Replace the middle one with blank space
* Add a full line below it
This creates the following for the first four steps:
```
*
* *
***
* * * *
*** ***
*********
* * * * * * * *
*** *** *** ***
********* *********
***************************
```
However, your challenge is not quite that simple. You see, after the cantor set gets really big, it becomes boring to look at the same character repeated over and over and over. So we're going to change that by overlaying an alternating series of asterisks `*` and pound signs `#`. You should alternate on every three characters horizontally, and on every row vertically. (Of course leaving the spaces the same) For example, the second example will become:
```
* *
###
```
and the third example will become:
```
* * * *
### ###
***###***
```
For completeness, here are examples four and five:
```
#4
* * * * * * * *
### ### ### ###
***###*** ***###***
###***###***###***###***###
#5
* * * * * * * * * * * * * * * *
### ### ### ### ### ### ### ###
***###*** ***###*** ***###*** ***###***
###***###***###***###***### ###***###***###***###***###
***###***###***###***###***###***###***###***###***###***###***###***###***###***
```
And one **mega** example, the 6th iteration:
```
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
***###*** ***###*** ***###*** ***###*** ***###*** ***###*** ***###*** ***###***
###***###***###***###***### ###***###***###***###***### ###***###***###***###***### ###***###***###***###***###
***###***###***###***###***###***###***###***###***###***###***###***###***###*** ***###***###***###***###***###***###***###***###***###***###***###***###***###***
###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###
```
# The challenge
You must write a full program or function that accepts a positive integer for input, and outputs the *N*'th generation of this minecraft castle fractal. You can take Input and output by any reasonable method, and you do not have to worry about invalid inputs (such as numbers less than 1, floating point numbers, non-numbers, etc.).
The shortest answer, measured in bytes wins!
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~43~~ ~~36~~ 35 bytes
```
ḶṚ3*µ5B¤xЀṁ€Ṁ×\Ṛ©1,‘xS$¤ṁ×®ị“*# ”Y
```
Just a start, I'm sure this could be shorter.
[Try it online!](http://jelly.tryitonline.net/#code=4bi24bmaMyrCtTVCwqR4w5DigqzhuYHigqzhuYDDl1zhuZrCqTEs4oCYeFMkwqThuYHDl8Ku4buL4oCcKiMg4oCdWQ&input=&args=NQ)
\*For *n* > 5, your browser might wrap the output but if you copy-paste it into a non-wrapping editor, you will see the proper output.
## Explanation
```
ḶṚ3*µ5B¤xЀṁ€Ṁ×\Ṛ©1,‘xS$¤ṁ×®ị“*# ”Y Input: integer n
Ḷ Create the range [0, n)
Ṛ Reverse it
3* Raise 3 to the power of each
µ Begin a new monadic chain on the powers of 3
5B¤ Nilad. Get the binary digits of 5 = [1, 0, 1]
xЀ Duplicate each of [1, 0, 1] to a power of 3 times
Ṁ Get the maximum of the powers of 3
ṁ€ Reshape each to a length of that value
×\ Cumulative products
Ṛ© Reverse and save the result
1,‘xS$¤ Niladic chain.
1 Start with 1
‘ Increment it
, Pair them to get [1, 2]
$ Operate on [1, 2]
S Sum it to get 3
x Repeat each 3 times to get [1, 1, 1, 2, 2, 2]
ṁ Reshape that to the saved table
×® Multiply elementwise with the saved table
ị“*# ” Use each to as an index to select from "*# "
Y Join using newlines
Return and print implicitly
```
[Answer]
## JavaScript (ES7), ~~132~~ 125 bytes
```
n=>[...Array(n)].map((_,i)=>[...Array(3**~-n)].map((_,j)=>/1/.test((j/3**i|0).toString(3))?" ":`*#`[j/3+i&1]).join``).join`\n`
```
Where `\n` represents the literal newline characer. ES6 version for 141 bytes:
```
f=
n=>[...Array(n)].map((_,i)=>[...Array(Math.pow(3,n-1))].map((_,j)=>/1/.test((j*3).toString(3).slice(0,~i))?" ":`*#`[j/3+i&1]).join``).join`
`
;
```
```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```
[Answer]
# Python 2, ~~142~~ ~~138~~ 136 bytes
```
r=range
def f(n):
for i in r(n+1):
s="";d=i%2<1
for k in r(3**i):s+="#*"[(6+d-1+k*(d*2-1))%6<3]
exec"s+=len(s)*' '+s;"*(n-i);print s
```
This is the piece of code from [here](https://codegolf.stackexchange.com/a/4804/49561), and then edited for this challenge.
Will post an explanation later.
Also, BTW, two spaces are tabs.
**Edit 1: 4 bytes saved thanks to @DJMcMayhem.**
**Edit 2: 2 bytes saved thanks to @daHugLenny.**
[Answer]
# Ruby, ~~115~~ ~~103~~ 102 bytes
```
->n{g=->{T.tr"*#","#*"}
*s=?*
(n-1).times{|i|T=s[-1]
s=s.map{|l|l+' '*3**i+l}+[i<1??#*3:g[]+T+g[]]}
s}
```
Based on jsvnm's solution to the [standard Cantor set golf](https://codegolf.stackexchange.com/a/4797/58569).
-12 bytes thanks to Jordan.
[Answer]
# J, ~~47~~ 45 bytes
```
' *#'{~3(]*$@]$1 2#~[)(,:1)1&(,~],.0&*,.])~<:
```
Based on my [solution](https://codegolf.stackexchange.com/a/93770/6710) to the Cantor set challenge.
## Usage
```
f =: ' *#'{~3(]*$@]$1 2#~[)(,:1)1&(,~],.0&*,.])~<:
f 1
*
f 2
* *
###
f 3
* * * *
### ###
***###***
```
## Explanation
```
' *#'{~3(]*$@]$1 2#~[)(,:1)1&(,~],.0&*,.])~<: Input: n
<: Decrement n
(,:1) A constant [1]
1&( )~ Repeating n-1 times on x starting
with x = [1]
] Identity function, gets x
0&* Multiply x elementwise by 0
,. Join them together by rows
] Get x
,. Join by rows
1 ,~ Append a row of 1's and return
3 The constant 3
( ) Operate on 3 and the result
[ Get LHS = 3
1 2 The constant [1, 2]
#~ Duplicate each 3 times
Forms [1, 1, 1, 2, 2, 2]
$@] Get the shape of the result
$ Shape the list of [1, 2] to
the shape of the result
] Get the result
* Multiply elementwise between the
result and the reshaped [1, 2]
' *#' The constant string ' *#'
{~ Select from it using the result
as indices and return
```
[Answer]
# PHP, 159 bytes
```
for($r=($n=--$argv[1])?["* *","###"]:["*"];++$i<$n;$r[]=$a.$b.$a){$a=strtr($b=end($r),"#*","*#");foreach($r as&$s)$s.=str_pad("",3**$i).$s;}echo join("\n",$r);
```
**breakdown**
```
for(
$r=($n=--$argv[1]) // pre-decrease argument, initialize result
?["* *","###"] // shorter than handling the special iteration 2 in the loop
:["*"] // iteration 1
;
++$i<$n // further iterations:
;
$r[]=$a.$b.$a // 3. concatenate $a, $b, $a and add to result
)
{
// 1. save previous last line to $b, swap `*` with `#` to $a
$a=strtr($b=end($r),"#*","*#");
// 2. duplicate all lines with spaces of the same length inbetween
foreach($r as&$s)$s.=str_pad("",3**$i).$s; # strlen($s)==3**$i
}
// output
echo join("\n",$r);
```
] |
[Question]
[
Given an input of a list of numbers in the format of a shorthand increasing
integer sequence, output the sequence in full.
Shorthand increasing integer sequence format works by finding every number *n*
with fewer digits than the number preceding it, *m*. With *d* as the number of
digits in *n*, the last *d* digits of *m* are replaced with all the digits of
*n*. Here's an example input:
```
123 45 6 7 89 200
```
Applying the replacement rule, we first turn 45 into 145 because 45 < 123:
```
123 145 6 7 89 200
```
Repeatedly applying the same rule, this becomes:
```
123 145 146 7 89 200
123 145 146 147 89 200
123 145 146 147 189 200
```
The sequence is now sorted (there are no numbers for which the rule applies),
so this is the final output.
You may assume that
* shorthand notation is always used when possible. For example, input will be
`12 3`, never `12 13`.
* numbers will never decrease while remaining the same number of digits. For
example, input will never be `333 222`.
* applying the shorthand rule will never result in a number that is still less
than the previous number in the sequence. For example, input will never be
`123 12`.
* numbers will always be positive integers and never contain leading 0s (if
using a string format).
* the full, expanded sequence will never contain duplicate numbers. (However,
the shorthand sequence might; ex. `10 1 20 1` -> `10 11 20 21`.)
* there will be at least one number in the input.
Input and output can be either lists/arrays of numbers/strings or a single
string with elements separated by any non-digit.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Test cases, with input and output on alternating lines:
```
1 2 3 10 1 2 20 5 100 200 10 3 5 26 9 99 999 9999
1 2 3 10 11 12 20 25 100 200 210 213 215 226 229 299 999 9999
223 1184 334 441 5 927 2073 589 3022 82 390 5 9
223 1184 1334 1441 1445 1927 2073 2589 3022 3082 3390 3395 3399
5 10 5 20 5 30 5 40 5 50 5
5 10 15 20 25 30 35 40 45 50 55
7 8 9 70 80 90 700 800 900 7000 8000 9000
7 8 9 70 80 90 700 800 900 7000 8000 9000
42
42
```
[Answer]
# Jelly, 7 bytes
```
DUṛ"\UḌ
```
[Try it online!](http://jelly.tryitonline.net/#code=RFXhuZsiXFXhuIw&input=&args=MTIzLDQ1LDYsNyw4OSwyMDA) or [verify all test cases](http://jelly.tryitonline.net/#code=RFXhuZsiXFXhuIwKxpPDh-KCrOG5hOKCrOG5m-KBtg&input=WzEsMiwzLDEwLDEsMiwyMCw1LDEwMCwyMDAsMTAsMyw1LDI2LDksOTksOTk5LDk5OTldLFsyMjMsMTE4NCwzMzQsNDQxLDUsOTI3LDIwNzMsNTg5LDMwMjIsODIsMzkwLDUsOV0sWzUsMTAsNSwyMCw1LDMwLDUsNDAsNSw1MCw1XSxbNyw4LDksNzAsODAsOTAsNzAwLDgwMCw5MDAsNzAwMCw4MDAwLDkwMDBd).
### How it works
```
DUṛ"\UḌ Main link. Input: A (list of integers)
D Convert each integer to a list of its base 10 digits.
U Reverse each digit list.
\ Do a cumulative reduce, applying the dyadic link to the left:
" For each pair of corresponding digits:
ṛ Select the right one.
Vectorization leaves digits that do not have a counterpart untouched.
U Reverse the resulting digit arrays.
Ḍ Convert from base 10 to integer.
```
[Answer]
# Javascript, ~~45~~ 42 bytes
3 bytes off thanks [@Neil](https://codegolf.stackexchange.com/users/17602/neil).
```
a=>a.map(x=>z=z.slice(0,-x.length)+x,z='')
```
The above function expects an array of strings.
```
f=
a=>a.map(x=>z=z.slice(0,-x.length)+x,z='')
F=a=>document.body.innerHTML+='<pre>'+a+'\n'+f(a)+'\n</pre>';
F(['1','2','3','10','1','2','20','5','100','200','10','3','5','26','9','99','999','9999'])
F(['223','1184','334','441','5','927','2073','589','3022','82','390','5','9'])
F(['5','10','5','20','5','30','5','40','5','50','5'])
F(['7','8','9','70','80','90','700','800','900','7000','8000','9000'])
```
[Answer]
# Retina, 45 bytes
```
+`(?=(?<1>\d)+)(?<=(\d)(?(1)x)(?<-1>\d)+ )
$1
```
Uses balancing groups to count the digits which costs a lot. Haven't found a better approach yet but I'm interested in it.
[Try it online here.](http://retina.tryitonline.net/#code=K2AoPz0oPzwxPlxkKSspKD88PShcZCopKD8oMSkoPyEpKSg_PC0xPlxkKSsgKQokMQ&input=MTIzIDE0NSAxNDYgNyA4OSAyMDAgNTQzMjEw)
[Answer]
# Gema, 35 characters
```
<D>=@set{p;@fill-right{${p;};$0}}$p
```
Input: string with numbers separated by anything, output string.
Sample run:
```
bash-4.3$ gema '<D>=@set{p;@fill-right{${p;};$0}}$p' <<< '123 45 6 7 89 200'
123 145 146 147 189 200
```
[Answer]
# Ruby, 39 characters
```
->a{l='';a.map{|c|l=l[0..-c.size-1]+c}}
```
Input: array of strings, output: array of strings.
Sample run:
```
2.1.5 :001 > ->a{l='';a.map{|c|l=l[0..-c.size-1]+c}}[%w{123 45 6 7 89 200}]
=> ["123", "145", "146", "147", "189", "200"]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
s=''
for i in input():s=s[:max(len(s)-len(i),0)]+i;print s
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWXZ0rLb9IIVMhMw@ICkpLNDStim2Lo61yEys0clLzNIo1dUFUpqaOgWasdqZ1QVFmXolC8f//0eqG6joK6kYgwhhEGBqASbigEZhvCpEygIgYIBQaw2WNzECkJZiAkjDKUj0WAA "Python 2 – Try It Online")
] |
[Question]
[
# Count the number of sides on a polygon
The polygon-side-counting robot has decided to travel the world without telling anyone before, but it is crucial that the process of polygon counting is not stopped for too long. So you have following task: Given a black and white image of a polygon, your program/functoin should return the number of sides.
The program will be fed to an old punch card computer, and as punchcards are very expensive nowadays, you better try to make your program as short as possible.
The edges are at least 10 pixels long, and the angles formed by two adjecent edges is at least 10° but no more than 170° (or again greater than 190°). The polygon is completely contained within the image, and the polygon as well as it's complement is connected (there are no isolated islands) so this input would **not** be valid:
[](https://i.stack.imgur.com/UgR2y.png)
# Scoring
This is codegolf, that means the shortest submission in bytes wins, your submission has to find the correct number of edges for every test case. (And the submission should work for other cases as well, optimization for just those test cases is not allowed.)
If you want to submit a solution that does not find the correct number each time, you can submit that too, but it will be ranked behind all the submissions that perform better.
Please include the total number in your submission title. (The total error the sum of the absolute differences between the real number of sides and the each output).
# Test cases
### n=10
[](https://i.stack.imgur.com/ibflB.png)[](https://i.stack.imgur.com/gnxtQ.png)
### n=36
[](https://i.stack.imgur.com/2hx6A.png)[](https://i.stack.imgur.com/SBN1Q.png)
### n = 7
[](https://i.stack.imgur.com/qvqPF.png)[](https://i.stack.imgur.com/aHdit.png)
### n=5
[](https://i.stack.imgur.com/lW7uO.png)[](https://i.stack.imgur.com/kX9ey.png)
### This is not a test case, just out of curiosity: How many edges do you get for this input?
[](https://i.stack.imgur.com/fdko6.png)
[Answer]
# Python 2 + PIL, no error, ~~313~~ 307 bytes
```
from Image import*
I=open(sys.argv[1])
w,h=I.size;D=I.getdata()
B={i%w+i/w*1j for i in range(w*h)if D[i]!=D[0]}
n=d=1;o=v=q=p=max(B,key=abs)
while p-w:
p+=d*1j;e=2*({p}<B)+({p+d}<B)
if e!=2:e%=2;d*=1j-e*2j;p-=d/1j**e
if abs(p-q)>5:
t=(q-v)*(p-q).conjugate();q=p;w=o
if.98*abs(t)>t.real:n+=1;v=p
print n
```
Takes an image file name on the command line, and prints the result to STDOUT.
Gives the correct result for all tests, and *n* = 28 for the circle.
## Explanation
The algorithm works by walking along the perimeter of the polygon, and counting the number of encountered vertices (detected as changes in direction).
We start at the pixel farthest away from the origin, `o`, which is guaranteed to be a vertex, and therefore, to be adjacent to an edge (i.e., a boundary between a foreground pixel and a background pixel).
We keep track of our position, `p`, the most recent vertex, `v`, and the most recent "checkpoint", `q`, all of which are initially equal to `o`.
We also keep track of the direction of the edge, `d`, relative to the current pixel; `d` initially points east, which is a safe direction, since we know there's an edge to the east of `o`, or else it wouldn't be farthest from the origin.
We move along the edge, in a direction perpendicular to `d`, such that `d` points to our left, i.e., in a clockwise direction.
Whenever we "fall off the edge", i.e., in any situation where `p` is outside the polygon, or where the pixel to our left (i.e., in the direction of `d`) is inside the polygon, we adjust `p` and `d` accordingly before resuming.
Every time the distance between `p` and the last checkpoint, `q`, gets bigger than 5, we try to determine whether we passed over a vertex between `q` and `p`:
We compare the angle between `vq` (i.e., the vector from `v` to `q`), which is the general direction of the side of the polygon we were walking along when we reached the last checkpoint, and `qp`, the displacement between the last checkpoint and the current position.
If the angle is greater than about 10°, we conclude that we're walking along a different side of the polygon, increase the vertex count, and set `v`, the current vertex, to `p`.
At each checkpoint, regardless of whether we detected a vertex or not, we update `q`, the last checkpoint, to `p`.
We continue in this fashion until we arrive back at `o`, the starting point, and return the number of vertices found (note that the vertex count is initially 1, since the starting point, `o`, is itself a vertex.)
The images below show the detected vertices.
Note that taking `p`, the current position at each checkpoint, as the position of the new vertex is not optimal, since the real vertex is probably somewhere between the last checkpoint, `q`, and `p`, along the perimeter.
As you can see, all the vertices other than the first one (generally, the bottom-right vertex) are a little off.
Fixing this would cost more bytes, but this seems to be working well enough as it is.
That being said, it's a little hard not to overfit with only four test cases.
[](https://i.stack.imgur.com/sEPfU.png)
[](https://i.stack.imgur.com/UBQFC.png)
[](https://i.stack.imgur.com/dGNhc.png)
[](https://i.stack.imgur.com/IyS6A.png)
[](https://i.stack.imgur.com/OJ4Sp.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
```
Length[ImageCorners[#,3,.01,4]]&
```
[Try it online!](https://tio.run/##1VdL06u4dp33rzjVqUrde@kK2GDAgx5I4v0wCBsDPnUGGIPAPM3DGG7lt3f4@lbSlVEqlZtBSwNtNpJK0l57LamOxzyt47FI4t@yX3@z0oaM@Xe9jkmK2r5J@@H7v/zC/vJvzO4X7sePf/3tL3/7dh7j/ttfxj5uhi7u02b8do@TkvTt1Dz@@u1vf/2pqMm3X7/pddf243nsi4Z8/7m4QsebGVMlLdjK6eznsk82C399yltrby2s31JbfXnU0FMCzbvc9zfmsVeWG4bwph6L2xka90BpblejigLvkCRV5X4NADd8UTzly6K30j3qjP19boPxy8OFnqVqXKG5ORDvVzK@ei07sbc5NEsdAjVCC7u8HJcz3Tl2jXrZ790Uh3t0i8dQyvEEK60yY4EP1SG04sRfrdXIakV5qU9lUqt7gySVnkNOsVG2hHMwW5Pdg6IGV3JU/Rn5yIjURTJ0J5di3abagSwm7AFP@48LYMl9sHvFiMFo7yJ4joXDCZiXS3ZgtAxM5ZWxriADQXtegDhrs0KBDF85KBCnupNwD3xsSOBQhFgTFVfi3wd68M9oxJ2o7Y9vBb0ZeRcW00w72QPls5vnvqy1c19IK17FcbhdFxgHXkKCsQx15X1TPvCueglOLdCgzBJhnRHYDBlJ05UmMkloDuqNOym@37CyVA17DiSPmgXwoF5tqHfjB3Bll08OZSurKqEltLHr3pKZJLBcz5uPTu@VPQnAJ9c7GB4lK8uk4GVQXodqJ5uNAOX5YUeSI/VPcFkeIkZekFT@iGNE2rDvkLwqAzh/MALGagf6CfUWZniEF6tUVZ@YMZjnqyBXT772TYk670hnDhhcq/k@n16vk91he1e74MqD1ru02qCl6LrNT5LRfy5427VlsaABUEX3lEZGfhWllfN9qnmR7lW2YL9KZoT27d33bkx6jQ62g98yyA9E0XfsJ8RU2Hqi@xaqhksoaS@2H7G953TOAOuZPZmnlGHKnJ@RLgx5w/Z7VYUamaySs0vttTZU4lzgw/6I4w7cn24DTohIPg/eHx6j131mErPzvfvOvmUKxkbKEhSBwCW9LIPKEWYLTXAvildGqYH8oQYztaTBsOaLSMNbDOEs6p@GCe7uHDltKwL9SUsPfzp2p3Q@b2H0byzP6Gt4dR5ewUinRyusdD8IT611uvhFV4z7Tt/TwdIVtHPJmtTnzG8EGXMGT/LDmy7cztczSt/3/Jjugw/sCY1mjoDMt5V5Ah7LWp/QB61zf8kEzi/gipWng3eeTrUk7Hd7FEJByaAGKgohsNtS7ByhNr8fjvXror4JoQxXaug8M6TgMJPPMCzrUdzddqiJQ8eZvzgAGp5/kPvSIIT8@uvPv3z7@88wHlKe28yf3ZP687//@MndiGr8nn330rp9p6Dq8hjlcdOk1feN0H4J8mJMf/z48dNPGwUipKI/MwXC4A8KDB1OkHUwqxw8er6my8/B8jiVJPn5hLv2WViZGdlI28dy3AdBM8rNXsmxfC8hxK2MICC@qaAcixLXinAGg27dxFjaKCkANsDrAGwakJHjbAGcE0hJ9qoBdAK3g5QCK5IGnB4Ac96ZYgRGyDA5UiNOrR63BMXLvI@ee@89A8sCQqtlJLyFuprTACpg9M1WKo0UKDbGcN2Y93yaYCfpeZAgju0LgKXP8mk3KqP8HQayHXLbUhh9IGhAZ4AMj02FSlbIGTsQHjCigGiw803f@44erbpsgpIFWgh9Gd6ZVmLBDVxwqW27v4z49IEZJMFHl3SicyVxOc0HEYwG80Mc6iFFiDzlzr/bOg0fOjAqkp4gR05PEm4RWB9JcwSicK/kkrC6vkKdOYPaUljqokUcRYGuBbA7CFdwsaP6@F4zM6EV8I@z/s9z3/Lri3bHdGibhJ7p32EgV8qlPE@4Ruj/DvVkA3n637HetdVC2uZPAfRW/kPr3UCQbDArEfDTKb/s5PDsa4jh61ZA@v5Z6gZ4MK8LVWbL2X0VF3bJRbDIhl2qWuLcbUqbC1EOpBo/OtcmTOmqhJFh59uJlH5Gm6edR4YTE7QxWD6vUouJ3hu3emVHLEtbWOq312H5BdphaQ9JYAISgf5YeWNS@@Cc3vz4fb9@nQ7@slmpAjIN1C2nMEw5yQdZsjw5UHCSSB6cTHznCKYBrKB9gfwDjyl/DTBEs6zthG6TVHk2TSJnWfgqTyJMwRNnDmHOkgs5XUo6rpXOLcdp3uyK0IB9Kfqw9dWCcIxakYjR6DIhFRVf6zFqbEiBAy08ZIccP97WkVOkUi2w7IFYAWcf5v9LH5T0EwQyIoxP/FbCIjz8j75sl4YfLSpOUf@Qg7dvkXyA1ngj1bE5pMVJAOp61fWKOtXxWeM56t4NmntU/HTlQA3Fk/YOYYIkw/Zi@bOwNH/8imt9OTXhMLOHK3MobwhFDPkdZWf/6njmAUW6/k/QjG5LnXhLmz9vLkV/iEa0iYakw7MSeUAx/JGoR@dzshbGUoMAOw0Su7JYLjNDruLzsHt5@ejyMmOEVv/Uplu91YYuGwxLEJAYpeSBi1fnJl6J8Mma2uocOVZevKOpgCm5duzlmeF3UFBgYR/2Y1mOYrohItxZEQtatjqAVgGGAfQbMBWMthMyDsABc0F8TOSFyGarZixL0/vbAWz3/a2rdbDR5icyFAFGxCdEToiMWoVXQQGMD9A9YBoY3TDaZgQTcAkDyEbWslirWJBVBs5HlU04lc15TmbQDop@etOmf/yjNlmxEk0gHhZ85eBWz67IDLF0PnAE23XmvamAI7hEEWqH2m25CceaY/c7HAKegOHez2s/CwAmYC88H7znTwVV6IbZ6TpkF@gRyDcNf5LF6LGeH9ErGOMN/f61Uh/jVc63KN0mI3iC3VIFL3rfsbO2g/MekAmMu4asw2p/Vc3eVKuNWjTWZf3A/w@4T4o@qdI/A76n/8L3/naJ@E0rPqoqaLpdZsSEy5gI@OtSVG4Pgzy4Xi6HKZNC3iZ5df@cyiNx@FB@HqfR48SU/lDSYs5IL3R6ebet3ltT/xk82VPfIYOEj8vAQrE23bkfpfebpay3xD5ZO2H3jfQeEOkEFObmW9G2cOCWK86y6qNHIqEP/3w@LUdOo9tdd7KnX8P7GnjHj1XNphUS/IqYF3x6nlfVyjKrg0DCu3QoJfxa1l7TTmQXDwMvrA05YfQJ@8C82iicjhe2qO7gJTsJCmZeZ@1gra@bWmrVl02agNlFy4wkwB92Tsps6@cgBiuRLSkEhb7hvyN4OPkglpyLEGMQ6hQ7fMpZdYEGiK0e3sk2RpmNCcyDMRtPmEfWfLXVE6GQiNzb25sfLyBdZ4fijppQaNTBFGanf8P4vtkNC5CTyskjgXlPs2AfCu39cuTGD03t5wQ7k8M8d4ro10MGp1o8n7Pg@FKjddwxyWt7ts4KT7zW5kvUbgKQ5l2b8K3ZXlKdKvJ25Idze41P6bNrjwKJuzD2qDLvHL4sulsapFXXpXz76u5pTNV59@aH5fCIs7TpOpqe9mAjmJaJT9pzoaxwJyFe493rfDL@qZey3/4D "Wolfram Language (Mathematica) – Try It Online") (Testcases are base64 encoded after running it through [optipng](https://optipng.sourceforge.net/))
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.